Ansible: Cannot configure sudo command even become

2019-03-03 19:41发布

问题:

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": []}

回答1:

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, and become: root which is default), so:

  • either add sudo permissions to ubuntu,
  • or connect with testuser.

sudo does not work the way you imply in the question.

Any command runs in a context of a specific user ― either testuser, or ubuntu, or root. There is no such thing as running a command as a "sudo testuser".

sudo executes a command as a different user (root by default). User executing sudo must have appropriate permissions.

  • If you log in as testuser and execute sudo -H apt-get update it is (almost*) the same as if you logged in as root and ran apt-get update.

  • If you log in as ubuntu and run sudo -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 with testuser and ran apt-get update.

    testuser running apt-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.



标签: ansible