Ansible become_user failing while logging-in as vagrant user

Hello,

Problem:
Via inventory, I am logging as “vagrant” user. I am trying to switch to another-user and then create .ssh directory with owner and group as this another-user. It is failing saying permission denied.

TASK [Ensure dot-ssh directory exists] ********************************************************************************************* fatal: [192.168.99.105]: FAILED! => {"changed": false, "msg": "There was an issue creating /home/mrajaa/.ssh as requested: [Errno 13] **Permission denied**: b'/home/mrajaa/.ssh'", "path": "/home/mrajaa/.ssh/"}

“vagrant” user has sudo permission in the target cluster.

`
sudo cat /etc/sudoers.d/vagrant-nopasswd
vagrant ALL=(ALL) NOPASSWD: ALL

`

Problem in detail:
I am trying to run a playbook on vagrant-provisioned-virtualbox, like

ap -i inventory-ansible main.yml --ask-vault-pass

Inventory is like this,

`
[vagrant-demo]
192.168.99.105

[vagrant-demo:vars]
ansible_user=vagrant
ansible_ssh_private_key_file=~/.vagrant.d/insecure_private_key
`

$ cat main.yml

`

remove
become_user: ‘{{ username }}’

By default become_user is root. [1]

[1] https://docs.ansible.com/ansible/latest/user_guide/become.html

Hello,

I have added that step intentionally. So that all the tasks are executed under “user” privileges. So that directory/file permission, etc will be proper.

This is probably because the parent directory isn’t there, and user mrajaa doesn’t have permission create it.

I don’t see any task to create that user.
Those steps are missing from your playbook (or you didn’t post them)

Hello,

Thanks for the e-mail. I have figured out the problem.

---
- hosts: all
  #become: yes
  #become_user: "{{ username }}"
  #become_method: sudo
- import_playbook: ../../main.yml

In the above case, becoming as another user is of no use. Once I have imported playbook ( ie., main.yml ), it was running as vagrant user somehow. So I have commented it out. Once I have added like this in …/…/main.yml, then everything is working fine. main.yml is the one which downloads and adds ssh keys.

$ head -6 ../../main.yml
---
- hosts: all

  become: yes
  become_user: "{{ username }}"
  become_method: sudo

become ONLY affects the play/task it is enabled for, you only set it
in the first play, the imported play does not inherit become settings.