Ansible is a very good tool, no doubt about this but there is something which has always been annoying me. Indeed, if you run a playbook with no limit specified as shown below:
Hopefully, ansible is a very complete tool and it is then easy to code a task preventing a playbook to run if no limit is specified using the special variable ansible_limit, we basically want to say no to "no limit" !
Here is what this task looks like:
Stay safe with ansible thanks to exit-if-no-limit.yml !
$ ansible-playbook patch-vm.ymlthen this playbook will be executed against all the hosts of your inventory and depending on the playbook, a simple "oops, I forgot to set up a limit" human error can be devastating for your system. And this is same if you use a tool like Ansible Tower (great tool as well) where you can prompt for a limit and put a dummy one per default but you cannot prevent someone to run a playbook with an empty limit -- then against all the host from your inventory.
Hopefully, ansible is a very complete tool and it is then easy to code a task preventing a playbook to run if no limit is specified using the special variable ansible_limit, we basically want to say no to "no limit" !
Here is what this task looks like:
$ cat exit-if-no-limit.yml --- - name: Verifying that a limit is set fail: msg: 'This playbook cannot be run with no limit' run_once: true when: ansible_limit is not defined - debug: msg: Limit is {{ ansible_limit }}, let's continue run_once: true when: ansible_limit is definedYou can then use this task in your playbooks as below:
- include_role:
name: myrole
tasks_from: "{{ item }}.yml"
loop:
- exit-if-no-limit
- something
- something_else
Easy to use, easy to reuse when needed, below an example of the output produced when no limit is specified:
TASK [myrole: Verifying that a limit is set]
fatal: [ahost]: FAILED! => {"changed": false, "msg": "This playbook cannot be run with no limit"}
And an output with a limit specified:
TASK [myrole: debug]
ok: [anotherhost] => {
"msg": "Limit is anotherhost, let's continue"
}
I never had to go further like testing how many hosts are specified, if the limit contains groups, how many groups, etc ... but it would be easy to do with a bit of regexp against the ansible_limit variable.Stay safe with ansible thanks to exit-if-no-limit.yml !
Great!
ReplyDeleteThanks!
ReplyDelete