Q: Is it bad form to create an Ansible role just for setting facts?
A: No. It is not. You say you 'want code reuse'
. Put the tasks into a file, e.g. tasks/get_latest_ami_id.yml, and create a role, e.g. roles/my_lib
shell> cat roles/my_lib/tasks/get_latest_ami_id.yml
- name: Lookup available AMI instances
amazon.aws.ec2_ami_info:
filters: ...
register: _ami_info
- name: Sort by creation date to get latest
ansible.builtin.set_fact:
_amis: '{{ _ami_info.images | sort(attribute="creation_date", reverse=True) }}'
- name: Set my facts for the latest AMI
ansible.builtin.set_fact:
latest_ami_id: '{{ _amis[0].image_id }}
...
Then use either include_role or import_role and run the tasks in your playbook, e.g.
- import_role:
name: my_lib
tasks_from: get_latest_ami_id.yml
See Re-using Ansible artifacts to learn what is the difference between including and importing.
You can use this role as a library of other tasks that can be reused.
If you run this role nothing will happen because of tasks/main.yml is missing. You can create it as a reminder, e.g.
shell> cat roles/my_lib/tasks/main.yml
- debug:
msg: Do not run this role. It is a library of standalone tasks.