Ansible docker module: expose multiple <IPv4>:<port>:<port> combos at once

449 views
Skip to first unread message

Walter Dolce

unread,
Mar 31, 2016, 3:49:41 PM3/31/16
to Ansible Project
Hello Ansiblers!

I was trying to think of a way to expose multiple ports in a row by using the docker module (http://docs.ansible.com/ansible/docker_module.html) but I can't think of anything except looping through the values I would need by means of the usual with_items way, which is not what I want because it would result in an overwrite of the previous iteration.
My scenario is as follows:


tasks:
  - name: Install Nginx container
    docker:
    name: webserver_nginx
   
image: nginx
   
state: reloaded
   
expose:
      - "{{ ansible_docker0.ipv4.address }}:80:80"
    ports:
      - "{{ ansible_docker0.ipv4.address }}:80:80"


But what I want would be something like:


tasks:
  - name: Install Nginx container
    docker:
    name: webserver_nginx
   
image: nginx
   
state: reloaded
   
expose:
      - "{{ ansible_docker0.ipv4.address }}:80:80"
        - "{{ ansible_eth0.ipv4.address }}:80:80"
- "{{ ansible_eth1.ipv4.address }}:80:80"
      ports:
      - "{{ ansible_docker0.ipv4.address }}:80:80"
        - "{{ ansible_eth0.ipv4.address }}:80:80"
        - "{{ ansible_eth1.ipv4.address }}:80:80"


Now, I know that the number of network interfaces is something that could change at some point, I was thinking to loop over the ansible_interfaces and dynamically get the ansible_{{interface}}.ipv4.address if any. But the problem remains: I would end up using a loop and running the task multiple times with a single expose/ports definition overwriting the previous ones.

Did anyone encounter this scenario so far?
How could I specify multiple expose/ports combos at once by dynamically grab the ansible_{{interface}}.ipv4.address items?

Thanks!


Walter Dolce

unread,
Mar 31, 2016, 6:41:38 PM3/31/16
to Ansible Project
I found a solution for now. I quickly wrote a filter plugin to obtain what I wanted - https://gist.github.com/walterdolce/93a89018d69392de7c94bf690b761455

The final product for now is:

tasks:
- name: Install Nginx container
docker:
name: webserver_nginx
image: nginx
state: reloaded
       expose: "{{ ansible_all_ipv4_addresses | map_ipv4_port_exports(container_port='80', host_port='80') }}"
ports: "{{ ansible_all_ipv4_addresses | map_ipv4_port_exports(container_port='80', host_port='80') }}"


I could probably change the name of the filter to make it more docker specific.

Any feedback is more than welcome!

Reply all
Reply to author
Forward
0 new messages