LoginSignup
2
1

More than 3 years have passed since last update.

Azure Functions for PowerShell をつかって Azure の操作をやってみた

Posted at

Windows Virtual Desktop の制御を Power Apps からやろうとしているので、Azure の操作を PowerShell で操作可能な Azure Automation を使ったのですが、実運用には全く耐えられないことがわかりました。
そもそも、Azure Automation はバッチ処理みたいな自動運用のためのサービスなんですよね。
なので、Azure Automation に実行要求を投げても、すぐには実行されずキュー待ちとなり、その後キューが実行されて初めて処理が実行されるのです。
早いときはそこそこ早いのですが(それでも2分ぐらい待つ)、遅いときは4~5分待つこともザラ。
ユーザー操作に対してのレスポンスがこれだと、正直使い物にならないですよね。

ですので、要求後即時実行可能で、PowerShell ができる Azure Functions for PowerShell を使ってみることにしました。

Azure Function for PowerShellを作る

image.png

ここで、ランタイムスタックを PowerShell Core に指定します。

image.png

あとは、Azure Functions を普通に作るのと一緒です。

image.png

関数の作成

関数の作成も Python などと同じです。
VS Code を環境にすることもできますし
ポータル上で直接開発することもできます

image.png

テンプレートも豊富に存在します。

image.png

仮に HTTP trigger を指定すると、以下のように自動生成されます。

run.ps1
using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)

# Write to the Azure Functions log stream.
Write-Host "PowerShell HTTP trigger function processed a request."

# Interact with query parameters or the body of the request.
$name = $Request.Query.Name
if (-not $name) {
    $name = $Request.Body.Name
}

$body = "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."

if ($name) {
    $body = "Hello, $name. This HTTP triggered function executed successfully."
}

# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    StatusCode = [HttpStatusCode]::OK
    Body = $body
})

Azure の認証

PowerShell で各種処理を行いたいときには、まずは Azure にて認証をしてあげる必要があります。

Azure Funtions には、マネージドIDを使って Azure RBAC を使用した認証を行うことができます。

デフォルトはオフになっていますので、こちらを有効化します。

image.png

あとは、操作したいリソースに対して、Azure ロールを割り当てることで、実行時に自動認証され、アクセス権が付与されます。

あとは・・・

自分の好きなように PowerShell を書いていただくことで、Azure の操作を自由に行うことができるようになります。

CI/CDももちろんできる!

デプロイセンターから様々なリポジトリを選択して、CI/CDを作ることもできます!

image.png

もちろん Azure Devops の Pipeline から、リポジトリの更新をトリガーとして、自動的にビルドされ、デプロイが完了します!

image.png

image.png

おまけ

Windows Virtual Desktop を Power Apps を使って操作することができます!
これも Azure Functions for PowerShell のおかげです。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1