Azure Automation実行アカウントが2023/9/30に廃止され、マネージドIDへの移行が必要になります。
これまで実行アカウントの証明書期限切れチェックが必要だったのでマネージドIDへの移行は嬉しいものの、既存Runbookに影響を及ぼす場合があります。
公式手順でやり方は書いてあるものの、エラーになったり細かい手順を残したかったのでまとめます。
変更するRunbook
- かなり前に使っていたVM自動起動/停止のRunbookが実行アカウントを利用していたので、これをマネージドIDに変更することにします。
Param(
[string]$Action,
[string]$VMName,
[string]$ResourceGroupName
)
$Conn = Get-AutomationConnection -Name AzureRunAsConnection
Add-AzureRMAccount -ServicePrincipal -Tenant $Conn.TenantID -ApplicationID $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint
if ($Action -eq "stop")
{
Write-Output "Stopping VM"
Stop-AzureRmVM -ResourceGroupName $ResourceGroupName -Name $VMName -Force
}
elseif ($Action -eq "start")
{
Write-Output "Starting VM"
Start-AzureRmVM -ResourceGroupName $ResourceGroupName -Name $VMName
}
else
{
throw "Please specify start or stop for the parameter"
}
マネージドID設定
-
システム割り当てIDもしくはユーザー割り当てIDを有効にします。システム割り当てとユーザー割り当ての違いは AzureユーザーマネージドIDを使ったVM→Blobへのアップロード に以前まとめてます。
RBAC設定
Runbookエクスポート/インポート
-
公式手順でもいきなりRunbookを修正するのではなく一度コピーしてからやってね。と記載があります。Runbookのコピー機能はないので一度エクスポートしてからインポートして新たなRunbookを作成します。
-
対象のRunnbookを選択し[エクスポート]を選択します。PowerShellスクリプトがローカルにダウンロードされたことを確認します。
Runbook修正
- 先ほどインポートした新しいRunbookを修正します。
Param(
[string]$Action,
[string]$VMName,
[string]$ResourceGroupName
)
# $Conn = Get-AutomationConnection -Name AzureRunAsConnection
# Add-AzureRMAccount -ServicePrincipal -Tenant $Conn.TenantID -ApplicationID $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint
try
{
"Logging in to Azure..."
Connect-AzAccount -Identity
}
catch {
Write-Error -Message $_.Exception
throw $_.Exception
}
if ($Action -eq "stop")
{
Write-Output "Stopping VM"
Stop-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName -Force
}
elseif ($Action -eq "start")
{
Write-Output "Starting VM"
Start-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName
}
else
{
throw "Please specify start or stop for the parameter"
}
テスト
- 修正したRunbookを実際に動かしてみます。私の環境では以下のエラーが出ました。
The term 'Connect-AzAccount' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
- Connect-AzAccountコマンドがないよっていうエラーですね。私の環境ではずっとAutomationモジュールの更新をしていなかったので出たエラーです。
AZモジュール更新(必要なら)
-
ここで注意しないといけないのが、モジュールの更新をすると、このAutomationアカウントに登録されているRunbook全体で古いコマンドが使えなくなるということです。私の環境ではStop-AzureRmVMコマンドを使っていましたが、Stop-AzVMコマンドに変更しました。
運用Runbookに適用
- テストしてみて問題なければ運用Runbookにも同じ変更を適用して完了です。
変更対象
- 全てのRunbookが対象というわけではなく、あくまでも実行アカウントに依存したコマンドを使ったRunbookのみが変更対象となります。今回の例だとこの部分です。
$Conn = Get-AutomationConnection -Name AzureRunAsConnection
Add-AzureRMAccount -ServicePrincipal -Tenant $Conn.TenantID -ApplicationID $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint
以上です。