Importing "terraform show -json <file>" to python

I am getting an error when trying to import the terraform json output from the "terraform show -json " command. My steps to replicate are as follows:

  • terraform plan -out .\plan.state.tfstate
  • terraform show -json .\plan.state.tfstate > plan.state.show.json

then run the following code in a python script.

import json
#terraform plan -out .\plan.state.tfstate 
#terraform show -json .\plan.state.tfstate > plan.state.show.json
with open('plan.state.show.json', 'r') as jsonfile:
    jsonfile.seek(0)
    data = json.load(jsonfile)
print(json.dumps(data, indent=4))

This returns the following error

Traceback (most recent call last):
  File ".\terraform-validate.py", line 15, in <module>
    data = json.load(jsonfile)
  File "C:\Python38\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
  File "C:\Python38\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Python38\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python38\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I am able to import this output into powershell without issue. But I was wondering if someone has run into this prior.

Terraform v0.12.20

  • provider.aws v2.47.0

Hi @SQLJames,

Does the content of your plan.state.show.json look like valid JSON if you inspect it directly in a text editor?

I’m wondering if perhaps the command failed for some reason and so the plan.state.show.json file is either empty or contains some non-JSON content, which the Python JSON parser then fails to read.

You need to pipe the file into jq before it will become readable like any other json file, otherwise it is only in a format that terraform can read.

terraform show -json tfplan | jq

Then you should be able to read it with json.load().