Terraform output values

2 min read

To be able to save data generated using terraform to be able to import the terraform state somewhere else using terraform_remote_state or retrieving it using the CLI we need to use the output directive:

output "alb_dns_name" {
  description = "ALB DNS name"
  value       = aws_alb.jenkins-alb.dns_name
}

We can use terraform output for getting all the outputs:

$ terraform output web
web = "jenkins.pet2cattle.com"
helm_jenkins_values = tolist([
  <<-EOT
  image:
    repository: jenkins
    tag: 2.60.3
    pullPolicy: IfNotPresent
    pullSecrets: []
    lts: true

  (...)

  EOT,
])

We can also retrieve just one of then, for example:

$ terraform output web
"jenkins.pet2cattle.com"

We can also use the -raw option for getting just the data:

$ terraform output -raw web
jenkins.pet2cattle.com

We can also output complex types, for example the compounded values from values and set attributes of a helm_release* resource:

output helm_jenkins_values {
  value = helm_release.jenkins.values
}

If we try to retrieve it we will get the following output:

$ terraform output helm_jenkins_values
tolist([
  <<-EOT
  image:
    repository: jenkins
    tag: 2.60.3
    pullPolicy: IfNotPresent
    pullSecrets: []
    lts: true

  (...)

  EOT,
])

But we won't be able to retrieve it as a raw value since it is a complex type:

$ terraform output -raw helm_jenkins_values 

Error: Unsupported value for raw output

The -raw option only supports strings, numbers, and boolean values, but output
value "helm_jenkins_values" is list of string.

Use the -json option for machine-readable representations of output values
that have complex types.

To be able to retrieve it as a yaml, we will need to tell terraform to output it as a json and then use jq for rendering the data contained in the first item of the array:

$ terraform output -json helm_jenkins_values | jq -r .[0]
image:
  repository: jenkins
  tag: 2.60.3
  pullPolicy: IfNotPresent
  pullSecrets: []
  lts: true

nameOverride: ""
fullnameOverride: ""

(...)

Posted on 16/04/2021

Categories