Home > Software engineering >  Is there any way to use a variable for a service connection to azure?
Is there any way to use a variable for a service connection to azure?

Time:06-29

I have been writing some terraform and using Azure Devops to deploy the pipeline. However if I use a variable $(serviceconnection) for the service connection it fails with the following error:

There was a resource authorization issue: "The pipeline is not valid. Job DeployDev: Step TerraformCLI1 input backendServiceArm references service connection $(serviceconnection) which could not be found. The service connection does not exist or has not been authorized for use. I Have tried authorising it but no luck. Is there any workaround?

The task is a YAML task to use terraform as below :

- task: charleszipp.azure-pipelines-tasks-terraform.azure-pipelines-tasks-terraform-cli.TerraformCLI@0
   displayName: 'Terraform Init'
   inputs:
     command: init
     workingDirectory: $(Agent.BuildDirectory)/a/azuredirectory/terraform
     backendType: azurerm
     backendServiceArm: $(serviceconnection)
     backendAzureRmResourceGroupName: $(ResourceGroupName)
     backendAzureRmStorageAccountName: $(StorageAccountName)
     backendAzureRmContainerName: $(ContainerName)
     backendAzureRmKey: $(AzureRmKey)

CodePudding user response:

If you want to use runtime variable like $(serviceconnection), it is not support now.

You can use ${{ variables.serviceconnection }} as Thomas recommended. But this practice means that you have to specify variables in advance(Before you run the pipeline).

For service connections, you can specify a value directly or use the ’compile-time variable‘ ${{xxx}}, which will expand and then populate the service connection section with values before running. In this usage of $(xxx), the service connection of the task cannot be obtained, because this is a runtime value.

The service connection needs to be specified before running. The changes (runtime changes) of the variables during the pipeline run will not be acquired by the service connection part of the subsequent task.

You are using a runtime variable.

But run time variables aren't supported for service connection OR azure subscription. The variable will get initialized at the run time.

enter image description here

CodePudding user response:

You need to use a Template expression syntax for the service connection variable:

backendServiceArm: ${{ variables.serviceconnection }}

I imagine it's because the service connection needs to be known before the pipeline runs.

Sample use case. Using a variable file called variable.dev.yaml:

variables:
  serviceconnection: my-dev-service-connection-name
...

You could then reference that in your pipeline:

jobs:
- job: myJob
  ...
  variables:
  - template: ./variable.dev.yaml
  steps:
  - task: AzureCLI@2
    inputs:
      azureSubscription: ${{ variables.serviceconnection  }}
...
  • Related