有没有更好的方法来使用 jinja 编写这些 ansible 任务?
Is there a better way to write these ansible tasks using jinja?
我的剧本中有这个任务:
- 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
- debug: msg="{{inventory_hostname}} (PASS) {{check_843_connection_count.stdout}} connections to port 843"
when: check_843_connection_count.stdout | int > 0
- debug: msg="{{inventory_hostname}} (FAIL) {{check_843_connection_count.stdout}} connections to port 843"
when: check_843_connection_count.stdout | int <= 0
when:
- stype is defined and stype == "foo"
tags: mmr_check_843_estiablished
我认为可能有一种方法可以将这两个 debug
任务结合起来。可能是这样的:
- debug: msg="{{inventory_hostname}} {{check_843_connection_count | int >0 ? '(PASS)' : '(FAIL)'}} {{check_843_connection_count.stdout}} connections to port 843"
但是,很明显,上面有语法错误。
Jinja 是一种 Python 模板语言,inline if 的编写方式与 Python.
完全相同
请注意,Ansible 是用 Python 编写的,因此,它也很有意义。
因此,您可以编写此调试任务:
- debug:
msg: >-
{{ inventory_hostname }}
({{ 'PASS' if check_843_connection_count.stdout | int > 0 else 'FAIL' }})
{{ check_843_connection_count.stdout }}
connections to port 843
我的剧本中有这个任务:
- 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
- debug: msg="{{inventory_hostname}} (PASS) {{check_843_connection_count.stdout}} connections to port 843"
when: check_843_connection_count.stdout | int > 0
- debug: msg="{{inventory_hostname}} (FAIL) {{check_843_connection_count.stdout}} connections to port 843"
when: check_843_connection_count.stdout | int <= 0
when:
- stype is defined and stype == "foo"
tags: mmr_check_843_estiablished
我认为可能有一种方法可以将这两个 debug
任务结合起来。可能是这样的:
- debug: msg="{{inventory_hostname}} {{check_843_connection_count | int >0 ? '(PASS)' : '(FAIL)'}} {{check_843_connection_count.stdout}} connections to port 843"
但是,很明显,上面有语法错误。
Jinja 是一种 Python 模板语言,inline if 的编写方式与 Python.
完全相同
请注意,Ansible 是用 Python 编写的,因此,它也很有意义。
因此,您可以编写此调试任务:
- debug:
msg: >-
{{ inventory_hostname }}
({{ 'PASS' if check_843_connection_count.stdout | int > 0 else 'FAIL' }})
{{ check_843_connection_count.stdout }}
connections to port 843