How to Manage Azure Resource Groups with Tags, Logic Apps, Automation Account and Runbooks Part — I

Managing Azure Resource Groups with Logic Apps, Automation Account and Powershell Runbooks.

When you create a Resource Group in Microsoft Azure, you can assign tags to it. Yes, this is an optional feature and this may seem like just another bit of administrivia, but savvy users will utilize this structure for better governance and production management.

Microsoft Azure’s Resource Group Creation Step 2 — Tags

And if you create, it will simply show up like this.

Microsoft Azure’s Resource Group after creation showing Tags

What are Azure Resources Groups?

It is a container that holds logically related resources for an Azure solution. In Azure, you logically group related resources to deploy, manage them as a single entity. In other words, a resource group can include all the resources for the solution, or only those resources that you want to manage as a group.

How to manage Azure Resource Groups with Tags?

Tags let you organize resources and resource groups by assigning them a name: value pair such as owner: your_name. This can be useful when it comes to things like Access control and compliance; keep track of who can interact with what. But don't just start slapping random tags because I mentioned! Here are few best tagging practices to follow — https://docs.microsoft.com/en-us/azure/architecture/cloud-adoption/decision-guides/resource-tagging/

How to Provision Azure Resource Groups Automatically?

Step1: Create an Automation Account.

Azure Automation provides capabilities to do process automation, update management, desired state configuration, track changes, and collect inventory.

Create a Run As account while creating Automation.

This will create Run As accounts in the Automation account which are useful for authenticating with Azure to manage Azure resources from Automation runbooks. This step will deploy the following 6 resources including 1 Automation Account and 5 Example Runbooks by default.

Microsoft Azure’s Resource Group with Resources after creating an Automation Account

Step2: Create Provision Runbook.

Automation Account’s Process Automation

Go to Automation Account and under the Process Automation Section in the left pane, look for Runbooks and create a runbook. You can also choose from various common runbooks from the runbooks gallery as per your needs.

This is the PowerShell code I wrote which accepts a JSON payload from a web app and acts as a backend system which creates a Resource Group with tag values from the payload.

<#
.DESCRIPTION
An example runbook that connects with a service principal, adds azure guest accounts and creates resource group in the appropriate subscription.
.NOTES
AUTHOR: Azure Automation Team
LASTEDIT: Mar 14, 2016
#>
param
(
[Parameter (Mandatory = $false)]
[object] $WebhookData
)
#This section uses the service principal that is connected as this logic app to log into azure for access to create resources.
#Make Sure the service principal is a contributor on the root management groups.
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint | Out-Null
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
#This receives the payload data from the message body of the incoming post. Make sure the payload is in Json.
$Request = $WebhookData
$Owner = ($Request.owner)
$Name = $Request.name
$RGName = ("Sandbox-" + $Name).tolower()
#Connect Azure AD
$myCred = Get-AutomationPSCredential -Name ''
$userName = $myCred.UserName
$securePassword = $myCred.Password
$myAADCred = New-Object System.Management.Automation.PSCredential ($userName,$securePassword)
Connect-AzureAD -Credential $myAADCred | Out-Null
#Select proper subscription to build RG in.$subname = "***"
$context = Set-AzureRmContext -SubscriptionName $subname
#$subscription = Get-AzureRmSubscription -SubscriptionName $subname
#Create the resource group with the name the end user provided in the form and create it with tags they provided.
#Make sure you add expiration days to the current date to get the Resource Group's expiration date.
try{
$NewRG = New-AzureRmResourceGroup -Name ($RGName).tolower() -Location "WEST US 2" -Tag @{ owner = $Owner; environment=$Request.environment; expiration = ([DateTime]::Now.addDays($Request.expiration))} -force
}
catch{
if (!$NewRG)
{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
$objOut = [PSCustomObject]@{
ResourceGroupName = $RGName
Owner = $Owner
ExpiryDate = (Get-Date).AddDays($Request.expiration).ToString('MM-dd-yyyy')
CreationDate = (Get-Date).ToString('MM-dd-yyyy')
}
Write-Output ( $objOut | ConvertTo-json )

Go to the test pane and test the output with this input as Webhook Data —

{
"expiration": "30",
"name": "kuharan",
"owner": [
"kuharan.bhowmik@gmail.com"
],
"environment":"dev"
}

Output —

{
"ResourceGroupName": "Sandbox-kuharan",
"OwnerList": [
"kuharan.bhowmik@gmail.com"
],
"ExpiryDate": "08-27-2019",
"CreationDate": "07-28-2019"
}

If your output is similar to this then copy the output and paste in a notepad (You will need this afterward)

Make sure you publish it before going further.

Step3: Create a logic app to automate this Runbook.

Create an action for When an Http request is received action. Use a JSON payload (should be configured in the frontend application) similar to this below:

{
"expiration": "30",
"name": "kuharan",
"owner": [
"kuharan.bhowmik@gmail.com"
],
"environment":"dev"
}

The resultant schema should look like this —

{
"type": "object",
"properties": {
"expiration": {
"type": "string"
},
"name": {
"type": "string"
},
"owner": {
"type": "array",
"items": {
"type": "string"
}
},
"environment": {
"type": "string"
}
}
}

As soon as you save the logic app, azure will magically generate a POST request URL for your app similar to this —

https://prod-06.westus2.logic.azure.com:443/workflows/<workflowid>/triggers/manual/paths/invoke?api-version=2016-10-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=<sigid>

Take this URL and configure your frontend application.

…and it looks like this —

Azure Resource Group Provisioning App — Step 1

Next, connect a Create Job action to the When an Http request is received action. To do this search for “Azure Automation” by clicking on the +New Step button. Here is what the Create Job should look like.

Azure Resource Group Provisioning App — Step 2

Next, connect a Get job output action from the Runbook. It just needs a Job ID

Azure Resource Group Provisioning App — Step 3

Let us parse the Output with Parse JSON action in this step. Copy the test output from the Powershell Runbook (step 2) and paste in the Use sample payload to generate schema box and the schema should be generated for you.

Azure Resource Group Provisioning App — Step 4

The overall flow should look like this. Beautiful!

Azure Resource Group Provisioning App — Overall

Once you hit it from your application or postman, you’ll notice the logic app is running behind the scenes. Sometimes the Resource group creation can take up to several minutes to get deployed in Azure. Meanwhile, you can take a deep breath — https://www.google.com/search?q=breathing+exercise That's what I do!

Congrats! You completed Part I of this dense piece of content on a Resource Group Provisioning Automation. I’ll be writing about de-provisioning a Resource Group in a couple of days and post my next column in this series. Stay tuned for Part — II.

I can be found here -
LinkedIn — https://www.linkedin.com/in/kuharan/
Github — https://github.com/kuharan

Data Engineer, Programmer, Thinker

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store