13
votes

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)
2
Why don't you use the ansible file module with ownerand group options?Zumo de Vidrio
Here id of user and group is fetched dynamically. How can i do the sameTechChain

2 Answers

21
votes

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

0
votes

Try below.

  - name: chown to username you login and chmod as required
    file:
      path: $HOME/.kube/config
      owner: "{{ ansible_user }}"
      group: "{{ ansible_user }}"
      mode: 0644