Run 'docker volume create' with Ansible?

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.


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"
    }
]

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

Tags:

Docker

Ansible