deiga
deiga

Reputation: 1637

How do I tag a local docker image with ansible docker_image module?

I'm building a local docker image and I'd like to tag it, but I have no idea how the repository field should be filled for a docker image I just built locally.

Is tagging local images even possible with the docker_image module?

Upvotes: 7

Views: 11826

Answers (3)

Paweł BB Drozd
Paweł BB Drozd

Reputation: 4913

Seems that there is better solution with docker_image:

tasks:
  - name: build_image
    docker_image:
      name: test_img:latest     # Name of image, may be with repo path.
      path: .
      state: present
    register: image_build
  
  - name: tag_version
    docker_image:
      name: test_img:latest     # Equal to name in build task.
      repository: test_img:1.2  # New tag there.
      pull: no
      state: present
    when: image_build.changed

Effect:

    $ docker images
    REPOSITORY   TAG       IMAGE ID            CREATED              SIZE
    test_img     1.2       ab14e8cce7ef        9 seconds ago        142MB
    test_img     latest    ab14e8cce7ef        9 seconds ago        142MB

Works also with pushing to repo (need to change name to full repo path).

Upvotes: 11

deiga
deiga

Reputation: 1637

I was able to find out that the repository of the docker_image module is just the name of the image when it's locally built.

This is how you first build the image with tag latest and then add a tag to it.

- name: Build docker image
  become: yes
  docker_image:
    path: /tmp/foo
    name: foo
    state: present

- name: Tag docker image
  become: yes
  docker_image:
    name: foo
    repository: foo
    tag: "{{ version.stdout }}"
    state: present

Upvotes: 1

BMitch
BMitch

Reputation: 263469

You can build and tag in one command. If you want it to stay local, you can't include a repository in the name (no /). The tag is just the equivalent of "latest". So the result looks something like:

  - name: 'Build an image with a tag'
    docker_image:
      path: .
      name: ansible-module
      tag: v1
      state: present

And the result will look like:

$ docker images
REPOSITORY                  TAG                 IMAGE ID            CREATED             SIZE
ansible-module              v1                  39be0dcc8dfa        2 minutes ago       1.093 MB

If you want to include your registry url or repository name (docker hub login) and don't want to automatically push after building, I don't believe you can use this Ansible plugin.


Update, for an additional tag, you can do:

  - name: 'Build an image'
    docker_image:
      path: .
      name: ansible-module
      tag: v1
      state: present
    register: docker_build

  - name: 'Retag image'
    shell: docker tag ansible-module:v1 ansible-module:dev
    when: docker_build.changed

Upvotes: 7

Related Questions