A way to include a string separator e.g. `/` based on whether a value exists in a Jinja2 template

I have a bunch of container images running on my internal registry and some images which I wish to pull from the Public Docker Hub.

Docker Hub’s registry is the default value when there is no specific registry name defined.

The way the docker client can pull the image from distinct registries is by the following string:

registry_uri/namespace/image:version

for the following variables that can be injected into a playbook how can set some sensible defaults so that:

when registry_uri exists add the / to the Jinja2 template else just use the namespace/image:version?

I am currently stuck with:

- community.docker.docker_pull:
    name: |
      {{ item.registry_uri | default('docker.io') }}/
      {{ item.namespace | default( 'library') }}/
      {{ item.image_name }}:{{ item.image_version | default('latest') }}
  loop: "{{ images }}"

where images:


images:
  - registry_uri: myregistry.internal # should pull from internal reg
    namespace: myns
    image_name: img1
 - image_name: centos # should pull from docker hub

The string separator / is a bit mischievous when it comes to pulling images from distinct registries.

Any help would appreciated.

In a nutshell

for images from docker hub i would like the jinja2 template to resolve to just the name of the image if registry / namespace are not mentioned

Hi, how about using ansible.builtin.path_join?

- community.docker.docker_pull:
    name: "{{ image | ansible.builtin.path_join }}"
  vars:
    image:
      - "{{ item.registry_uri | default('') }}"
      - "{{ item.namespace | default('') }}"
      - "{{ item.image_name }}:{{ item.image_version | default('latest') }}"
  loop: "{{ images }}"
2 Likes