開始使用:使用 Azure Cloud Shell 設定 Ansible

在 Azure 上設定 Ansible 並建立基本的 Azure 資源群組,以開始使用 Ansible

Ansible 是一項開放原始碼產品,可自動佈建雲端、進行組態管理和應用程式部署。 您可以使用 Ansible 佈建虛擬機、容器和網路,以及完整的雲端基礎結構。 此外,Ansible 也可讓您自動化環境中資源的部署和設定。

本文說明從 Azure Cloud Shell 環境開始使用 Ansible。

設定您的環境

  • Azure 訂用帳戶:如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶
  • 設定 Azure Cloud Shell - 如果您不熟悉 Azure Cloud Shell ,請參閱 Azure Cloud Shell 中的 Bash 快速入門。
  1. 如果您已經開啟 Cloud Shell 工作階段,您可以跳至下一節。

  2. 瀏覽至 Azure 入口網站

  3. 如有必要,請登入您的 Azure 訂用帳戶並變更 Azure 目錄。

  4. 開啟 Cloud Shell。

    Open Cloud Shell from the top menu in the Azure portal.

  5. 如果您先前尚未使用 Cloud Shell,請設定環境和記憶體設定。

  6. 選取命令行環境。

    Select the CLI you want to use in Cloud Shell.

自動認證設定

登入 Cloud Shell 時,Ansible 會向 Azure 進行驗證,以管理基礎結構,而不需要任何額外的設定。

使用多個訂用帳戶時,請導出 AZURE_SUBSCRIPTION_ID 環境變數來指定 Ansible 所使用的訂用帳戶。

若要列出所有 Azure 訂用帳戶,請執行下列命令:

az account list

使用您的 Azure 訂用帳戶標識碼,設定 AZURE_SUBSCRIPTION_ID 如下:

export AZURE_SUBSCRIPTION_ID=<your-subscription-id>

測試 Ansible 安裝

您現在已設定 Ansible 以在 Cloud Shell 中使用!

本節說明如何在新的 Ansible 設定內建立測試資源群組。 如果您不需要這麼做,您可以略過本節。

建立 Azure 資源群組

  1. 將下列程式代碼儲存為 create_rg.yml

    ---
    - hosts: localhost
      connection: local
      tasks:
        - name: Creating resource group - "{{ name }}"
          azure_rm_resourcegroup:
            name: "{{ name }}"
            location: "{{ location }}"
          register: rg
        - debug:
            var: rg
    
  2. 使用 ansible-playbook 執行劇本。 將佔位元取代為要建立之資源群組的名稱和位置。

    ansible-playbook create_rg.yml --extra-vars "name=<resource_group_name> location=<resource_group_location>"
    

    重點︰

    • register由於劇本的變數和debug區段,因此命令完成時會顯示結果。

刪除 Azure 資源群組

  1. 將下列程式代碼儲存為 delete_rg.yml

    ---
    - hosts: localhost
      tasks:
        - name: Deleting resource group - "{{ name }}"
          azure_rm_resourcegroup:
            name: "{{ name }}"
            state: absent
          register: rg
        - debug:
            var: rg
    
  2. 使用 ansible-playbook 命令執行劇本 。 將佔位元取代為要刪除的資源群組名稱。 將會刪除資源群組中的所有資源。

    ansible-playbook delete_rg.yml --extra-vars "name=<resource_group>"
    

    重點︰

    • register由於劇本的變數和debug區段,因此命令完成時會顯示結果。

下一步