4: Terraform configuration

    Use and differentiate `resource` and `data` blocks

    A Terraform configuration is, at its heart, a directed graph of two block kinds. A resource block describes a real object whose full lifecycle (create, update, delete) Terraform owns, while a data block describes an existing object that Terraform reads but does not mutate. Mixing the two correctly is the first decision in almost every module, and getting it wrong produces either silent drift (the configuration "reads" something that no one is keeping in sync) or accidental destruction (a resource adopts an object that another team owns).

    A resource block has the form resource "<TYPE>" "<NAME>" { ... }. The first label is the resource type as exported by the provider (for example aws_s3_bucket, azurerm_storage_account, random_id); the second label is a local name unique within the module. The combination of type and name forms the resource address, which is how every other expression, the dependency graph, and the state file refer to the object. Inside the block, arguments configure the desired state, meta-arguments such as count, for_each, lifecycle, provider, and depends_on adjust how Terraform handles the block, and nested blocks (like tags, ingress, versioning) carry sub-configuration. When terraform apply runs, the provider compares the desired state in the configuration against the recorded state for that address and issues whichever API calls are required to converge.

    A data block has an almost identical shape: data "<TYPE>" "<NAME>" { ... }. The first label is a data source type (often a _ suffixed counterpart of a resource type, like aws_ami, azurerm_resource_group, or kubernetes_namespace), the second label is a local name. Arguments inside the block are filters, not desired-state declarations: they tell the provider what to look up. During the refresh phase of plan, Terraform calls the provider's read implementation with those filters and stores the returned attributes in state as a data-source instance. The configuration can then reference those attributes the same way it references a resource's attributes, but Terraform will never propose to create, update, or destroy the underlying object.

    The single most important rule is the rule of intent. If the configuration is the system of record for an object's life, it must be a resource block. If the object's life is owned somewhere else (another module, another team, a click-ops setup, a pre-existing account-level resource like the default VPC), it must be a data block. Switching intent without thinking can be expensive: replacing a data "aws_s3_bucket" lookup with a resource "aws_s3_bucket" in the same module would, on the next apply, create a second bucket with a generated name, leaving the first one orphaned. Replacing a resource block with a data block of the same type would remove the resource from the state's management scope, and Terraform would propose to destroy the object on the next plan.

    Anatomy of a resource block

    resource "aws_s3_bucket" "audit_logs" {
     bucket = "acme-audit-logs"
     force_destroy = false
    
     tags = {
     purpose = "audit"
     cost_center = "platform"
     }
    }
    

    The arguments bucket and force_destroy are top-level configuration; the tags nested block (technically an argument with an object value here) carries sub-configuration. The address of this object is aws_s3_bucket.audit_logs. Inside state, this address maps to one instance; if the block carried count = 3, the addresses would expand to aws_s3_bucket.audit_logs[0], [1], [2], and the state would carry three instances.

    Anatomy of a data block

    data "aws_ami" "ubuntu_lts" {
     most_recent = true
     owners = ["099720109477"]
    
     filter {
     name = "name"
     values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
     }
    }
    
    resource "aws_instance" "bastion" {
     ami = data.aws_ami.ubuntu_lts.id
     instance_type = "t3.micro"
    }
    

    The data source name is prefixed with data. whenever it appears in an expression: data.aws_ami.ubuntu_lts.id. That data. prefix is what differentiates a data-source reference from a resource reference; forgetting it produces an "unknown resource" error at validate time. The data source itself does not appear in the plan as a + create line; instead, it appears in the refresh phase output with a <= read symbol, indicating that the provider will fetch the latest values before the rest of the plan is computed.

    Decision Anchor: when to choose resource vs data

    Choose resource when this configuration is the source of truth for the object and Terraform should converge it on every apply. Choose data when another system, module, or team owns the object's life and you only need its attributes as inputs. A useful tie-breaker: if terraform destroy should remove the object, it must be a resource. If terraform destroy should leave it alone, it must be a data block.

    Mermaid: where each block kind fits in the workflow

    💡 Exam Trap: A common distractor flips the prefix rule. Resource attributes are referenced as <type>.<name>.<attr> (no data. prefix); data source attributes are referenced as data.<type>.<name>.<attr>. A stem that writes aws_ami.ubuntu_lts.id and asks "is this valid?" is testing whether you notice the missing data. qualifier.

    💡 Exam Trap: data blocks are not free. Every refresh phase calls the data source's read function, which can rate-limit the upstream API. Modules that wrap a slow API in dozens of data blocks make every plan slow even when nothing has changed. The exam frames this as a "why is plan slow" question; the answer is usually the count of data sources, not the count of resources.

    ⚠️ Anti-Pattern: Replacing a resource block with a data block of the same type "to stop Terraform from managing it." That action removes the resource from management scope, and the next apply proposes to destroy it because the state still contains the resource instance. The correct deactivation path is terraform state rm <address> followed by removing the block, or wrapping the resource with removed blocks where applicable.

    🎯 Scenario: A module is supposed to attach an IAM policy to an existing role that another team owns. The first author writes resource "aws_iam_role" "shared" and the next apply errors with EntityAlreadyExists. The correct shape is data "aws_iam_role" "shared" with a name filter, then resource "aws_iam_role_policy_attachment" referencing data.aws_iam_role.shared.name. The data block reads the role; the resource block writes the attachment; ownership stays where it belongs.

    📊 Limit: A single configuration can declare any number of resource and data blocks, but each block must have a unique (type, name) pair within its module. Reusing the same name for a resource and a data block of the same type is allowed (the data. prefix disambiguates), but it makes diffs and error messages harder to read.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the HashiCorp - Terraform Associate learning hub.