クラウド上のリソースはIaCしろ。という風潮がある。僕にとってそれは大変面倒くさいことなのでそんなことはせずGUIでリソースを作ったり変更したりする場面はとてもよくある。いや、複数の環境を作るならともかく、とりあえず遊びたいだけだったりする場合にはそちらが主流だ。
とは言え、どういう操作をしたのかの履歴は見たいという欲求もある。
Microsoft Azure上のリソースはARMテンプレートを使って管理できる。そして、既存のリソースのテンプレートをエクスポートする機能がある。
じゃぁ、エクスポートしたテンプレートの履歴を取っておけば最低限変更を見られるようになるのでは? と思ったので試してみた。
ワークフロー例
最近はGitHub Actionsを試していたので、GitHub ActionsでGitHubのリポジトリに履歴を取るようにしてみた。
こんな感じのActionsのワークフローを配置する。
arm-template-history/monitor-test-group.yml at master · 7474/arm-template-history · GitHub
# 契機は適当に設定するといいと思う。外部のイベントをフックするのは面倒くさいので…… on: [push] #on: # schedule: # - cron: '05 13 * * *' jobs: build-and-deploy: runs-on: ubuntu-latest steps: # エクスポートはAzure CLIで行うのでログインする。 - name: Azure Login uses: azure/login@v1 with: creds: ${{ secrets.AZURE_CREDENTIALS }} # 自リポジトリに履歴を取る。masterブランチだ。 - name: Checkout uses: actions/checkout@v1 - run: git checkout master # エクスポートコマンドを実行する。 # 僕のAzureサブスクリプションには `test` というリソースグループが存在するのでこの指定は本物だ。 - name: Export ARM Template uses: azure/CLI@v1 with: azcliversion: 2.0.72 inlineScript: | az group export --name test > test.json.txt # 差分があるかチェックして、あればコミットしてプッシュする。 - name: Push ARM template to GitHub run: | if [ -n "$(git status --porcelain)" ]; then git config --global user.name "koudenpa" git config --global user.email "koudenpa@hotmail.com" git add test.json.txt git commit -m 'Update test group ARM template.' git remote set-url origin https://7474:${GITHUB_TOKEN}@github.com/7474/arm-template-history.git git push else echo "No change" fi env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
本来は変数になるべきところは適当に読み替えて欲しい。
秘密な環境変数のうち GITHUB_TOKEN
はGitHub Actionsが勝手に設定してくれるが AZURE_CREDENTIALS
は手動でSettings->Secretsから設定する。
案内は GitHub - Azure/login: Connect to Azure にある。
テンプレートのエクスポートに必要な権限を与えた認証情報を作成する。面倒くさいので例示通り強い権限で作成した。
$ az ad sp create-for-rbac --name "GitHubActions-arm-template-history" --role contributor --scopes /subscriptions/guid --sdk-auth Retrying role assignment creation: 1/36 Retrying role assignment creation: 2/36 Retrying role assignment creation: 3/36 Retrying role assignment creation: 4/36 { "clientId": "hoge", "clientSecret": "fuga", "subscriptionId": "guid ", "tenantId": "hige", "activeDirectoryEndpointUrl": "https://login.microsoftonline.com", "resourceManagerEndpointUrl": "https://management.azure.com/", "activeDirectoryGraphResourceId": "https://graph.windows.net/", "sqlManagementEndpointUrl": "https://management.core.windows.net:8443/", "galleryEndpointUrl": "https://gallery.azure.com/", "managementEndpointUrl": "https://management.core.windows.net/" }
実例
丁度リソースグループ内に完全なゴミがあったので削除してみた。
その後、とりあえず手動で履歴取り用のワークフローを実行した。
Hook action. · 7474/arm-template-history@01bb5f1 · GitHub
Update test group ARM template. · 7474/arm-template-history@cece868 · GitHub
最低限のリソース変更の履歴にはなるのでは?
GitHub Actionsの整備済みアクションは非常に便利。とてもスムーズにAzureのリソースを操作できる。
余談
AZURE_CREDENTIALS
を作るときにゴミクレデンシャルを作ってしまった。自分はGUIが好きなのでAzure Portalから消した。Azure Portal最高!
Azureのアドベントカレンダーネタにでもなるかな、と思って見てみたら埋まっていた。そういうこともある。