gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 09:20:13 24 4
gpt4 key购买 nike

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

vars:
images:
- foo
- bar

现在,我想 checkout 存储库,然后仅在源更改时构建 docker 镜像。
由于获取源和构建图像对于除名称之外的所有项目都是相同的,因此我使用 with_items: images 创建了任务
并尝试注册结果:
register: "{{ item }}"

也试过了
register: "src_{{ item }}"

然后我尝试了以下条件
when: "{{ item }}|changed"


when: "{{ src_item }}|changed"

这总是导致 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

最佳答案

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



你不需要。为具有 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}}"

关于loops - 在 Ansible playbook 的 with_items 循环中注册变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29512443/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com