David Ham
David Ham

Reputation: 923

Use Ansible to start Docker containers on docker-machine?

I have a Rails app I am deploying in Docker containers. I want to do development from the Docker container so it will behave consistently between environments.

I have an Ansible playbook that starts up the Docker containers on the remote server, and that's working fine. I thought I'd use the same Ansible tasks to start the containers and link them together on my Mac.

However, when I run the playbook against my local instance, I get errors like:

fatal: [localhost]: FAILED! => {"changed": false, "failed": true, "msg": "`docker-py` doesn't seem to be installed, but is required for the Ansible Docker module."}

It seems like the problem is that Ansible is doing a local ssh to the Mac, but I need it to connect to the docker-machine.

How do I use Ansible to run tasks on Docker containers running on my Mac?

Upvotes: 2

Views: 2398

Answers (2)

David Ham
David Ham

Reputation: 923

The issue was indeed that Ansible is trying to ssh into my local machine. When you run Docker on a Mac, it creates a virtual machine, and when you run commands like docker ps in a terminal, it is running against the Docker Engine running on that virtual machine.

I ended up following the advice in this article: Using Vagrant and Docker Machine Together. I created a new VM with vagrant, based on the ubuntu/trusty64 image, and then I enabled it for use with Docker using docker create. I then added the IP of this VM to my Ansible inventory file, like so:

192.168.99.101 ansible_user=vagrant ansible_ssh_private_key_file=/path/to/virtualbox/private_key

It's a little awkward because there's no way to make this new VM the default one that Docker Toolbox uses, but otherwise it's a nice way to control the host os of your virtual machine.

I'm trying out docker-compose again, as I think it might be better for local development, but it is nice to be able to run the same playbook to deploy to any environment.

Upvotes: 1

Gal Gibli
Gal Gibli

Reputation: 534

When you write the ansible you need to make sure where it is running

- hosts: HOSTS_TO_RUN_FOLLOWING_TASKS
  tasks:
    - name: NAME_OF_TASK
      shell: SHELL_CMD

When you want to run on different hosts in the same ansible you just need to write this again:

- hosts: NEW_HOST_TO_RUN_TASKS
  tasks:
    - name: NAME_OF_TASK
      shell: SHELL_CMD

If you put "localhost" in the "hosts:" then it will run on local host. If you want to run on a specific host then run the command /etc/ansible/hosts --refresh-cache and use the tags in the result.

For instance if the result is

"tag_Name_Production":
[
   "124.125.125.121", 
   "124.125.125.122", 
   "124.125.125.123"
]

and you want to run the command on all these just use:

- hosts: tag_Name_Production
  tasks:
    - name: NAME_OF_TASK
      shell: SHELL_CMD

Upvotes: 1

Related Questions