benibilme
benibilme

Reputation: 87

ansible: filtering the content of a variable with regex

I am trying to write an ansible role to automate installing julia programming language in arch linux enviroment. Unfortunately, because of llvm, arch linux advises not to use delivered by package manager.

My playbook receives the version information from command line with extra-var which is represented as target_version variable. Following task which is part of a role gives an error stating that major_version is not defined that is derived from target_version by filtering target_version with regex. target_version is something similar to a string as 1.8.2. I am trying to capture the initial 1.8 part of the version string to create the url. Assume the conditions on julia_installed_version and target_version hold true. I have marked the offending part of the code

- name: Check if install is needed
  ansible.builtin.set_fact:
     install_needed: true
     # FOLLOWING LINE CREATES ERROR
     major_version: "{{ target_version | regex_search('\\d+\\.\\d+')}}" 
     tar_file_name: "julia-{{ target_version }}-linux-x86_64.tar.gz"  
     download_url: "https://julialang-s3.julialang.org/bin/linux/x64/{{ major_version }}/{{ tar_file_name }}" 
  when: julia_installed_version is defined  and  target_version is version(julia_installed_version.stdout, '>') 

I wrote a tiny test code, the marked line works if target_version is a string, but gives error if it is variable. I really do not know what is going on. Any help is much appreciated.

Upvotes: 0

Views: 200

Answers (1)

Carlos Monroy Nieblas
Carlos Monroy Nieblas

Reputation: 2283

You will need to separate the definition of the fact:

- name: Check if installed needed
  ansible.builtin.set_fact:
     install_needed: true
     major_version: "{{ target_version | regex_search('\\d+\\.\\d+')}}" 
     tar_file_name: "julia-{{ target_version }}-linux-x86_64.tar.gz"
  when:
    - julia_installed_version is defined
    - target_version is version(julia_installed_version.stdout, '>') 

- name: Assign download URL
  ansible.builtin.set_fact:
     download_url: "https://julialang-s3.julialang.org/bin/linux/x64/{{ major_version }}/{{ tar_file_name }}" 
  when:
    - julia_installed_version is defined
    - major_version is defined
    - tar_file_name is defined

A way to understand it is that all the templates of the set_fact happen at the same time, the template of download_url assumes that the values for major_version and tar_file_name have been already assigned.

Upvotes: 1

Related Questions