---
title: "Utilizing Terraform Output Variables in Infrastructure Configuration"
description: "Need to effectively build and manage infrastructures? Learn how to utilize Terraform output variables in infrastructure configuration in this tutorial!"
canonical: "https://adamtheautomator.com/terraform-output-variables/"
---

# Utilizing Terraform Output Variables in Infrastructure Configuration

> Need to effectively build and manage infrastructures? Learn how to utilize Terraform output variables in infrastructure configuration in this tutorial!

Source: https://adamtheautomator.com/terraform-output-variables/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![Utilizing Terraform Output Variables in Infrastructure Configuration](https://adamtheautomator.com/wp-content/uploads/2021/11/Utilizing-Terraform-Output-Variables-in-Infrastructure-Configuration.jpg)

# Utilizing Terraform Output Variables in Infrastructure Configuration

[![](https://secure.gravatar.com/avatar/2beb65fca997135120ed98dc6a2e57dcdf1a7d7d2f5ff687b5d91dc7ccd7a6b5?s=192&d=mm&r=g)Sagar](https://adamtheautomator.com/author/shanky-mendiratta/)24 November 20215 min. read

Categories: [DevOps](/category/devops/)

Tags:[Terraform](/tag/terraform/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [Declaring Terraform Output Variables](#declaring-terraform-output-variables)
*   [Verifying Terraform Outputs within the AWS Console](#verifying-terraform-outputs-within-the-aws-console)
*   [Conclusion](#conclusion)

Have you ever needed to automate infrastructures in a public cloud, such as [AWS](https://aws.amazon.com/vpc/?vpc-blogs.sort-by=item.additionalFields.createdDate&vpc-blogs.sort-order=desc)? If you haven’t found a solution to interlink multiple Terraform resources or modules, don’t fret. Let [Terraform output](https://www.terraform.io/docs/language/values/outputs.html) variables do the trick!

In this tutorial, you will learn how to level up your infrastructure configuration with Terraform output variables!

## Prerequisites

This tutorial will be a hands-on demonstration. If you’d like to follow along, be sure you have the following:

*   [Terraform](https://www.terraform.io/docs/enterprise/install/index.html) – This tutorial uses Terraform v1.0.8 running on Ubuntu 18.04.5 LTS, but any operating system like Windows with Terraform will work.

Related:[How to Install Terraform on Windows](https://adamtheautomator.com/terraform-windows/)

*   An [Amazon Web Service (AWS) account](https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account/).
*   A code editor – Any text editor will work, but it’s best to have one that understands the HCL Terraform language like [Visual Studio (VS) Code](https://code.visualstudio.com/).

## Declaring Terraform Output Variables

In today’s DevOps era, building and managing infrastructures are all integrated into an automated process. Terraform is your best option for automation, primarily because of its essential concept, which is Terraform output variables.

Terraform output variables allow you to display a resource’s (e.g., AWS resource) output on the console. Output variables are also used as an input parameter for other resources if declared in an output configuration file.

1\. Open your terminal and run the commands below to create a folder in your home directory, and change the working directory to that folder.

In this demo, the folder is called _terraform-output-demo_, stored in your home directory. But you can name the folder differently as you prefer. This folder stores your Terraform configuration files.

```bash
mkdir ~/terraform-output-demo
cd ~/terraform-output-demo
```

Next, open your favorite code editor, and copy/paste the configuration below. Save the configuration as _main.tf_ inside the _~/terraform-output-demo_ directory.

> _Terraform uses several different types of configuration files. Each file is written in either plain text or JSON format with a specific naming convention of either [.tf or .tfjson format](https://www.terraform.io/docs/language/files/index.html)._

The configuration in the _main.tf_ file allows you to create various AWS cloud resources as follows:

*   [AWS VPC](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html) in default tenancy. This VPC contains other resources such as public subnets, route tables, AWS EC2 instances.
*   [Internet Gateway](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html) – IGW routes traffic from the EC2 instance in the public subnet to the internet.
*   [Public Subnets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Scenario2.html) – Resources within the public subnets allows you to expose resource publicly.
*   [Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html#RouteTables) – Route tables provide you route from the EC2 instance to the internet.
*   [AWS EC2 instances](https://aws.amazon.com/ec2/?ec2-whats-new.sort-by=item.additionalFields.postDateTime&ec2-whats-new.sort-order=desc) – The instance that launches within a newly created VPC.
*   cidr\_block, [ami](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html), and [instance type](https://aws.amazon.com/ec2/instance-types/?trkCampaign=acq_paid_search_brand&sc_channel=PS&sc_campaign=acquisition_IN&sc_publisher=Google&sc_category=Cloud%20Computing&sc_country=IN&sc_geo=APAC&sc_outcome=acq&sc_detail=amazon%20ec2%20instance%20types&sc_content=%7Bad%20group%7D&sc_matchtype=e&sc_segment=536392685920&sc_medium=ACQ-P%7CPS-GO%7CBrand%7CDesktop%7CSU%7CCloud%20Computing%7CEC2%7CIN%7CEN%7CSitelink&s_kwcid=AL!4422!3!536392685920!e!!g!!amazon%20ec2%20instance%20types&ef_id=Cj0KCQjwssyJBhDXARIsAK98ITQem3BsxzQ6K0bJYLG7zuCFqalemJ4STyfGcvXcNhTGMJZsJaDn8McaAmmBEALw_wcB:G:s&s_kwcid=AL!4422!3!536392685920!e!!g!!amazon%20ec2%20instance%20types) are declared as variables. These variables have their values defined in another file named _terraform.tfvars_ that you will create later in the next step.

> _You can find [Linux AMIs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html) (Amazon Machine Image) via the Amazon EC2 console_`.`

```yaml
## Creating a VPC
resource "aws_vpc" "Main" {                
  ## Defining the CIDR block use 10.0.0.0/24 for demo
  cidr_block       = var.main_vpc_cidr     
  instance_tenancy = "default"
}

## Creating Internet Gateway and attach it to VPC
resource "aws_internet_gateway" "IGW" {   
   # vpc_id will be generated after we create VPC 
   vpc_id =  aws_vpc.Main.id               
}

## Creating a Public Subnet
resource "aws_subnet" "publicsubnets" {    
  vpc_id =  aws_vpc.Main.id
  # CIDR block of public subnets
  cidr_block = var.public_subnets          
}

## Creating Route Table for Public Subnet
resource "aws_route_table" "PublicRT" {    
   vpc_id =  aws_vpc.Main.id
   route {
     cidr_block = "0.0.0.0/0"               
     ## Traffic from Public Subnet reaches Internet via Internet Gateway
     gateway_id = aws_internet_gateway.IGW.id
    }
}

## Route table association with Public Subnet
resource "aws_route_table_association" "PublicRTassociation" {
   subnet_id = aws_subnet.publicsubnets.id
   route_table_id = aws_route_table.PublicRT.id
}
  
## Creating the EC2 instance based on the ami and instance_type
resource "aws_instance" "my-machine" {
  ami = var.ami 
  instance_type = var.instance_type 
  subnet_id     = aws_subnet.publicsubnets.id
  tags = {
    Name = "my-ec2-machine"
  }
}
```

3\. Now, create another file named _vars.tf_ inside the _~/terraform-output-demo_ directory, and copy/paste the content below to the _vars.tf_ file. The _vars.tf file_ is a [Terraform variables file](https://www.terraform.io/docs/language/values/variables.html) containing all variables that the configuration file (_main.tf_) references.

```bash
variable "main_vpc_cidr" {}
variable "public_subnets" {}
# Creating a Variable for ami
variable "ami" {       
  type = string
}
# Creating a Variable for instance_type
variable "instance_type" {    
  type = string
}
```

4\. Create one more file called _provider.tf_ inside _~/terraform-output-demo_ directory and put the provider’s code below to the _provider.tf_ file. The _provider.tf_ file defines the AWS provider so that Terraform can connect to the correct cloud services.

Related:[Getting Started with the Terraform AWS Provider](https://adamtheautomator.com/terraform-aws/)

The code below defines the AWS provider named `aws` and creates resources in the `us-east-2` region.

> _You can launch aws resources in [any regions](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/)_

```yaml
provider "aws" {
  region = "us-east-2"
}
```

5\. Next, create a new file inside the _~/terraform-output-demo_ directory. Name the file as _terraform.tfvars,_ and paste in the code below.

The _terraform.tfvars_ file contains the values Terraform uses to replace the variable references inside a configuration file (_main.tf_).

```yaml
ami = "ami-0742a572c2ce45ebf"
instance_type = "t2.micro"
```

6\. Create one last file inside the _~/terraform-output-demo_ directory. Name the file as _output.tf,_ and copy/paste the code below.

The Terraform output configuration file below provides AWS resources such as AWS EC2 instance arn, and public IP address after executing the `terraform apply` command.

> _Including all configuration values in a single configuration file is possible. But to keep things clear for developers and admins, breaking the logic and variables into separate files is preferable._

```bash
## Output variable which will store the arn of instance 
## and display after terraform apply command.
output "ec2_arn" {
  ## Value depends on resource name and type (same as that of main.tf)
  value = aws_instance.my-machine.arn
}
## Output variable which will store instance public IP 
## and display after terraform apply command 
output "instance_ip_addr" {
  value       = aws_instance.my-machine.public_ip
  description = "The public IP address of the main server instance."
}
```

7\. Run the `tree` command below to verify that all required files are in the `terraform-output-demo` folder.

```bash
tree terraform-output-demo  
```

![Verifying Required Files Exist](https://adamtheautomator.com/wp-content/uploads/2021/11/image-321.png)

Verifying Required Files Exist

8\. Finally, run the commands below to navigate to `~\terraform-output-demo` directory and initiate [Terraform](https://adamtheautomator.com/terraform-eks-module/). Terraform initializes the plugins and providers which are required to work with resources.

Related:[Creating the AWS EKS Cluster with a Terraform Configuration](https://adamtheautomator.com/terraform-eks-module/)

> _Terraform typically uses a three-stage approach [terraform init](https://www.terraform.io/docs/cli/commands/init.html) → [terraform plan](https://www.terraform.io/docs/cli/commands/plan.html) → [terraform apply](https://www.terraform.io/docs/cli/commands/apply.html)._

```bash
cd ~\terraform-output-demo
terraform init
terraform plan
terraform apply
```

If all goes well after running `terraform apply` command, you’ll get the **Apply complete! Resources: 6 resources added, 0 changed, 0 destroyed** message shown below.

Note the output instance ID and IP address as you’ll need them to verify if they exist in the AWS Management Console later.

> _Terraform output variables are used within the same parent or child module to print specific values in the command line output and are also used as inputs to create resources using the [`terraform apply` command](https://www.terraform.io/docs/cli/commands/apply.html)._

Below, you can see the command displays the output’s EC2 instance arn and instance public IP address.

![Noting the Instance ID and IP Address](https://adamtheautomator.com/wp-content/uploads/2021/11/image-322.png)

Noting the Instance ID and IP Address

## Verifying Terraform Outputs within the AWS Console

By now, you should have the VPC and EC2 instances, but let’s verify by manually checking for the VPC in the AWS Management Console.

1\. Open your favorite web browser and navigate to the [AWS Management Console](https://aws.amazon.com/console/) and log in.

2\. While in the console, click on the search bar at the top, search for ‘EC2’, as shown below.

Click on the **EC2** menu item, and your browser redirects you to a page where you can see all EC2 instances.

![](https://adamtheautomator.com/wp-content/uploads/2021/11/image-323.png)

Searching for EC2

3\. Next, click on the same instance ID you noted in the “Declaring Terraform Output Variables” section (step eight) to view the instance’s details.

![Viewing EC2 Instances](https://adamtheautomator.com/wp-content/uploads/2021/11/image-324.png)

Viewing EC2 Instances

4\. Verify if the IP address of the EC2 instance is the same as the IP address you noted in the “Declaring Terraform Output Variables” section (step eight).

![Verifying EC2 Instance's IP Address](https://adamtheautomator.com/wp-content/uploads/2021/11/image-325.png)

Verifying EC2 Instance’s IP Address

## Conclusion

In this tutorial, you’ve learned how to use Terraform output variables to return the AWS EC2 instance details, such as IP address and arn. With Terraform producing outputs, you directly access the instance via putty or SSH clients without logging into AWS.

With this newfound knowledge as the first step, why not utilize Terraform output variables with other AWS services?

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fterraform-output-variables%2F&text=Utilizing%20Terraform%20Output%20Variables%20in%20Infrastructure%20Configuration)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fterraform-output-variables%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fterraform-output-variables%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2023/02/terraform-best-practices.jpg)

### [Ensuring Success by Learning Terraform Best Practices](/terraform-best-practices/)

Discover Terraform best practices and ensure that your DevOps environment is being utilized safely and securely to it’s fullest potential!

![](https://adamtheautomator.com/wp-content/uploads/2022/08/Which-Tool-Terraform-vs-Cloudformation-in-the-Fight-for-AWS.jpg)

### [Which Tool? Terraform vs. Cloudformation in the Fight for AWS](/terraform-vs-cloudformation/)

Learn which tool, Terraform vs Cloudformation is right for infrastructure as configuration with AWS in this ATA Learning tutorial!

![](https://adamtheautomator.com/wp-content/uploads/2022/07/A-Definitive-Guide-to-Leveraging-the-AWS-Terraform-IAM-Role.jpg)

### [A Definitive Guide to Leveraging the AWS Terraform IAM Role](/terraform-iam-role/)

Discover this definitive guide to the AWS Terraform IAM role and take your devops game to the next level in this ATA Learning tutorial.

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
