Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate dynamic variable name in ansible

I have vars where I put something like this:

vars/main.yml
hello_port: 80
world_port: 81

in my ansbile file I load the vars with

vars_files:
  - ./vars/main.yml

This is how I initialize m_name:

 - name: set_fact
     set_fact:
        m_name:
          - 'hello'
          - 'world'

and after that I have task with iterate using with_items:

 - debug:
      msg: "{{ (item + '_port') }}"
   with_items: "{{ m_name }}"

But I've got as output

hello_port
world_port

not their values.


OK I find that if I use debug var it is working. But If I want to put this expression "{{ (item + '_port') }}" for an example in shell task it does not evaluate it. Is there a way to evaluate the dynamically created variables name - to get the value?

like image 773
Jordan Borisov Avatar asked Jan 26 '17 14:01

Jordan Borisov


People also ask

How do I use dynamic variables in ansible?

Create an Ansible Playbook which will dynamically load the variable file named the same as OS_name and just by using the variable names we can Configure our target node. (Note: No need to use when keyword here.)

How do you define a new dynamic variable in task ansible?

To define a variable dynamically when you run a playbook, use the --extra-vars option along with the key and value of the variable you want to define. In this example, the key is my_var because that's the string referenced in the playbook, and the value is any string you want the variable to contain.

How are variables referenced in an ansible template?

The variables are referenced through the Jinja2 template system, known to many from the Python language. It is very flexible. It supports both conditional expressions and loops. We reference the value of a variable in Jinja2 by placing its name inside double curly braces “{{ }}“.

What is variable name in ansible?

Variable Name Rules Ansible has a strict set of rules to create valid variable names. Variable names can contain only letters, numbers, and underscores and must start with a letter or underscore. Some strings are reserved for other purposes and aren't valid variable names, such as Python Keywords or Playbook Keywords.


1 Answers

https://docs.ansible.com/ansible/2.5/plugins/lookup/vars.html

- name: Show value of 'variablename'
  debug: msg="{{ lookup('vars', 'variabl' + myvar)}}"
  vars:
    variablename: hello
    myvar: ename
like image 82
abc Avatar answered Sep 23 '22 20:09

abc