Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get specific value out of the Terraform state file

Tags:

terraform

I've deployed my infra using Terraform and I noticed that I have some interesting information in the state (terraform.tfstate) file of terraform which I would like to extract. For example

$ terraform state show 'packet_device.worker'
id                = 6015bg2b-b8c4-4925-aad2-f0671d5d3b13
billing_cycle     = hourly
created           = 2015-12-17T00:06:56Z
facility          = ewr1
...

which I would like to transform somehow to

$ terraform state show 'packet_device.worker.id'
6015bg2b-b8c4-4925-aad2-f0671d5d3b13

But adding the id at the end doesn't seem to work. Any suggestions how I can achieve this behaviour?

like image 440
Jeanluca Scaljeri Avatar asked Sep 05 '19 19:09

Jeanluca Scaljeri


2 Answers

You can utilize terraform show -json and jq to get a specific value out of a Terraform state file.

terraform show -json <state_file> | jq '.values.root_module.resources[] | select(.address=="<terraform_resource_name>") | .values.<property_name>'

You have a state file named terraform.tfstate and a Terraform resource as packet_device.worker and you want to get id. Then it would be as follows:

terraform show -json terraform.tfstate | jq '.values.root_module.resources[] | select(.address=="packet_device.worker") | .values.id'

terraform.tfstate also can be omitted since it is a default name for a state file.

like image 112
Akif Avatar answered Sep 22 '22 04:09

Akif


Terraform state show command is used to retrieve all the attributes of a given resource and you won't be able to fetch a single attribute from it as the argument is resource ADDRESS and is used to refer a resource specifically. Documented in https://www.terraform.io/docs/internals/resource-addressing.html

What you can do is store the resource attribute in output value and use the command

terraform output {output-valaue-extractor}

Refer: https://www.terraform.io/docs/configuration/outputs.html

like image 24
Sajeer Noohukannu Avatar answered Sep 23 '22 04:09

Sajeer Noohukannu