I have a variable dir_lst_raw in an ansible playbook whose value is a list as shown below:
"dir_lst_raw": [
        "/path1/dir1/user",
        "/path2/dir2/admin",
        "/path3/dir3/user.ansible_backup_2020-03-16",
        "/path1/dir1/config.ansible_backup_2020-03-16",
        "/path2/dir2/dir3/somefile"
      ]
I need to remove all the lines containing .ansible_backup_ and save to another variable as a list.
I've googled for regex and tried to not match the pattern with the select filter as below:
  - set_fact:
      dir_lst: "{{ dir_lst_flt_r | select('match','(^.ansible_backup_)+') | list }}"
but the new variable dir_lst turned out as an empty list. I am expecting dir_lst as below:
"dir_lst_raw": [
        "/path1/dir1/user",
        "/path2/dir2/admin",
        "/path2/dir2/dir3/somefile"
     ]
Could somebody please suggest how can I get it done?
Q: "Remove all the lines containing .ansible_backup_"
A: You can either use the simple test search. Quote:
search succeeds if it finds the pattern anywhere within the string.
  dir_lst: "{{ dir_lst_raw | reject('search', dir_lst_search) | list }}"
  dir_lst_search: '\.ansible_backup_'
or you can use the test regex. Quote:
regex works like search, but regex can be configured to perform other tests as well by passing the match_type keyword argument ...
  dir_lst: "{{ dir_lst_raw | reject('regex', dir_lst_regex) | list }}"
  dir_lst_regex: '^(.*)\.ansible_backup_(.*)$'
Both options give the same result
  dir_lst:
    - /path1/dir1/user
    - /path2/dir2/admin
    - /path2/dir2/dir3/somefile
Example of a complete playbook for testing
- hosts: localhost
  vars:
    dir_lst_raw:
      - /path1/dir1/user
      - /path2/dir2/admin
      - /path3/dir3/user.ansible_backup_2020-03-16
      - /path1/dir1/config.ansible_backup_2020-03-16
      - /path2/dir2/dir3/somefile
    dir_lst1: "{{ dir_lst_raw | reject('search', dir_lst_search) | list }}"
    dir_lst_search: '\.ansible_backup_'
    dir_lst2: "{{ dir_lst_raw | reject('regex', dir_lst_regex) | list }}"
    dir_lst_regex: '^(.*)\.ansible_backup_(.*)$'
  tasks:
    - debug:
        var: dir_lst1
    - debug:
        var: dir_lst2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With