Output data from Terraform | Terraform | HashiCorp Developer (2024)

Terraform output values let you export structured data about yourresources. You can use this data to configure other parts of your infrastructurewith automation tools, or as a data source for another Terraform workspace.Outputs are also how you expose data from a child module to a rootmodule.

In this tutorial, you will use Terraform to deploy application infrastructureon AWS and use outputs to get information about the resources. Then, you willuse the sensitive flag to reduce the risk of inadvertently disclosing thedatabase administrator username and password. You will also learn how to format outputs into machine-readable JSON.

You can complete this tutorial using the same workflow with either TerraformCommunity Edition or HCP Terraform. HCP Terraform is a platform that you can use tomanage and execute your Terraform projects. It includes features like remotestate and execution, structured plan output, workspace resource summaries, andmore.

Select the HCP Terraform tab to complete this tutorial using HCP Terraform.

This tutorial assumes that you are familiar with the Terraform workflow. If you are new to Terraform, complete the Get Started collection first.

In order to complete this tutorial, you will need the following:

This tutorial assumes that you are familiar with the Terraform and HCPTerraform workflows. If you are new to Terraform, complete the Get Started collection first. If you are new to HCP Terraform, complete the HCP Terraform Get Startedtutorials first.

In order to complete this tutorial, you will need the following:

  • Terraform v1.2+ installed locally.
  • An AWS account.
  • An HCP Terraform account with HCP Terraform locally authenticated.
  • An HCP Terraform variable set configured with your AWS credentials.

Note

Some of the infrastructure in this tutorial may not qualify forthe AWS free tier. Destroy the infrastructureat the end of the tutorial to avoid unnecessary charges. We are notresponsible for any charges that you incur.

Create infrastructure

Clone the example repository for this tutorial, which contains Terraform configuration for a web application including a VPC, load balancer, EC2 instances, and a database.

$ git clone https://github.com/hashicorp/learn-terraform-outputs.git

Change to the repository directory.

$ cd learn-terraform-outputs

Initialize this configuration.

$ terraform initInitializing the backend...##...Terraform has been successfully initialized!You may now begin working with Terraform. Try running "terraform plan" to seeany changes that are required for your infrastructure. All Terraform commandsshould now work.If you ever set or change modules or backend configuration for Terraform,rerun this command to reinitialize your working directory. If you forget, othercommands will detect it and remind you to do so if necessary.

Open your terraform.tf file and uncomment the cloud block. Replace theorganization name with your own HCP Terraform organization.

terraform.tf

terraform { cloud { organization = "organization-name" workspaces { name = "learn-terraform-outputs" } } required_providers { aws = { source = "hashicorp/aws" version = "~> 4.4.0" } } required_version = "~> 1.2"}

Initialize your configuration. Terraform will automatically create the learn-terraform-outputs workspace in your HCP Terraform organization.

$ terraform initInitializing HCP Terraform...Initializing provider plugins...- Reusing previous version of hashicorp/aws from the dependency lock file- Installing hashicorp/aws v4.4.0...- Installed hashicorp/aws v4.4.0 (signed by HashiCorp)HCP Terraform has been successfully initialized!You may now begin working with HCP Terraform. Try running "terraform plan" tosee any changes that are required for your infrastructure.If you ever set or change modules or Terraform Settings, run "terraform init"again to reinitialize your working directory.

Note: This tutorial assumes that you are using a tutorial-specificHCP Terraform organization with a global variable set of your AWScredentials. Review the Create a Credential VariableSet for detailed guidance. If you are using a scoped variable set, assign it to your new workspace now.

Now apply the configuration. Respond yes to the prompt to confirm the operation.

$ terraform apply##...Plan: 46 to add, 0 to change, 0 to destroy.Do you want to perform these actions? Terraform will perform the actions described above. Only 'yes' will be accepted to approve. Enter a value: yes##...Apply complete! Resources: 46 added, 0 changed, 0 destroyed.

You can add output declarations anywhere in your Terraform configuration files.However, we recommend defining them in a separate file called outputs.tf tomake it easier for users to understand your configuration and review its expected outputs.

Add a block to outputs.tf to show the ID of the VPC.

outputs.tf

output "vpc_id" { description = "ID of project VPC" value = module.vpc.vpc_id}

While the description argument is optional, you should include it in alloutput declarations to document the intent and content of the output.

You can use the result of any Terraformexpressionas the value of an output. Add the following definitions to outputs.tf.

outputs.tf

output "lb_url" { description = "URL of load balancer" value = "http://${module.elb_http.elb_dns_name}/"}output "web_server_count" { description = "Number of web servers provisioned" value = length(module.ec2_instances.instance_ids)}

The lb_url output uses stringinterpolationto create a URL from the load balancer's domain name. The web_server_countoutput uses the length()function tocalculate the number of instances attached to the load balancer.

Terraform stores output values in the configuration's state file. In order to see these outputs,you need to update the state by applying this new configuration, even though theinfrastructure will not change. Respond to the confirmation prompt with a yes.

$ terraform applyrandom_string.lb_id: Refreshing state... [id=5YI]module.vpc.aws_vpc.this[0]: Refreshing state... [id=vpc-004c2d1ba7394b3d6]## ...Plan: 0 to add, 0 to change, 0 to destroy.Changes to Outputs: + lb_url = "http://lb-5YI-project-alpha-dev-2144336064.us-east-1.elb.amazonaws.com/" + vpc_id = "vpc-004c2d1ba7394b3d6" + web_server_count = 4Do you want to perform these actions? Terraform will perform the actions described above. Only 'yes' will be accepted to approve. Enter a value: yesApply complete! Resources: 0 added, 0 changed, 0 destroyed.Outputs:lb_url = "http://lb-5YI-project-alpha-dev-2144336064.us-east-1.elb.amazonaws.com/"vpc_id = "vpc-004c2d1ba7394b3d6"web_server_count = 4

Query outputs

After creating the outputs, use theterraform output command to query all of them.

$ terraform outputlb_url = "http://lb-5YI-project-alpha-dev-2144336064.us-east-1.elb.amazonaws.com/"vpc_id = "vpc-004c2d1ba7394b3d6"web_server_count = 4

Next, query an individual output by name.

$ terraform output lb_url"http://lb-5YI-project-alpha-dev-2144336064.us-east-1.elb.amazonaws.com/"

Starting with version 0.14, Terraform wraps string outputs in quotes bydefault. You can use the -raw flag when querying a specified output formachine-readable format.

$ terraform output -raw lb_urlhttp://lb-5YI-project-alpha-dev-2144336064.us-east-1.elb.amazonaws.com/

Use the lb_url output value with the -raw flag to cURL the load balancerand verify the response.

$ curl $(terraform output -raw lb_url)<html><body><div>Hello, world!</div></body></html>

If you are using HCP Terraform, you can also find a table of your configuration's outputs on your workspace's overview page.

You can designate Terraform outputs as sensitive. Terraform will redact thevalues of sensitive outputs to avoid accidentally printing them out to theconsole. Use sensitive outputs to share sensitive data from your configurationwith other Terraform modules, automation tools, or HCP Terraform workspaces.

Terraform will redact sensitive outputs when planning, applying, or destroyingyour configuration, or when you query all of your outputs. Terraform willnot redact sensitive outputs in other cases, such as when you query aspecific output by name, query all of your outputs in JSON format, or when youuse outputs from a child module in your root module.

Add the following output blocks to your outputs.tf file. Note that the sensitive attribute is set to true.

outputs.tf

output "db_username" { description = "Database administrator username" value = aws_db_instance.database.username sensitive = true}output "db_password" { description = "Database administrator password" value = aws_db_instance.database.password sensitive = true}

Apply this change to add these outputs to your state file, and respond to theconfirmation prompt with yes.

$ terraform applyrandom_string.lb_id: Refreshing state... [id=5YI]module.vpc.aws_vpc.this[0]: Refreshing state... [id=vpc-004c2d1ba7394b3d6]## ...Apply complete! Resources: 0 added, 0 changed, 0 destroyed.Outputs:db_password = <sensitive>db_username = <sensitive>lb_url = "http://lb-5YI-project-alpha-dev-2144336064.us-east-1.elb.amazonaws.com/"vpc_id = "vpc-004c2d1ba7394b3d6"web_server_count = 4

Notice that Terraform redacts the values of the outputs marked as sensitive.

Use terraform output to query the database password by name, and notice thatTerraform will not redact the value when you specify the output by name.

$ terraform output db_password"notasecurepassword"

Terraform stores all output values, including those marked as sensitive, as plain text in your state file.

Use the grep command to see the values of the sensitiveoutputs in your state file.

$ grep --after-context=10 outputs terraform.tfstate "outputs": { "db_password": { "value": "notasecurepassword", "type": "string", "sensitive": true }, "db_username": { "value": "admin", "type": "string", "sensitive": true },

Pull down your remote state file from HCP Terraform.

$ terraform state pull > terraform.tfstate

Use the grep command to see the values of the sensitiveoutputs in your state file.

$ grep --after-context=10 outputs terraform.tfstate "outputs": { "db_password": { "value": "notasecurepassword", "type": "string", "sensitive": true }, "db_username": { "value": "admin", "type": "string", "sensitive": true },

Tip

If you are using an operating system without the grep command,open the terraform.tfstate file in your text editor and search for outputsto review the relevant lines.

The sensitive argument for outputs can help avoid inadvertent exposure ofthose values. However, you must still keep your Terraform state secure to avoidexposing these values.

Generate machine-readable output

The Terraform CLI output is designed to be parsed by humans. To getmachine-readable format for automation, use the -jsonflag for JSON-formattedoutput.

$ terraform output -json{ "db_password": { "sensitive": true, "type": "string", "value": "notasecurepassword" }, "db_username": { "sensitive": true, "type": "string", "value": "admin" }, "lb_url": { "sensitive": false, "type": "string", "value": "http://lb-5YI-project-alpha-dev-2144336064.us-east-1.elb.amazonaws.com/" }, "vpc_id": { "sensitive": false, "type": "string", "value": "vpc-004c2d1ba7394b3d6" }, "web_server_count": { "sensitive": false, "type": "number", "value": 4 }}

Terraform does not redact sensitive output values with the -json option,because it assumes that an automation tool will use the output.

Before moving on, destroy the infrastructure you created in this tutorial toavoid incurring unnecessary costs. Be sure to respond to the confirmationprompt with yes.

$ terraform destroy##...Do you really want to destroy all resources? Terraform will destroy all your managed infrastructure, as shown above. There is no undo. Only 'yes' will be accepted to confirm. Enter a value: yes##...Apply complete! Resources: 0 added, 0 changed, 46 destroyed.

If you used HCP Terraform for this tutorial, after destroying your resources, delete the learn-terraform-outputs workspace from your HCP Terraform organization.

Next steps

In this tutorial you used Terraform outputs to query data about yourinfrastructure. Terraform outputs let you share data between Terraformconfigurations, and with other tools and automation. Outputs are also the only wayto share data from a child module to your configuration's root module.

Now that you know how to use Terraform outputs, check out the followingresources for more information.

  • Read the Terraform Outputsdocumentation.
  • Manage sensitive data instate.
  • Use and create Terraformmodules.
  • Connect HCP TerraformWorkspaceswith run triggers, and use outputs from one workspace to configure anotherworkspace.
Output data from Terraform | Terraform | HashiCorp Developer (2024)
Top Articles
Caffeine Effects on Sleep Taken 0, 3, or 6 Hours before Going to Bed
Voters back housing for vets, homeless, mentally ill
Poe T4 Aisling
Truist Bank Near Here
Koopa Wrapper 1 Point 0
Palm Coast Permits Online
Best Big Jumpshot 2K23
What spices do Germans cook with?
Craigslist Campers Greenville Sc
Triumph Speed Twin 2025 e Speed Twin RS, nelle concessionarie da gennaio 2025 - News - Moto.it
Es.cvs.com/Otchs/Devoted
Merlot Aero Crew Portal
What is IXL and How Does it Work?
Olivia Ponton On Pride, Her Collection With AE & Accidentally Coming Out On TikTok
Degreeworks Sbu
ExploreLearning on LinkedIn: This month&#39;s featured product is our ExploreLearning Gizmos Pen Pack, the…
Vcuapi
Connect U Of M Dearborn
Kiddle Encyclopedia
Missed Connections Dayton Ohio
Craigslist Toy Hauler For Sale By Owner
Yard Goats Score
Puss In Boots: The Last Wish Showtimes Near Cinépolis Vista
Iroquois Amphitheater Louisville Ky Seating Chart
Www.publicsurplus.com Motor Pool
Surplus property Definition: 397 Samples | Law Insider
Greensboro sit-in (1960) | History, Summary, Impact, & Facts
Ltg Speech Copy Paste
January 8 Jesus Calling
Royalfh Obituaries Home
Ncal Kaiser Online Pay
Navigating change - the workplace of tomorrow - key takeaways
Rocketpult Infinite Fuel
Ewwwww Gif
Ise-Vm-K9 Eol
What Is Kik and Why Do Teenagers Love It?
303-615-0055
Go Bananas Wareham Ma
Discover Things To Do In Lubbock
Makes A Successful Catch Maybe Crossword Clue
9:00 A.m. Cdt
Alba Baptista Bikini, Ethnicity, Marriage, Wedding, Father, Shower, Nazi
Boyfriends Extra Chapter 6
Oefenpakket & Hoorcolleges Diagnostiek | WorldSupporter
Heat Wave and Summer Temperature Data for Oklahoma City, Oklahoma
Who Is Nina Yankovic? Daughter of Musician Weird Al Yankovic
How to Do a Photoshoot in BitLife - Playbite
The Hardest Quests in Old School RuneScape (Ranked) – FandomSpot
Minecraft Enchantment Calculator - calculattor.com
Craigslist Yard Sales In Murrells Inlet
Inside the Bestselling Medical Mystery 'Hidden Valley Road'
Cheryl Mchenry Retirement
Latest Posts
Article information

Author: Nathanael Baumbach

Last Updated:

Views: 6396

Rating: 4.4 / 5 (55 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Nathanael Baumbach

Birthday: 1998-12-02

Address: Apt. 829 751 Glover View, West Orlando, IN 22436

Phone: +901025288581

Job: Internal IT Coordinator

Hobby: Gunsmithing, Motor sports, Flying, Skiing, Hooping, Lego building, Ice skating

Introduction: My name is Nathanael Baumbach, I am a fantastic, nice, victorious, brave, healthy, cute, glorious person who loves writing and wants to share my knowledge and understanding with you.