become:yes for local connection: when and how often is sudo called?

Hi,

I’m trying to understand when ansible uses sudo in a scenario where a playbook with become:yes is running with a local connection.

I have a playbook where I need to change the default execution PATH in sudoers for a following step to succeed. In order to run the playbook remotely, I need the tasks to run under “become:yes”

Something like this:

  • hosts: all
    become: yes
    tasks:

  • name: Add npm executable to sudo secure_path
    lineinfile:
    dest: /etc/sudoers
    regexp: ‘^(Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin)$’
    line: ‘\1:/usr/local/lib/npm/bin’
    backrefs: yes
    state: present

  • name: Add service to run PM2
    shell: /usr/local/lib/npm/bin/pm2 startup systemd --user nodejs --hp /home/nodejs
    args:
    creates: /etc/systemd/system/pm2.service

Running each of the above tasks in separate sessions sets things up properly. But when I run this locally in the same play, the change to the sudoers file has no effect on the “pm2 startup” task.

When does ansible call sudo? Just at the start of the block? Is there any way to force ansible to leave a sudo session and to start a new one?

Thanks,
David