Each time we run terraform it records the infrastructure created in a Terraform state file. It is a custom JSON format that maps the resources in Azure, AWS, Google, etc to the Terraform resource in the configuration files. An example of the following configuration:
# Create a resource group
resource "azurerm_resource_group" "rg" {
name = "InfraAsCodeDemo"
location = "westus2"
}
Once Terraform apply has been run, the terraform.tfstate contains relevant information:
{
"mode": "managed",
"type": "azurerm_resource_group",
"name": "rg",
"provider": "provider.azurerm",
"instances": [
{
"schema_version": 0,
"attributes": {
"id": "/subscriptions/40e864e7-82c2-4189-9b82-9c68d6455c4f/resourceGroups/InfraAsCodeDemo",
"location": "westus2",
"name": "InfraAsCodeDemo",
"tags": {}
},
"private": "bnVsbA=="
}
]
},
Using the state file, Terraform is able to map the resource named rg of type azurerm_resource_group to the Azure id “/subscriptions/40e864e7-82c2-4189-9b82-9c68d6455c4f/resourceGroups/InfraAsCodeDemo”
Each time that we run Terraform it is able to get the up to date info from Azure and compare it to the configuration files to see what will change, this is discovered by the IDs in the state file. Thus when we run a terraform plan, it is the differential between infrastructure in Azure and the code in the configuration files.