TransWikia.com

Ansible Create SubFolders Matching Pattern

Stack Overflow Asked by Switch on November 15, 2021

I have an ansible playbook, that creates directories by passed an array of directories, owner, and permissions. Our admins are worried, someone will create directories under our O/S Volumes and cause issues with the system. Since we only have a few folders that require root, I’m researching how to whitelist specific folders that are passed in for root only. Other directories and use our internal user to directories that don’t require root.

This is what I’ve come up with, but I have concern with /vs_volue/etc instead of /etc being passed. I can’t find a starts with /etc for example. Is there a better way?

---
- name: Create Directories
  hosts: target_hosts
  vars:
    dir_list: '{{ dir_list }}'
    permissions: {{ permissions }}
    linux_user: 'webuser'
    whitelist_dir:
      - "/etc"
      - "/usr"

  tasks:
    - name: User to root when creating folders in /etc or /usr
      set_fact:
          linux_user: "root"
      when: dir_list|string|regex_search('{{ item }}')
      with_items:
        - "{{ whitelist_dir }}"

    - name: Create Directories as WebUser by Directory Array Lists by Line Feed
      file:
        path: "{{ item }}"
        mode: "{{ permissions }}"
        recurse: yes
        state: directory
        become: true
        become_user: "{{ linux_user }}"
      with_items: "{{ dir_list.split('n') }}"
      when: dir_list | search('n')

One Answer

Try this.

main.yml

- hosts: target_hosts
  vars:
    default_linux_user: "webuser"
    permissions: "{{ permissions | default(0664) }}"
    whitelist_dir:
      - "^/etc/.*"
      - "^/usr/.*"
  tasks:
    - include_tasks: create_dir.yml
      loop: "{{ dir_list.split('n') }}"
      loop_control:
         loop_var: dir

create_dir.yml

- block:
    - set_fact:
        linux_user: "{{ 'root' if dir is regex(item) else default_linux_user }}"
      when: linux_user is undefined and (not linux_user == 'root')
      loop: "{{ whitelist_dir }}"

    - debug:
        msg: "For {{ dir }} - {{ linux_user }} will be set as owner"
        
    - file:
        path: "{{ dir }}"
        state: directory
        mode: "{{ permissions }}"
        owner: "{{ linux_user | default(default_linux_user) }}
        recurse: yes
      become: true
      become_user: root
      become_method: sudo
  always:
    - set_fact:
        linux_user: default_linux_user   

Answered by initanmol on November 15, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP