Bootstrap FreeKB - Ansible - Manage Docker images using the docker_image module
Ansible - Manage Docker images using the docker_image module

Updated:   |  Ansible articles

If you are not familiar with modules, check out Ansible - Getting Started with Modules.

A Docker image contains the code used to create a Docker container, such as creating a Nginx web server, or a mySQL server, or a home grown app, and the list goes on. In this way, an image is like a template used to create a container. An image is kind of like a virtual machine, but much more light weight, using significantly less storage a memory (containers are usually megabytes in size).

 

Outside of Ansible, using Docker, there are various ways to pull down an image:

  • Using the docker pull command (as-is image as-is is pulled down)
  • Using the docker run command (as-is image is pulled down and container is created/started)
  • Using the docker build command (image can be customized)
  • Using the docker stack deploy command (Docker Compose)

 

Typically, this module is not included in the default Ansible collections, thus you will probably need to install the community.docker collection.

ansible-galaxy collection install community.docker

 

The docker_image module with the source: pull argument is similar to the docker pull command, to pull down an image. Here is how you would pull down the latest hello-world image.

AVOID TROUBLE

Often, root or sudo permission are needed. If you are running your playbook as a non-root user, you may need to use become to avoid Permission Denied.

---
- hosts: docker
  become: true
  become_user: root
  tasks:
  - docker_image:
      name: hello-world:latest
      source: pull
...

 

Let's say /usr/local/ansible/Dockerfile on your Ansible control node contains the following.

FROM hello-world:latest

 

The source: build argument is similar to the docker build command. Here is how you would copy Dockerfile from your Ansible control node to the target Docker systems and then use Dockerfile to build the latest hello-world image.

---
- hosts: docker
  become: true
  become_user: root
  tasks:
  - name: copy Dockerfile to Docker systems
    copy:
      src: /usr/local/ansible/Dockerfile
      dest: /tmp/Dockerfile

  - docker_image:
      name: hello-world
      source: build
      build:
        path: /tmp
        pull: false

  - name: delete Dockerfile
    file:
      path: /tmp/Dockerfile
      state: absent
...

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 6ff052 in the box below so that we can be sure you are a human.