Ansible List Variable and Select Filter to ignore matched items

Viewed 4241

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?

1 Answers

Q: "Remove all the lines containing .ansible_backup_"

A: The task below does the job

    - set_fact:
        dir_lst: "{{ dir_lst_raw|reject('match', my_regex)|list }}"
      vars:
        my_regex: '^(.*)\.ansible_backup_(.*)$'
    - debug:
        var: dir_lst

gives

dir_lst:
  - /path1/dir1/user
  - /path2/dir2/admin
  - /path2/dir2/dir3/somefile
Related