Apart from provisioning localhost (the machine where you have Ansible installed), you can also tell Ansible to:
- create a new docker container,
- provision that container,
- destroy that container.
For this to work you need such a hosts.yaml file:
all:
  hosts:
    mycontainer:
      ansible_connection: docker
    localhost:
      ansible_connection: local
such a playbook.yaml file:
---
- name: Create a container to be provisioned later
  hosts: localhost
  tasks:
    - name: create docker container
      docker_container:
        name: mycontainer
        image: python:2.7.16-slim-stretch
        command: ["sleep", "1d"]
- name: Provision the container created above
  hosts: mycontainer
  roles:
    - simple
and another playbook file: destroy.yaml used to destroy the container:
---
- name: Destroy a container
  hosts: localhost
  tasks:
    - name: destroy docker container
      docker_container:
        name: mycontainer
        state: absent
Create also a simple role: roles/simple/taksks/main.yaml
---
- name: Create a file
  copy:
    content: "hi!!"
    dest: /tmp/hello
    force: yes
    mode: 0555
And now to create a container and provision it, run:
ansible-playbook -i ./hosts.yaml ./playbook.yml
Verify that container was provisioned (the file was created):
docker exec mycontainer cat /tmp/hello
To destroy the container run:
ansible-playbook -i ./hosts.yaml ./destroy.yml
There are of course disadvantages:
- the container must have python installed
- some Ansible modules might not work, because additional python packages have to be installed. E.g. if you wanted to deploy docker containers (in the docker container), you have to install docker python SDK (pip3 install docker)
I was inspired by this blog post: https://medium.com/@andreilhicas/provision-docker-containers-with-ansible-30cc5ee6d950