dockeransible

Stop docker container based on public port using ansible


I am trying to create a ansible-playbook which can stop docker container which is running on a specific port.

From what I found online it seems we can get all the containers using

  tasks:
 - name: Get running containers
   docker_host_info:
    containers: yes
   register: docker_info

and stop container using

 - name: Stop running containers
   docker_container:
    name: "<container on port 8080>"
    state: stopped

But how can I stop a container which is running on port 8080


Solution

  • If some one else stumbles across this question, here is how I did it

    tasks:
     - name: Get docker Info
       docker_host_info:
        containers: yes
       register: docker_info
    
     - name: Stop the container running on port 8080
       docker_container:
        name: "{{ docker_info | dict2items | json_query('[?key==`containers`].value[] | [?Ports[?PublicPort==`8080`]] | [0].Id') }}"
        state: stopped