- hosts: testhost
  gather_facts: no
  tasks:
    - name: Use a template in a key with set_fact
      set_fact:
        "{{ a_key }}": "{{ a_value }}"
      vars:
        a_key: my_key
        a_value: my_value
      register: result

    - name: Verify set_fact templates keys
      assert:
        that:
          - my_key == "my_value"
          - result.ansible_facts.my_key == "my_value"

    - name: Attempt to use a template to set an invalid variable name with set_fact
      set_fact:
        "{{ 'true' }}": value
      register: result
      ignore_errors: yes

    - name: Verify set_fact refused to accept an invalid variable name sourced from a template
      assert:
        that:
          - result is failed
          - result.msg is contains "Invalid variable name 'true'"

    - name: Attempt to use a template to set an invalid variable name type with set_fact
      set_fact:
        "{{ 1 }}": value
      register: result
      ignore_errors: yes

    - name: Verify set_fact refused to accept an invalid variable name type sourced from a template
      assert:
        that:
          - result is failed
          - result.msg is contains "Invalid variable name '1' of type 'int'"
