Create a Docker Container With Volume Using Ansible

Working with containers without volumes is only half of the story of what Docker is capable of doing, and when throwing the Docker module for Ansible, there are a few more things to learn.

This post will show you how to create and mount a storage volume into a Docker container using Ansible.

For more information on how to use the Docker module for Ansible, visit this post.

Playbook

The following Ansible playbook has two tasks. The first task will create a names storage volume called data. The second task will create a container and mount the data volume to it.

Technically we don’t have to create the volume first, and we can add the volume line into the 2nd task where we create the container. If we do that, the volume will receive a random name.


- hosts: localhost
  

  tasks:
    - name: Create a volume for a container 
      community.docker.docker_volume:
        name: data
          

    - name: Create a container
      community.docker.docker_container:
        name: myansiblecontainer
        image: ubuntu
        volumes:
          - /data
        state: absent
 

After running the playbook, you will end up with a container, and a volume called data.


Posted

in

, ,

by