如何使用ansible部署自定义VM并通过主机在来宾VM上运行后续步骤?

时间:2017-09-21 08:29:29

标签: ansible virtual-machine inventory

我有一个Playbook,我将其运行以将guest虚拟机部署到目标节点上。 guest虚拟机启动后,它不可用于整个网络,而只能用于主机。 此外,在启动来宾VM后,我需要运行一些命令 该来宾配置它并使其可供所有网络成员使用。

---
- block:
  - name: Verify the deploy VM script
    stat: path="{{ deploy_script }}"
    register: deploy_exists
    failed_when: deploy_exists.stat.exists == False
    no_log: True

  rescue:
  - name: Copy the deploy script from Ansible
    copy:
      src: "scripts/new-install.pl"
      dest: "/home/orch"
      owner: "{{ my_user }}"
      group: "{{ my_user }}"
      mode: 0750
      backup: yes
    register: copy_script

- name: Deploy VM
  shell: run my VM deploy script

<other tasks>

- name: Run something on the guest VM
  shell: my_other_script
  args:
     cdir: /var/scripts/

- name: Other task on guest VM
  shell: uname -r

<and so on>

如何通过主机在来宾VM上运行后续步骤? 我唯一的解决方法是使用虚拟机详细信息填充新的清单文件,并添加使用主机作为堡垒主机。

[myvm]
myvm-01 ansible_connection=ssh ansible_ssh_user=my_user ansible_ssh_common_args='-oStrictHostKeyChecking=no -o ProxyCommand="ssh -A -W %h:%p someuser@host_machine"'

然而,我希望一切都发生在一个剧本上,而不是分裂它们。

1 个答案:

答案 0 :(得分:0)

我自己已经解决了。 我设法动态地将主机添加到清单并使用了一个组:新创建的主机的vars将VM管理器用作堡垒主机

Playbook:

---
  hosts: "{{ vm_manager }}"
  become_method: sudo
  gather_facts: False

  vars_files:
    - vars/vars.yml
    - vars/vault.yml

  pre_tasks:

  - name: do stuff here on the VM manager
    debug: msg="test"

  roles:
    - { role: vm_deploy, become: yes, become_user: root }

  tasks:
  - name: Dinamically add newly created VM to the inventory
    add_host:
      hostname: "{{ vm_name }}"
      groups: vms
      ansible_ssh_user: "{{ vm_user }}"
      ansible_ssh_pass: "{{ vm_pass }}"

- name: Run the rest of tasks on the VM through the host machine
  hosts: "{{ vm_name }}"
  become: true
  become_user: root
  become_method: sudo

  post_tasks:
  - name: My first task on the VM
    static: no
    include_role: 
      name: my_role_for_the_VM

清单:

[vm_manager]
vm-manager.local

[vms]
my-test-01
my-test-02

[vms:vars]
ansible_connection=ssh 
ansible_ssh_common_args='-oStrictHostKeyChecking=no -o ProxyCommand="ssh -A -W %h:%p username@vm-manager.local"'

运行playbook:

ansible-playbook -i hosts -vv playbook.yml -e vm_name=some-test-vm-name