bashazure-pipelinesazure-cliazure-pipelines-release-pipeline

Azure Devops - How to pass database connection string as environment variable dynamically (azure cli)


Currently I'm using azure devops to deploy an app container to azure.

I've created my release pipeline and added each ENVIRONMENT VARIABLE within variable group.

In order to call the Environment variables dynamically, used below CLI commands in Azure CLI task

#!/bin/bash

# Initialize variable
ENV_VARS=""

# Loop through all environment variables
while IFS= read -r var
do
  # Check if the variable contains __ and starts with specific prefixes
  if [[ "$var" == APPSETTINGS__* || "$var" == AWSS3CONFIG__* || "$var" == CONNECTIONSTRINGS__* || "$var" == SMTPSETTINGS__* ]]; then
    # Extract the variable name and value
    name=$(echo "$var" | cut -d '=' -f 1 | sed 's/^//')
    value=$(echo "$var" | cut -d '=' -f 2-)

    if [[ "$value" == *" "* ]]; then
      value="\"$value\""
    fi

    # Append the variable and its value to the result
    ENV_VARS+="$name=$value "
  fi
done <<< "$(env)"

echo "Constructed envVars: $ENV_VARS"

# Example command using constructed envVars
az containerapp update \
            --name api-dev \
            --resource-group resource-group \
            --image dev.azurecr.io/api:$(Build.BuildId) \
            --set-env-vars "$ENV_VARS"

But, database connection string not set correctly and due to white space it consider as new key. e.g. User Id and Persist security info.

enter image description here

How to escape white space? Please help!

I've tried setting up value as double quote for variable stored in variable group and also directly in script too, but none of them work


Solution

  • You can pass environment variables in 3 ways..