新版Azure Automation Account 浅析(二) --- 更新Powershell模块和创建Runbook

前篇我们讲了怎样创建一个自动化账户以及创建时候“Run As Account”选项背后的奥秘。这一篇针对在Azure自动化账户中使用Powershell Runbook的用户讲一下怎样更新powershell 模块。

更新Powershell模块

首先,我们需要先了解一下Azure Automation的系统架构。我们已经知道用户可以通过运行Runbook来实现自动化运维,Runbook运行则是在Azure Automation的沙盒里执行的,沙盒是一组由Azure管理的虚机资源, 我们可以把其当做是Azure的一个PaaS服务。Pass服务自然是需要提供可伸缩高可用多租客隔离的运行环境。显然,我们需要能够为Runbook的运行环境指定所需要的Powershell模块和版本。同时,我们还需要能够升级更新相关的powershell模块。

打开我们前面创建的azpoctest自动化账户,在左边菜单选择“共享的资源”-》“模块”。

非常好,用户可以添加自定义的模块“添加模块”,也可以升级已有模块版本“更新Azure模块”。用户还可以浏览powershell模块库来导入新模块。

仔细研究一下这个页面,目测创建自动化账户时候自带的模块远少于目前Azure已经release的Powershell模块。如果需要运行Runbook来自动化运维Azure资源的话,目前这些模块是远远不够的。

记得光是ARM相关的powershell模块就有几十个,一个个导入的话工作量实在太大,那我们能不能像在powershell 命令行那样,用Install-Module和Import-Module两条命令就可以完成所有AzureRM

相关的模块安装呢?

点击“浏览库”,选择“AzureRM”,点击“导入”。“确定”按钮是灰色的,显然在Azure Portal中不支持有依赖关系的模块集中导入。

记得16年在Global做Automation Account的时候,毫无怨言地填坑,手动一个个把这些模块导入。今天我们换个填坑的法子

接下来我们会写一个Runbook,用脚本来导入AzureRM的Powershell模块

创建Runbook

在自动化账户左边菜单选取“流程自动化”-》“Runbook”-》“添加Runbook“ ,创建一个新的Runbook

创建成功后,浏览器会自动跳转到Runbook编辑器,我们可以开始写Powershell脚本了

首先,因为Runbook是运行在一个多租户的沙盒中,我们需要登录这个自动化账户所在的Azure订阅才能为这个自动化账户导入模块。

登录的代码可以reuse我们在上一篇提到的Runbook模板

$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
    }
}

  

接下来,我们需要在Powershell Gallery里查找导入模块及其版本,如果存在,我们会先去找一个模块实际存储的Blob Storage地址,用New-AzureRmAutomationModule这条命令来导入

如果有Dependency的模块,脚本会首先去导入Dependency模块。下文脚本包含了资源组,自动化账户,模块(AzureRM)和模块版本(最新),考虑到模块和模块版本在不同时期可能有变化,这2部分其实可以做参数化,由Automation的variable来存储。那样脚本就不需要经常修改。

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,

        # if not specified latest version will 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 -UseBasicParsing

    if($SearchResult.Length -and $SearchResult.Length -gt 1) {
        $SearchResult = $SearchResult | Where-Object -FilterScript {
            return $_.properties.title -eq $ModuleName
        }
    }

    if(!$SearchResult) {
        Write-Error "Could not find module ‘$ModuleName‘ on PowerShell Gallery."
    }
    else {
        $ModuleName = $SearchResult.properties.title # get correct casing for the module name
        $PackageDetails = Invoke-RestMethod -Method Get -UseBasicParsing -Uri $SearchResult.id 

        if(!$ModuleVersion) {
            # get latest version
            $ModuleVersion = $PackageDetails.entry.properties.version
        }

        $ModuleContentUrl = "https://www.powershellgallery.com/api/v2/package/$ModuleName/$ModuleVersion"

        # Make sure module dependencies are imported
        $Dependencies = $PackageDetails.entry.properties.dependencies

        if($Dependencies -and $Dependencies.Length -gt 0) {
            $Dependencies = $Dependencies.Split("|")

            # parse depencencies, which are in the format: module1name:module1version:|module2name:module2version:
            $Dependencies | ForEach-Object {

                if($_ -and $_.Length -gt 0) {
                    $Parts = $_.Split(":")
                    $DependencyName = $Parts[0]
                    $DependencyVersion = $Parts[1]

                    # check if we already imported this dependency module during execution of this script
                    if(!$ModulesImported.Contains($DependencyName)) {

                        $AutomationModule = Get-AzureRmAutomationModule `
                            -ResourceGroupName $ResourceGroupName `
                            -AutomationAccountName $AutomationAccountName `
                            -Name $DependencyName `
                            -ErrorAction SilentlyContinue

                        # check if Automation account already contains this dependency module of the right version
                        if((!$AutomationModule) -or $AutomationModule.Version -ne $DependencyVersion) {
                            $DependencyVersion = $DependencyVersion.Split("[")[0].Split("]")[0]
                            Write-Output "Importing dependency module $DependencyName of version $DependencyVersion first."

                            # this dependency 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 -MaximumRedirection 0 -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 -Seconds 10
            $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

编辑完成,点击保存。随后继续点击“测试窗格”。这个功能将测试我们刚完成的Runbook。

在输出窗口会看到后台沙盒运行脚本把AzureRM的dependency模块一个个被导入到自动化账户

最后导入AzureRM的时候运行会报错,这个没有关系。AzureRM模块本身不包含任何功能。所以ARM管理的Powershell命令都在AzureRM的Dependency 模块里。

现在回到模块列表,可以看到AzureRM相关模块已经全部导入了

现在万事具备,下一篇我们可以开始在日常工作中运用Azure自动化账户

原文地址:https://www.cnblogs.com/meowmeow/p/8372207.html

时间: 2024-08-03 00:51:52

新版Azure Automation Account 浅析(二) --- 更新Powershell模块和创建Runbook的相关文章

新版Azure Automation Account 浅析(三) --- 用Runbook管理AAD Application Key

新版Azure Automation Account 浅析(三) --- 用Runbook管理AAD应用的Key 前篇讲过有一个面向公众的Runbook库,社区和微软一直往其中加入新的Runbook,用户可以下载也可以在直接在Azure Portal中导入.这样大家都可以参考全世界范围内工程师怎样利用Runbook来解决工作中的难题,提高生产效率.https://gallery.technet.microsoft.com/scriptcenter/site/search?f[0].Type=Ro

新版Azure Automation Account 浅析(一) --- 创建和Run As Account

去年年底Azure中国的Automation Account悄悄做了升级.新版本不管从功能还是end user experience方面都让人耳目一新.如果说升级前只是一个运行脚本的小工具,升级后的Azure自动化账号则提供用户对Azure环境和非Azure环境的现代化的自动运维服务.简单来讲,如果用户需要: 提高效率,节约成本,实施开发运维自动化 实现自动化配置管理,资产管理,变化跟踪管理 同时管理Windows和Linux 管理Azure,AWS,OnPrem以及任何集成Powershell

利用Azure Automation实现云端自动化运维(1)

Azure Automation是Azure上的一个自动化工作流引擎,基于Powershell,来帮助用户简化,集成和自动化Azure上的运维工作,例如: 实现定时开关虚拟机,节约成本 实现定时创建删除HDInsight cluster执行大数据计算任务 定时备份虚拟机上的数据库 定时归档或者删除无用的日志文件 自动化部署或者更新应用 等等 微软实际上有3个基于runbook的工作流引擎,用来完成不同的自动化工作: Azure automation用来自动化云端Azure环境中的各项任务,也是基

Azure Automation (1) 入门

<Windows Azure Platform 系列文章目录> 通过Azure Automation(自动化),开发人员可以自动完成通常要在云环境中执行的手动.长时间进行.易出错且重复性高的任务.你可以使用 Runbook 来创建.监视.管理和部署 Azure 环境中的资源.所谓的 Runbook,基本上就是指 Windows PowerShell 工作流. Azure Automation概念上类似Windows Service,SQL Server Job. 举个例子,假设我们每天早上9点

Azure Automation (2) 定期删除存储账号中的文件

<Windows Azure Platform 系列文章目录> 本文介绍的是国内由世纪互联运维的Azure China. 本文是对笔者之前的文档Azure Backup (1) 将SQL Server 2012虚拟机中数据库备份到Azure Storage进行的补充. 希望笔者先阅读Azure Automation (1) 入门,对Azure Automation有基本的概念认识. 需求: 在之前的文档中Azure Backup (1) 将SQL Server 2012虚拟机中数据库备份到Az

使用Azure Automation Hybrid管理本地SQL Server备份状态(一)

Azure Automation是一种云解决方案,可通过自动执行任务,为服务器提供所需的状态配置以及配置管理来帮助组织满足其基础结构和安全性要求.默认情况下,创建Azure自动化后,它将允许在Azure中执行脚本.但是某些组织希望能够在其他云和本地环境中自动化任务,那么此时Hybrid Worker工具是提供这种解决方案的关键.利用 Azure Automation Hybrid worker功能,既可以直接在托管角色的计算机上运行 Runbook,也可以对环境中的资源运行 Runbook,从而

免费电子书:微软Azure基础之Azure Automation

(此文章同时发表在本人微信公众号"dotNET每日精华文章") Azure Automation是Azure内置的一项自动化运维基础功能,微软为了让大家更快上手使用这项功能,特意推出了一本免费电子书供大家下载阅读. 随着Azure在各国的不断落地和推广,微软也加大了Azure技术的布道工作.最近微软就开始发布一套名为"微软Azure基础(Microsoft Azure Essentials)"的系列电子书,第一本涉及Azure的基础知识,而第二本就详细讲述了Azur

利用Azure Automation实现云端自动化运维(2)

Azure automation的认证: 用户名和密码 在Azure的automation中使用Powershell可以管理当前订阅的资源,也可以管理不同订阅的资源,那么问题就来了,安全性如何保障呢?Azure的自动化和其他使用或者管理Azure的客户端一样,对任何需要管理的Azure,都需要认证,最基本的有两种认证方式,一种是基于订阅的用户名密码的,一种是基于证书的,本节介绍基于用户名密码. 不建议直接在automation中使用当前管理生产订阅的账号的OrgID和密码,建议单独为automa

利用Azure Automation实现云端自动化运维(3)

Azure automation的认证方式:证书 该种方式是推荐的进行Automation认证的方式,好处在于安全性高,过期时间由自己控制,不好的地方在于大家在Windows上要生成证书比较麻烦,而且必须上传到Azure management和Automation, Automation需要两个文件:.pfx证书用于用户自动化端连接Azure,.cer文件,Azure管理端证书文件,这两个文件必须互相匹配. 对于创建证书,个人比较推荐的办法,或者我喜欢用的方法,就是利用开源的openssl工具,