Terraform plan output to JSON

PR Code - Christopher Pateman
2 min readSep 22, 2021

--

The Terraform CLI currently doesn’t output the plan to a human readable file when running the plan command. It currently prints to the console in a readable format, at least within Azure DevOps, but the tfplan file outputted is not. This can be very unhelpful within a deployment pipeline when you save the output file to be processed with scripts.

The use case I had was to read the output to understand if there was any outstanding changes, which was to be used to determining what actions to be taken. I have seen some example where they would read the CLI output and parse that to find the information, but this didn’t seem standard or best practice.

Terraform CLI does have a command ‘terraform show’ that can read a plan file, then with the attribute ‘-json’ it prints it into a JSON output.

Details on the command can be found here > https://www.terraform.io/docs/cli/commands/show.html

You can then also read the JSON Schema here > https://www.terraform.io/docs/internals/json-format.html

This command will print out the plan file to JSON, which you could process, but I also wanted it downloaded so I needed it as a file. You can push this to a file by appending ‘ > outputfile.json’ to the command so it looks as per below:

terraform show -no-color -json output.tfplan > output.json

One very annoying part of this, is it still needs connection to the state file where the plan was made from. Therefore, even though we have the plan file locally and want to just read it, we still need to connect to the remote state. This makes it hard for testing as I can download the tfplan from the pipeline, but then need to make sure I have the connection details to the state file in, for example the Azure Blob Storage.

Visit PR Code to get the full PowerShell Script.

Originally published at http://prcode.co.uk on September 22, 2021.

--

--

PR Code - Christopher Pateman

I’m a Azure DevOps Engineer with a wide knowledge of the digital landscape. I enjoy sharing hard to find fixes and solutions for the wider community to use.