I would like to disable hosts: all in the Ansible inventory file.
Sometimes people forget modify the hosts column in YAML file so they push new configuration to all hosts in the intranet accidentally.
I am very new to Ansible, any help is appreciated!
CodePudding user response:
Let's say you want to keep hosts: all in all playbooks and want to limit the hosts in the runtime by the option --limit. Next, you want to prevent running the playbooks without limitation at all hosts.
Q: How to disable hosts: all in Ansible?
A: There is no such option in Ansible that would disable the group all. The group all is created automatically and comprises all hosts in the inventory.
Instead, in the playbook, you can test whether the playbook targets all hosts or not, e.g.
shell> cat playbook.yml
- hosts: all
tasks:
- assert:
that: ansible_play_hosts_all|length < groups.all|length
fail_msg: '[ERROR] All hosts not allowed.'
run_once: true
the play will not continue without the limitation of the hosts
shell> ansible-playbook playbook.yml
...
TASK [assert] **************************************************************
fatal: [host01]: FAILED! => changed=false
assertion: ansible_play_hosts_all|length < groups.all|length
evaluated_to: false
msg: '[ERROR] All hosts not allowed.'
Implementation
You don't have to modify all playbooks. Instead, create wrappers. For example, given the playbook
shell> cat playbook-509.yml
- hosts: all
tasks:
- debug:
msg: playbook-509 is running ...
create the wrapper
shell> cat playbook-509-wrapper.yml
- hosts: all
gather_facts: false
tasks:
- assert:
that: ansible_play_hosts_all|length < groups.all|length
fail_msg: '[ERROR] All hosts not allowed.'
run_once: true
- import_playbook: playbook-509.yml
Allow the users to run the wrappers only. For example, the play won't run if a user runs the wrapper without limitation
shell> ansible-playbook playbook-509-wrapper.yml
...
TASK [assert] ***************************************************
fatal: [host01]: FAILED! => changed=false
assertion: ansible_play_hosts_all|length < groups.all|length
evaluated_to: false
msg: '[ERROR] All hosts not allowed.'
The play will run if the hosts are limited
shell> ansible-playbook playbook-509-wrapper.yml --limit host01
PLAY [all] *****************************************************
TASK [assert] **************************************************
ok: [host01] => changed=false
msg: All assertions passed
PLAY [all] *****************************************************
TASK [debug] ***************************************************
ok: [host01] =>
msg: playbook-509 is running ...
You can use Ansible to create the wrappers automatically.
CodePudding user response:
This is not possible. The only host that can kind-of-exist and not be part of the all group is implicit localhost; any other host is automatically part of all, even if you don't explicitly list it as a parent group.
