Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Command Inside of Docker Container Using Ansible

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 
like image 760
Nigel Earle Avatar asked Oct 01 '15 03:10

Nigel Earle


People also ask

Can I run Docker command inside container?

To run docker inside docker, all you have to do it just run docker with the default Unix socket docker. sock as a volume. Just a word of caution: If your container gets access to docker. sock , it means it has more privileges over your docker daemon.

Can Ansible connect to Docker container?

To handle docker containers from ansible, the requirement is to install docker SDK, to install that we will install pip, and using pip we will download docker SDK. Lastly, start a docker service. We want to create a container in such a way that, we can connect the docker container using ssh public key authentication.

Can Ansible manage Docker containers?

To make this combination work on your system, you'll need the following before you begin: Docker installed on the local system. Ansible 2.4 or higher installed and running on your local machine. Passwordless SSH connection between your local machine and remote server.


1 Answers

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.

like image 97
Bernie Avatar answered Oct 11 '22 08:10

Bernie