> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# What are data sources

> Explains using Terraform data sources to read existing Azure resources, reference attributes in configurations, avoid duplication, and create compatible resources with examples, errors, and best practices.

In this lesson we introduce Terraform data sources — a read-only mechanism that lets Terraform query existing infrastructure and expose attributes you can reference in your configuration. Data sources are ideal when you need to reference resources that are managed outside your current Terraform run (for example, an IT-managed resource group or storage account) without importing or recreating them.

Why use data sources?

* Reuse attributes (location, id, name) from existing resources.
* Avoid duplicating configuration values across stacks or pipelines.
* Keep Terraform operations non-destructive for resources managed elsewhere.

General data source structure

```hcl theme={null}
data "azurerm_<type>" "<name>" {
  # lookup filters or required parameters
}
```

Reference attributes from a data source using:

```hcl theme={null}
data.azurerm_<type>.<name>.<attribute>
```

Common example: read an existing Resource Group and reference its attributes

```hcl theme={null}
provider "azurerm" {
  features {}
  # Optionally set subscription_id here or via environment variables (AZURE_SUBSCRIPTION_ID)
}

data "azurerm_resource_group" "rg" {
  name = "rg-qe-workshop-riskaria"
}

resource "azurerm_storage_account" "example" {
  name                        = var.storage_account_name
  location                    = data.azurerm_resource_group.rg.location
  resource_group_name         = data.azurerm_resource_group.rg.name
  account_tier                = "Standard"
  account_replication_type    = "LRS"
  public_network_access_enabled = true
}
```

In this example Terraform creates the storage account, but it derives the location and resource group from an existing resource group via the data source. This ensures consistency and prevents duplicating values.

Scenario: Deploying into IT-managed resources

Imagine your IT team manages a resource group and a storage account. You want to deploy additional resources into that same resource group from a separate pipeline without modifying or recreating the IT-managed resources. Use data sources to read the existing resources, then create your own resources that reference them.

Step 1 — Read the existing resource group

```hcl theme={null}
data "azurerm_resource_group" "rg" {
  name = "lifecycle-resources"
}
```

Step 2 — Two common approaches

Option A: Create your own storage account inside the existing resource group

```hcl theme={null}
variable "st_name" {
  type = string
}

resource "azurerm_storage_account" "myst" {
  name                = var.st_name
  location            = data.azurerm_resource_group.rg.location
  resource_group_name = data.azurerm_resource_group.rg.name
  account_tier        = "Standard"
  account_replication_type = "LRS"
}
```

Option B: Reference an existing storage account (managed by IT) and create a blob container inside it

```hcl theme={null}
data "azurerm_storage_account" "storage" {
  name                = "lifecyclestorage5836"
  resource_group_name = data.azurerm_resource_group.rg.name
}

resource "azurerm_storage_container" "reports" {
  name                  = "reports"
  # Prefer using storage_account_id (not storage_account_name) to avoid deprecated arguments
  storage_account_id    = data.azurerm_storage_account.storage.id
  container_access_type = "private"
}
```

Common errors and fixes

| Error                                                                   | Typical cause                                                                          | Fix                                                                                                        |
| ----------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| Reference to undeclared input variable                                  | You referenced a variable (e.g., `st_name`) but did not declare it.                    | Declare the variable: <br />`hcl<br>variable "st_name" { type = string }<br>`                              |
| Invalid resource type (e.g., using `azurerm_storage_account_container`) | Wrong resource name for a blob container.                                              | Use the correct resource: `azurerm_storage_container`. See provider docs for resource names.               |
| Using deprecated arguments                                              | Some resource arguments are deprecated and may be removed in future provider versions. | Use provider-recommended attributes (for example, `storage_account_id` instead of `storage_account_name`). |

Running Terraform in the configuration directory

Initialize the working directory:

```bash theme={null}
terraform init
```

Plan with a variable value (if `st_name` is declared):

```bash theme={null}
terraform plan --var="st_name=myst6878766"
```

Apply (with the same variable):

```bash theme={null}
terraform apply --var="st_name=myst6878766"
```

Example plan output (creating an `azurerm_storage_container`):

```plaintext theme={null}
# azurerm_storage_container.reports will be created
+ resource "azurerm_storage_container" "reports" {
    + container_access_type      = "Private"
    + default_encryption_scope   = (known after apply)
    + encryption_scope_override_enabled = true
    + has_immutability_policy    = (known after apply)
    + id                         = (known after apply)
    + name                       = "reports"
    + resource_manager_id        = (known after apply)
    + storage_account_id         = (known after apply)
  }
Plan: 1 to add, 0 to change, 0 to destroy.
```

<Callout icon="lightbulb" color="#1CB2FE">
  The argument `storage_account_name` on `azurerm_storage_container` is deprecated in favor of `storage_account_id`. Use `storage_account_id = data.azurerm_storage_account.storage.id` to be future-proof.
</Callout>

Verify in the Azure portal

After `terraform apply`, confirm the blob container appears under the storage account's Blob containers in the Azure portal. The screenshot below shows the Storage Account overview and navigation to Storage browser / Blob containers.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/9l60TCpe5-axPZIp/images/Terraform-On-Azure/Data-Sources/What-are-data-sources/azure-portal-storage-account-overview.jpg?fit=max&auto=format&n=9l60TCpe5-axPZIp&q=85&s=5fab1e823ee29d3d38630b1016665d62" alt="The image shows a Microsoft Azure portal interface displaying a storage account overview with metrics for blob containers, file shares, tables, and queues. The sidebar includes options like overview, activity log, tags, and storage browser." width="1920" height="1080" data-path="images/Terraform-On-Azure/Data-Sources/What-are-data-sources/azure-portal-storage-account-overview.jpg" />
</Frame>

You should see the "reports" container (or whatever name you used) created inside the storage account retrieved by the data block.

Summary and best practices

* Use data sources to read existing infrastructure and expose attributes for use in resources and modules.
* Define data sources with `data "<provider>_<type>" "<name>" { ... }` and reference attributes with `data.<provider>_<type>.<name>.<attribute>`.
* Prefer provider-recommended attributes (e.g., `storage_account_id`) to avoid deprecated arguments.
* Common issues are usually due to undeclared variables or incorrect resource/type names—declare variables and verify resource names against the provider documentation.

Links and references

* Terraform documentation: [https://www.terraform.io/docs](https://www.terraform.io/docs)
* AzureRM provider docs: [https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs)
* Azure portal: [https://portal.azure.com](https://portal.azure.com)

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/terraform-on-azure/module/5e64ee11-c3c3-4d9c-be0c-53989a38ae8f/lesson/2332899d-d3c8-44a7-9801-7529ea94ac08" />
</CardGroup>
