EricMM
EricMM

Reputation: 41

edit tfvars file using python

I don't know whether I'm asking this is the right group, but is there a way to edit a .tfvars using python. For example, I have a .tfvars file with the some variables with following values:

owner ='operations'
port_number='80'

I would like to edit port number = '22' and to use gcp_region = 'us_central2' can I open,edit the file and save it using python?

Upvotes: 4

Views: 7640

Answers (3)

JTD
JTD

Reputation: 77

You can convert your .tfvars files to JSON.

Terraform supports JSON input files seamlessly, using the extension .tfvars.json.

This syntax is useful when generating portions of a configuration programmatically

See: Terraform JSON Syntax and Terraform input variables

You can read the files in HCL using the python-hcl2 library to convert to JSON. Then read, edit and write the JSON in Python. For example:

import json
import hcl2

with open("vars.tfvars", "r") as file_in:
  data = hcl2.load(file_in)

data["port_number"] = "22"
data["gcp_region"] = "us_central2"

with open("vars.tfvars.json", "w") as file_out:
  file_out.write(json.dumps(data, indent=4))

The suggested python-hcl2 library is only able to read HCL files. If you are set on using HCL, Golang is the recommended method.

Upvotes: 4

maxirz
maxirz

Reputation: 21

Take a look at pyhcl, which is a parser for HCL (HashiCorp Configuration Language):

This module is intended to be used in mostly the same way that one would use the json module in python, and load/loads/dumps are implemented.

import hcl

with open('file.hcl', 'r') as fp:
    obj = hcl.load(fp)

EDIT: From the project GitHub page:

pyhcl does not support HCL2 (which is what modern terraform uses). You might try https://pypi.org/project/python-hcl2/ instead (though I've never personally tried it).

So if this is your case, check the python-hcl2 project.

Upvotes: 2

EricMM
EricMM

Reputation: 41

I couldn't find any way to edit the .tfvars using python, but since python works with json, I converted the .tfvars file into tfvars.json which is still an allowed format in terraform and used that within my python script instead. I hope this will be helpful to people out there.

Upvotes: 0

Related Questions