先ほどのログイン自動化に続いて、Azure PowerShell 4.4.0 以降で使える便利な TIPS をもう一つ。
各コマンドレットに AzureRmContext というオプションが追加されて、PSJob 内に認証情報を渡せるようになっています。
Start-Job {
# ArgumentList で渡した Context を引数 ($ctx) として使用して、
param ($ctx)
# 並列実行したいコマンドを $ctx の認証情報で実行
Get-AzureRMVM -AzureRmContext $ctx
} -ArgumentList (Get-AzureRmContext)
# ジョブの一覧を表示
Get-Job
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
1 Job1 BackgroundJob Completed True localhost ...
# ジョブの実行結果を表示 (↑で State が Running の場合は待つべし)
Receive-Job 1 # Job ID
ResourceGroupName Name Location VmSize OsType NIC ProvisioningState Zone
----------------- ---- -------- ------ ------ --- ----------------- ----
SHUDA1215 shuda1215a japaneast Succeeded
SHUDA1215 shuda1215b japaneast Succeeded
SHUDA1221 shuda1221a japaneast Succeeded
SHUDA1221 shuda1221b japaneast Succeeded
これの何がうれしいかというと、PSJob を使いこなすことで時間のかかるコマンドをパラレル実行できるようになるので、作成に時間のかかるリソース (Gateway とか) を複数作るときや、サブスクリプションをまたいで並列処理をしたいときに大変はかどります。
例えば、こんな感じでサブスクリプションを切り替えて、全サブスクリプションの VM 一覧を取得したりとか。
Get-AzureRmSubscription | foreach{
# サブスクリプションを切り替えて
Select-AzureRmSubscription -SubscriptionId $_.SubscriptionID
# ジョブを実行
Start-Job{
param($ctx)
Get-AzureRmVM -AzureRmContext $ctx
} -ArgumentList (Get-AzureRmContext)
}
# 各サブスクリプションに対してジョブが実行される
Get-Job
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
1 Job1 BackgroundJob Completed True localhost ...
3 Job3 BackgroundJob Completed True localhost ...
5 Job5 BackgroundJob Completed True localhost ...
7 Job7 BackgroundJob Completed True localhost ...
9 Job9 BackgroundJob Completed True localhost ..
ということで、去年までは「口を動かす前に、手を動かせ」が口癖でしたが、今年は手を動かす手間さえも省きたいと思います。









