Working with Outputs in Terraform
Learn how to work with outputs in Terraform configuration.
Overview
Previously, we looked at the flexibility that using variables, especially input variables, gives us. When we create resources in Terraform, these resources have unique attributes that can be passed on as output to create another resource. The syntax for creating an output variable is as below:
Press + to interact
output "variable_name" {decsription = "Any description"value = "${resource_type.resource_name.attribute}"}
A practical use case
Let’s consider a situation where we have to create an EC2 instance and then obtain the public IP address so that we can initiate an SSH connection to the instance. We can create the needed resource and then use the output
keyword to obtain the public IP address, as shown below:
Press + to interact
resource "aws_vpc" "my_vpc" {cidr_block = "10.0.0.0/16"}resource "aws_internet_gateway" "igw" {vpc_id = aws_vpc.my_vpc.id}resource "aws_route_table" "public" {vpc_id = aws_vpc.my_vpc.idroute {cidr_block = "0.0.0.0/0"gateway_id = aws_internet_gateway.igw.id}}resource "aws_default_route_table" "default" {default_route_table_id = aws_vpc.my_vpc.default_route_table_idroute {cidr_block = "0.0.0.0/0"gateway_id = aws_internet_gateway.igw.id}}resource "aws_subnet" "demo_subnet" {vpc_id = aws_vpc.my_vpc.idcidr_block = "10.0.1.0/24"}resource "aws_security_group" "http_access" {name = "http_access"description = "Allow HTTP inbound traffic"vpc_id = aws_vpc.my_vpc.idingress {description = "HTTP Access"from_port = 80to_port = 80protocol = "tcp"cidr_blocks = ["0.0.0.0/0"]}ingress {description = "SSH Access"from_port = 22to_port = 22protocol = "tcp"cidr_blocks = ["0.0.0.0/0"]}egress {from_port = 0to_port = 0protocol = "-1"cidr_blocks = ["0.0.0.0/0"]}tags = {Name = "http_access"}}resource "aws_eip" "my_eip" {vpc = true}resource "aws_instance" "demo_instance" {ami = "ami-0a606d8395a538502"instance_type = "t2.micro"key_name = "sampleKey"subnet_id = aws_subnet.demo_subnet.idvpc_security_group_ids = [aws_security_group.http_access.id]associate_public_ip_address = truetags = {Name = "new-instance"}}output "my_instance2_ip" {value = aws_instance.demo_instance.public_ip}
Terraform outputs are available after a resource is created using terraform apply
. The ...