Link conditions with or under failed_when:

Hello Community,

i am trying to verify my FQDN in a playbook against some subdomains.

  tasks: 
 - name: Check Hostname
   debug:
     var: ansible_fqdn
   failed_when:  "'.1.domain.local' or '.2.domain.local' or '.3.domain.local' not in ansible_fqdn"

Where is my mistake?

Thanks in advance.

2 Likes

Hi @myservertechnik and welcome to the forum.

For future reference you can use three backticks (```) around your code and it will make it easier to read (monospace font and it avoids markdown stuff like converting the initial dash to a list bullet).

Also, it would be helpful in the future to include the error you are seeing, and what you are expecting to see.

In this case, the problem is almost certainly your failed_when line.

This uses a Python-style (Jinja2) syntax, and so your line is getting parsed like this:

failed_when: "('.1.domain.local') or ('.2.domain.local') or ('.3.domain.local' not in ansible_fqdn)"
And non-empty strings are truthy...
$ ansible -m debug -a "msg={{ 'true' if 'I am nonempty' else 'false' }}" localhost
localhost | SUCCESS => {
    "msg": "true"
}

…so your expression simplifies to:

failed_when: True or True or ('.3.domain.local' not in ansible_fqdn)

You’d want to use a full boolean expression for each of these. For example:

failed_when: "'.1.domain.local' not in ansible_fqdn or '.2.domain.local' not in ansible_fqdn or '.3.domain.local' not in ansible_fqdn"

However, you might also consider using a regex test here instead.

Perhaps something like this could work:

failed_when: ansible_fqdn is not regex('\.[1-3]\.domain\.local')

Example:

$ ansible -m debug -a "msg={{ 'foo.1.domain.local' is regex('\.[1-3]\.domain\.local') }}" localhost
localhost | SUCCESS => {
    "msg": true
}

$ ansible -m debug -a "msg={{ 'foo.99.domain.local' is regex('\.[1-3]\.domain\.local') }}" localhost
localhost | SUCCESS => {
    "msg": false
}
6 Likes

going further you could also make it multi-line similar to and statements by just adding the or at the end. In fact ansible-lint might encourage you do this with certain line lengths

when: >
  "'.1.domain.local' not in ansible_fqdn or
  '.2.domain.local' not in ansible_fqdn or
  .3.domain.local' not in ansible_fqdn"

have not tested the above, but should be close to correct

1 Like

Yep, also a valid solution, though you’d want to remove the outer quotes (the > makes them redundant and they will likely break the expression since it is just getting evaluated to a string - I’m not sure if ansible will reject it or just evaluate it to True).

1 Like