Understanding become_user Privilege Escalation

Hi All,

I am trying to create a file in /opt folder. My playbook(from test role) looks like,


  • name: create file
    file:
    path: /opt/testfile
    state: touch

And main.yml looks like,


  • hosts: ‘{{ host }}’
    become: yes
    become_method: sudo
    become_user: jenkins
    roles:
  • test

I am running the playbook as,

ansible-playbook -i /tmp/ansible-workspace/environments/QA/inventory --extra-vars “host=QA” --ask-pass --ask-become-pass main.yml -vvv

And the error I get is,

“mode”: “0644”,
“msg”: “Error while touching existing target: [Errno 13] Permission denied: ‘/opt/testfile’”,
“owner”: “root”,
“path”: “/opt/testfile”,
“secontext”: “unconfined_u:object_r:etc_t:s0”,
“size”: 0,
“state”: “file”,
“uid”: 0

But when I comment out the line become_user: jenkins in main.yml and run it with the command

ansible-playbook -i /tmp/ansible-workspace/environments/QA/inventory --extra-vars “host=QA” -u jenkins --ask-pass --ask-become-pass main.yml -vvv

it works perfectly fine.

Can someone please say teh differnce between the two ways?

Thanks

https://docs.ansible.com/ansible/latest/user_guide/become.html
-u and become_user don't do the same. One time you create the file as root and other time as jenkins user.

Greetings
Klaas

Thanks Klaas!

But jenkins user is a sudo user on the remote machine. Why does it have to throw error “Error while touching existing target: [Errno 13] Permission denied: ‘/opt/testfile’” when sudo user has permission to create files in /opt folder.

Also, I tried creating file in /opt folder manually(not through Ansible) and I was able to create file without any issues.

Could you please clarify?

Need below info.

  1. Can you paste here, sudo entry lines of jenkins user from sudoers file.
  2. From which user id you are executing the playbook?

Hi Pandu,

  1. jenkins user is added to the wheel group(but not a password less sudo). My aim is to create a playbook where it gets connected to the remote machines and add ssh keys for password less ssh and add a line entry to sudoers file for password less sudo.
  2. I am executing playbook with the same user jenkins