在Ansible playbook中的with_items循环中注册变量

sou*_*ver 29 variables loops ansible

我有一本不同名字的字典

vars:
    images:
      - foo
      - bar
Run Code Online (Sandbox Code Playgroud)

不,我想检查存储库,然后仅在源已更改时才构建docker镜像.由于获取源和构建图像的所有项目都是相同的,除了我创建任务的名称,with_items: images 并尝试使用以下内容注册结果:

register: "{{ item }}"
Run Code Online (Sandbox Code Playgroud)

并尝试过

register: "src_{{ item }}"
Run Code Online (Sandbox Code Playgroud)

然后我尝试了以下条件

when: "{{ item }}|changed"
Run Code Online (Sandbox Code Playgroud)

when: "{{ src_item }}|changed"
Run Code Online (Sandbox Code Playgroud)

这总是导致 fatal: [piggy] => |changed expects a dictionary

那么如何根据迭代的列表正确保存变量名中的操作结果呢?

更新:我希望有类似的东西:

- 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
Run Code Online (Sandbox Code Playgroud)

Kas*_*yap 49

那么如何根据迭代的列表正确保存变量名中的操作结果呢?

你不需要.为with_items具有不同格式的任务注册的变量,它们包含所有项目的结果.

- 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}}"
Run Code Online (Sandbox Code Playgroud)