Ansible Pattern: Calculation Step

Published On: 2017-06-24, Reading Time: 1 minute

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
    uploads_dir:    "{{ base_dir }}/uploads"
    api_url:        "{{ api_ver }}"
    fetch_endpoint: "{{ api_ver }}/fetch"
    half_memory:    "{{ ( / 2) | int }}"

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

This then simplifies the tasks themselves.

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