Bootstrap FreeKB - Ansible - Execute a command in a Docker container using the docker_container_exec module
Ansible - Execute a command in a Docker container using the docker_container_exec module

Updated:   |  Ansible articles

If you are not familiar with modules, check out Ansible - Getting Started with Modules.

The docker_container_exec module is used to execute a command in a Docker container, just like using the docker exec command. docker_container_exec is part of the community.docker collection. Typically, the community.docker collection is not included in the default Ansible collections. The ansible-galaxy collection install command can be used to install the community.docker collection.

ansible-galaxy collection install community.docker

 

The Docker system that contains the Docker container will need the Python Docker SDK (Software Development Kit). The Python Docker SDK is used to run Docker commands using Python. To ensure the AWS EC2 Instance had the latest Docker SDK for pip (Python version 2.6) and pip2 (Python version 2.7 and above) and pip3 (Python version 3) I used the shell module.

---
- hosts: all
  tasks:
  - shell: "{{ item }}"
    with_items:
    - yes | sudo pip uninstall docker
    - yes | sudo pip2 uninstall docker
    - yes | sudo pip3 uninstall docker
    - yes | sudo pip uninstall docker-py
    - yes | sudo pip2 uninstall docker-py
    - yes | sudo pip3 uninstall docker-py
    - yes | sudo pip install docker
    - yes | sudo pip2 install docker
    - yes | sudo pip3 install docker

  - community.docker.docker_container_exec:
      container: hello-world
      command: df
    register: out

  - debug:
      var: out
...

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter dad9d6 in the box below so that we can be sure you are a human.