rik1254
rik1254

Reputation: 13

Understanding Ansible conditionals

I have a playbook (CIS compliance standard) with multiple tasks and I want to produce a "success" or "failed" depending on the ansible return code.

---
- name: 2.2.# Ensure ### Server is not enabled
  block:
    - name: Check if ### exists
      stat: path=/usr/lib/systemd/system/###.service
      register: exists

    - name: Disable if exists
      service:
        name: ###
        state: stopped
        enabled: no
      when: exists.stat.exists
      register: result



- name: To File
  block:
    - name: Success
      lineinfile:
        dest: ./results/{{ customer }}-{{ scan_type }}-{{ inventory_hostname }}.txt
        line: "{{ inventory_hostname }} 2.2.9 success"
        insertafter: EOF
      delegate_to: localhost
      check_mode: False
      when: ((result is skipped) or (result.enabled == false))

    - name: Failed
      lineinfile:
        dest: ./results/{{ customer }}-{{ scan_type }}-{{ inventory_hostname }}.txt
        line: "{{ inventory_hostname }} 2.2.9 failed"
        insertafter: EOF
      delegate_to: localhost
      check_mode: False
      when: ((result is not skipped) or (result.enabled == true))

From my observation, 'result' can have two different outputs depending on if the "Disable if exists" block is triggered. If it is triggered, it'll give an output based on the "service" module. If it is skipped, it'll give the generic Ansible output.

I'm fine with that, but what I can't seem to work out is the conditional statement.

when: ((result is not skipped) or (result.enabled == true))

This will always try to resolve both options, so if the module triggers, it will fail because "skipped" is not an attribute of the service module. If it skips, it'll pass, but obviously fail if it ever gets triggered. It's like it wants all conditions to exist before evaluating despite the "or" statement.

What am I doing wrong?

Upvotes: 0

Views: 55

Answers (1)

larsks
larsks

Reputation: 311606

Do you mean result is skipped rather than result is not skipped? In any case, you can solve this using the default filter, which provides a default value if the input expression is undefined. For example:

when: result.enabled|default(false) == true

Of course, since that's a boolean, you can further simplify it to:

when: result.enabled|default(false)

Upvotes: 1

Related Questions