Using a variable inside reference

9 views
Skip to first unread message

Jason Bullen

unread,
Mar 17, 2020, 3:21:25 PM3/17/20
to Ansible Project
I have 2 var files with a top level of dev and prod.  All sublevels are the same.  For example:

dev:
  accesspolicies:
  -  policy1
  -  policy 2

and 

prod:
  accesspolicies:
  - policy1


There is a problem that i keep running into where my design requires a var_prompt input to be used to define which variable to loop over.  When I run into this problem I have to go back to the drawing board because I cannot find a way to do the following:

vars_prompt:
  - name: env
    prompt: "Environment"
include_vars:
  file: "{{env}}.yml"

 - debug:
   msg: "{{env}}.accesspolicies"

Is there a way to do this better?

Vladimir Botka

unread,
Mar 17, 2020, 4:57:08 PM3/17/20
to Jason Bullen, ansible...@googlegroups.com
On Tue, 17 Mar 2020 12:21:25 -0700 (PDT)
Jason Bullen <jmbul...@gmail.com> wrote:

> file dev.yml
> dev:
> accesspolicies:
> - policy1
> - policy2
>
> file prod.yml
> prod:
> accesspolicies:
> - policy1
>
> [...]
> vars_prompt:
> - name: env
> prompt: "Environment"
> tasks:
> - include_vars:
> file: "{{ env }}.yml"
> - debug:
> msg: "{{ env }}.accesspolicies"
>
> Is there a way to do this better?

"lookup" plugin "vars" helps to reference the variable. For example

shell> cat play.yml
- hosts: localhost
vars_prompt:
- name: env
private: false
prompt: "Environment"
tasks:
- include_vars: "{{ env }}.yml"
- set_fact:
my_env: "{{ lookup('vars', env ) }}"
- debug:
var: my_env.accesspolicies

gives

shell> ansible-playbook play.yml
Environment: dev
...
TASK [debug] ***
ok: [localhost] => {
"my_env.accesspolicies": [
"policy1",
"policy2"
]
}

HTH,
-vlado
Reply all
Reply to author
Forward
0 new messages