1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Azure Functions(PowerShell)でユーザー割り当てManaged Identityを使用してAzure SQL Databaseにセキュア接続

Posted at

はじめに

忘れっぽいので覚え書き
Azure functions(PowerShell)でユーザー割り当てManaged Identityを使ってAzure SQL Databaseに接続する方法が解らなかったので調査して記します

Managed Identityの登録

  • 他に説明されているサイトが多数あるので割愛

Azure Functionsの関数アプリでManaged Identityを有効にする

関数アプリをクリック
プラットフォーム機能 ⇒ ネットワーク ⇒ ID
システム割り当て済み
  オンにして保存
ユーザー割り当て済み
  追加 ⇒ 作成したManaged Identityを登録

Azure Functionsに関数を作成しコードを記述

run.ps1
param($Timer)

$ConStr = "Server=tcp:<サーバURI>,<ポート>; Initial Catalog=<データベース>;"
$resourceURI = "https://database.windows.net/"
$tokenAuthURI = $env:MSI_ENDPOINT + "?resource=$resourceURI&api-version=2017-09-01&clientid=<Managed IdentityのクライアントID>"
$tokenResponse = Invoke-RestMethod -Method Get -Headers @{"Secret"="$env:MSI_SECRET"} -Uri $tokenAuthURI
$accessToken = $tokenResponse.access_token
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = $ConStr
$SqlConnection.AccessToken = $accessToken
$SqlConnection.Open()

Invoke-RestMethodを使ってManaged Identityのトークンを取得し、そのトークンを接続に使用しています。
clientidが無いとシステム割り当て済みのManaged Identityが使用されるので注意が必要(ドはまりしました💦)

※[$env:MSI_ENDPOINT]と[$env:MSI_SECRET]はManaged Identityを有効にすると自動的に環境変数にセットされます。

1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?