使用with_items进行迭代并注册 [英] iteration using with_items and register
问题描述
在我一直困扰着几个小时的问题上寻求帮助.我想遍历一个列表,运行一个命令,为每个命令注册输出,然后对每个唯一的寄存器{{someregister}}.stdout
Looking for help with a problem I've been struggling with for a few hours. I want to iterate over a list, run a command, register the output for each command and then iterate with debug over each unique registers {{ someregister }}.stdout
例如,以下代码将吐出"msg":"1" 和"msg":"2"
For example, the following code will spit out "msg": "1" and "msg": "2"
---
- hosts: localhost
gather_facts: false
vars:
numbers:
- name: "first"
int: "1"
- name: "second"
int: "2"
tasks:
- name: Register output
command: "/bin/echo {{ item.int }}"
register: result
with_items: "{{ numbers }}"
- debug: msg={{ item.stdout }}
with_items: "{{ result.results }}"
但是,如果我尝试在使用with_list命名的寄存器变量中捕获命令的输出,则无法访问列表或列表中的元素.例如,将代码略微更改为:
If however, I try and capture the output of a command in a register variable that is named using with_list, I am having trouble accessing the list or the elements within it. For example, altering the code slightly to:
---
- hosts: localhost
gather_facts: false
vars:
numbers:
- name: "first"
int: "1"
- name: "second"
int: "2"
tasks:
- name: Register output
command: "/bin/echo {{ item.int }}"
register: "{{ item.name }}"
with_items: "{{ numbers }}"
- debug: var={{ item.name.stdout }}
with_items: "{{ numbers }}"
给我:
TASK [debug]
> ******************************************************************* fatal: [localhost]: FAILED! => {"failed": true, "msg": "'unicode
> object' has no attribute 'stdout'"}
是否不可能将命令的输出动态命名为寄存器,以便稍后在播放中调用该命令?我希望命令的每次迭代及其后继的 register 名称都可以唯一地访问,例如,给定最后一个示例,我希望可以注册名为"first"的变量和第二",但没有.
Is it not possible to dynamically name the register the output of a command which can then be called later on in the play? I would like each iteration of the command and its subsequent register name to be accessed uniquely, e.g, given the last example I would expect there to be variables registered called "first" and "second" but there aren't.
从debug节中删除with_items,仅使用first.stdout显式定义var或消息即可返回未定义".
Taking away the with_items from the debug stanza, and just explicitly defining the var or message using first.stdout returns "undefined".
Ansible版本是Centos 7_2上的2.0.2.0.
Ansible version is 2.0.2.0 on Centos 7_2.
谢谢.
推荐答案
OK so I found a post on stackoverflow that helped me better understand what is going on here and how to access the elements in result.results.
我最终得到的代码是:
---
- hosts: localhost
gather_facts: false
vars:
numbers:
- name: "first"
int: "1"
- name: "second"
int: "2"
tasks:
- name: Register output
command: "/bin/echo {{ item.int }}"
register: echo_out
with_items: "{{ numbers }}"
- debug: msg="item.item={{item.item.name}}, item.stdout={{item.stdout}}"
with_items: "{{ echo_out.results }}"
哪个给了我想要的结果:
Which gave me the desired result:
"msg": "item.item=first, item.stdout=1"
"msg": "item.item=second, item.stdout=2"
这篇关于使用with_items进行迭代并注册的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!