Home > Mobile >  dynamic add ports to ansible docker_container
dynamic add ports to ansible docker_container

Time:09-04

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

CodePudding user response:

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
  • Related