Loop over two versions with multiple subelements

Viewed 204

I am trying to reduce the amount of tasks we have to repeat for some of our playbooks when publishing versions of services to our repository. What I want to do is publish the latest version "latest" and the version of it which we use set_fact for and loop through all the services we define.

Example of current:

  - name: Push Helm Template to ACR
    command: helm chart push {{ docker_registry }}/helm/{{ service_name }}:{{ item }}
    loop:
      - latest
      - "{{ version }}"

What I want to do is have it publish all latest versions of

- service1
- service2
- service3

etc

and in the same task, publish the {{ version }} of that service using the same loop. Is this possible to do in one task or is it better to just separate out the tasks?

1 Answers

See the product filter. In a nutshell:

- hosts: localhost
  gather_facts: false

  vars:
    version_list:
      - latest
      - "{{ version }}"

    services:
      - service1
      - service2
      - service3

    docker_registry: https://my.reg.com

  tasks:
    - name: set version
      set_fact:
        version: a.b.c

    - name: Show how to use with a debug task
      debug:
        msg: "Command is:
          helm chart push {{ docker_registry }}/helm/{{ item.0 }}:{{ item.1 }}"
      loop: "{{ services | product(version_list) }}"

Which gives:

PLAY [localhost] *****************************************************************************

TASK [set version] *****************************************************************************
ok: [localhost]

TASK [Show how to use with a debug task] *****************************************************************************
ok: [localhost] => (item=['service1', 'latest']) => {
    "msg": "Command is: helm chart push https://my.reg.com/helm/service1:latest"
}
ok: [localhost] => (item=['service1', 'a.b.c']) => {
    "msg": "Command is: helm chart push https://my.reg.com/helm/service1:a.b.c"
}
ok: [localhost] => (item=['service2', 'latest']) => {
    "msg": "Command is: helm chart push https://my.reg.com/helm/service2:latest"
}
ok: [localhost] => (item=['service2', 'a.b.c']) => {
    "msg": "Command is: helm chart push https://my.reg.com/helm/service2:a.b.c"
}
ok: [localhost] => (item=['service3', 'latest']) => {
    "msg": "Command is: helm chart push https://my.reg.com/helm/service3:latest"
}
ok: [localhost] => (item=['service3', 'a.b.c']) => {
    "msg": "Command is: helm chart push https://my.reg.com/helm/service3:a.b.c"
}

PLAY RECAP *****************************************************************************
localhost: ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
Related