Generating meaningful outputs with Terraform

Wouldn't it be great if Terraform could show us useful, informational output after a successful run? Following what we've done so far, it would be helpful to know how to connect to the instance, what are the local and public IP addresses, or see the security groups used. That's what Terraform's outputs are for.

Getting ready

To step through this recipe, you will need the following:

  • A working Terraform installation
  • An AWS provider and an EC2 instance (using a SSH keypair and a Security Group), all configured in Terraform (refer to the previous recipes)
  • An Internet connection

How to do it…

Thankfully, we can use the same syntax we're already using to access variables and attributes of references, but this time in an output resource.

Let's start by simply adding a line in outputs.tf that would show us how to connect to our virtual machine, using the public_ip attribute of our dev EC2 instance:

output "login" {
  value = "ssh ubuntu@${aws_instance.dev.public_ip} -i ${var.aws_ssh_admin_key_file}"
}

When applying terraform next time, it will display the following:

login = ssh [email protected] -i keys/aws_terraform

No doubt it's much quicker than having to log into the AWS dashboard, find the instance, and copy and paste the IP in the terminal.

What if it's important for us to know at a glimpse under what security groups our EC2 instance is running? We know security groups can be multiple, so it's an array. We can access the content of this array using the formatlist interpolation syntax as follows:

output "security_groups" {
  value = "${formatlist("%v", aws_instance.dev.security_groups)}"
}

So now, at the next terraform apply, we'll instantly know our security groups:

security_groups = [
    base_security_group
]

Also, if we have a lot of information to display from multiple sources, we can use the same syntax:

output "instance_information" {
  value = "${formatlist("instance: %v public: %v private: %v", aws_instance.dev.*.id, aws_instance.dev.*.public_ip, aws_instance.dev.*.private_ip)}"
}

This will display the instance ID and its local and public IP addresses.

There's more…

Note that we used ${aws_instance.dev.public_ip} in the first output and aws_instance.dev.*.public_ip in our last output. If you use the latter, the output will iterate through all available machines. It's very useful if you launch more than one instance using the count=n parameter in the aws_instance Terraform resource.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.247.31