Ansible:使命令的输出成为下一个命令的键值 item/variable
Ansible: make output from a command become a key-value item/variable for the next command
我想将此输出(来自上一个命令)用作键值数组或用作同一剧本中下一个命令的清单
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
像这样:
- shell: "echo {{ item.key }} has value {{ item.value }}"
with_items: "{{ output.stdout_lines }}"
或:
- add_host: name={{ item.key }} ansible_ssh_host={{ item.value }}
with_items: "{{ output.stdout_lines }}"
echo 命令的期望输出:
hot-01 has value 10.100.0.101
我也试过 with_dict: "{{ output.stdout }}" 但还是不行
"fatal: [ANSIBLE] => with_dict expects a dict"
据我所知,没有 Jinja2 过滤器可以将字符串转换为字典。
但在您的特定情况下,您可以使用 python's split
string function 将键与值分开:
- shell: "echo {{ item.split(': ')[0] }} has value {{ item.split(': ')[1] }}"
with_items: "{{ output.stdout_lines }}"
我知道,不得不使用 split 两次有点草率。
在这种情况下,您的输出是有效的 YAML,您还可以执行以下操作:
- shell: "echo {{ item.key }} has value {{ item.value }}"
with_dict: "{{ output.stdout | from_yaml }}"
作为最后的手段,您还可以创建自己的 ansible 模块来创建 Jinja2 过滤器来涵盖您的案例。这里有一个 split
模块过滤器,您可以将其用作灵感:https://github.com/timraasveld/ansible-string-split-filter
我想将此输出(来自上一个命令)用作键值数组或用作同一剧本中下一个命令的清单
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
像这样:
- shell: "echo {{ item.key }} has value {{ item.value }}"
with_items: "{{ output.stdout_lines }}"
或:
- add_host: name={{ item.key }} ansible_ssh_host={{ item.value }}
with_items: "{{ output.stdout_lines }}"
echo 命令的期望输出:
hot-01 has value 10.100.0.101
我也试过 with_dict: "{{ output.stdout }}" 但还是不行
"fatal: [ANSIBLE] => with_dict expects a dict"
据我所知,没有 Jinja2 过滤器可以将字符串转换为字典。
但在您的特定情况下,您可以使用 python's split
string function 将键与值分开:
- shell: "echo {{ item.split(': ')[0] }} has value {{ item.split(': ')[1] }}"
with_items: "{{ output.stdout_lines }}"
我知道,不得不使用 split 两次有点草率。
在这种情况下,您的输出是有效的 YAML,您还可以执行以下操作:
- shell: "echo {{ item.key }} has value {{ item.value }}"
with_dict: "{{ output.stdout | from_yaml }}"
作为最后的手段,您还可以创建自己的 ansible 模块来创建 Jinja2 过滤器来涵盖您的案例。这里有一个 split
模块过滤器,您可以将其用作灵感:https://github.com/timraasveld/ansible-string-split-filter