如何在Terraform文件中为Azure DevOps / VSTS引用变量

时间:2019-01-18 02:38:57

标签: azure-devops terraform terraform-provider-azure

我创建了一个简单的管道。带有Azure DevOps Build 管道的Github存储库。

我已经在Github私有存储库中的ax.tf文件中定义了以下变量:

ARM_CLIENT_ID
ARM_CLIENT_SECRET
ARM_SUBSCRIPTION_ID
ARM_TENANT_ID

构建管道具有一个简单的命令行作业,如下所示:

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

我想知道如何在Terraform ax.tf文件中引用这些Build变量?

根据Azure DevOps文档,我已经完成了以下操作,但是它不起作用:

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

不幸的是,它无法按预期运行,并停止在以下执行级别:

[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

任何帮助将不胜感激。

谢谢。

2 个答案:

答案 0 :(得分:1)

对于每个Terraform documentation,您必须创建名为TF_VAR_x的环境变量,以便Terraform自动拾取它们。因此,在您的构建定义中,创建一个名为TF_VAR_ARM_SUBSCRIPTION_ID的变量。非秘密的构建变量会自动转换为环境变量。

另一种选择是通过在命令行上指定-var 'ARM_SUBSCRIPTIONID=$(ARM_SUBSCRIPTION_ID)'将变量值传递到Terraform脚本中

答案 1 :(得分:0)

我所做的是我有一个 terraform.tfvars 文件,其中的值引用了 Azure DevOps 变量,例如

tenant              = "${tenantId}"
environment         = "${environmentName}"
location            = "${resourceLocation}"
resource_group_name = "${resourceGroup}"

然后是一个 Replace Tokens 任务来替换此文件中的 AzDo 变量,该任务由 TF 自动选取(我将语法从 __ 更改为 ${},我更喜欢这样)