在 ansible 中使用 chown 命令?

Using chown command in ansible?

我在 ubuntu 中有一个命令作为

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

我想转换成ansible脚本。我在下面试过

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

但我收到如下错误

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": []}

编辑: 文件模块也没有工作。

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

在下面试试。

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

假设文件已经存在并且您只想更改权限,您可以从 Ansible facts 中检索用户 ID 和组并执行如下操作:

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

您也可以根据需要使用 ansible_real_group_id / ansible_real_user_idansible_user_gid/ansible_user_uid

请不要忘记 ansible 表达式周围的双引号。

真实用户与有效用户的区别详见this post

有关所有可用变量,请参阅 Ansible docs on system variables