简体   繁体   中英

Is there a balancing concept in ansible for creating virtual machines across multiple hosts?

I have two hosts and I want to create four virtual machines. Is there a concept of balancing in ansible, which will create two virtual machines on each host as follows?

HOST1: VM1, VM3, ...

HOST2: VM2, VM4, ...

I know I can specify the host on which a VM is created but this is a little strict as I may add more hosts and many more virtual machines and I'd like a dynamic solution if possible.

The best I can manage is:

    with_items:
##    - "{{ groups.production }}"
    - prod-test1
    delegate_to: "{{ groups['control'][1] }}"

This is far from ideal though as it requires hard references to host group members and virtual machine items.

There is no generic concept in ansible for doing such things, but possible solutions exist. Somewhat ugly, but this works for me. Given the following inventory hosts

[control]
server1
server2
server3

[production]
vm1
vm2
vm3
vm4

and a playbook play.yml

---
- hosts: all
  gather_facts: False

  tasks:
  - name: Just loop through a group
    debug:
      msg: 'VM is {{inventory_hostname}} target is {{ansible_host}}'
    delegate_to: '{{ groups["control"][play_hosts.index(inventory_hostname) % groups["control"]|length] }}'

that is executed with ansible-playbook -i hosts play.yml -l production gives the following result:

PLAY [all] *********************************************************************

TASK [Just loop through a group] ***********************************************
ok: [vm1 -> server1] => {
    "msg": "VM is vm1 target is server1"
}
ok: [vm2 -> server2] => {
    "msg": "VM is vm2 target is server2"
}
ok: [vm3 -> server3] => {
    "msg": "VM is vm3 target is server3"
}
ok: [vm4 -> server1] => {
    "msg": "VM is vm4 target is server1"
}

PLAY RECAP *********************************************************************
vm1                        : ok=1    changed=0    unreachable=0    failed=0
vm2                        : ok=1    changed=0    unreachable=0    failed=0
vm3                        : ok=1    changed=0    unreachable=0    failed=0
vm4                        : ok=1    changed=0    unreachable=0    failed=0

I think that is what you want. You just have to replace the debug task with your desired action.

Other load balancing and roling upgrade scenarios are discussed in the ansible documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM