🌊

サクッとコマンド実行させたい?それならデプロイスクリプトだよ

2024/12/10に公開

前置き

どうも風邪っぴきの生き別れの兄です。乾燥してる毎日ですね。
本来ならAKSで遊ぶ第二回をするつもりでしたがダウン気味なので箸休めをば。
Azure PoC部 Advent Calendar 2024の9日目の記事です。

間違っていたら優しくマサカリを手渡しでください。

はじめに

ちょっとスクリプト動かしたいけど、ContainerInstanceするほどでもないし、、、みたいなシチュエーションにありよりありなので紹介しようかなと。

デプロイスクリプトについて

deploymentScripts リソースは PowerShell または Bash スクリプトであり、テンプレート配置の一部として Docker コンテナーで実行されます。 既定のコンテナー イメージでは、Azure CLI または Azure PowerShell のいずれかを使用できます。

配置スクリプトとは何ですか?

要はPowerShell / BashスクリプトをARMテンプレートまたはBicepで定義してDockerコンテナ(ContainerInstance)上で実行できるというものです。

デプロイ スクリプト サービスでは、スクリプトの実行とトラブルシューティングのために、ストレージ アカウントとコンテナー インスタンスという 2 つのサポート リソースが必要になります。

ARM テンプレートでデプロイ スクリプトを使用する

課金はContainerInstanceとStorageAccount分かかります。実行時間や利用するファイルの容量に課金額が左右されるということなので注意です。

やってみよう

環境に合わせてよくあるサブスクリプションを指定とかしてください。

  1. リソースグループとマネージドIDをシュっと作る
RESOURCE_GROUP_NAME="myResourceGroup"
LOCATION="japaneast"

az group create --name $RESOURCE_GROUP_NAME --location $LOCATION

IDENTITY_NAME="myManagedIdentity"
az identity create --name $IDENTITY_NAME --resource-group $RESOURCE_GROUP_NAME

IDENTITY_ID=$(az identity show --name $IDENTITY_NAME --resource-group $RESOURCE_GROUP_NAME --query 'id' -o tsv)
echo "Managed Identity Resource ID: $IDENTITY_ID"
  1. テンプレートスペックでデプロイスクリプトをサクッと実行する
vim deploymentScript.json
{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.1",
  "apiProfile": "",
  "parameters": {
    "userAssignedIdentityId": {
      "type": "string",
      "metadata": {
        "description": "ユーザーマネージドIDのリソースID"
      }
    }
  },
  "variables": {},
  "functions": [],
  "resources": [
    {
      "type": "Microsoft.Resources/deploymentScripts",
      "apiVersion": "2020-10-01",
      "name": "myFirstDeploymentScript",
      "location": "[resourceGroup().location]",
      "kind": "AzurePowerShell",
      "identity": {
        "type": "UserAssigned",
        "userAssignedIdentities": {
          "[parameters('userAssignedIdentityId')]": {}
        }
      },
      "properties": {
        "azPowerShellVersion": "3.0",
        "scriptContent": "
            $output = 'Hello Learner!'
            Write-Output $output
            $DeploymentScriptOutputs = @{}
            $DeploymentScriptOutputs['text'] = $output
        ",
        "retentionInterval": "P1D"
      }
    }
  ],
  "outputs": {
    "scriptResult": {
      "type": "string",
      "value": "[reference('myFirstDeploymentScript').outputs.text]"
    }
  }
}
az deployment group create --resource-group $RESOURCE_GROUP_NAME --template-file ./deploymentScript.json --parameters userAssignedIdentityId=$IDENTITY_ID

うまくいきましたね~。

  1. せっかくなのでサブスクリプションレベルの権限付与して新規リソースグループでも作ってみましょう。
SUBSCRIPTION_ID=$(az account show --query 'id' -o tsv)
IDENTITY_OBJECT_ID=$(az identity show --name $IDENTITY_NAME --resource-group $RESOURCE_GROUP_NAME --query 'principalId' -o tsv)
echo "Managed Identity Object ID: $IDENTITY_OBJECT_ID"

az role assignment create --assignee-object-id $IDENTITY_OBJECT_ID --role "Contributor" --scope /subscriptions/$SUBSCRIPTION_ID --assignee-principal-type ServicePrincipal

vim deploymentScript2.json
{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "userAssignedIdentityId": {
      "type": "string",
      "metadata": {
        "description": "ユーザーマネージドIDのリソースID"
      }
    },
    "newResourceGroupName": {
      "type": "string",
      "metadata": {
        "description": "新しいリソースグループの名前"
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "eastus",
      "metadata": {
        "description": "リソースグループの場所"
      }
    }
  },
  "resources": [
    {
      "type": "Microsoft.Resources/deploymentScripts",
      "apiVersion": "2020-10-01",
      "name": "createResourceGroupScript",
      "location": "[parameters('location')]",
      "kind": "AzurePowerShell",
      "identity": {
        "type": "UserAssigned",
        "userAssignedIdentities": {
          "[parameters('userAssignedIdentityId')]": {}
        }
      },
      "properties": {
        "azPowerShellVersion": "3.0",
        "scriptContent": "
            param(
                [string]$newResourceGroupName,
                [string]$location
            )
            New-AzResourceGroup -Name $newResourceGroupName -Location $location
        ",
        "arguments": "[concat('-newResourceGroupName ', parameters('newResourceGroupName'), ' -location ', parameters('location'))]",
        "retentionInterval": "P1D"
      }
    }
  ]
}
NEW_RESOURCE_GROUP_NAME="newResourceGroup"

az deployment group create  --resource-group $RESOURCE_GROUP_NAME --template-file ./deploymentScript2.json --parameters userAssignedIdentityId=$IDENTITY_ID newResourceGroupName=$NEW_RESOURCE_GROUP_NAME

うまくいきましたね!
マネージドIDの権限を使ってリソースグループができることも確認できました。

終わりに

こいつのちょっといい点は既存のPowershellスクリプトを呼び出せること、マネージドIDを使えるところですかね。本格的にAzureを使おうとすると適切な方法はあると思いますがシュッと使いたいのであれば手段として持っておくとお得かもですね?

ど~しても薄味なので次はもうちょい濃い味のPoCにしたいと思います。

Discussion