Run Command Inside of Docker Container Using Ansible

You should be able to execute a script (with your sequence of command in it) with docker exec:

docker exec container-name bash -l -c /path/to/script > /path/to/log

(See also "Why do I have to use bash -l -c inside my container?")

  • /path/to/script should be accessible by your Ansible process.
  • /path/to/log is a path inside the container, that could be shared in a volume.

Since Ansible 2.10 docker_container_exec is part of the community.docker collection:

- name: Run a simple command (command)
  community.docker.docker_container_exec:
    container: foo
    command: /bin/bash -c "ls -lah"
    chdir: /root
  register: result

- name: Print stdout
  debug:
    var: result.stdout

You can run commands within docker containers using the command module For example this code will execute echo "Hello remote machine" within my_container on the remote machine:

   tasks:
        - name: Execute commands in docker container
          command: docker exec -it my_container bash -c 'echo "Hello remote machine"'

For running the same command within the local machine, just use the local_action flag:

   tasks:
        - name: Execute commands in docker container
          local_action: command docker exec -it my_container bash -c 'echo "Hello local machine"'

After discussion with some very helpful developers on the ansible github project, a better way to do this is like so:

- name: add container to inventory
  add_host:
    name: [container-name]
    ansible_connection: docker
  changed_when: false

- name: run command in container
  delegate_to: [container-name]
  raw: bash

If you have python installed in your image, you can use the command module or any other module instead of raw.

If you want to do this on a remote docker host, add:

ansible_docker_extra_args: "-H=tcp://[docker-host]:[api port]"

to the add_host block.

See the Ansible documentation for a more complete example.