19

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
  • 1
    Why don't you use the ansible file module with ownerand group options? Commented Jul 17, 2019 at 7:53
  • Here id of user and group is fetched dynamically. How can i do the same Commented Jul 17, 2019 at 8:32

2 Answers 2

33

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.