Professional Documents
Culture Documents
Ansible - Sudo Sometimes
Ansible - Sudo Sometimes
org
Raymii.org
Quis custodiet ipsos custodes?
Home | About | All pages | RSS Feed | Gopher
Table of Contents
This Ansible tutorial shows you how run some actions via sudo and some not. It also shows you
how to run an entire role via sudo or not.
If you like this article, consider sponsoring me by trying out a Digital Ocean VPS. With this link
you'll get $100 credit for 60 days). (referral link)
Ansible has the option to run playbooks via sudo. You can setup passwordless sudo, but also
execute a playbook with the extra --ask-sudo-pass / -K option so that Ansible asks you for
the sudo password. However, you can also have very specific control over how and when sudo
is used in a playbook.
I have a playbook with a few roles which I use to bootstrap a new debian server. It installs
software, sets up ssh, sets up sudo and places a few config files. It is organized in roles, the main
playbook looks like this:
---
- hosts: new-servers
user: username
connection: ssh # or paramiko
roles:
- { role: basic-debian-setup, sudo: yes }
- { role: git-setup }
- { role: vim }
- { role: bash }
- { role: screen }
https://raymii.org/s/tutorials/Ansible_-_Better_sudo_control.html 1/3
6/28/2019 Ansible - Sudo sometimes - Raymii.org
As you can see, I have a few playbooks run with sudo on, and a few with sudo off. The git-set
up , vim , screen and bash playbooks all do basically the same, they install software and place
a configuration file. However, if the entire playbook is run as root, the configuration files placed
would be owned by root. If the playbook is not run via sudo, the software cannot be installed.
Note that in the first case Ansible also supports setting file permissions on files. This however is
not the case when configuration files are cloned from a git repository. The git module does not
support setting permissions, and I don't like recursive chmod 's.
https://raymii.org/s/tutorials/Ansible_-_Better_sudo_control.html 2/3
6/28/2019 Ansible - Sudo sometimes - Raymii.org
This playbook makes sure both vim and git are installed. It uses sudo for that action. It then
clones the git repository with my personal dotfiles, without using sudo. If this action would use
sudo, the git repository in my home folder would me owned by root and I could not update it
later on without using sudo. The last action symlinks the .vimrc file from the repo to the correct
location. If that would be done with sudo I could not remove the file without root access.
If you define a role with sudo, like in the above example the postfix role, then you can use the
sudo: no option in that playbook to make sure one or more actions are not executed with
sudo.
Search
https://raymii.org/s/tutorials/Ansible_-_Better_sudo_control.html 3/3