Using chown command in ansible?

20,503

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

Share:
20,503
TechChain
Author by

TechChain

I have 4+ of experience of overall experience.Currently working on Hyperledger Fabric blockchain framework. I have strong knowledge of Objective c, Swift.I have developed lot of apps from chat app, finance apps,location & map based apps.

Updated on January 17, 2020

Comments

  • TechChain
    TechChain over 4 years

    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)