How to write HCL2 from python

Nicolai Antiferov
2 min readJul 5, 2021

--

Technically, the only way now to write HCL2 (Hashicorp Configuration Language) files is to use Golang with hclwrite package, python-hcl2 library is able only to read this format 😢.

However, it’s quite easy to serialize Python dictionary to hcl2 compatible format using json.dump parameters, which could be useful to generate .tfvars file from scripts.

I will take random provider as an example, but this approach could be used in any situation when you need to generate data for terraform automatically (like fetch manually created resources and prepare terraform import).

So, as you can see, we are creating here usual python dictionary and then write it to valid HCL2 with separators=[“,”, “ = “] for json.dump function. NOTE: we have to output first variable name to file.

Output:

$ ./pets-gen.py -c 3
{
"0": {
"length": 3,
"separator": "-"
},
"1": {
"length": 2,
"separator": " or "
},
"2": {
"length": 5,
"separator": "-"
}
}
$ terraform applyTerraform will perform the following actions:# random_pet.this["0"] will be created
+ resource "random_pet" "this" {
+ id = (known after apply)
+ length = 3
+ separator = "-"
}
...Plan: 3 to add, 0 to change, 0 to destroy.Changes to Outputs:
+ pets = [
+ (known after apply),
+ (known after apply),
+ (known after apply),
]
Apply complete! Resources: 3 added, 0 changed, 0 destroyed.Outputs:pets = [
"eagerly-wanted-mammoth",
"informed or guppy",
"formerly-repeatedly-ideally-great-starfish",
]

In general I would say it’s quite hackish, but working way to generate variables data for Terraform. Another option is to use plain JSON, but in this case you lost all advantages, like autoformat with terraform fmt , ability to add comments, etc.

All code from this article is available on GitHub at https://github.com/Nklya/terraform-python-hcl2-example

--

--