David Ham
David Ham

Reputation: 923

Run 'docker volume create' with Ansible?

I have a Rails app I am deploying in Docker containers via Ansible. My app includes three containers so far:

My deploy playbook is working, but I had to run the docker volume create command on the server via SSH. I'd love to do that via Ansible, so I could deploy a fresh instance of the app onto an empty container.

Is there a way to run docker volume create via Ansible, or is there some other way to do it? I checked the docs for the Ansible Docker module but it doesn't look like they support volume create yet. Unless I'm missing something?

Upvotes: 7

Views: 7465

Answers (3)

LunkRat
LunkRat

Reputation: 346

You can manage docker volumes with Ansible's own docker_volume module. New in version 2.4.

Examples:

- name: Create a volume
  docker_volume:
    name: volume_one

- name: Remove a volume
  docker_volume:
    name: volume_one
    state: absent

- name: Create a volume with options
  docker_volume:
    name: volume_two
    driver_options:
      type: btrfs
      device: /dev/sda2

Upvotes: 5

Tomas Tomecek
Tomas Tomecek

Reputation: 6456

You can now use -v argument to create named volumes, from man page of docker run:

If you supply a name, Docker creates a named volume by that name.

  - name: Run mariadb
    docker_container:
      name: mariadb-container
      image: mariadb
      env:
        MYSQL_ROOT_PASSWORD: "secret-password"
        MYSQL_DATABASE: "db"
        MYSQL_USER: "user"
        MYSQL_PASSWORD: "password"
      ports:
        - "3306:3306"
      volumes:
        - mariadb-data:/var/lib/mysql

mariadb-data is a named volume which was automatically created by docker:

$ docker volume inspect mariadb-data
[
    {
        "Name": "mariadb-data",
        "Driver": "local",
        "Mountpoint": "/var/lib/docker/volumes/mariadb-data/_data",
        "Labels": null,
        "Scope": "local"
    }
]

Upvotes: 5

larsks
larsks

Reputation: 311606

Here's one option, using the command module.

- hosts: localhost
  tasks:
    - name: check if myvolume exists
      command: docker volume inspect myvolume
      register: myvolume_exists
      failed_when: false

    - name: create myvolume
      command: docker volume create --name myvolume
      when: myvolume_exists|failed

We first check if the volume exists by using docker volume inspect. We save the result of that task in the variable myvolume_exists, and then we only create the volume if the inspect task failed.

Upvotes: 11

Related Questions