ndrone
ndrone

Reputation: 3582

Ansible apt module to execute with sudo

I'm trying to get ansible to execute sudo apt-get update. I already have the sudoers setup to run without a password and it works if I login as the user ansible is using and execute sudo apt-get update. If I use the following ansible playbook

---
  - name: updates
    hosts: pis
    tasks:
      - name: Update APT
        become: true
        apt:
          update_cache: yes

It will give me the following error

fatal: [127.0.0.1]: FAILED! => {"changed": false, "module_stderr": "Shared connection to 127.0.0.1 closed.\r\n", "module_stdout": "sudo: a password is required\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

but the following playbook works fine

---
  - name: updates
    hosts: pis
    tasks:
      - name: Update APT
        command: sudo apt-get update

Upvotes: 3

Views: 6895

Answers (1)

Bonzaii
Bonzaii

Reputation: 90

When using become: yes the connection will try to spawn shell as root (as you haven't specified become_user).

It seems you have access to run sudo apt-get update without password, i.e:

/etc/sudodoers may contain something similar to this:

ansible ALL=(ALL) NOPASSWD: /bin/apt-get update

To replicate the issue, login as user ansible and issue a command sudo -i

If you're using a dedicated user (ansible ?) for all ansible connectivity, you might want to give that user access to all commands via sudo without password. Read Here this is however not the best practice, you are always better off giving access to specific commands for security reasons

Add the following line to /etc/sudoers file using visudo /etc/sudoers

ansible ALL=(ALL) NOPASSWD:ALL

If you opt for this, I would also advise to use a key-pair authentication for this privileged account rather than password authentication. More info

Upvotes: 6

Related Questions