Passing Environment Variables to Terraform with RegExp

In a Terraform template, an input variable can be used to set some configuration point for a resource, such as

variable "some_prefix" {
  type = string

resource "google_service_account" "some-sa" {
  account_id   = "${var.some_prefix}-sa"
  display_name = "Some Service Account"

In some scenario the input variable can get its value from an environment variable in the shell where terraform runs. It looks like

export TF_VAR_some_prefix=my-test
terraform plan

This is handy where there is just a few variables. If there are many input variables to be set from environment variables, I thought it’s cool to let sed have a go to reformat shell environment variables to Terraform .tfvars file which terraform can load automatically.

# tested with GNU sed 4.7 in Ubuntu 20.04
# given input
# KEY1=value1
# KEY2="value with space"
# ...
# expected output in tfvars file
# key1 = "value1"
# key2 = "value with space"
# ...
env | sed -r 's|^(.+)="*([^"]+)"*$|\L\1\E = "\2"|g' | terraform fmt > terraform.tfvars
# note:
# this only considers double quotes
# \L starts the transformation to lower case
# \E stops that
# the terraform fmt command is optional, just to make the .tfvars file linted with nice indentations