Score:1

Is it bad form to create an Ansible role just for setting facts?

kg flag

I've got one of those situations where I could write a three task role to lookup, sort and extract a set of values like:

- 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
    latest_ami_id: '{{ _amis[0].image_id }}
    ...

I need to do this sort of thing in a couple different playbooks, so I want code reuse. What seems cooler and more Anible-like would be to implement a Lookup plugin, but that's many more lines of Python with calls to Boto3 to effectively do the same thing (except returning the details as a dict).

Can't seem to find anything in best practices for roles that covers this, or more than likely I am missing something.

Score:2
br flag

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.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.