我有以下Ansible手册来从模板创build(克隆)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>
我怎么能创build多个虚拟机,而无需多次运行剧本,即回答所有提示问题? 虚拟机的名字( guest
)被改变的唯一variables。 我想要这样的东西:
ansible-playbook createvm.yml --ask-become-pass -e guest=server1,server3,server3
你也可以为guest参数写一个with_items
循环。 喜欢这个:
- 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 }}"
如果你不想在游戏中硬编码variables(这不是一个坏主意),你可以将列表存储在一个variables中,并将其置于host_vars/hostname
如下所示:
--- serverlist: - server1 - server2
Ansible将vault
包含在内,用于存储密码和敏感信息。 查看文档以获取更多信息。
您可以创build一个用Vaultencryption的variables文件,并将其包含在您的播放中
- include_vars: vault.yml
我发现一个似乎工作正常的解决scheme – 使用环境variables。 我用下面的vars_prompt
replace了剧本的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') }}"
在运行剧本之前,我设置了环境variables
export ANS_VCENTER="vcenter01.example.com"
(我有点担心在一个环境variables中存储密码,但似乎足够安全 )。
然后,我可以使用shell for循环创build多个guest虚拟机
for g in server1 server2 server3; do echo "--> Create $g"; ansible-playbook createvm.yml -e guest=$g; done