如何使用Jinja语法优化Ansible任务 合并两个条件判断debug语句
正确实现方式
你原有写法的错误点有两处:
- 取值逻辑错误:判断连接数时直接对
check_843_connection_count注册变量整体做int转换,没有取其返回的标准输出属性stdout - 语法不匹配:Ansible采用Jinja2模板语法,三元表达式不支持
条件?真值:假值的写法,对应格式为{{ 真值 if 条件 else 假值 }}
合并后的单条debug任务正确写法
- debug: msg: "{{ inventory_hostname }} {{ '(PASS)' if check_843_connection_count.stdout | int > 0 else '(FAIL)' }} {{ check_843_connection_count.stdout }} connections to port 843"
完整优化后的任务块代码
新增了changed_when和failed_when参数,避免grep无匹配内容时shell任务异常中断,同时修正了原有标签的拼写错误:
- name: service check block: - name: service check | check port 843 is connected. shell: | netstat -n | grep 843 | grep ESTABLISHED |wc -l register: check_843_connection_count changed_when: false failed_when: false - name: service check | output port 843 check result debug: msg: "{{ inventory_hostname }} {{ '(PASS)' if check_843_connection_count.stdout | int > 0 else '(FAIL)' }} {{ check_843_connection_count.stdout }} connections to port 843" when: - stype is defined - stype == "foo" tags: mmr_check_843_established
内容的提问来源于stack exchange,提问作者Red Cricket
相关产品推荐
相关产品推荐

