A brief analysis of the new Azure Automation account (ii)---Updating the PowerShell module and creating a Runbook

Source: Internet
Author: User

We talked about how to create an automated account and the secret behind the "Run as account" option when you created it. This article tells you how to update the PowerShell module for users who use PowerShell Runbooks in the Azure Automation account.

Updating the PowerShell module

First, we need to look at the system architecture of Azure automation first. We already know that users can run runbooks to automate operations, and Runbooks run in Azure Automation sandbox, a set of virtual machine resources managed by Azure that we can think of as a PAAs service for Azure. The pass service is naturally required to provide a scalable, highly available, multi-tenant isolated operating environment. Obviously, we need to be able to specify the required PowerShell modules and versions for the Runbook's running environment. At the same time, we also need to be able to upgrade the relevant PowerShell modules.

Open the Azpoctest Automation account we created earlier and select "Shared Resources"-"module" on the left menu.

Very well, users can add custom module "Add Module" or upgrade existing module version "Update Azure module". Users can also browse the PowerShell module library to import new modules.

Take a closer look at this page and visually create an automated account with a module that is much smaller than the current PowerShell module that Azure has already release. If you need to run Runbooks to automate operational Azure resources, these modules are far from enough.

Remember that the only arm related PowerShell module Dozens of, one by one the workload is too large, then we can be like in the PowerShell command line, With Install-module and import-module two commands you can complete all azurerm

What about the module installation?

Click "Browse Library", select "Azurerm" and click "Import". The OK button is grayed out, and it is clear that a dependency-dependent module is not supported in the Azure portal in a centralized import.

Remember 16 when the global do automation account, without complaint pits, manually put these modules into. Today we're going to change a pits.

Next we'll write a runbook with a script to import the Azurerm PowerShell module

Create a Runbook

In the left menu of the Automation account, choose Process Automation-"Runbook"-"Add Runbook" to create a new Runbook

Once created, the browser will automatically jump to the Runbook editor and we can start writing PowerShell scripts.

First, because the Runbook is running in a multi-tenant sandbox, we need to log in to the Azure subscription where this automation account is located to import modules for this automation account.

The login code can reuse the Runbook template we mentioned in the previous article

$connectionName = "Azurerunasconnection" try{    # Get the connection "Azurerunasconnection"    $ Serviceprincipalconnection=get-automationconnection-name $connectionName    "Logging in to Azure ..."    Add-azurermaccount '        -serviceprincipal '        -tenantid $servicePrincipalConnection. TenantId '        - ApplicationID $servicePrincipalConnection. ApplicationID '        -certificatethumbprint $ Serviceprincipalconnection.certificatethumbprint '        -environmentname azurechinacloud}catch {    if (!$ Serviceprincipalconnection)    {        $ErrorMessage = "Connection $connectionName not found."        Throw $ErrorMessage    } else{        write-error-message $_. Exception        throw $_. Exception    }}

  

Next, we need to find the import module and its version in PowerShell Gallery, and if so, we will first find a BLOB storage address that the module actually stores, and use the New-azurermautomationmodule command to import

If there are dependency modules, the script will first import the dependency module. The following script contains resource groups, automation accounts, modules (Azurerm), and module versions (up-to-date), taking into account that the module and module versions may vary over time, and these 2 parts can actually be parameterized and stored by Automation's variable. That way, the script doesn't need to be modified frequently.

param ([Parameter (Mandatory=$true)] [String] $ResourceGroupName, [Parameter (Mandatory=$true)] [String] $AutomationAccountName, [Parameter (Mandatory=$true)] [String] $ModuleName, [Parameter (Mandatory=$false)] [String] $ModuleVersion) $ModulesImported=@ () function _doimport {param ([Parameter (Mandatory=$true)] [String] $ResourceGroupName, [Parameter (Mandatory=$true)] [String] $AutomationAccountName, [Parameter (Mandatory=$true)] [String] $ModuleName, #ifNot specified latest version would be imported [Parameter (Mandatory=$false)] [String] $ModuleVersion) $Url="https://www.powershellgallery.com/api/v2/Search ()? ' $filter =islatestversion&searchterm=%27$modulename% 27&targetframework=%27%27&includeprerelease=false& ' $skip =0& ' $top =40"$SearchResult= Invoke-restmethod-method Get-uri $Url-usebasicparsingif($SearchResult. Length-and $SearchResult. length-gt1) {$SearchResult= $SearchResult | Where-object-Filterscript {return$_.properties.title-eq $ModuleName}} if(!$SearchResult) {Write-error"Could not the Find module ' $ModuleName ' on PowerShell Gallery."    }    Else{$ModuleName= $SearchResult. Properties.title #GetCorrect casing forThe module name $PackageDetails= Invoke-restmethod-method Get-usebasicparsing-Uri $SearchResult. IDif(!$ModuleVersion) {            # GetLatest Version $ModuleVersion=$PackageDetails. entry.properties.version} $ModuleContentUrl="https://www.powershellgallery.com/api/v2/package/$ModuleName/$ModuleVersion"# Make sure module dependencies is imported $Dependencies=$PackageDetails. Entry.properties.dependenciesif($Dependencies-and $Dependencies. length-gt0) {$Dependencies= $Dependencies. Split ("|") # parse Depencencies, which isinchThe format:module1name:module1version:|module2name:module2version: $Dependencies| foreach-Object {if($_-and $_. Length-gt0) {$Parts= $_. Split (":") $DependencyName= $Parts [0] $DependencyVersion= $Parts [1] # CheckifWe already imported ThisDependency module during execution of ThisScriptif(!$ModulesImported. Contains ($DependencyName)) {$AutomationModule= get-Azurermautomationmodule '-resourcegroupname $ResourceGroupName '-automationaccountname $AutomationAccountName '-Name $DependencyName '-erroraction silentlycontinue # CheckifAutomation account already contains ThisDependency Module of the right versionif((! $AutomationModule)-or $AutomationModule. Version-NE $DependencyVersion) {$DependencyVersion= $DependencyVersion. Split ("[")[0]. Split ("]")[0] Write-output"Importing Dependency Module $DependencyName of version $DependencyVersion first."                                                        #  ThisDependency module has not been imported, import it first _doimport ' -resourcegroupname $ResourceGroupName '-automationaccountname $AutomationAccountName '-modulename $DependencyName '-moduleversion $DependencyVersion $ModulesImported+=$DependencyName}} }}} # Find the actual blob storage location of the module Do{$ACTUALURL=$MODULECONTENTURL $ModuleContentUrl= (Invoke-webrequest-uri $ModuleContentUrl-maximumredirection0-usebasicparsing-erroraction Ignore). Headers.location} while(! $ModuleContentUrl. Contains (". Nupkg")) $ActualUrl=$MODULECONTENTURL Write-output"importing $ModuleName module of version $ModuleVersion from $ACTUALURL to Automation"$AutomationModule= new-Azurermautomationmodule '-resourcegroupname $ResourceGroupName '-automationaccountname $AutomationAccountName '-Name $ModuleName '-ContentLink $ActualUrl while($AutomationModule. Provisioningstate-ne"Created"-and $AutomationModule. Provisioningstate-ne"succeeded"-and $AutomationModule. Provisioningstate-ne"Failed") {Write-verbose-message"Polling for module import completion"Start-sleep-secondsTen$AutomationModule= $AutomationModule | get-Azurermautomationmodule}if($AutomationModule. Provisioningstate-eq"Failed") {Write-error"importing $ModuleName module to Automation failed."        }        Else{Write-output"importing $ModuleName module to Automation succeeded."}}}_doimport '-resourcegroupname"Chdaiac" `    -automationaccountname"acpoctest" `    -modulename"Azurerm" `    -moduleversion $ModuleVersion

Edit done, click Save. Then continue to click on "Test Pane". This feature will test the runbook we just completed.

In the Output window you will see the background sandbox run script to import the Azurerm dependency module into the Automation account

When the last import Azurerm run will error, this does not matter. The Azurerm module itself does not contain any functionality. So the PowerShell commands managed by ARM are in the Azurerm dependency module.

Now back to the module list, you can see that the Azurerm related modules have all been imported

Now everything is available, next we can start using Azure Automation account in our daily work

A brief analysis of the new Azure Automation account (ii)---Updating the PowerShell module and creating a Runbook

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.