Ansible – Managing Multiple Containers on Host

ansibleansible-playbookdocker

Am wrote a playbook to create a container within a host machine. my idea is to create multiple containers per hosts. am trying to use the host.ini file to divide the host machines as a group and each container as an Ansible host within the group. Do you know how to structure the host file to use the Variable ansible_host to name the containers in the playbook used to create them.

my host file:

-----

[host.machine.1]
machine.1.container-1
machine.1.container-2
machine.1.container-3

[host.machine.2]
machine.2.container-1
machine.2.container-2
machine.2.container-3

[host.machine.3]
machine.3.container-1
machine.3.container-2
machine.3.container-3

my functional playbook:

---
- name: Create container
  hosts: host.machine.1:host.machine.2:host.machine.3
  vars:
    agent_name: "{{ container_name }}"

  tasks:
   - name: Docker pull 
     command: docker pull container.image:latest

   - name: Docker volume 
     command: docker volume create agent_{{ container_name }}

   - name: Docker run 
     command: docker run -d -it --privileged --name agent-{{ container_name }} -e AGENT_NAME="{{ container_name }}"   --network network1 --cpus=8 --memory=32g --ipc=host -e TZ=CET docker-registry/container.image:latest

Thank you

Best Answer

Create a variable that lists the containers for every host

host_vars/host1.yml

containers:
  - name: agent1
    image: docker-registry/container.image:latest
  - name: agent2
    image: docker-registry/container.image:latest
  - name: agent3
    image: docker-registry/container.image:latest

The same for the other hosts

Then, in the playbook you can loop over that list:

hosts: host1,host2,host3
tasks:
  - name: Docker volume 
    command: "docker volume create agent_{{ item.name }}"
    loop: {{ containers }}
  - name: Docker run 
    command: "docker run -d -it --privileged --name agent-{{ item.name }} -e AGENT_NAME=\"{{ item.name }}\"   --network network1 --cpus=8 --memory=32g --ipc=host -e TZ=CET {{ item.image }}"
    loop: "{{ containers }}"

Or, using the proper modules:

hosts: host1,host2,host3
tasks:
  - name: Docker volume 
    docker_volume:
      name: "agent_{{ item.name }}"
    loop: {{ containers }}
  - name: Docker run 
    docker_container:
      name: "agent-{{ item.name }}"
      image: "{{ item.image }}"
      privileged: yes
      volumes:
        - "agent_{{ item.name }}"
    loop: "{{ containers }}"