使用 vsphere_guest 模块创建多个 VMware 客户机

使用 vsphere_guest 模块创建多个 VMware 客户机

我有以下 Ansible 剧本,用于从模板创建(克隆)VMware 虚拟机(VM):

- name: Create VMware guest
  hosts: localhost
  connection: local
  gather_facts: False

  vars_prompt:
    - name: "vcenter"
      prompt: "vCenter hostname?"
      default: "vcenter01.example.com"
    - name: "user"
      prompt: "Enter username"
      private: no
    - name: "pass"
      prompt: "Enter password"
      private: yes
    - name: "template"
      prompt: "Template?"
      default: "linux-template.example.com_deb8"
    - name: "cluster"
      prompt: "Cluster?"
      default: "cl03"
    - name: "resource_pool"
      prompt: "Resource pool?"
      default: "/Resources/IT/IT Department/Linux Systems Team"

  tasks:
  - name: Make sure we have pip
    become: true
    apt: pkg=python-pip state=latest
  - name: Install Python modules
    become: true
    pip: name={{ item }} state=latest
    with_items:
      - pysphere
      - pyvmomi
  - name: Deploy guest from template
    vsphere_guest:
      vcenter_hostname: "{{ vcenter }}"
      username: "{{ user }}"
      password: "{{ pass }}"
      guest: "{{ guest }}"
      from_template: yes
      template_src: "{{ template }}"
      cluster: "{{ cluster }}"
      resource_pool: "{{ resource_pool }}"

我像这样调用它:

ansible-playbook createvm.yml --ask-become-pass -e guest=<guest-name>

我如何才能创建多个虚拟机而无需多次运行剧本,即回答所有提示问题?唯一发生变化的变量是虚拟机的名称(guest)。我想要这样的东西:

ansible-playbook createvm.yml --ask-become-pass -e guest=server1,server3,server3

答案1

with_items您也可以为 guest 参数编写一个循环。如下所示:

- name: Deploy guest from template
  vsphere_guest:
    vcenter_hostname: "{{ vcenter }}"
    username: "{{ user }}"
    password: "{{ pass }}"
    guest: "{{ item }}"
    from_template: yes
    template_src: "{{ template }}"
    cluster: "{{ cluster }}"
    resource_pool: "{{ resource_pool }}"
   with_items: "{{ serverlist }}"

如果您不想在游戏中对变量进行硬编码(这不是一个坏主意),您可以将列表存储在一个变量中,并将其放在如下位置host_vars/hostname

---
serverlist:
  - server1
  - server2

Ansible 已vault包含用于存储密码和敏感信息的功能。请查看文档了解更多信息。

您可以创建一个用 vault 加密的变量文件,并将其包含在您的游戏中

- include_vars: vault.yml

答案2

我找到了一个似乎运行良好的解决方案 - 使用环境变量。我vars_prompt用以下内容替换了剧本的部分内容:

  vars:
    vcenter: "{{ lookup('env','ANS_VCENTER') }}"
    cluster: "{{ lookup('env','ANS_CLUSTER') }}"
    template: "{{ lookup('env','ANS_TEMPLATE') }}"
    resource_pool: "{{ lookup('env','ANS_RESOURCE_POOL') }}"
    user: "{{ lookup('env','ANS_USER') }}"
    password: "{{ lookup('env','ANS_PASS') }}"

我在运行剧本之前设置了环境变量,例如

export ANS_VCENTER="vcenter01.example.com"

(我有点担心将密码存储在环境变量中,但似乎足够安全)。

然后我可以使用 shell for 循环创建多个来宾

for g in server1 server2 server3; do echo "--> Create $g"; ansible-playbook createvm.yml -e guest=$g; done

相关内容