如何定义多个以适当方式维护目录特定属性的目录?

时间:2019-05-02 12:07:05

标签: ansible

以以下示例为例:

    - name: setup jitsi-meet volumes (0/5)
      file:
        path: /srv/jitsi-meet/.jitsi-meet-cfg
        state: directory
        owner: root
        group: root
        mode: 0755

    - name: setup jitsi-meet volumes (1/5)
      file:
        path: /srv/jitsi-meet/.jitsi-meet-cfg/web
        state: directory
        owner: 2000
        group: 2000
        mode: 0644

    - name: setup jitsi-meet volumes (2/5)
      file:
        path: /srv/jitsi-meet/.jitsi-meet-cfg/prosody
        state: directory
        owner: root
        group: root
        mode: 0600

有没有一种正确的方法,不仅可以将这三个单独的任务简化为一个任务,还可以保持修改每个路径的所有者,组和模式的可能性?

1 个答案:

答案 0 :(得分:3)

一个选择是循环文件列表。

vars:
  my_files_dir: /srv/jitsi-meet/.jitsi-meet-cfg
  my_files:
    - path: "{{ my_files_dir }}"
      state: directory
      owner: "root"
      group: "root"
      mode: "0755"
    - path: "{{ my_files_dir }}/web"
      state: directory
      owner: "2000"
      group: "2000"
      mode: "0644"
    - path: "{{ my_files_dir }}/prosody"
      state: directory
      owner: "root"
      group: "root"
      mode: "0600"
tasks:
  - file:
      path: "{{ item.path }}"
      state: "{{ item.state }}"
      owner: "{{ item.owner }}"
      group: "{{ item.group }}"
      mode: "{{ item.mode }}"
    loop: "{{ my_files }}"

可以使用参数的默认值进一步简化

vars:
  my_files_dir: /srv/jitsi-meet/.jitsi-meet-cfg
  my_files:
    - path: "{{ my_files_dir }}"
    - path: "{{ my_files_dir }}/web"
      owner: "2000"
      group: "2000"
      mode: "0644"
    - path: "{{ my_files_dir }}/prosody"
      mode: "0600"
tasks:
  - file:
      path: "{{ item.path }}"
      state: "{{ item.state|default('directory') }}"
      owner: "{{ item.owner|default('root') }}"
      group: "{{ item.group|default('root') }}"
      mode: "{{ item.mode|default('0755') }}"
    loop: "{{ my_files }}"