0
votes

I am new to Terraform and trying to understand data sources. I have read the documentation and this StackOverflow post, but I'm still unclear about the use cases of data source.

I have the following block of code:

resource "azurerm_resource_group" "rg" {
  name     = "example-resource-group"
  location = "West US 2"
}


data "azurerm_resource_group" "test" {
  name = "example-resource-group"
}

But I get a 404 error:

  • data.azurerm_resource_group.test: data.azurerm_resource_group.test: resources.GroupsClient#Get: Failure responding to request: StatusCode=404 -- Original Error: autorest/azure: Service returned an error. Status=404 Code="ResourceGroupNotFound" Message="Resource group 'example-resource-group' could not be found."

I don't understand why the resource group is not found. Also, I am unclear about the difference between data and variable and when should I use which.

Thanks

2

2 Answers

2
votes

I have provided a detailed explanation of what a data source is in this SO answer. To summarize:

  • Data sources provide dynamic information about entities that are not managed by the current Terraform configuration
  • Variables provide static information

Your block of code doesn't work because the resource your data source is referencing hasn't been created yet. During the planning phase, Terraform will try to find a resource group named example-resource-group, but it won't find it, and so it aborts the whole run. The ordering of the blocks makes no difference to the order they are applied.

If you remove the data block, run terraform apply, and then add the data block back in, it should work. However, data sources are used to retrieve data about entities that are not managed by your Terraform configuration. In your case, you don't need the data.azurerm_resource_group.test data source, you can simply use the exported attributes from the resource. In the case of azurerm_resource_group, this is a single id attribute.

0
votes

Think of a data source as a value you want to read from somewhere else.

A variable is something you define when you run the code.

When you use the data source for azurerm_resource_group terraform will search for an existing resource that has the name you defined in your data source block.

Example

    data "azurerm_resource_group" "test" {
      name = "example-resource-group"
    }

Quoting @ydaetskcoR from the comment below about 404 error:

It's 404ing because the data source is running before the resource creates the thing you are looking for. You would use a data source when the resource has already been created previously, not in the same run as the resource you are creating.