Question:
I’ve got a dictionary with different names like
1 2 3 4 5 |
vars: images: - foo - bar |
Now, I want to checkout repositories and afterwards build docker images only when the source has changed.
Since getting the source and building the image is the same for all items except the name I created the tasks with with_items: images
and try to register the result with:
1 2 |
register: "{{ item }}" |
and also tried
1 2 |
register: "src_{{ item }}" |
Then I tried the following condition
1 2 |
when: "{{ item }}|changed" |
and
1 2 |
when: "{{ src_item }}|changed" |
This always results in fatal: [piggy] => |changed expects a dictionary
So how can I properly save the results of the operations in variable names based on the list I iterate over?
Update: I would like to have something like that:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
- hosts: all vars: images: - foo - bar tasks: - name: get src git: repo: git@foobar.com/repo.git dest: /tmp/repo register: "{{ item }}_src" with_items: images - name: build image shell: "docker build -t repo ." args: chdir: /tmp/repo when: "{{ item }}_src"|changed register: "{{ item }}_image" with_items: images - name: push image shell: "docker push repo" when: "{{ item }}_image"|changed with_items: images |
Answer:
So how can I properly save the results of the operations in variable names based on the list I iterate over?
You don’t need to. Variables registered for a task that has with_items
have different format, they contain results for all items.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
- hosts: localhost gather_facts: no vars: images: - foo - bar tasks: - shell: "echo result-{{item}}" register: "r" with_items: "{{ images }}" - debug: var=r - debug: msg="item.item={{item.item}}, item.stdout={{item.stdout}}, item.changed={{item.changed}}" with_items: "{{r.results}}" - debug: msg="Gets printed only if this item changed - {{item}}" when: item.changed == true with_items: "{{r.results}}" |