Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible use task return varible in variable templates

Tags:

ansible

I am trying to craft a list of environment variables to use in tasks that may have 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 variables.yml file that gets 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

I then 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 get some Ansible errors about variables not being defined.

Alternatively I tried to predefine the unique_part.stdout in hopes of register overwriting predefined variable, but then I got other ansible errors - failure to template.

Is there another way to craft these variables based on command returns?

like image 864
RMSe17 Avatar asked Feb 11 '23 08:02

RMSe17


1 Answers

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 dynamicaly add variable to your hosts before using them.

like image 64
ant31 Avatar answered Mar 24 '23 00:03

ant31