Output Attributes

It is possible to output attributes of the instances that are being provisioned in Terraform. A typical output code block would looks like below.

output "ip" {
  value = aws_instance.example.public_ip
}

Outputs are referred using the instance type, instance name and then the attribute. In below example I'm going to output the public IP address of the newly provisioned EC2 instance and then output the private IP address of the same into a text file.

Lets' create a file named terraform.tfvars with below content,

AWS_ACCESS_KEY="<AWS_ACCESS_KEY>"
AWS_SECRET_KEY="<AWS_SECRET_KEY>"

Create a file named vars.tf with below content,

variable "AWS_ACCESS_KEY" {
}

variable "AWS_SECRET_KEY" {
}

variable "AWS_REGION" {
  default = "eu-west-1"
}

variable "AMIS" {
  type = map(string)
  default = {
    us-east-1 = "ami-13be557e"
    us-west-2 = "ami-06b94666"
    eu-west-1 = "ami-844e0bf7"
  }
}

Create a file named provider.tf with below content,

Create a file named instance.tf with below content,

In here, as usual I am defining a new EC2 instance. In addition to that, I have included a new provisioner local-exec. This will execute the command provided in the local machine. In this instance I output the private IP address of the new EC2 instance to a text file called private_ips.txt in the current folder in then local machine. Then I am printing the public IP address to the console.

Execute the below command to setup the required Terraform providers,

Initiate the deployment like below,

And if you inspect the current directory, you would be able to see a file named private_ips.txt.

Don't forget to delete the instance once the activities are done,

Last updated

Was this helpful?