HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

How to define constants in Ansible?

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
ansibleconstantsdefinehow

Problem

If one writes a constant in Python, then one uses uppercase:

SOME_CONSTANT = "helloworld"


Now I wonder how to define constants in Ansible. My first impression was to use the same convention as in Python as Ansible is written in python, but when one checks the variables information page then this does not seem to be a best practice.

Current approach

https://github.com/030/ansible-firefox/blob/master/vars/main.yml

---
firefox_download: /tmp/firefox-{{ firefox_version }}.tar.bz2
firefox_bin: "{{ firefox_home }}/firefox/firefox"


https://github.com/030/ansible-firefox/blob/master/tasks/main.yml

- name: Download.
  get_url:
    url: https://ftp.mozilla.org/pub/firefox/releases/{{ firefox_version }}/linux-x86_64/en-US/firefox-{{ firefox_version }}.tar.bz2
    dest: /tmp/firefox-{{ firefox_version }}.tar.bz2
checksum: "{{ firefox_checksum }}"


Discussion

I am considering to define https://ftp.mozilla.org/pub/firefox/releases/{{ firefox_version }}/linux-x86_64/en-US/firefox-{{ firefox_version }}.tar.bz2 as a constant in the vars/main.yml, but I did not see any other ansible roles that define constants as:

FIREFOX_DOWNLOAD_URL: https://ftp.mozilla.org/pub/firefox/releases/{{ firefox_version }}/linux-x86_64/en-US/firefox-{{ firefox_version }}.tar.bz2


while this is valid python and the convention to write constants.

One could argue that an Ansible constant could be defined in the default/main.yml, but on the other hand, as a CONSTANT is immutable it should not be possible to overwrite it and should reside in vars/main.yml.

Solution

As pointed out in the other comment, there are no constants in python. It's just a convention, but defining a variable in capitals, doesn't mean you can't reassign the value.

There are many ways to pass/define variables in ansible (command line, vars in playbook, include a yaml, vars dir in a role, defaults dir, etc) however, there isn't a way to define a constant.

The closest to setting a constant in the way you ask for it is setting your variables as defaults(that is defaults/main.yml inside the role structure). The defaults of a role are the type of variables that have the lowest precedence and are being overwritten by any other way you can define a var but are a great place to put a variable that is unlikely to change and won't clutter your "important" role vars.

Regarding the way you define them - I'd say it's up to you. Just stick to it. I haven't seen anybody using capitals and I would probably make the variable lower case, however, since ansible provides tremendeous amount of flexibility and freedom to do what you like the way you like it, it really is up to you.

Context

StackExchange DevOps Q#3474, answer score: 3

Revisions (0)

No revisions yet.