Search code examples
azureazure-devopsyamlazure-pipelinesazure-pipelines-yaml

how do I do an azcli task with an spn?


Ive got a devops pipeline and im trying to use the azcli task to look at blobs but I dont thin k its logging in successfully, im trying to log in with a service principal but I dont think its working. Any ideas whats wrong?

- task: AzureCLI@2
  inputs:
    azureSubScription:'$(subName)'
    scriptType: 'bash'
    scriptLocation: 'inlineScript'
    inlineScript: |
      az login --service-principal -u $servicePrincipalId -p $servicePrincipalKey --tenant $tenantId
      if [ $? -eq 0]; then
        echo 'Azure login success'
      else
        echo 'Azure login failure'
        exit $?
      fi
      az storage blob list --account-name $(accountName) --container-name $(containerName)
    addSpnToEnvironment: true

I know that the cli task should login automatically I added the login and the if as a way of checking what was going on and it now saysazure login failure all the time which explains why I keep on getting no results from the storage blob list in the logs. Above the login failed output in the logs it says "/home/vsts/work/_temp/azureclitasksript1704664334724.sh: line 2: [:missing `]' Any idea what this means?


Solution

  • Based on the error message,

    line 2: [:missing `]'

    The line 2 (if [ $? -eq 0]; then) in your bash script has a syntax error. you need to correct this line by add a whitespace after the condition like as below:

    if [ $? -eq 0 ]; then
    

    When using if statement in bash script, the correct syntax should look like below.

    if [ condition ]
    

    You need to ensure the whitespaces exist before and after the condition between the brackets ([ ]). If you miss any of the whitespaces between the brackets, bash will report an error about a "missing ]" just like as the one you get.

    For example, the following will not work and report the error:

    if [$x==0]
    
    if [ $x==0]
    
    if [$x==0 ]