Ansible:使命令的输出成为下一个命令的键值项/变量

ady*_*531 3 variables allocation output ansible

我想将此输出(来自上一个命令)用作键值数组或同一剧本中下一个命令的清单

stdout:
hot-01: 10.100.0.101
hot-02: 10.100.0.102
hot-03: 10.100.0.103
....
hot-32: 10.100.0.132
Run Code Online (Sandbox Code Playgroud)

像这样:

- shell: "echo {{ item.key }} has value {{ item.value }}"
  with_items: "{{ output.stdout_lines }}"
Run Code Online (Sandbox Code Playgroud)

或者:

- add_host: name={{ item.key }} ansible_ssh_host={{ item.value }}
  with_items: "{{ output.stdout_lines }}"
Run Code Online (Sandbox Code Playgroud)

echo 命令的期望输出:

hot-01 has value 10.100.0.101
Run Code Online (Sandbox Code Playgroud)

我也试过 with_dict: "{{ output.stdout }}" 但仍然没有运气

"fatal: [ANSIBLE] => with_dict expects a dict"
Run Code Online (Sandbox Code Playgroud)

zua*_*azo 6

AFAIK 没有 Jinja2 过滤器可以将字符串转换为字典。

但在您的特定情况下,您可以使用python 的split字符串函数将键与值分开:

- shell: "echo {{ item.split(': ')[0] }} has value {{ item.split(': ')[1] }}"
  with_items: "{{ output.stdout_lines }}"
Run Code Online (Sandbox Code Playgroud)

我知道,不得不使用 split 两次有点草率。

由于在这种情况下您的输出是有效的 YAML,您还可以执行以下操作:

- shell: "echo {{ item.key }} has value {{ item.value }}"
  with_dict: "{{ output.stdout | from_yaml }}"
Run Code Online (Sandbox Code Playgroud)

作为最后的手段,您还可以创建自己的 ansible 模块来创建 Jinja2 过滤器来覆盖您的情况。有一个split模块过滤器,您可以在这里用作灵感:https : //github.com/timraasveld/ansible-string-split-filter