In my playbook I supply a Jenkins build ID as follows: -e frontend_build_id=43

This ID is used to tag Docker images created during the build process. Later I want to remove old images as follows:

- name: remove old frontend images
  docker_image:
    state: absent
    name: "{{ docker_registry }}/{{ frontend_image_name }}"
    tag: "{{ item }}"
    force: yes
    with_sequence:
      start="{{ frontend_build_id }} - 10" end="{{ frontend_build_id }} - 1" stride=1

However I get following error:

TASK [FrontEnd : remove old frontend images] ***********************************
fatal: [10.98.68.116]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'item' is undefined\n\nThe error appears to have been in '/home/jenkins/workspace/myproject_development/roles/FrontEnd/tasks/main.yml': line 31, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: remove old frontend images\n  ^ here\n"}
  1. What do I do wrong?
  2. Maybe its better to achieve this with loop somehow?

1 Answers

1
Vladimir Botka On Best Solutions

Is this the sequence you're looking for?

with_sequence:
  start="{{ frontend_build_id - 10 }}" end="{{ frontend_build_id - 1 }}" stride=1

The default of 'stride' is 1. For simplicity, it can be removed.

with_sequence:
  start="{{ frontend_build_id - 10 }}" end="{{ frontend_build_id - 1 }}"

Loop 'range' will do the same. The end element is not inclusive and shall be incremented.

loop: "{{ range(frontend_build_id - 10, frontend_build_id)|list }}"

The explicit cast of the variable 'frontend_build_id' to the integer will make it more robust. Change each reference to 'frontend_build_id' to 'frontend_build_id|int'. For example:

with_sequence:
  start="{{ frontend_build_id|int - 10 }}" end="{{ frontend_build_id|int - 1 }}"

This should probably solve the problem

unsupported operand type(s) for -: 'unicode' and 'int'