Using a variable inside reference

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?

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

  > 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

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

HTH,
  -vlado