团队,我收到json_query的响应,它是一个dict键:值,我想遍历所有值并为每个值运行ssh命令
以下获取了我所有节点的列表
- name: "Fetch all nodes from clusters using K8s facts"
k8s_facts:
kubeconfig: $WORKSPACE
kind: Node
verify_ssl: no
register: node_list
- debug:
var: node_list | json_query(query)
vars:
query: 'resources[].{node_name: metadata.name, nodeType: metadata.labels.nodeType}'
ok: [target1] => {
"node_list | json_query(query)": [
{
"nodeType": null,
"node_name": "host1"
},
{
"nodeType": "gpu",
"node_name": "host2"
},
{
"nodeType": "gpu",
"node_name": "host3"
}
]
}
要写的剧本:解析node_name并将其在ssh命令中用于所有1-3主机
- name: "Loop on all nodeNames and ssh."
shell: ssh -F ~/.ssh/ssh_config bouncer@{{ item }}.internal.sshproxy.net "name -a"
register: ssh_result_per_host
failed_when: ssh_result_per_host.rc != 0
with_item: {{ for items in query.node_name }}
- debug:
var: ssh_result_per_host.stdout_lines
> The offending line appears to be:
failed_when: ssh_result_per_host.rc != 0
with_item: {{ for items in query.node_name }}
^ here
当我执行循环时,解决方案2也会失败:
shell: ssh -F ~/.ssh/ssh_config bouncer@{{ item.metadata.name }}.sshproxy.internal.net "name -a"
loop: "{{ node_list.resources }}"
loop_control:
label: "{{ item.metadata.name }}"
输出溶胶2:
failed: [target1] (item=host1) => {"msg": "Invalid options for debug: shell"}
failed: [target1] (item=host2) => {"msg": "Invalid options for debug: shell"}
fatal: [target1]: FAILED! => {"msg": "All items completed"}
答案 0 :(得分:1)
要扩展Ash的正确答案:
$company_id
另外,除非您确实只是想运行该一个 - name: "Fetch all nodes from clusters using K8s facts"
k8s_facts:
kubeconfig: $WORKSPACE
kind: Node
verify_ssl: no
register: node_list
- set_fact:
k8s_node_names: '{{ node_list | json_query(query) | map(attribute="node_name") | list }}'
vars:
query: 'resources[].{node_name: metadata.name, nodeType: metadata.labels.nodeType}'
- name: "Loop on all nodeNames and ssh."
shell: ssh -F ~/.ssh/ssh_config bouncer@{{ item }}.internal.sshproxy.net "name -a"
register: ssh_result_per_host
with_items: '{{ k8s_node_names }}'
命令,否则ansible会通过add_host:
来思考该问题:
ssh
这是一个人为的示例,因为如果您实际上只想获取kubernetes节点列表并在剧本中使用它们,则可以使用a dynamic inventory script
答案 1 :(得分:0)
不是with_item
,而是with_items
您不能使用with_item: {{ for items in query.node_name }}
将值保存到变量,然后在with_items: {{ new_variable }}