Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference a variable in Terraform file for Azure DevOps/VSTS

I have created a simple pipeline. A Github repo with Azure DevOps Build pipeline.

I have defined the below mentioned variables in ax.tf file which is in Github private repository:

ARM_CLIENT_ID
ARM_CLIENT_SECRET
ARM_SUBSCRIPTION_ID
ARM_TENANT_ID

Build pipeline has a simple Command line Job which is as below:

sudo apt install wget

wget https://releases.hashicorp.com/terraform/0.11.11/terraform_0.11.11_linux_amd64.zip

sudo apt-get install unzip

unzip terraform_0.11.11_linux_amd64.zip

terraform init

terraform plan -var-file=terraform.tfvars -out=ax.plan

terraform apply ax.plan

terraform destroy -auto-approve

I want to know how to reference these Build variables in Terraform ax.tf file?

I have done something like below as per Azure DevOps documentation but it is not working:

variable "ARM_SUBSCRIPTION_ID" {
    default="$(Build.ARM_SUBSCRIPTION_ID)"
}

Unfortunately, it's not working as expected and it stops at the below execution level:

[0m[1m[32mTerraform has been successfully initialized![0m[32m[0m
[0m[32m
You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.
If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.[0m
[0m[1mvar.ARM_CLIENT_ID[0m

Any help would be greatly appreciated.

Thank you.

like image 974
learner Avatar asked Jan 18 '19 02:01

learner


People also ask

Can you reference environment variables in Terraform?

Terraform can directly access environment variables that are named using the pattern TF_VAR_ , for example TF_VAR_foo=bar will provide the value bar to the variable declared using variable "foo" {} .

How do I use VAR in Terraform?

All files in your Terraform directory using the . tf file format will be automatically loaded during operations. Create a variables file, for example, variables.tf and open the file for edit. Add the below variable declarations to the variables file.


1 Answers

Per the Terraform documentation, you have to create environment variables named TF_VAR_x for Terraform to automatically pick them up. So in your build definition, create a variable named TF_VAR_ARM_SUBSCRIPTION_ID. Non-secret build variables are automatically turned into environment variables.

The other option is to pass the variable value in to the Terraform script by specifying -var 'ARM_SUBSCRIPTIONID=$(ARM_SUBSCRIPTION_ID)' on the command line

like image 177
Daniel Mann Avatar answered Oct 07 '22 12:10

Daniel Mann