Reputation: 3840
I know that one can add host with the following task:
- name: Add new instance to host group
add_host:
hostname: '{{ item.public_ip }}'
groupname: "tag_Name_api_production"
with_items: ec2.instances
But I can't seem to find a way to remove a host from inventory. Is there any way to do this?
Upvotes: 15
Views: 17475
Reputation: 6158
You can just stop the play for those hosts:
- name: Remove unwanted hosts from play_hosts
meta: end_host
when: unwanted
This assumes, of course, that the unwanted
variable exists on all the hosts and is set properly.
Upvotes: 5
Reputation: 7867
I just got the same problem. I have tests which run converge
for a given playbook (which I can't modify), and then I need to run the same playbook with smaller set of hosts in the group.
My solution is:
Let's say you have group target
you want to make smaller.
target
group.target_addon
group.- hosts: target_addon
tasks:
- add_host:
name: '{{ inventory_hostname }}'
groups: [target]
- import_playbook: converge.yaml # uses group `target` with added hosts
# Removing hosts added from target_addon group from group target by reloading inventory
- hosts: localhost
tasks:
- meta: refresh_inventory
- import_playbook: converge.yaml # uses group `target` without added hosts
Upvotes: 0
Reputation: 7740
Can not removing hosts, but can choose to run on the new created group.
- name: kubectl
hosts: localhost
gather_facts: false
tasks:
- add_host:
name: nextcloud
ansible_connection: kubectl
ansible_kubectl_context: cluster
ansible_kubectl_namespace: default
ansible_kubectl_pod: nextcloud-75fc7f5c6f-hxrq6
groupname: "pods"
# only run on pods
- hosts: pods
gather_facts: false
tasks:
- raw: pwd
register: raw_result
- debug:
msg: "{{raw_result.stdout_lines[0]}}"
Upvotes: 2
Reputation: 16406
We typically do it like this in a playbook using multiple hosts:
sections.
- hosts: auth:!ocp
roles:
- ntp-server
- hosts: all:!auth:!ocp
roles:
- ntp-client
This will remove the groups of hosts from consideration via the !group
mechanism. Specifically here in the 1st block we're removing the !ocp
group and in the 2nd we're removing both the !auth
and !ocp
groups.
Upvotes: 1
Reputation: 4230
Unfortunately, it seems, that you can't do this using Ansible 2. There is no such a module called remove_host
or another one.
However, using Ansible 2 you can refresh your inventory mid-play:
- meta: refresh_inventory
Another idea might be to filter hosts beforehand. Try adding them to group, and then excluding this group in a play lately, e.g. :
- hosts: '!databases'
Upvotes: 9