Is there a better way to write these ansible tasks using jinja?

Viewed 46

I have this task in my playbook:

- 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

I think there is probably a way I could combine the two debug tasks. Maybe something like:

- debug: msg="{{inventory_hostname}} {{check_843_connection_count | int >0 ? '(PASS)' : '(FAIL)'}}  {{check_843_connection_count.stdout}} connections to port 843"

But, obviously, the above has syntax errors.

1 Answers

Jinja being a Python templating language, the inline if would write quite the same as in Python.
Mind that Ansible is written in Python, so, it also makes all the sense.

So, you could write this debug task:

- debug: 
    msg: >-
      {{ inventory_hostname }} 
      ({{ 'PASS' if check_843_connection_count.stdout | int > 0 else 'FAIL' }}) 
      {{ check_843_connection_count.stdout }} 
      connections to port 843
Related