cloud, technology and trends

Variables in Azure Automation

Shared Resources in Azure Automation allow for the reuse of credentials, modules, scheduled, connections, certificates and variables. Variable assets provide a way to share values between multiple runbooks as well as between multiple jobs from the same runbook. In this post, I outline how to reference variables that are encrypted and non-encrypted in an Azure Automation runbook.

A little context always helps understanding. In this case, I need to reference a secure key in my runbook. The simple way to do this would be to reference the key directly in the script by setting a variable like this:

$secureKey = ‘0123456789abcdef==’

This will work, but it has some drawbacks. The first and most obvious is the security implications of keeping the key directly in the code. Anyone with access to the runbook or source files could view the key.

Another drawback is that the key sometimes needs to be regenerated. Once regenerated, the value will need to be updated in every runbook that uses it. This is manageable with a small number of runbooks, but this won’t scale well in larger environments.

These drawbacks can be avoided with the use of an Azure Automation Variable. The key value is referenced, not added to the code. The value can be set in one location and called from multiple runbooks. There is no need to update individual runbooks when the Variable changes.

Non-Encrypted Variables

Variables can be created in the portal by going into the Automation account and select Variable, New Variable. The following commands can be used to create the asset and update the value. Reference Microsoft’s complete documentation here.

This can be set and retrieved in PowerShell by logging into Azure with an account that has rights to the Automation Account.

Encrypted Variables

That’s all fine and good, but what if you want to encrypt the variable? Encrypted variables are secured by a unique key generated for each Automation Account. There are a couple rules with encrypted variables to keep in mind:

Once an encrypted variable has been saved, it cannot be viewed in the portal, only updated.

You cannot retrieve the value of an encrypted variable with the Get-AzureRmAutomationVariable. The Get-AutomationVariable command is used to retrieve the encrypted variable instead.

The Get-AutomationVariable command won’t work in PowerShell, only in a runbook job.

So, you can only retrieve the value of an encrypted variable with the Get-AutomationVariable command when the runbook runs. Here is how to see this work:

First, I’ll set a new encrypted variable. This is done the same as an unencrypted variable, only change the -Encrypted property to $true: