我有一个默认的目标 Linux 节点
umask=0077
。
当我运行剧本时
- name: Create folder for app
ansible.builtin.file:
path: "{{ item }}"
state: directory
owner: app_user
mode: 0755
with_items:
- "/opt/app/folder1/bin"
- "/etc/program/folder2"
参数“mode”仅适用于最后一个文件夹(
bin
和folder2
)。
根据 umask,所有父目录都有严格的权限。
如何设置父目录所需的权限(不适用于所有
/opt
或/etc
,仅适用于链):
/opt
、/opt/app
、/opt/app/folder1
、/opt/app/folder1/bin
/etc
、/etc/program
、/etc/program/folder2
问:“更改所有中间父文件夹的权限。”
A:例如,给定路径,声明您想要开始更改权限的位置深度。在这种情况下,深度= 1是根目录,深度= 2是/tmp9
path1: /tmp9/a/b/c
path2: /tmp9/x/y/z
depth: 2
创建一个带有增量更改子目录的循环的文件
shell> cat subdirs.yml
- file:
path: "{{ root }}/{{ subs[:ansible_loop.index] | join('/') }}"
state: directory
owner: admin
mode: 0755
loop: "{{ subs }}"
loop_control:
extended: true
vars:
dirs: "{{ outer_item | split('/') }}"
root: "{{ dirs[:depth] | join('/') }}"
subs: "{{ dirs[depth:] }}"
将此任务包含在循环中
- include_tasks: subdirs.yml
loop:
- "{{ path1 }}"
- "{{ path2 }}"
loop_control:
loop_var: outer_item
鉴于下面的树,任务是幂等的
shell> tree -pu /tmp9
[drwxr-xr-x root ] /tmp9
├── [drwxr-xr-x admin ] a
│ └── [drwxr-xr-x admin ] b
│ └── [drwxr-xr-x admin ] c
└── [drwxr-xr-x admin ] x
└── [drwxr-xr-x admin ] y
└── [drwxr-xr-x admin ] z
如果改变模式
mode: 0700
任务会改变权限
shell> sudo tree -pu /tmp9
[drwxr-xr-x root ] /tmp9
├── [drwx------ admin ] a
│ └── [drwx------ admin ] b
│ └── [drwx------ admin ] c
└── [drwx------ admin ] x
└── [drwx------ admin ] y
└── [drwx------ admin ] z
用于测试的完整剧本示例
- hosts: localhost
become: true
vars:
path1: /tmp9/a/b/c
path2: /tmp9/x/y/z
depth: 2
tasks:
- include_tasks: subdirs.yml
loop:
- "{{ path1 }}"
- "{{ path2 }}"
loop_control:
loop_var: outer_item