Using chown command in ansible?

TechChain picture TechChain · Jul 17, 2019 · Viewed 10.9k times · Source

I have a command in ubuntu as

  sudo chown $(id -u):$(id -g) $HOME/.kube/config 

I want to convert into ansible script. I have tried below

- name: Changing ownership
      command: chown $(id -u):$(id -g) $HOME/.kube/config
      become: true 

but i am getting error as below

fatal: [ubuntu]: FAILED! => {"changed": t> fatal: [ubuntu]: FAILED! => {"changed": true, "cmd": ["chown", "$(id", "-u):$(id", "-g)", "$HOME/.kube/config"], "delta": "0:00:00.003948", "end": "2019-07-17 07:22:31.798773", "msg": "non-zero return code", "rc": 1, "start": "2019-07-17 07:22:31.794825", "stderr": "chown: invalid option -- 'u'\nTry 'chown --help' for more information.", "stderr_lines": ["chown: invalid option -- 'u'", "Try 'chown --help' for more information."], "stdout": "", "stdout_lines": []}rue, "cmd": ["chown", "$(id", "-u):$(id", "-g)", "$HOME/.kube/config"], "delta": "0:00:00.003948", "end": "2019-07-17 07:22:31.798773", "msg": "non-zero return code", "rc": 1, "start": "2019-07-17 07:22:31.794825", "stderr": "chown: invalid option -- 'u'\nTry 'chown --help' for more information.", "stderr_lines": ["chown: invalid option -- 'u'", "Try 'chown --help' for more information."], "stdout": "", "stdout_lines": []}

EDIT: File module also did not work.

  - name: Create a symbolic link
    file:
      path: $HOME/.kube
      owner: $(id -u)
      group: $(id -g)

Answer

Pierre B. picture Pierre B. · Jul 17, 2019

Assuming the file already exists and you just want to change permissions, you can retrieve user ID and group from Ansible facts and do something like:

- name: Change kubeconfig file permission
  file:
    path: $HOME/.kube/config 
    owner: "{{ ansible_effective_user_id }}"
    group: "{{ ansible_effective_group_id }}"

You can also use ansible_real_group_id / ansible_real_user_id or ansible_user_gid/ansible_user_uid depending on your need.

Please don't forget double quotes around ansible expression.

See this post for details on the difference between real and effective user

See Ansible docs on system variables for all available variables