Dynamic value assignment to ansible fact based on condition

Sorry for the delay; busy week :confused:

Here is an awful mess that kind of does what you’re looking for, relying solely on Jinja2 filters and a bit of logic using inline Jinja2 in yaml folds. I’m pretty confident it can be improved in many ways.

---

- name: Add new group to groupslist, ensuring group names are unique
  gather_facts: false
  connection: local
  hosts: localhost
  become: false
  vars:
    groupslist: "{{ hostvars['localhost']['groupslist'] | d([]) }}" # ANSIBLE_CACHE_PLUGIN=jsonfile ANSIBLE_CACHE_PLUGIN_CONNECTION=/tmp/groupslist.json
  tasks:
    - name: Get user input
      when: _groupname_input is undefined
      ansible.builtin.pause:
        prompt: |
          ==============================================================================================================
            Group Name ?
          ==============================================================================================================
      register: _groupname_input
      delay: 1
      retries: 999

    - name: Register last existing group name matching pattern
      ansible.builtin.debug:
        msg: "{{ groupslist | map('regex_findall', '(^' + _groupname_input.user_input|lower + '(?:_[0-9]+)?$)') | flatten | unique | last |d() }}"
      register: _last_matching_groupname
      failed_when: false
      no_log: true

    - name: Define new group name based on last existing group name pattern
      when: _last_matching_groupname.msg|length
      ansible.builtin.set_fact:
        _newgroup: >-
          {%- set _last_matching_groupname_nb = (_last_matching_groupname.msg|lower).split('_')[-1] | regex_search('^[0-9]+$') | string -%}
          {%- if _last_matching_groupname_nb | regex_search('^[0-9]+$') -%}
              {%- set _newgroup_nb = (_last_matching_groupname_nb | int + 1) | string -%}
              {{ _last_matching_groupname.msg|lower | regex_replace('(_[0-9]+$)', '_' + _newgroup_nb) }}
          {%- else -%}
              {{ _last_matching_groupname.msg|lower + '_1' }}
          {%- endif -%}

    - name: Store new (unique) group in var
      when: _newgroup|d() not in groupslist
      ansible.builtin.set_fact:
        groupslist: "{{ groupslist + [_newgroup | d(_groupname_input.user_input)] }}"
        cacheable: true

    - name: Print groupslist content
      ansible.builtin.debug:
        msg: "{{ groupslist }}"
1 Like