An optional use task returns a variable in variable templates
I am trying to create a list of environment variables for use in tasks, which may have a slightly different path on each host due to version differences.
For example, /some/common/path/v_123/rest/of/path
I created a list of these variables in the variables.yml file, which is imported via roles.
roles/somerole/varables/main.yml
contains the following
somename:
somevar: 'coolvar'
env:
SOME_LIB_PATH: /some/common/path/{{ unique_part.stdout }}/rest/of/path
Then I have a task that runs something like this
- name: Get unique path part
shell: 'ls /some/common/path/'
register: unique_part
tags: workflow
- name: Perform some actions that need some paths
shell: 'binary argument argument'
environment: somename.env
But I am getting some Ansible errors regarding variables that are not defined.
Alternatively, I tried to predefine unique_part.stdout
in the hope of overwriting a predefined registry variable, but then I got other obscure errors - template failure.
Is there any other way to handle these variables based on the return of the command?
source to share
You can also use facts: http://docs.ansible.com/set_fact_module.html
# Prepare unique variables
- hosts: myservers
tasks:
- name: Get unique path part
shell: 'ls /some/common/path/'
register: unique_part
tags: workflow
- name: Add as Fact per for each hosts
set_fact:
library_path: "{{ unique_part.stdout }}"
# launch roles that use those unique variables
- hosts: myservers
roles:
- somerole
This way you can dynamically add a variable to your hosts before using them.
source to share
Vars files are evaluated when read by Ansible. Your only chance is to include a placeholder that you then have to replace, for example:
somename:
somevar: 'coolvar'
env:
SOME_LIB_PATH: '/some/common/path/[[ unique_part.stdout ]]/rest/of/path'
And then in your play, you can replace this placeholder:
- name: Perform some actions that need some paths
shell: 'binary argument argument'
environment: '{{ somename.env | replace("[[ unique_part.stdout ]]", unique_part.stdout) }}'
source to share