我寫了一本劇本來在主機內建立一個容器。我的想法是為每個主機建立多個容器。我嘗試使用 host.ini 檔案將主機劃分為一個群組,並將每個容器劃分為群組內的 Ansible 主機。您是否知道如何建構主機檔案以使用變數 ansible_host 來命名用於建立它們的劇本中的容器。
我的主機檔案:
-----
[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
我的功能手冊:
---
- 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
謝謝
答案1
建立一個變數來列出每個主機的容器
主機變數/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
其他主機也一樣
然後,在劇本中您可以循環該列表:
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 }}"
或者,使用適當的模組:
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 }}"