49

what I'm trying to accomplish is to run commands inside of a Docker container that has already been created on a Digital Ocean Ubuntu/Docker Droplet using Ansible.

Can't seem to find anything on this, or I'm majorly missing something. This is my Ansible task in my play book. I'm very new to Ansible so any advice or wisdom would be greatly appreciated.

- name: Test Deploy
    hosts: [my-cluster-of-servers]

tasks: 
  - name: Go Into Docker Container And Run Multiple Commands
    docker:
      name: [container-name]
      image: [image-ive-created-container-with-on-server]
      state: present
      command: docker exec -it [container-name] bash
1
  • 13
    unfortunately the answer you accepted doesn't show how to execute the script via Ansible, instead it shows how to execute from the docker host. If you got it to work via Ansible could you please post your solution
    – schmidlop
    Feb 12, 2016 at 21:13

7 Answers 7

75

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.

11
  • 2
    Interesting, and more precise than my answer. +1
    – VonC
    Jan 13, 2017 at 5:12
  • 7
    This does require Docker API access to the host with the Docker Engine (if not localhost) - if firewall rules block this, you may need to use the docker exec ... bash -c ... approach. I don't see how you could use delegate_to for the remote host, since it's already being used for the docker connection to container.
    – RichVel
    Apr 26, 2017 at 10:26
  • 2
    @Ayra - It's not strictly necessary. It will just make the play feedback show: ok: [127.0.0.1], instead of: changed: [127.0.0.1] -- It's just arguably more descriptive of what's going on, as the host has been added, rather than changed (when talking about it in English anyway).
    – Jack_Hu
    Jan 21, 2019 at 19:44
  • 2
    Is there a way to use this to run commands inside docker container in remote hosts?
    – Mani
    Jul 3, 2019 at 11:27
  • 1
    @Mani has a point. One don't necessarily has to configure custom remote docker deamon access. Just access docker locally from the target host... Mani plz share if you found a way...
    – Vano
    Oct 28, 2019 at 22:44
17

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?")

Conditions:

  • Ansible SSH user has docker exec permission
  • In the container, the default user has permission with that script (or docker exec -u user if you need to use another user with script permission in the container)
  • /path/to/log is a path inside the container, that could be shared in a volume.
5
  • Could you clarify the meaning of "should be accessible by your Ansible process."? Does that mean the script should be on the ansible control machine? The docker host? or inside the container?
    – schmidlop
    Feb 12, 2016 at 18:13
  • 1
    @schmidlop I meant: there is an container already running. Inside that container, there is /path/to/script which did not execute properly. A way to try again that script is to execute it (from a docker exec command run from the Linux host) and log its results on the host in /path/to/log
    – VonC
    Feb 12, 2016 at 20:12
  • 1
    @schmidlop I agree. My answer is meant to be run from the docker host.
    – VonC
    Feb 12, 2016 at 21:08
  • the description /path/to/script should be accessible by your Ansible process seems a bit misleading. the script is in container, and docker exec use container default user role to exec cmd, which is no relation with ansible. The condition could be ansible ssh user has docker exec permission and in container default user has permission with that script (or docker exec -u user to use other user in container which has script permission)
    – yurenchen
    Jan 11 at 4:26
  • 1
    @yurenchen Thank you for this useful feedback. I have rewritten the conditions accordingly. Let me know If I misconstrued anything.
    – VonC
    Jan 11 at 9:22
14

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"'
3
  • This works if the docker container is on the same machine on which the ansible script is running. What if the docker container is running on a different machine?
    – Bernie
    Jan 9, 2017 at 0:27
  • I don't believe that's true, @Bernie. My understanding is that local_action does as you describe, but the command module always runs on the remote host, unless the delegate_to parameter is supplied.
    – DMCoding
    Feb 16, 2017 at 2:26
  • 6
    I had to use docker exec -i <my_container> to avoid this error the input device is not a TTY
    – vikas027
    Jun 8, 2017 at 12:45
8

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
0
0

Update: there is a way to do this without using my module, see my other answer

I wrote a simple module to run exec on a remote Docker host. I've submitted it to the ansible project, but you can easily add it to your own projects if you need to. The module is only 23 lines long, take it from my pull request and add it to your ./library directory, and then you can add a task in your playbook like so:

  - name: Run docker exec command
    docker_exec: 
      command: <some command>
      docker_host: <docker host>
      name: <container name>
    register: exec_output

  - name: Show exec output
    debug: msg="{{ exec_output.result }}"
4
  • 1
    The PR was not merged and the author closed it with the note "I admit now, there is no point to my module.". Feb 22, 2018 at 10:10
  • This answer should be updated to reflect that the MR is closed. The upvotes are misleading as well. Unless the code can be directly shared as an alternative where someone can leverage this as their own custom plugin to do this?
    – idjaw
    May 29, 2018 at 16:42
  • 1
    @idjaw See the first line of the answer. Also, if you read through the comments in the pull request it seems like there may be some value to the plugin after all. I was able to solve my problem at the time without using the plugin, so have left it for others to take the code from my pull request and use it as they see fit. The code is still available in the pull request: github.com/ansible/ansible/pull/20112/files. I haven't copied it here as I think it's easily enough accessible from GitHub.
    – Bernie
    May 29, 2018 at 22:35
  • @Bernie Thanks for the message back! (I just noticed the 'other' answer is your answer as well.... :)). The other answer did in fact help me get on track to solving my problem. I ended up doing something like this when it came to the execution of the actual command. My challenge was having to copy a templated file to the container, while wanting to minimize custom docker commands in shell to facilitate testing for idempotent behaviour. Thanks again. :)
    – idjaw
    May 30, 2018 at 0:41
0

Ended up doing something like that:

- name: execute command in docker
  shell: |
    docker exec container sh -l -c "cat /tmp/secret"
  register: hello

- debug: msg="{{ hello.stdout }}"
0

To run command inside docker container using latest versions of Ansible:

ansible-galaxy collection install community.docker

or better by creating file requirements.yml in the project with contents:

---
collections:
    - community.docker

and running ansible-galaxy install -r requirements.yml (similar to pip install -r requirements.txt)

  • use the collection in the following way:
---
- name: local actions 
  hosts: localhost
  gather_facts: false

  tasks:
  - name: task
    community.docker.docker_container_exec: 
      container: container_name
      command: ls /tmp

More about working with collections here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.