跳到内容

no-relative-paths

此规则检查`ansible.builtin.copy`和`ansible.builtin.template`模块中的相对路径。

任务中的相对路径通常指示Ansible指向托管节点上的远程文件和目录。在`ansible.builtin.copy`和`ansible.builtin.template`模块中,`src`参数指的是控制节点上的本地文件和目录。

建议的存储文件位置如下:

  • 对于`copy`模块,使用剧本或角色目录中的`files/`文件夹。
  • 对于`template`模块,使用剧本或角色目录中的`templates/`文件夹。

这些文件夹允许您在使用`src`参数指定文件时省略路径或使用子文件夹。

注意

如果资源位于Ansible剧本或角色目录之外,则应使用`src`参数指定绝对路径。

警告

不要将资源存储在与Ansible剧本或任务文件相同的目录级别。这样做会导致项目杂乱无章,并会在区分相同类型(例如YAML)的资源时造成用户困惑。

有关更多信息,请参阅Ansible文档中的任务路径

问题代码

---
- name: Example playbook
  hosts: all
  tasks:
    - name: Template a file to /etc/file.conf
      ansible.builtin.template:
        src: ../my_templates/foo.j2 # <- Uses a relative path in the src argument.
        dest: /etc/file.conf
        owner: bin
        group: wheel
        mode: "0644"
- name: Example playbook
  hosts: all
  vars:
    source_path: ../../my_templates/foo.j2 # <- Sets a variable to a relative path.
  tasks:
    - name: Copy a file to /etc/file.conf
      ansible.builtin.copy:
        src: "{{ source_path }}" # <- Uses the variable in the src argument.
        dest: /etc/foo.conf
        owner: foo
        group: foo
        mode: "0644"

正确代码

---
- name: Example playbook
  hosts: all
  tasks:
    - name: Template a file to /etc/file.conf
      ansible.builtin.template:
        src: foo.j2 # <- Uses a path from inside templates/ directory.
        dest: /etc/file.conf
        owner: bin
        group: wheel
        mode: "0644"
- name: Example playbook
  hosts: all
  vars:
    source_path: foo.j2 # <- Uses a path from inside files/ directory.
  tasks:
    - name: Copy a file to /etc/file.conf
      ansible.builtin.copy:
        src: "{{ source_path }}" # <- Uses the variable in the src argument.
        dest: /etc/foo.conf
        owner: foo
        group: foo
        mode: "0644"