Deploy Ansible project which include a docker-comp

2019-09-19 01:49发布

问题:

I woud like to use Ansible to deploy one of my project (let's call it project-to-deploy).

project-to-deploy can be run locally using a docker-compose.yml file, which, among other things, mount the following volumes inside the docker-container.

version: "2"
services:
  database:
    image: mysql:5.6
      volumes:
        - ./docker/mysql.init.d:/docker-entrypoint-initdb.d
  messages:
      image: private.repo/project-to-deploy:latest

Nothing more useful here. To run the project: docker-compose up. I have created a docker image of the project (in which I copy all the files from the project to the newly created docker image), and uploaded it to private.repo/project-to-deploy:latest.

Now comes the Ansible part.
For the project to run, I need:

  1. The docker image
  2. A MySQL instance (see part of my docker-compose.yml below)

In my docker-compose.yml (above), it is quite easy to do so. I just create the 2 services (database and project-to-deploy) and link them each-other.

How can I perform such action in Ansible?

First things I did is to fetch the image:

- name: Docker - pull project image
  docker:
    image: "private.repo/project-to-deploy:latest"
    state: restarted
    pull: always

Then, how can I link the MySQL docker image to this, knowing that the MySQL docker image need files from project-to-deploy ?

If you think of another way to do it, feel free to make suggestions !

回答1:

slight correction, the docker module is for running containers, in your example you are not just fetching the image. You're actually pulling the image, creating a container, and running it.

I would typically accomplish this by using ansible to template each container's config files with the needed IP addresses, ports, credentials, etc. providing them all they need to know to communicate with each other.

Since your example only involves few connections you could set the links option in your ansible task. You should only need to set it on the "messages" container side.

- name: Docker - start MySQL container
  docker:
    name: database
    image: "mysql:5.6"
    state: restarted
    volumes:
    - /path/to/docker/mysql.init.d:/docker-entrypoint-initdb.d
    pull: always

- name: Docker - start project container
  docker:
    name: messages
    image: "private.repo/project-to-deploy:latest"
    state: restarted
    pull: always
    links:
    - database