我正在通过 Azure DevOps 设置 CI/CD 管道来测试我的 Terraform 代码,我的组织正计划将我们的基础设施切换到 CI/CD。 我正在尝试通过 YAML 管道中的服务连接验证 Azure 租户中的 Terraform:
name: Azure Infrastructure CI/CD
trigger:
branches:
include:
- main
pool:
vmImage: ubuntu-latest
variables:
- name: public_key
value: $(public_key)
- name: terraformSecret
value: $(client_secret)
steps:
- checkout: self
submodules: true
- task: TerraformInstaller@0
inputs:
terraformVersion: 'latest'
- script: az login --service-principal -u "$(client_id)" -p $(client_secret) --tenant "$(tenant_id)"
displayName: 'Azure CLI Login'
- script: az account set --subscription "$(subscription_id)"
displayName: 'Azure Subscription Set'
- script: |
terraform init
terraform plan -out=tfplan \
-var="public_key=${public_key}" \
-var="client_secret=${terraformSecret}"
displayName: 'Terraform Init and Plan'
workingDirectory: .
- script: |
terraform apply -auto-approve tfplan
displayName: 'Terraform Apply'
workingDirectory: .
这是我的 Terraform 提供程序文件:
provider "azurerm" {
features {}
client_id = "xxxxx"
client_secret = var.client_secret
tenant_id = "xxxxx"
subscription_id = "xxxxx"
}
以及我的变量 Terraform 变量文件的摘录:
variable "client_secret" {
type = string
}
我已在 Azure DevOps 的管道上正确设置所有环境变量。 我收到此错误:
Planning failed. Terraform encountered an error while generating this plan.
╷
│ Error: building AzureRM Client: Authenticating using the Azure CLI is only supported as a User (not a Service Principal).
│
│ To authenticate to Azure using a Service Principal, you can use the separate 'Authenticate using a Service Principal'
│ auth method - instructions for which can be found here: https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/guides/service_principal_client_secret
│
│ Alternatively you can authenticate using the Azure CLI by using a User Account.
│
│ with provider["registry.terraform.io/hashicorp/azurerm"],
│ on providers.tf line 10, in provider "azurerm":
│ 10: provider "azurerm" {
│
╵
##[error]Bash exited with code '1'.
我已经检查了 Terraform 文档,它们没有显示如何通过脚本对 terraform 连接进行身份验证,并且我想尽可能保护客户端秘密,而不是让每个访问此代码的人都可以使用它。我还使用过很多法学硕士,与大多数与 terraform 相关的项目一样,这些见解的帮助微乎其微。
如何通过 YAML 管道上的服务主体验证我的 terraform 代码?
根据在 Terraform 中配置服务主体,您可以使用环境变量向 azurerm 提供程序进行身份验证:
export ARM_CLIENT_ID="00000000-0000-0000-0000-000000000000"
export ARM_CLIENT_SECRET="12345678-0000-0000-0000-000000000000"
export ARM_TENANT_ID="10000000-0000-0000-0000-000000000000"
export ARM_SUBSCRIPTION_ID="20000000-0000-0000-0000-000000000000"
在 Azure 管道中,您可以在任务级别为运行 terraform 命令(例如
init
、plan
和 apply
)的所有任务设置这些环境变量 - 示例:
- script: |
terraform ...
displayName: 'Run Terraform command'
workingDirectory: .
env:
ARM_CLIENT_ID: $(my_client_id)
ARM_CLIENT_SECRET: $(my_client_secret)
ARM_SUBSCRIPTION_ID: $(my_subscription_id)
ARM_TENANT_ID: $(my_tenant_id)