Wednesday, May 10, 2017

Azure Automation Runbooks: Who ran me?

One of the interesting challenges with Azure automation is enforcing security throughout the runbook process.  As I have mentioned in previous posts, permissions within the system are not super granular and automation jobs execute in a service account context.

It turns out there is a way to at determine who actually executed a particular runbook.  You could use this identity in authorization/authentication decisions within the runbook as required.  It is important to note that this is a string reference to the email address of the person running the runbook.  This is set by the system, so trust it if you wish!

The first part is to get the job id of the currently running job.  You can accomplish this by looking at the $PSPrivateMetadata object which contains a JobId.  For example,

$jobId = $PSPrivateMetadata.JobId.Guid

The second part is using this job ID and the Get-AzureRMAutomationJob cmdlet to determine who ran the runbook.  For example,

$job = Get-AzureRmAutomationJob -Id $jobId -ResourceGroupName "resourceGroup" -AutomationAccountName "automationAccount"

Keep in mind that you do need to log in to Azure to run the above command.  After this, the output looks like this:

As you can see, there is a StartedBy property that contains my email address.  You can now use that string to make decisions in your automation runbooks.

One interesting thing to note is that "StartBy" appears blank when you use the "Test Draft In Azure" functionality of the Automation Authoring Toolkit.

1 comment: