Reading terraform state with jq
There are some methods available to fetch state data. You can read the
.tfstate file directly, either by reading the local file or by looking inside your remote backend (most commonly s3). You can also use
terraform state show in conjunction with
terraform state list which is an improvement over the latter. Both these methods are fine when you just want to take a look at the data, but they are not perfect for your tooling to interact with. You could always set up
outputs but there they are not the best fit for sensitive values, for example.
Terraform show -json
For those cases, you probably want to use the
terraform show -json command. It’ll output your entire state in json format, you can then can pipe that to jq or any other tool that handles json. I commonly use this to fetch the ssh private keys generated by the
tls_private_key resources. One usage example would be the following:
# for reference, this example is based on the following .tf file # https://github.com/dimmaski/terraform-aws-minecraft-server/blob/master/terraform/ssh.tf PRIVATE_SSH_KEY=$(terraform show -json | jq -r '.values.resources | select(.address == "tls_private_key.example") | .values.private_key_pem')
It’s a fine way of retrieving sensitive data, but I also tend to use this pattern when I want to create some sort of script around a project. For example, you could have a generic script that automatically fetches the IP of one instance, an ssh private key, and runs an ssh command based on the terraform state of your current directory. It ain’t fancy but will save you some typing.