简体   繁体   中英

dynamic add ports to ansible docker_container

I want to deploy multiple (same) containers, one with 2 exposed ports, one with 1 exposed port.

How do i tell ansible to do sometimes 1 port, somtimes multiple? Is there a loop for "ports:"?

localhost.yml:

services:
  - { "name": "item1", "image": "some_container_image:1", "count": "2", "ports": "12345,12346" }
  - { "name": "item2", "image": "some_container_image:1", "count": "1", "ports": "12347" }

ansible role:

---
- name: Start services 
  docker_container:
    name: "{{ item.name }}"
    image: "{{ item.image }}"
    state: started
    ports:
      - "{{ item.ports }}"
    env:
      item1: "{{ item.count }}"
  with_items: "{{ services }}"
  when: services is defined

The ports (alias for published_ports ) option expects a list of ports or port mappings to expose/map.

Simply modify your variable

services:
  - { "name": "item1", "image": "some_container_image:1", "count": "2", "ports": ["12345","12346"] }
  - { "name": "item2", "image": "some_container_image:1", "count": "1", "ports": ["12347"] }

Then pass that port list as is to the option in your loop:

- name: Start services 
  docker_container:
    name: "{{ item.name }}"
    image: "{{ item.image }}"
    state: started
    ports: "{{ item.ports }}"
    env:
      item1: "{{ item.count }}"
  with_items: "{{ services }}"
  when: services is defined

Note that since service is defined in a yaml file, you can make this more legible for everyone

services: - name: item1 image: some_container_image:1 count: 2 ports: - 12345 - 12346 - name: item2 image: some_container_image:1 count: 1 ports: - 12347

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