
Let's say you have the following files on your Terraform server.
├── modules.tf
├── locals.tf
├── outputs.tf
├── providers.tf
├── terraform.tfstate
├── variables.tf
├── child (directory)
│ ├── main.tf (child module)
│ ├── data.tf
│ ├── outputs.tf
│ ├── resources.tf
Let's say resources.tf in your child module is using a resource block to create or update a resource. In this example, the aws_security_group resource block is being used to create or update an Amazon Web Services (AWS) Security Group.
resource "aws_security_group" "my-security-group" {
name = "my security group for port 443"
description = "security group for port 443"
vpc_id = data.aws_vpc.my-vpc.id
ingress {
description = "TLS from VPC"
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["10.0.0.0/16"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "security group for port 443"
}
}
And perhaps outputs.tf in the same directory as your main root module (main.tf) is being used to access the values of the resource in other blocks. For example, you could use an output block and the value would contain the resource (aws_security_group.my-security-group).
output "my-security-group" {
value = aws_security_group.my-security-group
}
And perhaps outputs.tf in the same directory as your main root module (main.tf) gets the "my-security-group" output from the child module.
output "security-group" {
value = module.child.my-security-group
}
The terraform output command can be used.
terraform output
Which should return all of the keys and values of the resource.
security-group = {
"arn" = "arn:aws:ec2:us-east-1:713542074252:security-group/sg-04216bae7e6f38d18"
"description" = "security group for port 443"
"egress" = toset([
{
"cidr_blocks" = tolist([
"0.0.0.0/0",
])
"description" = ""
"from_port" = 0
"ipv6_cidr_blocks" = tolist([])
"prefix_list_ids" = tolist([])
"protocol" = "-1"
"security_groups" = toset([])
"self" = false
"to_port" = 0
},
])
"id" = "sg-04216bae7e6f38d18"
"ingress" = toset([
{
"cidr_blocks" = tolist([
"172.31.0.0/16",
])
"description" = "ingress for port 443"
"from_port" = 443
"ipv6_cidr_blocks" = tolist([])
"prefix_list_ids" = tolist([])
"protocol" = "tcp"
"security_groups" = toset([])
"self" = false
"to_port" = 443
},
])
"name" = "my security group for port 443"
"name_prefix" = ""
"owner_id" = "713542074252"
"revoke_rules_on_delete" = false
"tags" = tomap({
"Name" = "security group for port 443"
})
"tags_all" = tomap({
"Name" = "security group for port 443"
})
"timeouts" = null /* object */
"vpc_id" = "vpc-014d2fcfa335d3c01"
}
And then you might want to reference the value of a specific key.
output "my-security-group-id" {
value = aws_security_group.my-security-group.id
}
So that only the value of the specific key is returned.
my-security-group-id = "sg-04216bae7e6f38d18"
Did you find this article helpful?
If so, consider buying me a coffee over at