Ansible become: useful and dangerous

OK, now that I have your attention with the catchy title, let me get right into the reason behind this post. Rob has been doing a lot of work lately on a set of roles to provision raspberry pi systems. I'm grateful for the work in this area, because frankly, I find them a bit annoying to get boot-strapped. Although we're not ready to fully publish the workflow (I expect that'll happen in due time and likely on Rob's fine Technotes blog).

About become

become and it's associates (become_user, become_method, and the least-used become_flags) provide a way to handle privilege escalation in situations where you otherwise are logging in to a system with an unprivileged user. In our particular context, the default configuration on a raspberry pi has a single default user who can sudo, but can't execute privileged commands natively.

By setting become: true, privilege execution will by default become user root using the method sudo. Clearly, become_user and become_method provide a way to modify who and how you become.

A warning about over-scoped become

In cases like the raspberry pi, it's tempting to just run all commands using become, and there's a seemingly convenient command-line flag to do just this, -b. By asserting -b, you tell ansible to execute all commands with escalated privilege.

Note that I said all commands? This includes commands that are executed locally using ansible's local_action command. My initial reaction to this was surprise, figuring that local_action, as opposed to delegate_to: localhost would likely avoid the become capability, but in retrospect, it's a good bit of consistency.

So, don't over-become, and don't use the -b command-line flag. If you have a host, such as the aforementioned pi, that you need to become: true for all commands, you can assign ansible_become=yes using your configuration method of choice (stick it in your inventory file, add it to group_vars/all.yml, or maybe even in a specific subgroup if you have a mix of machines that have varying become needs).

Other interesting uses for become

become is a really useful feature, and we regularly use it in plays for command-specific one-offs, such as using become: yes and become_user: postgres to run PostgreSQL commands with the benefit of being the postgres user. Or with live content systems like django, I use become_user: www to run some of the maintenance scripts so that we don't have to manually re-chown all of the files that are collected for static web service.


All told, become is really useful, but pay attention to where you're using it, and just avoid entirely using -b, because you never really know what role might include some local_action that has a bug and might execute rm -rf / for you...