testuser is a sudo user,
sudo cat /etc/sudoers.d/90-cloud-init-testuser
testuser ALL=(ALL) NOPASSWD:ALL
I can login testuser manually and run following without password:
sudo -H apt-get update
sudo -H apt-get upgrade
but if I run following ansible code, although I saw whoami command return testuser, then the code stops with fatal error (see code and error below).
Must I set become_user as root in order to run (see the line I comment out)? Note I CAN login testuser manually and run sudo command, can't I use become_user=testuser to Install apt? Note I think remote_user does not matter because whoami command only depends on become_user.in fact I feel remote_user is useless, it just log me in. if become_user is unset. then whoami become root, if become_user is set as testuser, then whoami become testuser.
- hosts: all
remote_user: ubuntu
become: yes
become_user: testuser
gather_facts: yes
become_method: sudo
tasks:
- name: test which user I am
shell: whomami
register: hello
- debug: msg="{{ hello.stdout }}"
- name: Update and upgrade apt.
# become_user: root
# become: yes
apt: update_cache=yes upgrade=dist cache_valid_time=3600
TASK [Update and upgrade apt.]
********************************
fatal: [XX.XX.XX.XX]: FAILED! => {"changed": false, "msg":
"'/usr/bin/apt-get dist-upgrade' failed: E: Could not open lock file
/var/lib/dpkg/lock - open (13: Permission denied)\nE: Unable to lock
the administration directory (/var/lib/dpkg/), are you root?\n", "rc":
100, "stdout": "", "stdout_lines": []}
You need to connect with an account which has sudo permissions ― in your case
testuser
― and then run play/task with elevated permissions (become: true
, andbecome: root
which is default), so:ubuntu
,testuser
.sudo
does not work the way you imply in the question.Any command runs in a context of a specific user ― either
testuser
, orubuntu
, orroot
. There is no such thing as running a command as a "sudotestuser
".sudo
executes a command as a different user (root
by default). User executingsudo
must have appropriate permissions.If you log in as
testuser
and executesudo -H apt-get update
it is (almost*) the same as if you logged in asroot
and ranapt-get update
.If you log in as
ubuntu
and runsudo -u testuser apt-get update
(which is a shell counterpart to the Ansible tasks in the question) ― it is (almost*) the same as if you logged on withtestuser
and ranapt-get update
.testuser
runningapt-get update
will get an error ― and this is what you get.* "almost", because it depends on settings regarding environment variables ― not relevant to the problem here.