Ansible - 如果不存在,则创建多个文件夹

时间:2017-02-12 10:09:41

标签: ansible

目标:

  • 创建多个目录(如果它们不存在)。
  • 不要更改现有文件夹的权限

当前的剧本:

- name: stat directories if they exist
  stat:
    path: "{{ item }}"
  with_items:
    - /data/directory
    - /data/another
  register: myvar

- debug: var=myvar.results

- name: create directory if they don't exist
  file:
    path: "{{ item.invocation.module_args.path }}"
    state: directory
    owner: root
    group: root
    mode: 0775
  with_items: "{{ stat.results }}"
  # when: myvar.results.stat.exists == false

when声明错误。

我看了一下提供的例子; http://docs.ansible.com/ansible/stat_module.html。但这仅适用于单个文件夹。

4 个答案:

答案 0 :(得分:26)

使用Ansible模块,您不需要检查是否存在某些内容,您只需描述所需的状态,所以:

- name: create directory if they don't exist
  file:
    path: "{{ item }}"
    state: directory
    owner: root
    group: root
    mode: 0775
  with_items:
    - /data/directory
    - /data/another

答案 1 :(得分:20)

Ansible - 创建多个文件夹而不更改以前存在的权限。

对我来说很好。希望这对您有用,只需尝试。

---
- name: "Creating multiple by checking folders"
  hosts: your_host_name
  tasks:
  - block:
    - name: "Checking folders"
      stat:
       path: "{{item}}"
      register: folder_stats
      with_items:
      - ["/var/www/f1","/var/www/f2","/var/www/f3","/var/www/f4"]
    - name: "Creating multiple folders without disturbing previous permissions"
      file:
       path: "{{item.item}}"
       state: directory
       mode: 0755
       group: root
       owner: root
      when: item.stat.exists == false
      with_items:
      - "{{folder_stats.results}}"
...

答案 2 :(得分:1)

从Ansible 2.5开始,应使用loop遍历列表,请参见https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html#standard-loops

由于Ansible file模块是幂等的,因此您不必检查文件夹是否已存在。

例如:

- name: create backup directories
  file:
    path: "{{ item }}"
    state: directory
    owner: backup
    group: backup
    mode: 0775
  loop:
    - /backupdisk/certificates
    - /backupdisk/mysql
    - /backupdisk/wordpress

答案 3 :(得分:0)

我的答案可能在每种情况下都行不通,但是如果您不提供任何选项,则ansible不会更改当前值。我已将其用于NFS挂载,其中NFS服务器上的权限有所不同。

- name: create directory if they don't exist
  file:
    path: "{{ item }}"
    state: directory
  with_items:
    - /share1
    - /share2