0
0
TerraformHow-ToBeginner · 3 min read

How to Reference Resource in Terraform: Syntax and Examples

In Terraform, you reference a resource by using the syntax resource_type.resource_name.attribute. This lets you access properties of a resource defined elsewhere in your configuration to connect or configure other resources.
📐

Syntax

To reference a resource in Terraform, use the format resource_type.resource_name.attribute. Here:

  • resource_type is the kind of resource, like aws_instance.
  • resource_name is the name you gave the resource in your Terraform file.
  • attribute is a property of that resource, such as id or arn.
terraform
resource_type.resource_name.attribute
💻

Example

This example shows how to create an AWS EC2 instance and then reference its ID to create a security group rule that allows traffic to that instance.

terraform
resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

resource "aws_security_group" "example_sg" {
  name = "example_sg"

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "example_sg"
  }
}

resource "aws_security_group_rule" "allow_ssh" {
  type                     = "ingress"
  from_port                = 22
  to_port                  = 22
  protocol                 = "tcp"
  security_group_id        = aws_security_group.example_sg.id
  source_security_group_id = aws_instance.example.id
}
Output
Terraform will create an EC2 instance and a security group, then link the security group rule to the instance using the instance's ID.
⚠️

Common Pitfalls

Common mistakes when referencing resources include:

  • Using the wrong resource name or type, which causes Terraform to fail to find the resource.
  • Trying to reference an attribute that does not exist or is not exported by the resource.
  • Referencing resources before they are created, which can cause dependency errors.

Always double-check resource names and attributes and use terraform plan to verify references.

terraform
/* Wrong reference example */
output "wrong_id" {
  value = aws_instance.wrong_name.id
}

/* Correct reference example */
output "correct_id" {
  value = aws_instance.example.id
}
📊

Quick Reference

PartDescriptionExample
resource_typeType of resource defined in Terraformaws_instance
resource_nameName given to the resource in configexample
attributeProperty of the resource to accessid
Full referenceCombines all parts to access attributeaws_instance.example.id

Key Takeaways

Reference resources using the format resource_type.resource_name.attribute in Terraform.
Ensure resource names and attributes are correct to avoid errors.
Use terraform plan to verify your references before applying.
Attributes expose useful information like IDs or ARNs for connecting resources.
References create dependencies so Terraform knows the order to create resources.