fileansibletouchcreatefile

How to use regex with ansible file module


I have the below file module that touches a file on remote hosts.

 - name: create file
   file:
     path: "/oracle/{{ inventory_hostname }}/del.tmp"
     state: touch
   register: direxists

 - fail:
     msg: "Directory missing"
   when: direxists.changed == False

The issue is on the target hosts I may have /oracle or /Oracle folder. The letter 'o' could be case insensitive. Thus, I wanted the regex to work

 path: "/[Oo]racle/{{ inventory_hostname }}/del.tmp"

But unfortunately, such regex is not supported by the file module.

I will have to fall back to shell module & use Unix commands instead; which I was not wanting.

I wish to fail the play if both /Oracle or /oracle directories are missing. If anyone of the [Oo]racle directory exists my play should not fail.

How can I achieve this requirement?


Solution

  • Find the directory. Fail if none is found. Create the link with the case of the first letter switched. This way both /Oracle and /oracle would exist and point to the same directory.

        - find:
            paths: /
            patterns: '[oO]racle'
            file_type: directory
          register: result
    
        - fail:
            msg: Directory is missing. Play failed.
          when: result.matched == 0
    
        - set_fact:
            mylink: "{{ mydir[0] ~ myswitch[mydir[1]] ~  mydir[2:] }}"
          vars:
            mydir: "{{ result.files.0.path }}"
            myswitch:
              o: O
              O: o
    
        - file:
            state: link
            src: "{{ result.files.0.path }}"
            dest: "{{  mylink }}"
    

    Example of a complete playbook for testing arbitrary path

    - hosts: localhost
    
      vars:
    
        mypath: /tmp/ansible/
        mydir: "{{ result.files.0.path|basename }}"
        myswitch:
          o: O
          O: o
        mylink: "{{ myswitch[mydir.0] ~  mydir[1:] }}"
    
      tasks:
    
        - find:
            paths: "{{ mypath }}"
            patterns: '[oO]racle'
            file_type: directory
          register: result
    
        - fail:
            msg: Directory is missing. Play failed.
          when: result.matched == 0
    
        - file:
            state: link
            src: "{{ result.files.0.path }}"
            dest: "{{  mypath ~ mylink }}"
    

    For example, given the directory

    shell> tree /tmp/ansible/
    /tmp/ansible/
    └── Oracle
    

    The play creates a link

    shell> tree /tmp/ansible/
    /tmp/ansible/
    ├── oracle -> /tmp/ansible/Oracle
    └── Oracle