Ansible Pattern: Calculation Step

When there are a lot of paths, URLs or other strings to keep track of in a role it can get really messy. Especially if the some of them contain variables and are used in multiple places. Often to make roles easier to work with, I place a task at the tops of the role that calculates the variables so that they can easily be referred to later.

It important to note that the set_fact role can set multiple facts at the same time. However you cannot depend on any variables set in the same task. If you need variables to depend on previous ones, just do them in seperate steps. this doesn’t affect performance as the set_fact task executes everything locally, so it is quite fast.

---
- name: Calculate Variables
  set_fact:
    uploads_dir:    "{{ base_dir }}/uploads"
    api_url:        "https://api.example.com/{{ api_ver }}"
    fetch_endpoint: "https://api.example.com/{{ api_ver }}/fetch"
    half_memory:    "{{ (ansible_memory_mb.real.total / 2) | int }}"

- name: Calculate more variables
  set_fact:
    quarter_memory: "{{ (half_memory / 4) | int }}"

This then simplifies the tasks themselves.

- name: Fetch from the API
  get_url:
    url: "{{ fetch_endpoint }}"
    dest: "{{ uploads_dir }}"
comments powered by Disqus