团队,我不知何故是什么错误。.我正在执行多字符串搜索,因此对于未找到的每个字符串都将失败。
- name: "Validate kubectl access and k8s node lables"
debug:
msg: "kubectl get nodes --show-labels -l nodeType={{item}}"
with_items:
- gpu
- cpu
- monitoring
register: k8s_labelsresponse
- debug:
var: k8s_labelsresponse.stdout
failed_when: '"nodeType=gpu" not in k8s_labelsresponse.stdout or "nodeType=cpu" not in k8s_labelsresponse.stdout or "nodeType=monitoring" not in k8s_labelsresponse.stdout'
输出:
TASK [Validate kubectl access and k8s node lables]
ok: [target1] => (item=gpu) => {
"msg": "kubectl get nodes --show-labels -l nodeType=gpu"
}
ok: [target1] => (item=cpu) => {
"msg": "kubectl get nodes --show-labels -l nodeType=cpu"
}
ok: [target1] => (item=monitoring) => {
"msg": "kubectl get nodes --show-labels -l nodeType=monitoring"
}
TASK [debug] **************************************************************************************************************************************************
fatal: [target1]: FAILED! => {"msg": "The conditional check '\"nodeType=gpu\" not in k8s_labelsresponse.stdout or \"nodeType=cpu\" not in k8s_labelsresponse.stdout or \"nodeType=monitoring\" not in k8s_labelsresponse.stdout' failed. The error was: error while evaluating conditional (\"nodeType=gpu\" not in k8s_labelsresponse.stdout or \"nodeType=cpu\" not in k8s_labelsresponse.stdout or \"nodeType=monitoring\" not in k8s_labelsresponse.stdout): Unable to look up a name or access an attribute in template string ({% if \"nodeType=gpu\" not in k8s_labelsresponse.stdout or \"nodeType=cpu\" not in k8s_labelsresponse.stdout or \"nodeType=monitoring\" not in k8s_labelsresponse.stdout %} True {% else %} False {% endif %}).\nMake sure your variable name does not contain invalid characters like '-': argument of type 'AnsibleUndefined' is not iterable"}
首先,您的变量k8s_labelsresponse
是一个映射,因此您没有stdout
。看看debug: var=k8s_labelsresponse
您可以通过以下方式创建该变量:
msg:
- kubectl get nodes --show-labels -l nodeType=gpu
- kubectl get nodes --show-labels -l nodeType=cpu
- kubectl get nodes --show-labels -l nodeType=monitoring
但是此解决方案非常丑陋,因为它具有硬代码。我建议在Jinja2和set_fact的帮助下创建一个动态变量:
- hosts: localhost
vars:
params:
- cpu
- gpu
- monitoring
tasks:
- set_fact:
k8s_labelsresponse: "{% for param in params -%}
nodeType={{ param }}
{% endfor %}"
- debug:
msg: "{{ k8s_labelsresponse.splitlines() }}"
failed_when: '"nodeType=gpu" not in k8s_labelsresponse or "nodeType=cpu" not in k8s_labelsresponse or "nodeType=monitoring" not in k8s_labelsresponse'