您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

教程:使用 Ansible 配置 Azure 资源的动态库存Tutorial: Configure dynamic inventories of your Azure resources using Ansible

使用 Ansible 可将各种源(包括 Azure 等云源)中的库存信息提取到动态库存中。Ansible can be used to pull inventory information from various sources (including cloud sources such as Azure) into a dynamic inventory.

在本教程中,Ansible 用于:In this tutorial, Ansible is used to:

  • 配置两个测试虚拟机。Configure two test virtual machines.
  • 标记其中一个虚拟机Tag one of the virtual machines
  • 在已标记的虚拟机上安装 NginxInstall Nginx on the tagged virtual machines
  • 配置动态库存,使其包含已配置的 Azure 资源Configure a dynamic inventory that includes the configured Azure resources

先决条件Prerequisites

  • Azure 订阅:如果还没有 Azure 订阅,可以在开始前创建一个 免费帐户Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
  • Azure 服务主体创建服务主体,记下以下值:“appId”、“displayName”、“密码”和“租户” 。Azure service principal: Create a service principal, making note of the following values: appId, displayName, password, and tenant.

创建测试 VMCreate the test VMs

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 打开 Cloud ShellOpen Cloud Shell.

  3. 创建一个 Azure 资源组,用于保存本教程创建的虚拟机。Create an Azure resource group to hold the virtual machines for this tutorial.

    重要

    在此步骤中创建的 Azure 资源组必须具有完全小写的名称。The Azure resource group you create in this step must have a name that is entirely lower-case. 否则,生成动态清单将会失败。Otherwise, the generation of the dynamic inventory will fail.

    az group create --resource-group ansible-inventory-test-rg --location eastus
    
  4. 使用以下方法之一在 Azure 上创建两个 Linux 虚拟机:Create two Linux virtual machines on Azure using one of the following techniques:

    • Ansible 演练手册 - 使用 Ansible 在 Azure 中创建基本的虚拟机一文演示了如何通过 Ansible 演练手册创建虚拟机。Ansible playbook - The article, Create a basic virtual machine in Azure with Ansible illustrates how to create a virtual machine from an Ansible playbook. 如果使用演练手册定义其中的一个或两个虚拟机,请确保使用 SSH 连接,而不要使用密码。If you use a playbook to define one or both of the virtual machines, ensure that the SSH connection is used instead of a password.

    • Azure CLI - 在 Cloud Shell 中发出以下每条命令,以创建两个虚拟机:Azure CLI - Issue each of the following commands in the Cloud Shell to create the two virtual machines:

      az vm create --resource-group ansible-inventory-test-rg \
                   --name ansible-inventory-test-vm1 \
                   --image UbuntuLTS --generate-ssh-keys
      
      az vm create --resource-group ansible-inventory-test-rg \
                   --name ansible-inventory-test-vm2 \
                   --image UbuntuLTS --generate-ssh-keys
      

标记 VMTag a VM

可以根据用户定义的类别使用标记来组织 Azure 资源You can use tags to organize your Azure resources by user-defined categories.

输入以下 az resource tag 命令和键 nginx 来标记虚拟机 ansible-inventory-test-vm1Enter the following az resource tag command to tag the virtual machine ansible-inventory-test-vm1 with the key nginx:

az resource tag --tags nginx --id /subscriptions/<YourAzureSubscriptionID>/resourceGroups/ansible-inventory-test-rg/providers/Microsoft.Compute/virtualMachines/ansible-inventory-test-vm1

生成动态库存Generate a dynamic inventory

定义(并标记)虚拟机后,便可以生成动态库存了。Once you have your virtual machines defined (and tagged), it's time to generate the dynamic inventory.

使用低于 2.8 的 Ansible 版本Using Ansible version < 2.8

Ansible 提供一个名为 azure_rm.py 的 Python 脚本,该脚本生成 Azure 资源的动态库存。Ansible provides a Python script named azure_rm.py that generates a dynamic inventory of your Azure resources. 以下步骤引导你使用 azure_rm.py 脚本连接到两个 Azure 测试虚拟机:The following steps walk you through using the azure_rm.py script to connect to your two test Azure virtual machines:

  1. 使用 GNU wget 命令检索 azure_rm.py 脚本:Use the GNU wget command to retrieve the azure_rm.py script:

    wget https://raw.githubusercontent.com/ansible/ansible/devel/contrib/inventory/azure_rm.py
    
  2. 使用 chmod 命令更改对 azure_rm.py 脚本的访问权限。Use the chmod command to change the access permissions to the azure_rm.py script. 以下命令使用 +x 参数允许执行(运行)指定的文件 (azure_rm.py):The following command uses the +x parameter to allow for execution (running) of the specified file (azure_rm.py):

    chmod +x azure_rm.py
    
  3. 使用 ansible 命令连接到资源组:Use the ansible command to connect to your resource group:

    ansible -i azure_rm.py ansible-inventory-test-rg -m ping 
    
  4. 连接后,将看到类似于以下输出的结果:Once connected, you see results similar to the following output:

    ansible-inventory-test-vm1 | SUCCESS => {
        "changed": false,
        "failed": false,
        "ping": "pong"
    }
    ansible-inventory-test-vm2 | SUCCESS => {
        "changed": false,
        "failed": false,
        "ping": "pong"
    }
    

Ansible 版本为 2.8 及更高版本Ansible version >= 2.8

从 Ansible 2.8 开始,Ansible 便已提供 Azure 动态库存插件Starting with Ansible 2.8, Ansible provides an Azure dynamic-inventory plugin. 以下步骤将指导你使用插件:The following steps walk you through using the plugin:

  1. 库存插件需要配置文件。The inventory plugin requires a configuration file. 配置文件必须以 azure_rm 结尾,且扩展名为 ymlyamlThe configuration file must end in azure_rm and have an extension of either yml or yaml. 对于本教程示例,请将以下 playbook 保存为 myazure_rm.ymlFor this tutorial example, save the following playbook as myazure_rm.yml:

    plugin: azure_rm
    include_vm_resource_groups:
    - ansible-inventory-test-rg
    auth_source: auto
    
  2. 运行以下命令以在资源组中对 VM 执行 ping 操作:Run the following command to ping VMs in the resource group:

    ansible all -m ping -i ./myazure_rm.yml
    
  3. 运行上述命令时,可能会收到以下错误:When running the preceding command, you could receive the following error:

    Failed to connect to the host via ssh: Host key verification failed.
    

    如果收到“主机密钥验证”错误,请将以下行添加到 Ansible 配置文件中。If you do receive the "host-key verification" error, add the following line to the Ansible configuration file. Ansible 配置文件位于 /etc/ansible/ansible.cfgThe Ansible configuration file is located at /etc/ansible/ansible.cfg.

    host_key_checking = False
    
  4. 运行 playbook 后,将看到类似于以下输出的结果:When you run the playbook, you see results similar to the following output:

    ansible-inventory-test-vm1_0324 : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    ansible-inventory-test-vm2_8971 : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    

启用 VM 标记Enable the VM tag

设置标记后,需要“启用”该标记。Once you've set a tag, you need to "enable" that tag. 启用标记的方法之一是通过 export 命令将标记导出到环境变量 AZURE_TAGSOne way to enable a tag is by exporting the tag to an environment variable AZURE_TAGS via the export command:

export AZURE_TAGS=nginx
  • 如果使用低于 2.8 版本的 Ansible,请运行以下命令:If you're using Ansible < 2.8, run the following command:

    ansible -i azure_rm.py ansible-inventory-test-rg -m ping
    
  • 如果使用版本 2.8 及更高版本的 Ansible,请运行以下命令:If you're using Ansible >= 2.8, run the following command:

    ansible all -m ping -i ./myazure_rm.yml
    

现在,只会看到一个虚拟机(其标记与导出到 AZURE_TAGS 环境变量的值匹配):You now see only one virtual machine (the one whose tag matches the value exported into the AZURE_TAGS environment variable):

ansible-inventory-test-vm1 | SUCCESS => {
    "changed": false,
    "failed": false,
    "ping": "pong"
}

在标记的 VM 上安装 NginxSet up Nginx on the tagged VM

标记的用途是让我们快速方便地使用虚拟机的子组。The purpose of tags is to enable the ability to quickly and easily work with subgroups of your virtual machines. 例如,假设我们只想在分配了 nginx 标记的虚拟机上安装 Nginx。For example, let's say you want to install Nginx only on virtual machines to which you've assigned a tag of nginx. 以下步骤演示如何轻松实现此目的:The following steps illustrate how easy that is to accomplish:

  1. 创建名为 nginx.yml 的文件:Create a file named nginx.yml:

    code nginx.yml
    
  2. 将以下示例代码粘贴到编辑器中:Paste the following sample code into the editor:

    ---
    - name: Install and start Nginx on an Azure virtual machine
      hosts: all
      become: yes
      tasks:
      - name: install nginx
        apt: pkg=nginx state=installed
        notify:
        - start nginx
    
      handlers:
        - name: start nginx
          service: name=nginx state=started
    
  3. 保存文件并退出编辑器。Save the file and exit the editor.

  4. 使用 ansible-playbook 命令运行 playbook:Run the playbook using the ansible-playbook command:

    • Ansible 版本低于 2.8:Ansible < 2.8:
    ansible-playbook -i azure_rm.py nginx.yml
    
    • Ansible 为版本 2.8 及更高版本:Ansible >= 2.8:
     ansible-playbook  -i ./myazure_rm.yml  nginx.yml
    
  5. 运行 playbook 后,可看到类似于以下结果的输出:After running the playbook, you see output similar to the following results:

    PLAY [Install and start Nginx on an Azure virtual machine] 
    
    TASK [Gathering Facts] 
    ok: [ansible-inventory-test-vm1]
    
    TASK [install nginx] 
    changed: [ansible-inventory-test-vm1]
    
    RUNNING HANDLER [start nginx] 
    ok: [ansible-inventory-test-vm1]
    
    PLAY RECAP 
    ansible-inventory-test-vm1 : ok=3    changed=1    unreachable=0    failed=0
    

测试 Nginx 安装Test Nginx installation

本部分演示一种测试是否在虚拟机上安装了 Nginx 的方法。This section illustrates one technique to test that Nginx is installed on your virtual machine.

  1. 使用 az vm list-ip-addresses 命令检索 ansible-inventory-test-vm1 虚拟机的 IP 地址。Use the az vm list-ip-addresses command to retrieve the IP address of the ansible-inventory-test-vm1 virtual machine. 然后,将返回值(虚拟机的 IP 地址)用作 SSH 命令的参数,以连接到该虚拟机。The returned value (the virtual machine's IP address) is then used as the parameter to the SSH command to connect to the virtual machine.

    ssh `az vm list-ip-addresses \
    -n ansible-inventory-test-vm1 \
    --query [0].virtualMachine.network.publicIpAddresses[0].ipAddress -o tsv`
    
  2. 连接到 ansible-inventory-test-vm1 虚拟机后,运行 nginx -v 命令来确定是否安装了 Nginx。While connected to the ansible-inventory-test-vm1 virtual machine, run the nginx -v command to determine if Nginx is installed.

    nginx -v
    
  3. 运行 nginx -v 命令后,会看到 Nginx 版本(第二行),这表示已安装了 Nginx。Once you run the nginx -v command, you see the Nginx version (second line) that indicates that Nginx is installed.

    tom@ansible-inventory-test-vm1:~$ nginx -v
    
    nginx version: nginx/1.10.3 (Ubuntu)
    
    tom@ansible-inventory-test-vm1:~$
    
  4. <Ctrl>D 组合键断开 SSH 会话。Click the <Ctrl>D keyboard combination to disconnect the SSH session.

  5. 针对 ansible-inventory-test-vm2 虚拟机执行上述步骤会生成一条信息性消息,其中指出可在何处获取 Nginx(这意味着,目前尚未安装 Nginx):Doing the preceding steps for the ansible-inventory-test-vm2 virtual machine yields an informational message indicating where you can get Nginx (which implies that you don't have it installed at this point):

    tom@ansible-inventory-test-vm2:~$ nginx -v
    The program 'nginx' can be found in the following packages:
    * nginx-core
    * nginx-extras
    * nginx-full
    * nginx-lightTry: sudo apt install <selected package>
    tom@ansible-inventory-test-vm2:~$
    

后续步骤Next steps