How to freeze a variable value in an Ansible playbook

Viewed 126

Given this Ansible playbook:


- name: CI/CD management, via cidre.io
  hosts: 127.0.0.1
  connection: local

  vars:
    cidre_version: "{{ lookup('file', '../VERSION') | default('v0.1.0') }}"

  roles:
  - role1
  - role2

I understand everytime I use cidre_version variable, Ansible read VERSION file, hence value is dynamic and can change across tasks.

How can I freeze this value when playbook starts?

3 Answers

Nice question.

You can do the following:

  1. Create a task in which you copy that file if exists otherwise you create a new file adding the default value.
  2. Initialize the variable reading from this new file.

This should solve your problem.

@vijesh answer is correct. Meanwhile, it is possible

  1. to override the var value statically keeping the same name
  2. to play that set_fact tasks before roles so you can use the value everywhere. You simply have to put it in the pre_tasks section.

Note: I fixed your initial var definition so it will work in case the version file does not exist.

---
- name: CI/CD management, via cidre.io
  hosts: 127.0.0.1
  connection: local

  vars:
    cidre_version: "{{ lookup('file', '../VERSION', errors='ignore') | default('v0.1.0', true) }}"

  pre_tasks:
    - name: Fix the value of version and override playbook definition
      set_fact:
        cidre_version: "{{ cidre_version }}"

  roles:
    - role1
    - role2

You may use set_fact at the start of the playbook to store the value of cidre_version. Something like:

- name: CI/CD management, via cidre.io
  hosts: 127.0.0.1
  connection: local

  vars:
    cidre_version: "{{ lookup('file', '../VERSION') | default('v0.1.0') }}"

  tasks:
  - set_fact:
      cidre_version_static: "{{ cidre_version }}"

  - name: remaining tasks...
Related