ubuntu-12.04sudoansibleprivilege-elevation

Executing the tasks with sudo privileges in ansible playbook


I have simple ansible playbook

- hosts: all
  remote_user: myusername
  become: yes
  become_user: myusername
  become_method: sudo
  tasks:
    - name: Install tmux
      apt: name=tmux state=present

I get the below error while running the playbook.

TASK: [Install tmux] ********************************************************** 
failed: [104.239.140.237] => {"failed": true}
stderr: E: Could not open lock file /var/lib/dpkg/lock - open (13: Permission denied)
E: Unable to lock the administration directory (/var/lib/dpkg/), are you root?

I referred to http://docs.ansible.com/ansible/become.html to escalate the privileges of the user.

The user 'myusername' belongs to sudo group.

$ sudo -l -U myusername
User myusername may run the following commands on this host:
    (ALL : ALL) ALL

I am able to successfully install the tmux using the below command on console. Not really sure what I am missing while doing the same inside the playbook.

$ sudo apt-get install tmux
Reading package lists... Done
Building dependency tree       
Reading state information... Done

Solution

  • I would check or modify the sudoers file for NOPASSWD, your playbook works for me and the only difference I see is:

    User myusername may run the following commands on this host:
        (ALL : ALL) ALL
        (ALL) NOPASSWD: ALL
    

    This is as much as confirmed by Ansible docs, which state:

    –become,-b
    run operations with become (no password implied)
    

    If you can't change the server-side config for this, you can still use the sudo directive.

    http://docs.ansible.com/ansible/become.html