-2

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"
}

and potentially / partially overwritten in terraform.tfvars file

location                 = "westeurope"

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

output "resource_group" {
  value = var.resource_group
}

output "location" {
  value = var.location
}

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

1
  • 1
    You might consider using JSON instead of HCL to write your configurations. They'll be more verbose, but there are more tools to manipulate JSON.
    – chepner
    Dec 7, 2022 at 1:08

1 Answer 1

1

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)"')

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/')

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/')

Then these variables are available in bash script:

LOCATION="westeurope"
RESOURCE_GROUP="my-rg"

and can be addressed as $LOCATION and $RESOURCE_GROUP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.