在 Ansible playbook 的 with_items 循环中注册变量 [英] Register variables in with_items loop in Ansible playbook

查看:32
本文介绍了在 Ansible playbook 的 with_items 循环中注册变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本不同名字的字典,比如

I've got a dictionary with different names like

vars:
    images:
      - foo
      - bar

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

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:

register: "{{ item }}"

也试过了

register: "src_{{ item }}"

然后我尝试了以下条件

when: "{{ item }}|changed"

when: "{{ src_item }}|changed"

这总是导致 fatal: [piggy] =>|changed 需要字典

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

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:

- 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

推荐答案

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

So how can I properly save the results of the operations in variable names based on the list I iterate over?

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

You don't need to. Variables registered for a task that has with_items have different format, they contain results for all 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}}"

这篇关于在 Ansible playbook 的 with_items 循环中注册变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆