CHAPTER 8

image

Azure Automation

Since the beginning of the book, we have talked about using PowerShell to automate different Azure services, such as virtual machines, virtual networks, SQL databases, and so many others. The focus, so far, has been mainly on learning how to perform certain tasks in PowerShell so that you can use it for automation purposes. For instance, how to provision a virtual machine via PowerShell so that you can later put this code inside a loop to provision a hundred virtual machines at a time. The same concept applies to other services, like creating Azure web sites, Azure AD users, uploading files to Azure storage, and so on.

In this chapter, you are going to learn about Azure Automation but in a different style. This time, it’s not about using PowerShell cmdlets to automate an Azure service but about an Azure service that uses PowerShell as a platform to automate other Azure components. This is the Azure Automation service.

What’s Azure Automation?

Azure Automation service is Microsoft’s answer to Automation as a Service. The reason it’s called Automation as a Service is that in order to automate components in a traditional on-premises scenario, you need an automation tool or software that needs underlying hardware and network requirements. Then, you can start building your automation workflows and scripts. However, in Azure Automation, everything is already set: you just log in to the console to build the workflows and scripts.

Azure Automation is the IT automation process for Azure. If you’ve had the chance to work with System Center Orchestrator, then you might say that Azure Automation is the “Orchestrator” for Azure services.

Azure Automation allows you to automate the creation, deployment, maintenance, and monitoring of Azure services and resources in your environment. It also allows you to take proper actions proactively based on some specific attributes and values.

The great thing about Azure Automation is that it’s based on Windows PowerShell and the Windows PowerShell Workflows engine. This means that your existing Azure scripts can work with Azure Automation with only minor modifications. You don’t have to learn something new. The knowledge you gain from this book applies to Azure Automation.

I know that this sounds a little confusing, and you are probably wondering why you need the Azure PowerShell module if you have Azure Automation services.

To make things clear, Azure Automation is not a replacement for Azure PowerShell. Actually, it uses the Azure PowerShell cmdlets to automate Azure services and resources. The point is that Azure Automation provides you with a reliable automation platform that you can use to automate your Azure services, instead of using local PowerShell consoles on a local computer.

For instance, if you want to shut down some Azure virtual machines, you can simply open your PowerShell console, use the respective cmdlets to perform that task, and everything is set. But with Azure Automation, you build a runbook using the same PowerShell cmdlets, save it, and configure a scheduler to run this script automatically at a specific time.

You don’t have to run anything manually. You don’t have to keep your machine up and running. You don’t have to do anything else. Just do it once, and enjoy it forever. That’s why I like to use the term “unattended automation” to describe the Azure Automation service.

Getting Started with Azure Automation

Chapter 3 talked about Azure storage. There I mentioned that to get access to Azure storage, you need to create an Azure storage account.

The same happens with Azure Automation. To start using it, you need to first create an Azure Automation account. The automation account contains automation resources such as runbooks, credentials, variables, and connections.

The resources held by one automation account are totally isolated and cannot be shared with another automation account. This means that you can have more than one account, each with its own resources. For instance, think of having one automation account for the test/dev environment and another automation account for the production environment.

To create an Azure Automation account, you use the New-AzureAutomationAccount cmdlet. This cmdlet requires the -Name parameter to specify the name of the automation account, and -Location to specify the region of the automation account.

Image Note  As of this writing, the Azure Automation service is available only in the following Azure regions: East US 2, Japan East, South Central US, Southeast Asia, and West Europe. However, an Azure Automation account can manage resources in different regions.

#Create New Azure Automation Account
New-AzureAutomationAccount -Name DevTestAA -Location "West Europe"

AutomationAccountName         Location             State                 Plan
---------------------         --------             -----                 ----
DevTestAA                     West Europe          Ready                 Free

So, you create your first Azure Automation account, DevTestAA, for the test/dev environment; it’s located in the West Europe region. You also find another property called plan and its value is free.

The plan property reflects the Azure Automation account’s pricing plan. There are two pricing offerings for Azure Automation: Free and Basic.

The difference between the two offerings is the amount of time that the automation job runs (CPU time). The free offering gives you up to 500 minutes of CPU time per subscription, while basic gives unlimited minutes of CPU time per automation account. The basic offering costs $0.02 per 10 minutes.

To change the offering from free to basic, or vice versa, go to the Azure portal. In Automation, select the automation account that you want to change. Click the Scale tab and choose either Free or Basic. Finally, click Save, as shown in Figure 8-1.

9781484206669_Fig08-01.jpg

Figure 8-1. Change the Azure Automation account offering

There is no cmdlet to modify the settings of an Azure Automation account, but you still have the Get-AzureAutomationAccount cmdlet that lists all the automation accounts, and the Remove-AzureAutomationAccount cmdlet to remove an automation account.

#Remove Azure Automation Account
Remove-AzureAutomationAccount -Name "DevTestAAA" -Force

Under each automation account, there are four tabs that represent the properties and resources of the account, as shown in Figure 8-2.

9781484206669_Fig08-02.jpg

Figure 8-2. Azure Automation account tabs

The account tabs can be described as follows.

  • Dashboard: Shows diagnostic information, jobs status history, runbooks, usage statistics, and assets.
  • Runbook: Shows the list of available runbooks and the status of each runbook. Also allows you to create, start, import, and export runbooks.
  • Assets: Where you manage automation account resources.
  • Scale: Where you change the automation account offering.

The next section discusses how to create and manage runbooks and assets using PowerShell cmdlets.

Azure Automation Runbooks

In the computer world in general, and in automation specifically, a runbook is the workflow that defines the processes, procedures, and operations to build, deploy, configure, manage, monitor, and report IT infrastructure, services, and components.

In Azure Automation, a runbook is the PowerShell workflow that automates Azure services and operations. There are two ways to author Azure Automation runbooks: graphical authoring and textual authoring.

The graphical authoring is very similar to System Center Orchestrator. There is a graphical runbook editor that visualizes the workflow. As you can see in Figure 8-3, there are the PowerShell cmdlets, variables, certificates, credentials, and other runbooks available to build your workflow.

9781484206669_Fig08-03.jpg

Figure 8-3. Azure Automation graphical runbook editor

Image Note  The graphical runbook editor is available only on the new Azure portal.

Although it’s a graphical editor, the runbook still uses PowerShell in the background. Also, the customization for the workflow is entirely via PowerShell. For instance, if you want to make an action based on a condition, you define this condition using PowerShell code, not the graphical editor.

The textual authoring is simply an online PowerShell editor where you can build a runbook from scratch using purely PowerShell code, as shown in Figure 8-4.

9781484206669_Fig08-04.jpg

Figure 8-4. Azure Automation textual runbook editor

Now that you understand runbooks, let’s learn how to create them.

Creating Runbooks

There are different ways to create Azure Automation runbooks. You can create a new empty runbook or a runbook from a template in the runbooks gallery, and you can import existing PowerShell scripts.

The options to create an empty runbook or import an existing PowerShell script as a runbook are available in both the Azure portal and via Azure PowerShell cmdlets. In contrast, the option to create runbooks from the gallery is available only on the Azure portal, but not via Azure PowerShell cmdlets. You can still download the scripts from the script center repository, however, at https://gallery.technet.microsoft.com/scriptcenter and import as runbooks.

To create an Azure Automation runbook using PowerShell, you use the New-AzureAutomationRunbook cmdlet. This cmdlet has two parameter sets: the ByRunbookName parameter set to create a new empty runbook and the ByPath parameter set to import a PowerShell script or workflow as a runbook.

The main difference between these two parameter sets is that ByRunbookName uses the -Name parameter to specify a name for the runbook, and ByPath uses the -Path parameter to specify the path of the PowerShell script to import. But the rest of parameters, such as -Description, -AutomationAccountName, and -Tags, remain the same.

#Create a new empty Runbook
New-AzureAutomationRunbook -AutomationAccountName ’DevTestAA’ -Name HelloWorldRunbook -Description "My first Azure Automation Runbook" -Tags @("Demo","IaaS")

AutomationAccountName : DevTestAA
Name                  : HelloWorldRunbook
Location              : East US
Tags                  : {Demo, IaaS}
JobCount              : 0
RunbookType           : Script
CreationTime          : 6/23/2015 1:16:08 PM +00:00
LastModifiedTime      : 6/23/2015 1:16:08 PM +00:00
Description           : My first Azure Automation Runbook
Parameters            : {}
LogVerbose            : False
LogProgress           : False
State                 : New

#Import PowerShell script as automation runbook
New-AzureAutomationRunbook -AutomationAccountName ’DevTestAA’ -Path C:ScriptsHelloWorldScript.ps1 -Description "My first Azure Automation Runbook" -Tags @("Demo","IaaS")

AutomationAccountName : DevTestAA
Name                  : HelloWorldScript
Location              : East US
Tags                  : {Demo, IaaS}
JobCount              : 0
RunbookType           : Script
CreationTime          : 6/23/2015 1:16:08 PM +00:00
LastModifiedTime      : 6/23/2015 1:16:08 PM +00:00
Description           : My first Azure Automation Runbook
Parameters            : {}
LogVerbose            : False
LogProgress           : False
State                 : New

In addition to the previous cmdlets, you have the Set-AzureAutomationRunbook cmdlet that allows you to modify the properties of an existing runbook, including name, description, and tags. It also allows you to enable and disable runbook logging.

There are two types of logging available for Azure Automation runbook: verbose logging and progress logging. To enable these logging capabilities, you use the -Logverbose parameter for verbose logging and the -LogProgress parameter for progress logging.

#Enable Runbook Logging
Set-AzureAutomationRunbook -AutomationAccountName ’DevTestAA’ -Name HelloWorldRunbook -LogProgress $true -LogVerbose $true

AutomationAccountName : DevTestAA
Name                  : HelloWorldRunbook
Location              : East US 2
Tags                  : {}
JobCount              : 0
RunbookType           : Script
CreationTime          : 6/23/2015 1:31:25 PM +00:00
LastModifiedTime      : 6/23/2015 2:31:54 PM +00:00
Description           : My first Azure Automation Runbook
Parameters            : {}
LogVerbose            : True
LogProgress           : True
State                 : Edit

In order to query the list of runbooks under a specific automation account, you use the Get-AzureAutomationRunbook cmdlet, which is very similar to all the other cmdlets that query items, such VMs, vNETs, and so forth. But this is not everything; there is also the Get-AzureAutomationRunbookDefinition cmdlet that shows the definition and the contents of the runbook itself.

#Get Runbook Definition
Get-AzureAutomationRunbookDefinition -AutomationAccountName DevTestAA -Name HelloWorldRunbook

AutomationAccountName : DevTestAA
Name                  : HelloWorldRunbook
Slot                  : Draft
RunbookType           : Script
CreationTime          : 6/23/2015 1:31:48 PM +00:00
LastModifiedTime      : 6/23/2015 1:31:48 PM +00:00
Content               : <#
                            This PowerShell script was automatically converted to PowerShell Workflow so it can be run as a runbook.
                            Specific changes that have been made are marked with a comment starting with "Converter:"
                        #>
                        workflow HellowWorldRunbook {
                            inlineScript {
                                Get-Service
                            }
                        }

On the other side, if you want to update a draft definition of a runbook, you can use the Set-AzureAutomationRunbookDefinition cmdlet to achieve this task. As usual, you use the -AutomationAccountName and -Name parameters to select the required runbook. Then, you use the -Path parameter to specify the path of the PowerShell file containing the updated definition. Finally, you use the -overwrite parameter to overwrite the existing draft definition.

#Update Runbook Definition
Set-AzureAutomationRunbookDefinition -AutomationAccountName ’DevTestAA’ -Name HelloWorldRunbook -Path "C:ScriptsHelloWorldv2.ps1" -Overwrite $true

When you create or import an automation runbook, it is in draft state, which means that you cannot use it or start it until the state is changed from draft to published. To publish a runbook, you use the Publish-AzureAutomationRunbook cmdlet. You use the -AutomationAccountName and -Name parameters to specify which runbook to publish.

#Publish Runbook
Publish-AzureAutomationRunbook -AutomationAccountName ’DevTestAA’ -Name HelloWorldRunbook

AutomationAccountName : DevTestAA
Name                  : HelloWorldRunbook
Location              : East US
Tags                  : {Demo, IaaS}
JobCount              : 0
RunbookType           : Script
CreationTime          : 6/08/2015 1:16:08 PM +00:00
LastModifiedTime      : 6/08/2015 1:16:08 PM +00:00
Description           : My first Azure Automation Runbook
Parameters            : {}
LogVerbose            : False
LogProgress           : False
State                 : Published

Once you publish a runbook, you will be able to start it from either the Azure portal or Azure PowerShell. To start a runbook via PowerShell, you use the Start-AzureAutomationRunbook cmdlet along with the -AutomationAccountName and -Name parameters.

#Start Automation Runbook
Start-AzureAutomationRunbook -AutomationAccountName ’DevTestAA’ -Name HelloWorldRunbook

The moment the runbook starts—either manually using the cmdlet or automatically via a predefined schedule, a runbook job is created for that runbook. Each runbook job has an id that can be used to get the job information and output, and to control the job execution with commands like suspend, stop, and resume.

If you start a runbook via PowerShell, then you get the job information, including the id. Otherwise, you can still get the runbook job information using the Get-AzureAutomationJob cmdlet. You can query runbook jobs by job id, runbook name, and job status.

#Get list of runbook jobs
Get-AzureAutomationJob -AutomationAccountName DevTestAA -RunbookName HelloWorldRunbook

AutomationAccountName  : DevTestAA
Id                     : a9747c86-e901-4272-bc29-96d48543faf7
CreationTime           : 6/08/2015 1:40:32 PM +00:00
Status                 : Completed
StatusDetails          :
StartTime              : 6/08/2015 1:40:42 PM +00:00
EndTime                : 6/08/2015 1:40:44 PM +00:00
Exception              :
LastModifiedTime       : 6/08/2015 1:40:44 PM +00:00
LastStatusModifiedTime : 1/1/0001 12:00:00 AM +00:00
JobParameters          : {}
RunbookName            : HelloWorldRunbook
HybridWorker           :

You can get the output of a specific runbook job by using the Get-AzureAutomationJobOutput cmdlet along with the -Id parameter to specify the job, and the -Stream parameter to specify the type of output. The stream parameter accepts the following values: Any, Debug, Error, Progress, Verbose, Warning, and Output.

#Query runbook job output
Get-AzureAutomationJobOutput -AutomationAccountName DevTestAA -Id a9747c86-e901-4272-bc29-96d48543faf7 -Stream Any

There are also the Suspend-AzureAutomationJob, Resume-AzureAutomationJob, and Stop-AzureAutomationJob cmdlets that allow you to control the execution of a runbook job.

I’ve mentioned a few times that the Azure Automation service is built on top of the Windows PowerShell Workflow engine. This means that you use the normal Windows PowerShell Workflows mechanism with Azure Automation. The next section explains why PowerShell workflows are important to Azure Automation.

PowerShell Workflows and Checkpoints

One powerful feature of Windows PowerShell Workflows is checkpoints. A checkpoint is like a snapshot of generated outputs, serialized state information, or variables, along with their values, at the moment the checkpoint was taken. So, you can say that checkpoints for a workflow are similar to snapshots for a virtual machine.

Checkpoints make workflows more persistent and reliable. For instance, let’s say you have a complex workflow that does multiple tasks on multiple environments. This long and complex workflow might trigger an error and an execution failure for a variety of reasons—it could be a syntax error, a resource that is unreachable or no longer available, or something else. It might be OK to restart the workflow if you get the error at an early stage. But what if the error happens in the middle of execution? You definitely don’t want to go back to square one and start everything from scratch.

Therefore, checkpoints allow you to divide the workflow into multiple stages and capture the output of each successful stage. So, if an error occurs and the workflow is suspended, checkpoints let you resume from the latest checkpoint (stage) rather than starting from the beginning.

You use the Checkpoint-Workflow activity within the PowerShell workflow to immediately persist a checkpoint.

Image Note  The term cmdlet refers to commands in Windows PowerShell scripts, but you use the term activity to refer to commands in Windows PowerShell Workflows. That’s why we say Checkpoint-Workflow activity, not cmdlet.

Image Caution  When a checkpoint is invoked, a serialization state of data persists to the storage. The more checkpoints you add, the more data to add to the storage. This affects the performance of the running workflow. So, make sure to use checkpoints wisely and when really needed. Also, sometimes it’s much faster to restart a workflow from the beginning than to use checkpoints.

By design, the Azure Automation service limits the amount of runbook execution time to 30 minutes. The Azure Automation service automatically unloads any runbook taking more than 30 minutes, assuming that either something went wrong or that the runbook is monopolizing the service.

Therefore, if you have a long runbook that might take more than 30 minutes to execute, make sure to use checkpoints at intervals under 30 minutes so that you can complete it later.

In some cases, the workflow depends on manual tasks, so you have to suspend the execution until you complete those manual steps and then resume it again. To suspend a workflow, you use the Suspend-Workflow activity, and you use the Resume-Workflow activity to resume it again.

Azure Automation Assets

Azure Automation assets are a set of predefined and reusable global resources that are shared across runbooks under the same Azure Automation account. These resources are used to make the process of building and editing runbooks easier and consistent.

For example, one of the assets is called a credentials asset, which allows you to define an object that stores your credentials securely; later on you can call this credential asset directly within the runbook rather than hard-coding it. This means that if you have multiple runbooks, use this credential the next time you change the password; you will have to update the credential asset instead of manually updating the credential in each and every runbook that you have.

There are different types of Azure Automation assets. The following sections describe and explain them, including how to create and use them.

Automation Credential

In Chapter 2, you learned how to prepare Azure PowerShell to connect to an Azure subscription. One of the steps was authenticating PowerShell against Azure in order to reach out to the Azure subscription(s). The authentication options you had were certificates and Azure AD accounts.

In this chapter, you have a very similar scenario. You still want to use PowerShell to manage and automate Azure, but this time from the Azure Automation console, not the PowerShell console on a local machine.

That’s why there are the automation credential settings that securely store the credential information used within the automation runbook. The automation credential assets could be used for Azure itself and the services running on it. For instance, you can use the credential to connect to Azure and to deploy Azure web apps.

The automation credential can store certificates and accounts as well, as shown in Figure 8-5.

9781484206669_Fig08-05.jpg

Figure 8-5. Azure Automation credential types

The next two sections explain how to create each of the types.

Credential Asset: Certificate

This example assumes that you already have an Azure management certificate. If you don’t have one, then please refer to the tutorial at https://msdn.microsoft.com/en-us/library/azure/gg551722.aspx to create a new one.

After creating and uploading the Azure management certificate, return to the same machine that you created the certificate, and then export it with private keys so that you have a .pfx certificate file that can be used by the automation service.

You can use the following PowerShell code to export the certificate with a private key.

#Export Certificate with Private Keys (PFX)
$CertPassword = ConvertTo-SecureString -String "P@ssw0rd" -Force –AsPlainText

$AzureMgmtCert = Get-ChildItem -Path Cert:CurrentUserMy | where {$_.Subject -match "AzureCert"}

Export-PfxCertificate -FilePath "C:CertsAzureCert.pfx" -Password $CertPassword -Cert $AzureMgmtCert

Now that you have the *.pfx file, let’s use it to create a new automation certificate asset. To do so, you use the New-AzureAutomationCertificate cmdlet.

#Create Azure Automation Certificate
$CertFile = "C:CertsAzureMgmtCert.pfx"

$CertPassword = ConvertTo-SecureString "P@ssw0rd" -AsPlainText -Force

New-AzureAutomationCertificate -AutomationAccountName DevTestAA -Name "AzureCert" -Description "Azure Automation Certificate" -Path $CertFile -Password $CertPassword

Once you create the certificate, you call in your runbooks using the Get-AutomationCertificate activity.

#Using Automation Certificate
workflow HelloWorldRunbook {
    $Cert = Get-AutomationCertificate -Name ’AzureAutomationCert’
}

You can update the automation certificate asset or overwrite an existing certificate using the Set-AzureAutomationCertificate cmdlet. You can also query the list of certificates using the Get-AzureAutomationCertificate cmdlet, and remove it using the Remove-AzureAutomationCertificate cmdlet.

Image Note  The Get-AzureAutomationCertificate cmdlet gets only the certificate information, whereas the Get-AutomationCertificate activity gets the certificate itself. Keep this in mind because this is the case with most of the automation assets.

Credential Asset: PowerShell Credential

The second type of automation credential asset is the PowerShell account. This asset stores security credentials (username and password) in a form of a PSCrdential object. Later on, this credential asset can be used for authentication purposes.

You create an automation credential asset using the New-AzureAutomationCredential cmdlet.

#Create Azure Automation Credential (Get-Credential)
New-AzureAutomationCredential -AutomationAccountName "DevTestAA" -Name "MyCredential" -Value (Get-Credential [email protected]) -Description "Azure Automation Credential"

In the previous code, you used the Get-Credential cmdlet to provide the credential (username and password) in PSCredential object format. The Get-Credential cmdlet prompts a credential box for you to manually enter the username and password.

If you want to do this silently without any prompts, then you can explicitly create PSCredential using the New-Object cmdlet and provide the username and password (in clear text) as arguments, as shown in the following code.

#Create Azure Automation Credential (New-Object)
$Username = [email protected]

$Password = ConvertTo-SecureString "Master@123" -AsPlainText -Force

$Cred = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $Username, $Password

New-AzureAutomationCredential -AutomationAccountName "DevTestAA" -Name "MyCredential" -Value $Cred -Description "Azure Automation Credential"

To use the automation credential within a runbook, you use the Get-AutomationPSCredential activity.

#Using Automation Credential
workflow HelloWorldRunbook {
    $Cred = Get-AutomationPSCredential -Name ’MyCredential’
    $Username = $Cred.UserName
    $securePassword = $Cred.Password
    $Password = $Cred.GetNetworkCredential().Password
}

You can update an automation credential asset or overwrite an existing credential using the Set-AzureAutomationCredential cmdlet. You can also query the list of certificates using the Get-AzureAutomationCredential cmdlet, and remove it using the Remove-AzureAutomationCredential cmdlet.

Variable Assets

Automation variable assets allow the creation of persistent variables and share their values across runbooks. You can retrieve and set the value of these variable assets during execution time. The variable asset value can be set by a runbook and retrieved by another runbook. Even if the runbook fails, the value remains because it’s persistent.

To create a new variable asset, you use the New-AzureAutomationVariable cmdlet along with the -Name parameter to specify the variable’s name, and the -Value parameter to specify its value. You can also use the -Encrypted parameter to specify whether the value of this variable is viewable from the portal or via the Get-AzureAutomationVariable cmdlet. The -Encrypted parameter is very important when storing confidential values such as passwords.

#Create Azure Automation Variable
New-AzureAutomationVariable -AutomationAccountName ’DevTestAA’ -Name "myPassword" -Encrypted $true -Value "P@ssw0rd"

The variable asset can store any kind of value of type <System.Object>; it could be regular data types (strings, int, double, etc.) like in the previous example, or it could be any PowerShell object. For example, you can store a VM or vNET object in a variable asset, as shown in the following code.

#Store VM object in Automation Variable
$VM = Get-AzureVM -ServiceName ’WebFarm’ -Name ’WebSrv01’

New-AzureAutomationVariable -AutomationAccountName ’DevTestAA’ -Name ’WebFarmVM’ -Encrypted $false -Value $VM

Unlike the Get-AzureAutomationCertificate and Get-AzureAutomationCredential cmdlets that return only information about the asset, the Get-AzureAutomationVariable cmdlet returns the variable and its value as long as the variable is not encrypted. If the variable asset is encrypted, then you get it only within your runbook using the Get-AutomationVariable activity.

#Using Automation Variable - Cmdlet
Get-AzureAutomationVariable -AutomationAccountName ’DevTestAA’ -Name varX

Name                  : varX
CreationTime          : 6/8/2015 12:03:32 AM +00:00
LastModifiedTime      : 6/8/2015 12:14:51 AM +00:00
Value                 : Hellow World
Description           :
Encrypted             : False
AutomationAccountName : DevTestAA

#Using Automation Variable - Runbook Activity
workflow HelloWorldRunbook {
    Get-AutomationVariable -Name ’varX’
}

Also, you can update the value of an existing variable asset using either the Set-AzureAutomationVariable cmdlet or from a runbook using the Set-AutomationVariable activity.

#Set Automation Variable Value - Cmdlet
Set-AzureAutomationVariable -AutomationAccountName ’DevTestAA’ -Name varX -Value ’Hello World’ -Encrypted $false

#Set Automation Variable Value - Activity
workflow HelloWorldRunbook {
    Set-AutomationVariable -Name ’varY’ -Value <System.Object>
}

Last but not least, you can remove a variable asset using the Remove-AzureAutomationVariable cmdlet.

Connection Assets

An automation connection asset stores the information required to connect to an external system, service, or application. Connection information includes IP addresses, ports, protocols, credentials, tokens, and so on. The connection information varies from one service to another. That’s why the connection asset is not specific to a strict format.

To create an automation connection asset, you use the New-AzureAutomationConnection cmdlet along with the -ConnectionTypeName parameter to specify the type of connection, and the -ConnectionFieldValues parameter to specify the PowerShell hash table that contains the connection information.

#New Azure Automation Connection
$CertName = "AUTOMATION_CERTIFICATE_NAME"
$SubID  = "SUBSCRIPTION_ID"
$FieldValues = @{"AUTOMATIONCERTIFICATENAME" = $CertName;"SUBSCRIPTIONID"=$SubID}

New-AzureAutomationConnection -AutomationConnectionName ’DevTestAA’ -Name ’AzureConn’ -Description "Connection to Azure Subscription XYZ" -ConnectionTypeName ’Azure’ -ConnectionFieldValues $FieldValues

The field values must match; they are identified in the connection type settings. For example, an Azure connection type requires an automation certificate name and a subscription ID. So, the field values hash table must contain these keys and values or it will trigger a "Field: <Field_Value_Name> not found" error.

There is no cmdlet to modify the settings of a connection asset. To be more specific, there is no cmdlet to change the connection type of a connection asset. However, there is a cmdlet to change the field values of an existing connection asset. This is the Set-AzureAutomationConnectionFieldValue cmdlet.

You use the Set-AzureAutomationConnectionFieldValue cmdlet along with the -ConnectionFieldName parameter to specify the name of the field to change, and the -Value parameter to specify its value.

#Set Connection asset Field Value
Set-AzureAutomationConnectionFieldValue -AutomationAccountName DevTestAA -Name AzureConn -ConnectionFieldName AutomationCertificateName -Value AzureCert2

Image Caution  The -ConnectionFieldName parameter is case sensitive. So make sure that you get the exact name of the field by using (Get-AzureAutomationConnection -AutomationAccountName ’DevTestAA’ -Name AzureConn).FieldDefinitionValues.

You might have noticed that in the preceding examples, you have used only connection type Azure. And this is because it is the only available connection type. If you want to manage a different system or service, then you have to make the following modifications to the PowerShell integration module of that service before uploading.

Let’s assume that you have a PowerShell module for external service XYZ. You will upload that module to be able to automate XYZ service using an automation runbook.

To create a custom connection for XYZ service, open the XYZ PowerShell module folder on your local computer, and then create a JSON file with the naming convention <Module-Name>-Automation.json, which in this case should be XYZ-Automation.json, and copy the following code to it.

//JSON code for automation file
{
    "ConnectionFields":  [
                             {
                                 "IsEncrypted"  :  false,
                                 "IsOptional"   :  false,
                                 "Name"         :  "WebServiceURL",
                                 "TypeName"     :  "System.String"
                             },
                             {
                                 "IsEncrypted"  :  true,
                                 "IsOptional"   :  false,
                                 "Name"         :  "WebServiceAuthToken",
                                 "TypeName"     :  "System.String"
                             }

                         ],
    "ConnectionTypeName":  "XYZ",
    "IntegrationModuleName":  "XYZ"
}

In the previous code, you defined the connection asset settings for the XYZ external service. You used ConnectionField to define the field values. Each field value has the following properties: IsEncrypted, IsOptional, Name, and TypeName. Also, you used ConnectionTypeName to specify the name of the connection type. Finally, you used IntegrationModuleName to specify the name of the PowerShell integration module.

Now, the module is ready—just zip and upload it. And feel free to use XYZ as a connection type the next time that you use the New-AzureAutomationConnection cmdlet.

Integration Module Assets

The integration module asset is a PowerShell module that you upload to an Azure Automation account in order to add new activities to an Azure Automation service.

You want to automate the XYZ external service using your runbooks, so you upload the respective PowerShell module as an asset in order to use its activities. While uploading the module, Azure Automation extracts the cmdlets of this module and converts them to activities, as shown in Figure 8-6, so that it can be embedded and used by runbooks later.

9781484206669_Fig08-06.jpg

Figure 8-6. Importing an integration module to an Azure Automation account

By default, the Azure Automation service comes with the following modules:

  • Azure
  • Microsoft.PowerShell.Core
  • Microsoft.PowerShell.Diagnostics
  • Microsoft.PowerShell.Management
  • Microsoft.PowerShell.Security
  • Microsoft.PowerShell.Utility
  • Microsoft.WSMan.Management

The integration module must be compressed with a *.zip file extension and have a maximum size of 40 MB. Also, the module file must contain one of the following files:

  • A Windows PowerShell module (psm1 file).
  • A Windows PowerShell module manifest (psd1 file).
  • An assembly (dll file)

Once the module zip file is ready, upload it to any public storage, such Azure blob, or even FTP. After that, you can use the New-AzureAutomationModule cmdlet to import it.

#Import Integration Module
New-AzureAutomationModule -AutomationAccountName ’DevTestAA’ -Name XYZ -ContentLink http://mylabstorage.blob.core.windows.net/modules/XYZ.zip

You can modify the settings of the module or upload a newer version of the module by using the Set-AzureAutomationModule cmdlet. To upload a newer version, you use the -ContentLinkUri parameter to specify the location of the updated version, and the -ContentLinkVersion parameter to specify the version of that update.

#Updating Integration Module
New-AzureAutomationModule -AutomationAccountName ’DevTestAA’ -Name XYZ -ContentLink http://mylabstorage.blob.core.windows.net/modules/XYZ.zip -ContentLinkVersion "1.1"

Besides this, you have the Get-AzureAutomationModule and Remove-AzureAutomationModule cmdlets.

Schedule Assets

The Automation Schedules asset is used to enable runbooks to automatically run at specific times. It’s like a task scheduler, but for the cloud. The schedule asset could be configured to run runbooks hourly, daily, or one time.

You use the New-AzureAutomationSchedule cmdlet to define a new schedule asset. This cmdlet has three parameter sets, each reflecting a specific schedule type: ByHourly, ByDaily, and ByOneTime. The next examples explain how each parameter set works.

In the first example, you create a one-time schedule asset to run the next day at 6:30 PM.

#Create Automation Schedule - ByOneTime
$StartTime = (Get-Date "18:30:00").AddDays(1)

New-AzureAutomationSchedule -AutomationAccountName DevTestAA -Name OneTimeSchedule -StartTime $StartTime -OneTime

In the second example, you create a recurring schedule asset to run every eight hours, starting the next day at 6:30 PM for a period of one month.

#Create Automation Schedule - ByHourly
$StartTime = (Get-Date "18:30:00")

$EndTime = $StartTime.AddMonths(1)

New-AzureAutomationSchedule -AutomationAccountName DevTestAA -Name HourlySchedule -StartTime $StartTime -ExpiryTime $EndTime -HourInterval 8

In the third example, you create a recurring schedule asset to run every two days, starting the next day at 6:30 PM for a period of one month.

#Create Automation Schedule - ByDaily
$StartTime = (Get-Date "18:30:00")

$EndTime = $StartTime.AddMonths(1)

New-AzureAutomationSchedule -AutomationAccountName DevTestAA -Name DailySchedule -StartTime $StartTime -ExpiryTime $EndTime -DayInterval 2

After creating the schedule asset, you can disable or enable it as needed using the Set-AzureAutomationSchedule cmdlet along with the -IsEnabled parameter.

#Disable Automation Schedule
Set-AzureAutomationSchedule -AutomationAccountName DevTestAA -Name HourlySchedule -IsEnabled $false

Once you create the automation asset, you have to link it to one of the runbooks. To do so, you use the Register-AzureAutomationScheduledRunbook cmdlet to link a specific schedule to a runbook, and the Unregister-AzureAutomationScheduledRunbook cmdlet to unlink it.

#Register Schedule to Runbook
Register-AzureAutomationScheduledRunbook -AutomationAccountName DevTestAA -RunbookName HelloWorldRunbook -ScheduleName HourlySchedule

#Unregister Schedule to Runbook
Unregister-AzureAutomationScheduledRunbook -AutomationAccountName DevTestAA -RunbookName HelloWorldRunbook -ScheduleName HourlySchedule

You can query the list of scheduled runbooks and get information on which runbook is linked to which schedule by using the Get-AzureAutomationScheduledRunbook cmdlet. You can also get the list of schedule assets and their properties using the Get-AzureAutomationSchedule cmdlet. Finally, you can remove any of the schedule assets using the Remove-AzureAutomationSchedule cmdlet.

Summary

This chapter focused on the Azure Automation service. You learned how the automation service is built on top of the PowerShell workflow engine. You also learned about automation runbooks—how they work, how to create them, and how to control them using checkpoints. The chapter also discussed how to use what you know about Azure PowerShell to build runbooks.

The chapter also covered automation assets, including credential, connection, variable, certificate, and schedule, as well as how to create and configure them using PowerShell.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.172.200