LoginSignup
0
0

More than 1 year has passed since last update.

Azure環境構築(Key Vault設定〜関数アプリでのシークレット操作)

Last updated at Posted at 2022-11-24

<前提条件>
・KeyVaultは作成済み

手順1:Azure CLIコマンドでAzureにログイン

az login

手順2:Azure CLIコマンドでシークレットキーを作成する

az keyvault secret set --vault-name "KeyVaultのコンテナ名" --name "シークレットキー名" --value "シークレット値"

手順3:Azure CLIコマンドで作成したシークレットキーを表示

az keyvault secret list --vault-name "KeyVaultのコンテナ名"
# 出力結果 
[
  {
    "attributes": {
      "created": "〇〇",
      "enabled": 〇〇,
      "expires": 〇〇,
      "notBefore": 〇〇,
      "recoveryLevel": "〇〇",
      "updated": "〇〇"
    },
    "contentType": 〇〇,
    "id": "〇〇",          # idをコピーして控えておく
    "managed": 〇〇,
    "name": "〇〇",
    "tags": {
      "〇〇": "〇〇"
    }
  }
]

手順4:AzureポータルでAzure Functionsにアクセス権を追加する(初回のみ実施)

スクリーンショット 2022-11-24 10.46.31.png

参照:https://yotiky.hatenablog.com/entry/azurefunctions_keyvault

手順5:Azure Functionsのアプリケーション設定で、シークレット識別子を以下の書式で値として設定する。

※名前は何でもOK

@Microsoft.KeyVault(SecretUri=手順3で控えたid)

保存後、作成したアプリケーションを設定開き、状態が "Resolved" になっていることを確認する

手順6:Azure Functions(Python)のrequirements.txtに書き内容を追加(モジュール追加)(初回のみ実施)

※x.x.xはバージョンで任意のバージョンを指定

azure-keyvault==x.x.x
azure-identity==x.x.x

手順7:Azure Functions(Python)でシークレットキーを取得・表示

import json
import logging

import azure.functions as func
from azure.keyvault.secrets import SecretClient
from azure.identity import DefaultAzureCredential

def main(event: func.EventGridEvent):
  keyVaultName = "xxxxx"  # キーコンテナ名
  KVUri = f"https://{keyVaultName}.vault.azure.net"

  credential = DefaultAzureCredential() # 資格情報の取得
  client = SecretClient(vault_url=KVUri, credential=credential)

  secretName = "yyyyy"  # シークレット名
  retrieved_secret = client.get_secret(secretName)
  logging.info(f"Your secret is : '{retrieved_secret.value}'.")

参照 

■Key Vaultの作成方法

■Key Vaultの料金

■Key VaultとAzure Functionsの連携

■Key VaultのシークレットキーをAzure Functions上から取得する

■Key Vault周りのモジュール追加

■Azure Functionsで環境変数を別ファイルから取得する

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