The Ops Community ⚙️

Kai Walter
Kai Walter

Posted on • Updated on

How can I source Terraform HCL variables in bash?

I have Terraform variables defined like

variable "location" {
  type        = string
  default     = "eastus"
  description = "Desired Azure Region"
}

variable "resource_group" {
  type        = string
  default     = "my-rg"
  description = "Desired Azure Resource Group Name"
}
Enter fullscreen mode Exit fullscreen mode

and potentially / partially overwritten in terraform.tfvars file

location                 = "westeurope"
Enter fullscreen mode Exit fullscreen mode

and then defined variables as outputs e.g. a file outputs.tf:

output "resource_group" {
  value = var.resource_group
}

output "location" {
  value = var.location
}
Enter fullscreen mode Exit fullscreen mode

How can I "source" the effective variable values in a bash script to work with these values?

One way is to use Terraform output values as JSON and then an utility like jq to convert and source as variables:

source <(terraform output --json | jq -r 'keys[] as $k | "\($k|ascii_upcase)=\(.[$k] | .value)"')
Enter fullscreen mode Exit fullscreen mode

note that output is only available after executing terraform plan, terraform apply or even a terraform refresh

If jq is not available or not desired, sed can be used to convert Terraform HCL output into variables, even with upper case variable names:

source <(terraform output | sed -r 's/^([a-z_]+)\s+=\s+(.*)$/\U\1=\L\2/')
Enter fullscreen mode Exit fullscreen mode

or using -chdir argument if Terraform templates / modules are in another folder:

source <(terraform -chdir=$TARGET_INFRA_FOLDER output | sed -r 's/^([a-z_]+)\s+=\s+(.*)$/\U\1=\L\2/')
Enter fullscreen mode Exit fullscreen mode

Then these variables are available in bash script:

LOCATION="westeurope"
RESOURCE_GROUP="my-rg"
Enter fullscreen mode Exit fullscreen mode

and can be addressed as $LOCATION and $RESOURCE_GROUP.

also on Stackoverflow

Latest comments (0)