Search code examples
variablesazure-devopsazure-pipelines

Access azure variables secrets from variable groups in library using cli in pipeline


Can I access the variables set as Secret using Azure CLI or any script in the pipeline?

I have to update the variables but those are set as secrets are not updating but the command setting them null So, my question is can we do this? if yes then how? Note: I don't want to link the variables with Azure key vault

I was trying to update the variables groups using the update command but it not updating the variable values which set as secret instead making them null:

Executing:

az pipelines variable-group variable update \
  --group-id 261 \
  --name <groupname> \
  --value <value> \
  --organization <orgURL> \
  --project "Test"

Output:

{
  "Variable": {
    "isSecret": true,
    "value": null
  }
}

Solution

  • The az pipelines variable-group variable update command will update the secret variable, but its value won't be displayed for security reasons - remember that is sensitive information that shouldn't be displayed in a console or pipeline logs.

    Regarding Azure DevOps CLI authentication, see Sign in with a personal access token (PAT).

    Example pipeline

    Consider the following pipeline with 2 jobs:

    • job1 updates the value of variable foo from variable group group1 (ID=14)
    • job2 references variable group group1 and displays the value of variable foo
    trigger: none
    
    pool:
      vmImage: 'ubuntu-latest'
    
    jobs:
      - job: job1
        steps:
        - checkout: none
        - bash: |
            az pipelines variable-group variable update \
              --group-id 14 \
              --name foo \
              --value 'updated value' \
              --organization 'https://dev.azure.com/myorg/' \
              --project 'myproject'
          displayName: 'Update variable'
          env:
            AZURE_DEVOPS_EXT_PAT: $(System.AccessToken) # ensure token has enough permissions to run the command
    
      - job: job2
        dependsOn: job1
        variables:
          - group: 'group1'
        steps:
        - checkout: none
    
        # See https://stackoverflow.com/a/71746562/558486
        # For debugging purposes only, do NOT use it in production
        - bash: |
            echo "MY_SECRET: ${MY_SECRET:0:1} ${MY_SECRET:1:100}"
          displayName: 'Display variable'
          env:
            MY_SECRET: $(foo)
    

    Output of task in job1:

    Updating the variable - logs

    Output of task in job2:

    Displaying the variable - logs