如何使用Ansible创建文件并管理其权限

47次阅读
没有评论

***localhost : ok=2 changed=1


### 方案2
另一种解决方案是使用`ansible.builtin.copy`模块来创建文件,并在文件已经存在时修复权限。需要注意的是,`ansible.builtin.copy`模块在文件已存在时不会更改权限,所以你需要确保文件的权限在之前已经设置正确。
```yaml
---
- hosts: localhost
  become: false
  gather_facts: false
  tasks:
    - name: Create or copy file
      copy:
        src: "/path/to/source/file"
        dest: "/home/{{ ansible_user }}/test.file"
        owner: "{{ ansible_user }}"
        group: "users"
      when: not ansible_statfile.stat.exists

在上面的示例中,我们使用ansible.builtin.copy模块来将源文件复制到目标位置,并指定了目标文件的路径、所有者和组。我们使用了when条件,以便仅当文件不存在时才执行复制操作。这样可以确保文件只在需要时才会被创建,且权限不会被更改。

请根据你的实际需求选择适合的解决方案,并根据Ansible版本进行相应的调整。

正文完