munish
munish

Reputation: 4634

How to show failure message for a loop with when in ansible?

---
- name: install httpd and mod_ssl
  hosts: all
  vars_files:
    - vars/package_list.yaml
  tasks:
    - name: install httpd,firewalld and mod_ssl
      yum:
        name: "{{ item }}"
        state: latest
      loop: "{{ package_list }}"
      when: >
        ( ansible_facts['distribution'] == 'Ubuntu' )
        or
        ( ansible_facts['distribution'] == 'CentOS' and ansible_facts['distribution'] == 'Fedora' and ansible_facts['distribution_version'] is version( '8' , '>=') )

    # some other tasks.

How can I send a failure message if task install httpd, firewalld and mod_ssl fails based on the condition that if distribution is ubuntu then proceed with the install or if the distribution is 'CenOS' ( Not 'Fedora' ) with version >= '8' then proceed with the install or show a failure message. If the condition is not met then it exits with the failure message or else it continues with the rest of the play.

something like:

if ( 
     ( distro == 'Ubuntu' ) or 
     ( distro == 'CentOS' and distro != 'Fedora' and version >= 8)
   )
    then install httpd, firewalld, mod_ssl and proceed further
else
    print "Error: requirements not met for setup"

Upvotes: 1

Views: 275

Answers (1)

Zeitounator
Zeitounator

Reputation: 44615

Simplify the pattern:

  1. fail early if your target does not meet the requirement
  2. go on with the rest of your tasks if it does

Note: I'm not sure I fully understand your condition which differs in your example playbook and pseudo code and is not really clear in both cases. So this is just a layout example. Put whatever condition is needed.

Moreover:

  • although it is possible, using yum on Ubuntu looks a bit awkward.
  • looping over yum is discouraged. You should pass the list of packages directly in the name attribute (fixed below)
---
- name: install something on my supported targets
  hosts: all

  vars_files:
    - vars/package_list.yml

  tasks:
    - name: Fail if the target isn't supported
      ansible.builtin.fail:
        msg: target isn't supported
      when: my_target_condition_is_false
         
    - name: install packages on supported target
      ansible.builtin.yum:
        name: "{{ package_list }}"
        state: latest

    # some other tasks.

Upvotes: 2

Related Questions