Use BuildKit for docker build within Ansible

1.2k Views Asked by At

I am using this Ansible module community.docker.docker_image to build docker images. I wanted to use the --secret flag and therefore I need to enable BuildKit.

I did edit the /etc/docker/daemon.json file and added this line "features": { "buildkit": true } then restarted the docker service.

However, Ansible still showing error when running;

fatal: [localhost]: FAILED! => {"changed": false, "msg": "Error building local:5000/test - code: None, message: the --mount option requires BuildKit. Refer to https://docs.docker.com/go/buildkit/ to learn how to build images with BuildKit enabled ...

ansible task:

- name: Build an image and push it to a private repo
  community.docker.docker_image:
    build:
      path: "{{ role_path }}/files/test"
      args:
        secret: 'id=test_app_secret_id,src={{ tempfile_1.path }}'
    name: local:5000/test
    tag: v1.1.2
    push: yes
    force_tag: yes
    source: build

And in Dockerfile I am using the secret as following:

RUN --mount=type=secret,id=test_app_secret_id

Any ideas on how to resolve this issue?

1

There are 1 best solutions below

0
On

Building with buildkit is not (yet as of 21st November 2023...) supported by the Ansible community.docker.docker_image module. Quoting the notes in documentation

Building images is done using Docker daemon’s API. It is not possible to use BuildKit / buildx this way.

So for time being, the solution is to go through shell setting the correct environment. Something like:

- name: Build an image with BuildKit and push it to a private repo
  vars:
    image: local:5000/test
    tag: v1.1.2
  ansible.builtin.shell:
    cmd: |-
      docker build --secret "id=test_app_secret_id,src={{ tempfile_1.path }}" -t {{ image }}:{{ tag }} .
      docker push {{ image }}:{{ tag }}
    chdir: "{{ role_path }}/files/test"
  environment: 
    DOCKER_BUILDKIT: 1