1

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.

1 Answers1

2

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.
Vladimir Botka
  • 5,138
  • 8
  • 20