ADO 中具有自代理主机 Linux 的 Terraform - 服务主体变量问题

问题描述 投票:0回答:1

我使用 Az Cli 登录与 addSpnToEnvironment。这应该填充 ARM_* 变量

基本上,我放置的所有向我显示值的回声实际上什么也没有显示。 我有一个 Linux Ubuntu 作为自我主机代理。

trigger:
  branches:
    include:
      - main  # Trigger the pipeline on any changes to the 'main' branch

pr:
  branches:
    include:
      - main  # Enable the pipeline to run for pull requests targeting the 'main' branch

parameters:
  - name: environment  # Define a parameter for the environment (dev, sit, prod)
    displayName: "Select Environment"
    type: string
    default: dev  # Default environment is set to 'dev'
    values:
      - dev
      - sit
      - prod

jobs:
- job: terraform_deploy
  displayName: "Deploy Infrastructure using Terraform"  # The job name and description

  pool: teste
  

  steps:
    - checkout: self  # Checkout the repository containing the Terraform code

    - task: UseDotNet@2  # Ensure .NET SDK is installed, required for running some scripts
      inputs:
        packageType: 'sdk'
        version: '6.x'  # Use .NET 6.x
        installationPath: $(Agent.ToolsDirectory)/dotnet

    # Install Azure CLI
    - task: Bash@3
      displayName: "Install Azure CLI"
      inputs:
        targetType: 'inline'
        script: |
          sudo apt-get update
          sudo apt-get install -y ca-certificates curl apt-transport-https lsb-release gnupg
          curl -sL https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor | sudo tee /etc/apt/trusted.gpg.d/microsoft.asc.gpg > /dev/null
          AZ_REPO=$(lsb_release -cs)
          echo "deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ $AZ_REPO main" | sudo tee /etc/apt/sources.list.d/azure-cli.list
          sudo apt-get update
          sudo apt-get install -y azure-cli

    # Then proceed with Terraform steps


    # Install Terraform CLI on the agent if it is not already installed
    - task: Bash@3
      displayName: "Install Terraform"
      inputs:
        targetType: 'inline'
        script: |
          sudo apt-get update && sudo apt-get install -y gnupg software-properties-common
          wget -O- https://apt.releases.hashicorp.com/gpg | gpg --dearmor | sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg
          echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
          sudo apt-get update && sudo apt-get install terraform

    # Login to Azure CLI using a Service Connection
    - task: AzureCLI@2
      displayName: 'Azure CLI login'
      inputs:
        azureSubscription: 'Azure ARM Connection'
        scriptType: 'bash'
        addSpnToEnvironment: true
        scriptLocation: 'inlineScript'
        inlineScript: |
          echo "Successfully logged into Azure CLI"

    # Test if Env Variables are okay
    - task: Bash@3
      displayName: "Check Environment Variables"
      inputs:
        targetType: 'inline'
        script: |
          echo "ARM_CLIENT_ID: $ARM_CLIENT_ID"
          echo "ARM_CLIENT_SECRET: $ARM_CLIENT_SECRET"
          echo "ARM_TENANT_ID: $ARM_TENANT_ID"
          echo "ARM_SUBSCRIPTION_ID: $ARM_SUBSCRIPTION_ID"

    # Initialize Terraform with the correct backend configuration for the environment
    - task: Bash@3
      displayName: "Terraform Init"
      env:
        ARM_CLIENT_ID: $(servicePrincipalId)
        ARM_CLIENT_SECRET: $(servicePrincipalKey)
        ARM_TENANT_ID: $(tenantId)
        ARM_SUBSCRIPTION_ID: $(subscriptionId)
      inputs:
        targetType: 'inline'
        script: |
          echo "ARM_CLIENT_ID: $ARM_CLIENT_ID"
          echo "ARM_CLIENT_SECRET: $ARM_CLIENT_SECRET"
          echo "ARM_TENANT_ID: $ARM_TENANT_ID"
          echo "ARM_SUBSCRIPTION_ID: $ARM_SUBSCRIPTION_ID"
          export TF_LOG=DEBUG
          cd project/terraform
          terraform init -backend-config="backend-config-${{ parameters.environment }}.tfvars"
    # Run 'terraform plan' to generate and display the changes Terraform will make
    - task: Bash@3
      displayName: "Terraform Plan"
      inputs:
        targetType: 'inline'
        script: |
          cd project/terraform
          export TF_LOG=DEBUG
          terraform plan -var-file="${{ parameters.environment }}.tfvars"

    # Run Terraform Apply only for dev and sit environments
    - task: Bash@3
      displayName: "Terraform Apply"
      condition: or(eq('${{ parameters.environment }}', 'dev'), eq('${{ parameters.environment }}', 'sit'))
      inputs:
        targetType: 'inline'
        script: |
          cd project/terraform
          export TF_LOG=DEBUG
          terraform apply -auto-approve -var-file="${{ parameters.environment }}.tfvars"

    # Publish Terraform state file as an artifact if the apply fails
    - publish: terraform/errored.tfstate
      artifact: terraform_state
      condition: failed()  # Only publish the state if the job fails

    # Optionally, send a success or failure notification (custom script)
    - task: Bash@3
      displayName: "Send Notification"
      inputs:
        targetType: 'inline'
        script: |
          echo "Deployment of environment ${{ parameters.environment }} completed."

# Separate job to handle production manually
- job: terraform_apply_prod
  displayName: "Manual Apply for Production"
  dependsOn: terraform_deploy
  condition: eq('${{ parameters.environment }}', 'prod')  # Only runs if 'prod' environment is selected
  pool: teste

  steps:
    # Manual apply for production after approval in the Azure DevOps UI
    - task: AzureCLI@2
      displayName: "Azure Login"
      inputs:
        azureSubscription: "Azure ARM Connection"  # Specify your ARM service connection here
        scriptType: bash
        scriptLocation: inlineScript
        inlineScript: |
          echo "Successfully logged into Azure"

    - task: Bash@3
      displayName: "Terraform Apply for Production"
      inputs:
        targetType: 'inline'
        script: |
          cd project/terraform
          terraform apply -auto-approve -var-file="prod.tfvars"

我的结果:

Pool: teste
Queued: Today at 17:21 [manage parallel jobs]
Agent: vm-shared-agent-1 <---- This is my Self Ho
Started: Just now

Starting: Azure CLI login
/usr/bin/az login --service-principal -u *** --password=*** --tenant xxxxxx --allow-no-subscriptions
[
  {
    "cloudName": "AzureCloud",
    "homeTenantId": "xxxxx",
    "id": "xxxx",
    "isDefault": true,
    "managedByTenants": [],
    "name": "xxxxx",
    "state": "Enabled",
    "tenantId": "xxxxx",
    "user": {
      "name": "***",
      "type": "servicePrincipal"
    }
  
Starting: Check Environment Variables
/usr/bin/bash /home/azureuser/myagent/_work/_temp/fb642037-7131-46f9-9676-a2e7b9af9531.sh
ARM_CLIENT_ID: 
ARM_CLIENT_SECRET: 
ARM_TENANT_ID: 
ARM_SUBSCRIPTION_ID: 

Finishing: Check Environment Variables
**(See ? no variables !!!)**

Terraform Init

ARM_CLIENT_ID: 
ARM_CLIENT_SECRET: 
ARM_TENANT_ID: 
ARM_SUBSCRIPTION_ID: 

**(See ? No vartiables !!!)**

Initializing the backend...
Initializing modules...
2024-10-18T16:26:54.335Z [DEBUG] Module installer: begin acr
2024-10-18T16:26:54.336Z [DEBUG] Module installer: begin acr_monitoring
2024-10-18T16:26:54.336Z [DEBUG] Module installer: begin aks
2024-10-18T16:26:54.337Z [DEBUG] Module installer: begin aks_monitoring
2024-10-18T16:26:54.337Z [DEBUG] Module installer: begin snet
2024-10-18T16:26:54.337Z [DEBUG] Module installer: begin vnet
╷
│ Error: Error building ARM Config: obtain subscription() from Azure CLI: parsing json result from the Azure CLI: waiting for the Azure CLI: exit status 1: ERROR: Please run 'az login' to setup account.


并且失败了。有什么帮助吗?这真让我抓狂。我尝试过的其他方法:

- task: Bash@3
  displayName: "Terraform Init"
  env:
    ARM_CLIENT_ID: $(servicePrincipalId)     
    ARM_CLIENT_SECRET: $(servicePrincipalKey)
    ARM_TENANT_ID: $(tenantId)               
    ARM_SUBSCRIPTION_ID: $(subscriptionId)   

根据文档,这些变量是内置的......但这也不能解决任何问题......

azure-devops terraform-provider-azure azure-devops-self-hosted-agent
1个回答
0
投票

该错误是由于您的

Azure CLI login
任务中未设置 terraform 环境变量。

在任务中使用

addSpnToEnvironment: true
,它会将您选择的 Azure 端点的服务主体 id、服务主体密钥和租户 id 添加到脚本的执行环境中,但它们是变量
$(servicePrincipalId)
不是 terraform 变量
$ARM_CLIENT_ID 
。您需要使用登录命令
##vso[task.setvariable variable=ARM_...
映射变量,如下所示,然后设置terraform变量。

variables:
  - name: ARM_SUBSCRIPTION_ID
    value: $(SubscriptionID)                    #<---- You need to set the subscription id manually

steps:
....

- task: AzureCLI@2
  displayName: 'Azure CLI login'
  inputs:
    azureSubscription: 'Azure ARM Connection'
    scriptType: 'bash'
    scriptLocation: 'inlineScript'
    inlineScript: |
      echo "##vso[task.setvariable variable=ARM_TENANT_ID;]$tenantId"
      echo "##vso[task.setvariable variable=ARM_CLIENT_ID;]$servicePrincipalId"
      echo "##vso[task.setvariable variable=ARM_CLIENT_SECRET;]$servicePrincipalKey"
    addSpnToEnvironment: true

# Test if Env Variables are okay
- task: Bash@3
  displayName: "Check Environment Variables"
  inputs:
    targetType: 'inline'
    script: |
      echo "ARM_CLIENT_ID: $ARM_CLIENT_ID"
      echo "ARM_CLIENT_SECRET: $ARM_CLIENT_SECRET"
      echo "ARM_TENANT_ID: $ARM_TENANT_ID"
      echo "ARM_SUBSCRIPTION_ID: $ARM_SUBSCRIPTION_ID"
© www.soinside.com 2019 - 2024. All rights reserved.