Azure

Invoke An Azure Runbook Utilizing Terraform

Introduction

 

 

Earlier than we begin with explaining the implementation, let’s first take a pause to acknowledge Azure Runbooks a bit and if you happen to haven’t already used Azure Automation Accounts, you completely ought to. So, what are Azure Automation Runbooks? Right here is the reply – an Azure Runbook is a characteristic of Azure Automation that lets you execute workflows from inside Azure or remotely to automate processes. Many firms who’ve their Infrastructure hosted on Microsoft Azure Cloud are utilizing Azure Automation Runbooks to provoke automated processes like powering on or off Azure Digital Machines, producing of customized experiences for sources, or checking the well being of particular sort of Azure Assets, and so on. on an outlined schedule or demand foundation. This characteristic could be very helpful in performing automated operations in Azure whenever you wish to carry out one thing from a centralized location because it runs by way of a PaaS useful resource referred to as Azure Automation Account. There are various kinds of Azure Runbooks out there which could be understood intimately on this article.

 

Let’s soar into the issue that we now have – we wish to invoke certainly one of our Azure Automation Runbooks from Terraform to carry out a selected process the place we needed to move some parameters that had been required for runbook execution. We’re going to state the apparent and it could come as a shock to a few of you – like another instruments/platforms, Terraform has its personal set of limitations and is understood for provisioning new sources solely, It doesn’t provide a direct option to invoke runbooks by passing required parameters.

With the choices out there in Terraform for runbooks, you possibly can solely create a brand new runbook with new schedule however can’t carry out operations like invoking an present runbook by passing required parameter values, utilizing terraform sources. So, we needed to search for different choices out there in Terraform. Guess what we received….local-exec provisioner. With this local-exec provisioner, we tried to meet our necessities. Allow us to clarify how we carried out this in order that others can reuse this prepared to make use of stuff and might keep away from spending hours on the identical factor. The reusable code for this use case is on the market right here: Invoke-Azure-Runbooks.

 

Pre-Requisites

  • Azure Automation Account
  • PowerShell Runbook hosted on the above automation account
  • Terraform Open Supply or Enterprise Model

Runbook Implementation

 

For the sake of simplicity, we will likely be explaining a easy state of affairs the place you possibly can invoke a runbook by passing the required parameters to it from Terraform and runbook will output the values of handed parameters. As talked about above, there are various kinds of Runbooks however for this weblog, we will likely be specializing in PowerShell sort runbook. In case you are new to PowerShell, please take a look at this superb article for extra particulars on Microsoft PowerShell. We’re not detailing the runbook implementation as it could differ primarily based on use circumstances or necessities and the aim of this text is to elucidate runbook invocation by way of terraform by passing parameters solely.

 

Let’s start with implementation. The primary order of motion is to create a runbook within the Azure Automation account and a easy PowerShell script for it which accepts parameters.

 

Please observe the beneath steps:

  • Open your Automation account in Azure Portal.
  • Click on Runbooks underneath Course of Automation. The listing of runbooks is displayed.
  • Click on Create a runbook on the prime of the listing.
  • Enter a reputation for the runbook identify within the Identify area and choose PowerShell for the Runbook sort area.
  • Click on on the Create button to create a runbook.
  • Now, on “Edit PowerShell Runbook”, copy and paste beneath PowerShell code.

    1. param(  
    2.     [Parameter(Mandatory = $true)]  
    3.     [object] $WebhookData)  
    4. attempt {  
    5.     # If runbook was referred to as from Webhook, WebhookData will not be null.  
    6.     if($WebhookData) {  
    7.         #Retrieve knowledge from Webhook request physique  
    8.         $inputs = (ConvertFrom – Json – InputObject $WebhookData.RequestBody)  
    9.         #Fetch values of parameters handed to webhook in kind of request physique  
    10.         $Attribute1 = $inputs.Attribute1  
    11.         $Attribute2 = $inputs.Attribute2  
    12.         Write – Output “==========================================================”  
    13.         Write – Output “Worth of First Parameter – “  
    14.         $Attribute1  
    15.         Write – Output “Worth of Second Parameter – “  
    16.         $Attribute2  
    17.         Write – Output “==========================================================”  
    18.     }  
    19. catch {  
    20.     Write – Output $_.Exception.Message  
    21.     Write – Error “This runbook is meant to be began from webhook solely.” – ErrorAction Cease  
    22. }  
  • Click on on Save after which publish buttons seen on the identical display screen.
  • Now, click on on Webhook button out there on the revealed runbook display screen

  • On the Add Webhook display screen, click on on Create a brand new Webhook possibility.

  • On the subsequent display screen, present a reputation within the Identify area and expiry DateTime to your Webhook. Copy the Webhook Url and maintain it apart as it will likely be utilizing in Terraform for invoking the runbook

  • Now, Click on on OK after which Create.

Now we’re all set with our runbook that may be invoked from anyplace utilizing its Webhook URL.

 

Terraform Implementation

 

We are going to observe the beneath code hierarchy that we adopted in our earlier article the place every deployment sort has a separate folder containing all required recordsdata together with a principal file, a variables file, an output file, and an elective .tfvars file that gives inputs for executions.

 

principal.tf

 

Let’s start with Terraform implementation by opening the primary.tf file and including the next code block. As we talked about within the above sections, Terraform doesn’t help the invocation of runbooks by means of its native sources and due to this fact, we will likely be utilizing a “local-exec” provisioner with a “null_resource” useful resource the place a PowerShell script will likely be used to invoke our runbook created within the above steps.

  1. #Invocation of Azure Runbook by way of Native – Exec  
  2. useful resource “null_resource”  
  3. “invoke_azure_runbook” {  
  4.     provisioner “local-exec” {  
  5.         command = “.Invocation-Script.ps1 -Param1 ‘${var.variable1}’ -Param2 ‘${native.variable2}'”  
  6.         interpreter = [“pwsh”“-Command”]  
  7.     }  
  8. }   

Right here, we’re making a “null_resource” useful resource of Terraform with “local-exec” provisioner used for executing a PowerShell script i.e. “Invocation-Script.ps1” by passing the arguments to it from variable.tf file or native variables. Now, we will likely be including a locals block to outline the native variables that we utilized in above code. On this block, we’re manipulating the “resource_group_name” variable worth a bit, handed from variable.tf file and passing the manipulated worth as a neighborhood variable worth to the local-exec provisioner.

 

We’re including this block to indicate that we are able to additionally move native variables (manipulated variables) accountable for the “local-exec” provisioner as argument values.

  1. #Outline Native Variables  
  2. locals {  
  3.     #Changing clean areas from variable worth and storing it in native variable referred to as“ variable2”  
  4.     variable2 = exchange(var.variable2, ” ““”)  
  5. }   

Now, let’s create “Invocation-Script.ps1” PowerShell file, add it to the basis of your Terraform listing the place all different recordsdata like principal.tf, variable.tf are positioned and add the next easy code.

  1. # Outline Parameters to be handed to script from Terraform by way of Native – Exec  
  2. param(  
  3.     [string] $Param1,  
  4.     [string] $Param2)  
  5. #Create a request physique object  
  6. for webhook  
  7. $physique = @ {  
  8.     Attribute1 = $Param1  
  9.     Attribute2 = $Param2  
  10. }  
  11. #Convert above object into Json  
  12. $requestBody = $physique | ConvertTo – Json  
  13. $uri = “Your_Runbook_Webhook_Uri which you copied throughout webhook creation”  
  14. #Invoke the webhook utilizing Webhook Uri  
  15. $response = Invoke – WebRequest – Methodology Submit – Uri $uri – Physique $requestBody  
  16. if ($response.StatusCode – eq “202” – and $response.StatusDescription – eq “Accepted”) {  
  17.     Write – Host “Your webhook invocation is accomplished.”  
  18. else {  
  19.     Write – Host “Your webhook invocation has failed.”  
  20. }   

This “Invocation-Script.ps1” is accepting the parameter values that are handed from Terraform to it as argument values and is invoking the webhook utilizing the “Invoke-WebRequest” command of PowerShell and passing the parameter values as Webhook request physique in Json format.

 

The principle executable code is now prepared and we are going to simply create the 2 further recordsdata for variables and output to outline the enter and output variables that will likely be a part of this execution.

 

variables.tf

  1. variable variable1 {  
  2.     sort = string  
  3.     description = “First variable to be handed to Terraform”  
  4.     default = “Runbook Invocation”  
  5. }  
  6. variable variable2 {  
  7.     sort = string  
  8.     description = “First variable to be handed to Terraform”  
  9.     default = “By way of Terraform”  
  10. }   

outputs.tf

 

As “null_resource” doesn’t return output of executed PowerShell script, so we are able to have a customized output saved in a variable that will likely be depending on “null_resource” useful resource execution completion.

  1. output “Remarks” {  
  2.     worth = “Your runbook has been invoked efficiently”  
  3.     depends_on = [  
  4.         null_resource.invoke_azure_runbook  
  5.     ]  
  6. }   

That’s it!! We’re prepared with the code now that may invoke runbook by means of webhook by passing required parameters from Terraform. As talked about in our earlier articles additionally, bear in mind to carry out a Terraform Init earlier than doing a plan and apply. We’re utilizing a pattern tfvars file for our native execution with variables outlined underneath,

  1. variable1 = “your-value-for-variable1”  
  2. variable2 = “your-value-for-variable2”  
  3. terraform plan –var-file=“<yourfilename>.tfvars” or terraform plan  
  4. terraform apply –var-file=“<yourfilename>.tfvars” or terraform apply  

As soon as you’ll run the “Terraform Apply” operation, it offers you beneath output:

 

 

If you’ll go to the runbook jobs at Azure Portal, following output will likely be displayed in underneath “All Logs” in opposition to job executed out of your webhook invocation.

 

 

Now we have now efficiently invoked Azure Runbook by means of Terrafrom by passing the required parameters. You will get the answer code at our GitHub Repository for this use case. Glad Coding!!

Tags
Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Close