1
votes

Running Ansible 2.9.3

Working in a large environment with hosts coming and going on a daily basis, I need to use wildcard hostnames in a host group: ie:

[excluded_hosts]

host01

host02

host03

[everyone]

host*

in my playbook I have


  • name: "Test working with host groups"

    hosts: everyone,!excluded_hosts

    connection: local

    tasks:

The problem is, the task is running on hosts in the excluded group. If I specifically list one of the excluded hosts in the everyone group, that host then gets properly excluded.

So Ansible isn't working as one might assume it would.

What's the best way to get this to work?

I tried: hosts: "{{ ansible_hostname }}",!excluded_hosts

but it errored as invalid yaml syntax.

requirements: I can not specifically list each host, they come and go too frequently. The playbooks are going to be automatically copied down to each host and the execution started afterwards, therefore I need to use the same ansible command line on all hosts.

2
We aren't sure why you are trying to do what you are saying - so it is difficult to know if we are answering the question correctly - can you explain your motivation more when asking questions?Mirv - Matt
It's a duplicate of the question Is there a way to use a regular expression to match hosts in ansible?. I voted to close this one.Vladimir Botka
If they "they come and go too frequently," it sounds like you need to create a dynamic inventory script.Jack

2 Answers

0
votes

I was able to come up with a solution to my problem:

---
- name: "Add host name to thishost group"

hosts: localhost

connection: local

tasks:

- name: "add host"

  ini_file:

    path: /opt/ansible/etc/hosts

    section: thishost

    option: "{{ ansible_hostname }}"

    allow_no_value: yes

-  meta: refresh_inventory

  - name: "Do tasks on all except excluded_hosts"

hosts: thishost,!excluded_hosts

connection: local

tasks:

What this does is it adds the host's name to a group called "thishost" when the playbook runs. Then it refreshs the inventory file and runs the next play. This avoids a having to constantly update the inventory with thousands of hosts, and avoids the use of wildcards and ranges.

-1
votes

Blaster,

Have you tried assigning hosts by IP address yet?

You can use wildcard patterns ... IP addresses, as long as the hosts are named in your inventory by ... IP address:

192.0.\*
\*.example.com
\*.com**

https://docs.ansible.com/ansible/latest/user_guide/intro_patterns.html