Ansible - Create multiple folders if don't exist

后端 未结 3 891
无人共我
无人共我 2021-02-03 23:44

Goal:

  • Create multiple directories if they don\'t exist.
  • Don\'t change permissions of existing folder

Current playbook:

- name:         


        
相关标签:
3条回答
  • 2021-02-04 00:11

    Starting from Ansible 2.5, loop should be used to iterate over a list, see https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html#standard-loops

    As the Ansible file module is idempotent, you do not have to check if the folders already exist.

    For example:

    - name: create backup directories
      file:
        path: "{{ item }}"
        state: directory
        owner: backup
        group: backup
        mode: 0775
      loop:
        - /backupdisk/certificates
        - /backupdisk/mysql
        - /backupdisk/wordpress
    
    0 讨论(0)
  • 2021-02-04 00:16

    Using Ansible modules, you don't need to check if something exist or not, you just describe the desired state, so:

    - name: create directory if they don't exist
      file:
        path: "{{ item }}"
        state: directory
        owner: root
        group: root
        mode: 0775
      loop:
        - /data/directory
        - /data/another
    
    0 讨论(0)
  • 2021-02-04 00:26

    Ansible - Creating multiple folders without changing permissions of previously existing.

    Working fine for me. Hope this works for you as well just try.
    ---
    - 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
          loop:
          - "{{folder_stats.results}}"
    ...
    
    0 讨论(0)
提交回复
热议问题