Skip to the content.
Back to Lab Index

Lab description

In this lab we learn about the output definition in Terraform.

Outputs

Setup

Make sure you are in the correct folder:

1
cd ~/terraform-labs
1
cd ~/terraform-labs

If you were unable to complete the last lab, you can find a copy of the files in the solutions folder

1. Create outputs.tf

  1. Similar to variables.tf, let’s now create a new file called outputs.tf

    outputs.tf will be used to define the output values from resources created/updated.

    1
    2
    
     cd ~/terraform-labs
     code outputs.tf
    
    1
    2
    
     cd ~/terraform-labs
     code outputs.tf
    
  2. Add output values definition such as below. Notice the use of expressions here to get the id of specified resource group.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
     output "contoso_rg_id" {
       value       = azurerm_resource_group.contoso_rg.id
       description = "don't show actual data on cli output"
       sensitive   = true
     }
        
     output "contoso_dev_rg_id" {
       value = azurerm_resource_group.contoso_dev_rg.id
     }
    

2. Plan and apply

1
2
terraform plan -var-file="contoso.uk.tfvars"
terraform apply -auto-approve -var-file="contoso.uk.tfvars"
1
2
terraform plan -var-file="contoso.uk.tfvars"
terraform apply -auto-approve -var-file="contoso.uk.tfvars"

3. Verify

  1. Observe the output on terminal.
  2. Notice that one of them simply shows sensitive. This doesn’t mean it’s fully secure, anyone with access to state file can still get to that data.

    1
    2
    3
    
     Changes to Outputs:
       + contoso_dev_rg_id = (known after apply)
       + contoso_rg_id     = (sensitive value)
    

4. Outputs via CLI

The following commands can be used to get outputs from state and values of sensitive outputs.

  1. Show all outputs

    1
    
     terraform output
    
    1
    
     terraform output
    
  2. Show a specific output in json format

    1
    
     terraform output -json contoso_rg_id
    
    1
    
     terraform output -json contoso_rg_id
    
  3. Show a specific output in raw format

    1
    
     terraform output -raw contoso_rg_id
    
    1
    
     terraform output -raw contoso_rg_id
    

5. Recap

Topics Covered:

The folder should now look like below.

1
2
3
4
5
6
7
8
9
10
11
12
13
📂terraform-labs
┣ 📂.terraform
┣ 📜.gitignore
┣ 📜.terraform.lock.hcl
┣ 📜contoso.europe.tfvars
┣ 📜contoso.tfplan
┣ 📜contoso.uk.tfvars
┣ 📜main.tf
┣ 📜outputs.tf
┣ 📜terraform.tfstate
┣ 📜terraform.tfstate.backup
┣ 📜terraform.tfvars
┗ 📜variables.tf

Back to Lab Index