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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With