Search code examples
linuxubuntuansiblesystem-administration

Ansible: Copy file into another users home directory


I am new to Ansible so this may be a silly question. Thank you for your patience.

I have two users on my child node: ubuntu and ansible

I have one user on my control node: ubuntu

I created the ansible user on my child node to test out multiple users/isolate ansible. Maybe this is not a good idea?

I am trying to copy a test file from my control node to my child node. I am connecting as the ansible user (because I've granted them passwordless sudo in the sudoers file, I don't want to do this for the ubuntu user). However I cannot copy the file into ubuntu user's home folder. I am able to copy into ansible user's home folder.

Is what I'm trying to do possible? I couldn't find much reading on this so I am guessing I am approaching this the wrong way... is there a better way to do this?

Here is my playbook:

---
- name: script transfer practice
  hosts: devdebugs
  remote_user: ansible

  tasks:
  - name: Copy file with owner and permissions
    ansible.builtin.copy:
      src: /home/ubuntu/files/test.txt
      dest: /home/ubuntu/test.txt
      owner: ubuntu
      group: ubuntu
      mode: '0600'
...

Note: It works with dest /home/ansible/test.txt. It does not work with dest /home/ubuntu/test.txt


Solution

  • I created the Ansible user on my child node to test out multiple users/isolate Ansible. Maybe this is not a good idea?

    Having a specific user for your deployments with full escalation rights on your target host is the most common setup to run ansible.

    Is what I'm trying to do possible?

    Absolutely. If you have correctly set escalation rights to your Ansible user as mentioned, all you are missing in your task or play is become: true. At play level, it will affect all task for that play:

    ---
    - name: script transfer practice
      hosts: devdebugs
      remote_user: ansible
      become: true
    
      # here goes the rest of your play....
    

    At task level, it will only affect the given task.

      - name: Copy file with owner and permissions
        ansible.builtin.copy:
          src: /home/ubuntu/files/test.txt
          dest: /home/ubuntu/test.txt
          owner: ubuntu
          group: ubuntu
          mode: '0600'
        become: true
    

    As reported by @SipSeb in the comments, you can also set the become flag for an entire playbook at runtime using the -b/--become flag on the ansible(-playbook) command line.

    I couldn't find much reading on this

    Probably because you are new to Ansible and do not know exactly what to look for. For this particular subject, a good starting point is understanding Ansible privilege escalation