【问题标题】:How to create Azure Automation runbook that will start VM and then execute (local or Azure) script on the VM?如何创建将启动 VM 并在 VM 上执行(本地或 Azure)脚本的 Azure 自动化运行手册?
【发布时间】:2020-12-31 16:23:42
【问题描述】:

我不想创建将启动特定(或参数控制)VM,然后在 VM 上运行脚本(本地或从 blob 存储)的 Runbook。

我检查了很多文档,但到目前为止还没有成功。

到目前为止我在同一个资源组下得到了什么:

  1. 已创建虚拟机

  2. 已创建自动化帐户,包括。运行方式帐号

  3. Azure 自动化解决方案 (OMS)

  4. 自动化帐户下的凭据(我自己的帐户)

  5. 使用了几个 Runbook 库和其他使用函数的代码示例,例如 启动-AzureVM ... 调用命令 ...

你们当中有没有人可以根据所使用的方法对需要什么的指南进行采样?

VM 启动部分正在工作,但我无法让登录 + 执行脚本工作!

我不是一个熟练的开发人员,我什至对在 Azure 中的脚本语言之间进行选择感到怀疑。

我们将不胜感激。

谢谢, 汤姆

调用命令

调用-AzureRmVMRunCommand

设置-AzureRmVMCustomScriptExtension

New-SSHSession + Invoke-SSHCommand

代码取自例如画廊“Connect-AzureVM”

【问题讨论】:

  • 关于在虚拟机上运行脚本(本地或从blob存储),本地是否意味着脚本文件在虚拟机上?
  • 是的,要么存储在 VM 上,要么存储在容器中。主要目标是运行让脚本在成功登录后运行:-)
  • 以下脚本运行并返回错误:Invoke-AzureRmVMRunCommand:找不到文件“C:\home\tdj\test.sh”。在 line:6 char:1 + Invoke-AzureRmVMRunCommand -ResourceGroupName 'SAPBASIS' -Name 'sles1 ...
  • PS 脚本:$conn = Get-AutomationConnection -Name AzureRunAsConnection Login-AzureRmAccount -ServicePrincipal -Tenant $conn.TenantID ` -ApplicationId $conn.ApplicationID -CertificateThumbprint $conn.CertificateThumbprint Start-AzureRmVM -Name ' VM' -ResourceGroupName 'RG' Invoke-AzureRmVMRunCommand -ResourceGroupName 'RG' -Name 'VM' -CommandId 'RunPowerShellScript' -ScriptPath '/home/user/test.sh' -Parameter @{"arg1" = "var1";" arg2" = "var2"}
  • 你可能误解了Invoke-AzureRmVMRunCommand的参数-ScriptPath,根据我的测试,-ScriptPath是你启动命令的路径,而不是在远程机器上。

标签: azure azure-automation


【解决方案1】:

参数-ScriptPath of Invoke-AzureRmVMRunCommand不应指向远程计算机中的路径,而应指向Runbook环境的本地路径。

示例代码如下(在远程虚拟机中创建一个名为 atestfile.txt 的文件):

$ServicePrincipalConnection = Get-AutomationConnection -Name 'AzureRunAsConnection'

Add-AzureRmAccount `
    -ServicePrincipal `
    -TenantId $ServicePrincipalConnection.TenantId `
    -ApplicationId $ServicePrincipalConnection.ApplicationId `
    -CertificateThumbprint $ServicePrincipalConnection.CertificateThumbprint

#define resource group and vm name
$resourceGroup ="xxx"
$VmName ="xxx"

#define the scripts in $scriptblock, and add the content of $scriptblock to aa.ps1 in current directory of runbook
write-output "create test file"
$scriptblock = "New-Item -path c:\test -name atestfile.txt -itemtype file -force"
Out-File -FilePath aa.ps1 -InputObject $scriptblock

#Note that the -ScriptPath should not point to the remote path(in remote vm), it should point to the local path where you execute the command Invoke-AzureRmVMRunCommand
Invoke-AzureRmVMRunCommand -ResourceGroupName $resourceGroup -Name $VmName -CommandId 'RunPowerShellScript' -ScriptPath aa.ps1

#after execution, you can remove the file
Remove-Item -Path aa.ps1

write-output "done now"

测试结果:

【讨论】:

    猜你喜欢
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    相关资源
    最近更新 更多