In `community.docker` collection what is the equivalent way of `docker ps` i.e., getting running containers on a device?

I am aware of community.docker.docker_container_info where one can mention the name of the container and obtain information about it. However I cannot find any information on what is the equivalent to obtaining a list of currently running containers on the device.

My goal is to perform a complete prune of the device, however the community.docker.docker_prune only provides pruning of non-running containers.

The only solution I have at the moment is:

   - name: '(DEVICE) - Running Containers Information'
      ansible.builtin.command:
        cmd: docker ps -a --format=json
      register: running_containers_info
      changed_when: running_containers_info.rc != 0
    - debug: msg="{{ item | from_json }}"
      loop: "{{ running_containers_info.stdout_lines }}"
    - community.docker.docker_container:
        name: "{{ container_info.Names }}"
        state: absent
      vars:
        container_info: "{{ item | from_json }}"
      loop: "{{ running_containers_info.stdout_lines }}"
    - name: '(DEVICE) - Prune system'
      community.docker.docker_prune:
        containers: true
        images: true
        images_filters:
          dangling: false
        networks: true
        builder_cache: true

because docker ps -a --format=json provides distinct JSON structures as opposed to a list of JSON, this is why I need to format from from_json gymnastics in the middle.

That looks fine to me, one thing I’d do differently though is this:

   - name: '(DEVICE) - Running Containers Information'
      ansible.builtin.command:
        cmd: docker ps -a --format=json
      register: running_containers_info
      changed_when: false  # 👈

As running this command doesn’t change anything.

I’d probably also set a fact for the docker ps -a --format=json output with a dict2items filter and then loop on that, but the way you have done it is fine, if it works :slight_smile: .

1 Like

Or simply use the community.docker.docker_host_info module with containers=true and containers_all=true instead of using the command module.

3 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.