Search code examples
includeansiblegroupname

Ansible: Include task only when server is not in group


I have some groups with different names and something like "raw-webservers", "raw-db", ... Now I want to include a playbook if the server is in a group which begins with 'raw-*' (works) and include another playbook if the server is not in a group which begins with 'raw-'. I have not been able to figure out how to do the last thing by specifying only a subset of the group.

- include_tasks: change_password.yml
  when: "'raw-' not in group_names"   # works only with complete group names


- include_tasks: change_password_raw.yml
  when: "group_names | search('raw-')"   # works

I've tried 'when: "group_names | not search('raw-')"' but it doesn't work. Any ideas?


Solution

  • You can do this using a few methods. Here is a sample playbook showing two such methods. One using select and the other using search.

    ---
    - hosts: all
      gather_facts: no
      tasks:
        - debug:
            msg: "hello world using select"
          delegate_to: 127.0.0.1
          when: group_names | select('match','raw-*') | list | length  > 0
    
        - debug:
            msg: "hello world using search"
          delegate_to: 127.0.0.1
          when: group_names | join(" ") is search('raw-')
    

    You'll see here that search works on strings and not lists, hence why the join.

    Alternative to this, you can use another group for this. For example, your inventory could add the following.

    [raw:children]
    db
    

    And this could be tested as 'raw' in group_names.