I am using ansible 2.0.2.0 to update my static website from any computer. My playbook runs on localhost only and essentially has two parts:
apt
tasks with become: true
command
tasks without become
.I would prefer having these two parts in the same playbook so that I do not need to worry about dependencies when switching computers. Ideally, I would like ansible to check if the apt
packages are installed and only ask for the become password if it needs to install any.
Other, less satisfactory alternatives that I have explored so far and their drawbacks are highlighted below:
sudo ansible-playbook ...
: Runs the unprivileged part as root
, asks sudo password when not required;ansible-playbook --ask-become-pass ...
: Always asks sudo password, even if no new packages need to be installed;ansible-playbook ...
: Fails with sudo: a password is required
.Is there any way to keep the privileged and unprivileged parts in the same playbook without needlessly typing the sudo password nor giving needless privileges to the unprivileged part?
If you run ansible-playbook
with the --ask-sudo-pass
parameter, then your second option will ask you for the password once, and will reuse that each time, where needed.
If do run as sudo as in your first case, then you can use become within the script, to lose your privilege status, as you need it.
However, you can setup ansible.cfg
to do remote installs to localhost
. Hence you can setup an unprivileged ansible user (I use centos
), which is setup to sudo
without needing a password. Then I setup my local user in the authorized_keys
for the centos
user.
Hence you run unprivileged (as centos
), but when you need to sudo, you can use become_method: sudo
to become root.
Using this method I do bare metal installs with the same ansible playbook, as I do remote AWS installs.
Looking at my ansible.cfg
I have:-
[defaults]
hostfile = inventory
# use local centos account, and ask for sudo password
remote_user = centos
#ask_pass = true
#private_key_file = ~/packer/ec2_amazon-ebs.pem
My inventory.yml
contains:-
[webservers]
localhost
my setup.sh
contains:-
ansible-playbook playbook.yml -vvv
#ansible-playbook --ask-sudo-pass playbook.yml
Hence all password asking statements are off. Remember as I don't specify a private_key_file
in the defaults, it assumes the running user has authority to ssh to centos@localhost
without requiring a password
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With