クイックスタート: Ansible の Azure サービス プリンシパルを作成する

このクイックスタートでは、AzureCLI または Azure PowerShell を使用して Azure サービス プリンシパルを作成し、Ansible から Azure に対して認証します。

この記事では、次のことについて説明します。

  • Azure CLI を使用して Azure サービス プリンシパルを作成する
  • Azure PowerShell を使用して Azure サービス プリンシパルを作成する
  • Azure サービス プリンシパルにロールを割り当てる
  • サービス プリンシパルからキー情報を取得する
  • Ansible がサービス プリンシパルの値を取得できるように環境変数を設定する
  • サービス プリンシパルをテストする

前提条件

  • Azure サブスクリプション:Azure サブスクリプションをお持ちでない場合は、開始する前に無料アカウントを作成してください。

Azure サービス プリンシパルを作成する

Azure サービス プリンシパルでは、Ansible を使用して Azure リソースを管理するための専用アカウントが提供されます。

次のコードを実行して、Azure サービス プリンシパルを作成します。

az ad sp create-for-rbac --name ansible \
            --role Contributor \
            --scopes /subscriptions/<subscription_id>

Note

出力からのパスワードを安全な場所に格納します。

Azure サービス プリンシパルにロールを割り当てる

既定では、サービス プリンシパルには、Azure のリソースを管理するために必要なアクセス権はありません。

次のコマンドを実行して、サービス プリンシパルに共同作成者ロールを割り当てます。

az role assignment create --assignee <appID> \
    --role Contributor \
    --scope /subscriptions/<subscription_id>

<appID> を、az ad sp create-for-rbac コマンドの出力から提供された値に置き換えます。

Note

セキュリティを強化するために、ロールの割り当てのスコープをサブスクリプションではなくリソース グループに変更します。

Azure サービス プリンシパル情報を取得する

サービス プリンシパルを使用して Azure に対して認証するには、次の情報が必要です。

  • SubscriptionID
  • サービス プリンシパルのアプリケーション ID
  • サービス プリンシパルのパスワード
  • TenantID

次のコマンドを実行して、サービス プリンシパルの情報を取得します。

az account show --query '{tenantId:tenantId,subscriptionid:id}';

az ad sp list --display-name ansible --query '{clientId:[0].appId}'

サービス プリンシパルを使用して Azure に対して認証する

次のコマンドを実行して、Ansible サーバーで必要な環境変数を設定します。

export AZURE_SUBSCRIPTION_ID=<SubscriptionID>
export AZURE_CLIENT_ID=<ApplicationId>
export AZURE_SECRET=<Password>
export AZURE_TENANT=<TenantID>

<SubscriptionID><ApplicationId><Password><TenantID> をサービス プリンシパル アカウントの値に置き換えます。

サービス プリンシパルのアクセス許可をテストする

次のコマンドを実行して、新しい Azure リソース グループを作成します。

ansible localhost -m azure_rm_resourcegroup -a "name=<resource_group_name> location=<resource_group_location>"

<resource_group_name><resource_group_location> を新しいリソース グループの値に置き換えます。

[WARNING]: No inventory was parsed, only implicit localhost is available
localhost | CHANGED => {
    "changed": true,
    "contains_resources": false,
    "state": {
        "id": "/subscriptions/<subscriptionID>/resourceGroups/azcli-test",
        "location": "eastus",
        "name": "azcli-test",
        "provisioning_state": "Succeeded",
        "tags": null
    }
}

次のコマンドを実行して、Azure リソース グループを削除します。

ansible localhost -m azure_rm_resourcegroup -a "name=<resource_group_name> state=absent force_delete_nonempty=yes"

<resource_group_name> は、リソース グループの名前に置き換えます。

[WARNING]: No inventory was parsed, only implicit localhost is available
localhost | CHANGED => {
    "changed": true,
    "contains_resources": false,
    "state": {
        "id": "/subscriptions/subscriptionID>/resourceGroups/azcli-test",
        "location": "eastus",
        "name": "azcli-test",
        "provisioning_state": "Succeeded",
        "status": "Deleted",
        "tags": null
    }
}

次のステップ