Automate the population of runbook content in Azure Automation with Terraform

Automate the population of runbook content in Azure Automation with Terraform

Introduction

In Azure Automation you can publish runbooks that contains code that you run either manually or on a schedule. You can do a lot of things with this and one thing you can do is deploy & schedule Powershell code.

Me being a fan of Powershell, using it daily when I did a lot of windows server and specifically active directory administration, really appreciate the tool still to this day.

Even though I write more declarative code these days I sometimes want to use Powershell with Azure Automation for some "housekeeping".

When reading the documentation I found the content propery to be very interesting, it seemed like I could import whatever code-snippet I had by populating this property with the information of my Powershell script.

Using the content property

It is pretty easy doing this using the file() function with Terraform. I simply call the function and specify the location of my powershell file

content = file("~/GitHub/lindbergtech-runbook-terraform/src/Get-DevResourceGroups.ps1")

In this case I have a powershell script called Get-DevResourceGroups.ps1 which will list any resource-group in the environment that contains any tags with "dev" in the name.

$resourceGroups = Get-AzResourceGroup

$resourceGroups | Where-Object {$PSItem.TagsTable -like "*dev*"} |
                  Select-Object -Property ResourceGroupName,Tags,Location |
                  Export-Csv -Path ".\devRGs-$(Get-Date -Format d)"

You could take the output CSV from this and send it perhaps to a storage account or send it as an attachment in an email.

The entire resource definition in terraform

resource "azurerm_automation_runbook" "aa-runbook" {
  name = "aa-runbook-dev-weu-001"
  resource_group_name = azurerm_resource_group.rg-automation.name
  location = azurerm_resource_group.rg-automation.location

  content = file("~/GitHub/lindbergtech-runbook-terraform/src/Get-DevResourceGroups.ps1")
  
  tags = {
    "deployedBy" = "terraform"
    "env"        = "dev"
    "workload"   = "lindbergtech-articles"
  }
}

References

file - Functions - Configuration Language | Terraform | HashiCorp Developer
The file function reads the contents of the file at the given path andreturns them as a string.

About the author

About me
If you have landed on my page you will have already understood my passion for tech, but obviously there is more to life than that. Here I will try and outline a few of my other hobbies. Strength training I am a person who loves to move around and challenge