How would I register a dynamically named variable in an Ansible task?

I suppose there's no easy way for that. And register with with_items loop just puts all results of them into an array variable.results. Try the following tasks:

  tasks:
    - name: Determine GIDs
      shell: "getent group {{ item }} | cut -d : -f 3"
      register: gids
      changed_when: false
      with_items:
        - syslog
        - utmp
    - debug:
        var: gids
    - assert:
        that:
          - item.rc == 0
      with_items: gids.results
    - set_fact:
        gid_syslog: "{{gids.results[0]}}"
        gid_utmp: "{{gids.results[1]}}"
    - debug:
        msg: "{{gid_syslog.stdout}} {{gid_utmp.stdout}}"

You cannot either use variable expansion in set_fact keys like this:

    - set_fact:
        "gid_{{item.item}}": "{{item}}"
      with_items: gids.results

Set fact supports variables, as opposed to the previous solution's statement

- set_fact:
    "{{ item.name }}": "{{ item.val }}"
  when: item.name not in vars           # this is optional. prevents overwriting vars
  with_items:
    - { name: test, val: myalue }
    - { name: notest, val: novalue }

Tags:

Ansible