akrantz01
akrantz01

Reputation: 648

Ansible chown operation not permitted for non-root user

I have the following in an Ansible playbook:

- name: Create certificates directory
  file:
    dest: "{{ '~/wireguard/certs' | expanduser }}"
    state: directory
    owner: "{{ ansible_user_id }}"
    group: "{{ ansible_user_id }}"
    mode: 0700
  run_once: true
  delegate_to: localhost

However, when it gets run in the playbook, I get the following error:

fatal: [1.2.3.4 -> localhost]: FAILED! => {
  "changed": false,
  "gid": 1000,
  "group": "alex",
  "mode": "0755",
  "msg": "chown failed: [Errno 1] Operation not permitted: b'/home/alex/wireguard'",
  "owner": "alex",
  "path": "/home/alex/wireguard",
  "size": 4096,
  "state": "directory",
  "uid": 1000
}

Do I need to run this as root or is it something else? If I do need to run it as root, does become work?

Upvotes: 4

Views: 14764

Answers (3)

Raymond Gan
Raymond Gan

Reputation: 4880

I got a similar error for my Ansible playbook. My problem was the owner of that directory was different from my username ($USER). Solve it with:

sudo chown -R $USER /home/alex/wireguard

or

sudo chown -R alex /home/alex/wireguard

Upvotes: 0

akrantz01
akrantz01

Reputation: 648

I realized that ansible_user_id didn't have the username that I was expecting, so I was trying to change the ownership to a user that didn't exist. I fixed it by setting a new variable to my local user.

Upvotes: 1

Vladimir Botka
Vladimir Botka

Reputation: 68144

Do I need to run this as root or is it something else?

root is needed. See for example Changing Ownership

"The super user, root, has the unrestricted capability to change the ownership of any file but normal users can change the ownership of only those files that they own."

This practically means that normal users are only able to change the group of a file they own to a group they are a member of.

If I do need to run it as root, does become work?

Yes. become works. Frequently used become plugin is sudo. Default value of become_user is root.

- file:
  become: yes
  become_method: sudo
  ...

Generally, enable remote/login user to become root. But in your specific case, because of delegate_to: localhost, enable the user who is running the play. For example change at localhost

$ grep alex /etc/sudoers
alex ALL=(ALL) NOPASSWD: ALL

See plugin list for other options.

Upvotes: 3

Related Questions