phydeauxman
phydeauxman

Reputation: 1722

Pass value into Terraform variable of type object from the CLI

I have a variable declared in my variables.tf file that looks like the below:

variable "linux_jb_0" {
    description = "Linux jump box settings"
    type = object(
        {
            vm_size  = string
            adm_acct = string
        }
    )
    default = {
            vm_size  = "Standard_A1"
            adm_acct = null
    } 
}

I am trying to determine how to pass in a value to the adm_acct property of this variable from the command line. I have tried the below but it does not work:

terraform apply -var "linux_jb_0={"adm_acct":$account","vm_size":"Standard_A1"}"

This command tells me Variables not allowed. Are variables truly not allowed to be used in this scenario or do I have the syntax incorrect?

Upvotes: 7

Views: 6975

Answers (5)

John Heyer
John Heyer

Reputation: 921

FWIW I'm using Terraform 1.3.4 on a Mac and this works fine:

terraform plan -var 'healthcheck={protocol="http", port=8000, regional=true}'

So key takeaway is only worry about double quotes if the variable or attribute is type=string.

Upvotes: 0

Philippe Carpentier
Philippe Carpentier

Reputation: 171

I know it is quite long after the question, but I've use the following input for object on windows, and it works. We never know if it can help someone else :

terraform plan -var 'environment_ids={application="""my_app""", scope="""my_scope""", region="""my_region"""}'

Upvotes: 0

Ben Whaley
Ben Whaley

Reputation: 34426

This syntax worked with Terraform v1.0.0:

terraform apply -var "linux_jb_0={\"adm_acct\"=\"$account\",\"vm_size\"=\"Standard_A1\"}"

Confirmed that this syntax works going back to Terraform v0.12.31.

Upvotes: 10

Martin Zeitler
Martin Zeitler

Reputation: 76807

Just run terraform plan & terraform apply without the -var and make the shell script export whatever environmental variables terraform may need; for example export ADM_ACCT=somevalue. These can then again be accessed with ${var.ADM_ACCT}'... if required, some helper script can prepare the script to parse (eg. from JSON input), as these exports will always be setup for the shell that runs them, which likely might not be the same shell.

Upvotes: 0

marcincuber
marcincuber

Reputation: 3791

Update answer:

The following should do the trick with escaped double quotes around variable:

terraform apply -var="linux_jb_0={"adm_acct":"\"${account}\"","vm_size":"Standard_A1"}"

Upvotes: 0

Related Questions