Global Variables

Global Variables enable you to share data between automation task steps at runtime. This powerful feature allows later steps to use output from earlier steps, creating dynamic and flexible workflows in AZExecute.


What are Global Variables?

Global Variables are key-value pairs that are created and stored during task execution. Each task run has its own set of variables that are securely encrypted and stored in the database. Steps can create variables by writing to the output stream, and later steps can reference these variables using a special syntax.

Variables are scoped to a single task execution. They are created when the task starts and are automatically cleaned up after the task completes.

Global Variables Concept

Creating Variables from Scripts

PowerShell scripts can create global variables by writing specially formatted output to the console. The format is:

##vso[task.setvariable variable=VariableName]VariableValue

Example PowerShell Script:

# Get the current server name
$serverName = $env:COMPUTERNAME

# Set it as a global variable
Write-Host "##vso[task.setvariable variable=ServerName]$serverName"

# Query database and store connection string
$connectionString = "Server=sql.example.com;Database=MyDB"
Write-Host "##vso[task.setvariable variable=DbConnection]$connectionString"

# Calculate and store a result
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Write-Host "##vso[task.setvariable variable=ExecutionTime]$timestamp"

Variable names are case-sensitive. "ServerName" and "servername" are different variables.


Referencing Variables in Later Steps

Once a variable is created by a step, subsequent steps can reference it using the double-curly-brace syntax:

{{"{{"}}VariableName{{"}}"}}


In Script Parameters:

When configuring a PowerShell Script step, you can use variable references in parameter values:

Variable Reference in Parameters
# This script receives the ServerName variable from a previous step
param(
    [string]$ServerName,
    [string]$DbConnection
)

Write-Host "Connecting to server: $ServerName"
Write-Host "Using connection: $DbConnection"

In Runbook Parameters:

Azure Automation Runbook steps also support variable references in their parameters:

Variable Reference in Runbook Parameters

In Custom Parameters:

Custom parameters can also reference global variables. This allows you to use output from scripts as default values or in expressions.


Variable Lifecycle

Understanding the lifecycle of global variables is important for building reliable automation tasks:

1. Task Execution Starts:

A new variable collection is created for this specific task run. This collection is empty at the start.

2. Steps Execute:

As each step runs, it can create new variables or update existing ones. Variables are immediately available to subsequent steps.

3. Variable Storage:

All variable values are encrypted using AES-256 encryption before being stored in the database. This ensures sensitive data like credentials or connection strings remain secure.

4. Task Completion:

After the task completes (successfully or with errors), the variables remain stored with the execution history. You can view variable values in the execution details.

5. Cleanup:

Variables are automatically cleaned up when execution history is purged according to your retention policies.

Variable Lifecycle

Parallel Execution Considerations

When using parallel step execution, be aware of variable timing:

Important: Steps running in parallel cannot reliably access variables created by other parallel steps, as there's no guarantee of execution order.

Best Practice:

• Create all necessary variables in sequential steps before parallel execution

• Use parallel steps only for independent operations that don't need to share data

• If parallel steps need to share data, make them sequential or use a subsequent step to consolidate results

Parallel Execution Variables

Viewing Variables in Execution History

After a task executes, you can view all variables created during the run in the execution history:

1. Navigate to the History tab of your automation task

2. Expand a specific task run to view details

3. Look for the Variables section showing all variables and their values

4. Each variable shows which step created it

View Variables in Execution History

Variables are decrypted only when viewed by authorized users. They remain encrypted at rest in the database.


Common Use Cases

1. Certificate Installation Workflow

Step 1 retrieves a certificate thumbprint, Step 2 uses it to bind the certificate to IIS:

# Step 1: Get certificate thumbprint
$cert = Get-ChildItem -Path Cert:\LocalMachine\My | 
    Where-Object { $_.Subject -like "*example.com*" } | 
    Select-Object -First 1

Write-Host "##vso[task.setvariable variable=CertThumbprint]$($cert.Thumbprint)"

# Step 2: Bind certificate to IIS (uses {{"{{"}}CertThumbprint{{"}}"}} in parameters)
param([string]$Thumbprint)
Import-Module WebAdministration
New-WebBinding -Name "Default Web Site" -Protocol https -Port 443
$binding = Get-WebBinding -Name "Default Web Site" -Protocol https
$binding.AddSslCertificate($Thumbprint, "My")

2. Dynamic Resource Provisioning

Step 1 creates an Azure resource, Step 2 configures it using the resource ID:

# Step 1: Create storage account
$storageAccount = New-AzStorageAccount -ResourceGroupName "MyRG" `
    -Name "mystorage" -Location "EastUS" -SkuName Standard_LRS

Write-Host "##vso[task.setvariable variable=StorageAccountId]$($storageAccount.Id)"
Write-Host "##vso[task.setvariable variable=StorageAccountKey]$($storageAccount.Context.ConnectionString)"

# Step 2: Configure application with storage (uses variables in parameters)
param([string]$StorageKey)
Set-Content -Path "C:\App\config.json" -Value "{\`"StorageConnection\`":\`"$StorageKey\`"}"

3. Multi-Stage Deployment

Pass deployment identifiers between stages:

# Step 1: Generate unique deployment ID
$deploymentId = "deploy-" + (Get-Date -Format "yyyyMMdd-HHmmss")
Write-Host "##vso[task.setvariable variable=DeploymentId]$deploymentId"

# Step 2: Tag resources with deployment ID (uses {{"{{"}}DeploymentId{{"}}"}} in parameters)
# Step 3: Trigger DevOps pipeline with deployment ID (uses {{"{{"}}DeploymentId{{"}}"}} in pipeline parameters)

Best Practices

Use Descriptive Variable Names:

Choose clear, descriptive names like "CertificateThumbprint" instead of "Cert1" or "Value1". This makes your automation tasks easier to understand and maintain.

Document Variable Dependencies:

In step descriptions or task documentation, note which variables each step creates and which it consumes. This helps other operators understand the workflow.

Validate Variable Values:

In scripts that consume variables, add validation to check that values are present and in the expected format. Fail early with clear error messages.

Limit Variable Scope:

Only create variables when they will be used by subsequent steps. Avoid creating unnecessary variables that clutter the execution history.

Secure Sensitive Data:

While variables are encrypted at rest, avoid logging sensitive variable values in your scripts. The encryption protects storage, but logged values may appear in execution output.

Test Variable References:

Always test your automation tasks end-to-end to ensure variable references work correctly. A typo in a variable name will cause step failures.


Troubleshooting Variable Issues

Variable Not Found Error

If a step references a variable that doesn't exist:

• Check that the variable name matches exactly (case-sensitive)

• Verify that the step creating the variable ran successfully before the consuming step

• If using parallel execution, ensure the variable is created in a sequential step first


Variable Value Not As Expected

If a variable contains unexpected data:

• Review the execution history to see the exact variable value that was set

• Check the script logic that creates the variable for errors

• Ensure PowerShell variable expansion is working correctly in your Write-Host statement

Troubleshoot Variables

If you encounter any issues or need further assistance, please contact us at

info@azexecute.com

. Our support team is here to help you.

An unhandled error has occurred. Reload 🗙
An unhandled error has occurred. Reload 🗙