共用方式為


快速入門:建立 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>

注意

將輸出的密碼儲存在安全的位置。

將角色指派給 Azure 服務主體

根據預設,服務主體沒有管理 Azure 中資源所需的存取權。

執行下列命令,將 參與者 角色指派給服務主體:

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

將取代 <appID> 為命令輸出 az ad sp create-for-rba 所提供的值。

注意

若要改善安全性,請將角色指派的範圍變更為資源群組,而不是訂用帳戶。

取得 Azure 服務主體資訊

若要使用服務主體向 Azure 進行驗證,您需要下列資訊:

  • SubscriptionID
  • 服務主體 ApplicationId
  • 服務主體密碼
  • 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>

將、 <ApplicationId><Password><TenantID> 取代<SubscriptionID>為您服務主體帳戶的值。

測試服務主體許可權

執行下列命令以建立新的 Azure 資源群組:

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

將和 <resource_group_location> 取代<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",
        "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
    }
}

下一步