Ansible constructing variable name from another variable

ansible

I have a ansible variable definition, and was wondering if i can get the variables value based on the variable defined during runtime

vars:
  test:
    user: ""
    dirs:
      base: ""
      logs: ""
      libs: ""
    region:

- name: debug
  debug:
    msg: "{{ newvar }}"

ansible-playbook playbook.yml -e "newvar=test"

execution of above should print, all values defined in the 'test' variable.

Best Answer

I would use an associative array in yaml.

playbook.yml

- hosts: localhost
  gather_facts: false
  vars:
    my_environments:
      test:
        user: "user_test"
        dirs:
          base: "/x"
          logs: "/y"
          libs: "/z"
        region:
      prod:
        user: "user_prod"
        dirs:
          base: "/a"
          logs: "/b"
          libs: "/c"
        region:

  tasks:

    - name: debug
      debug:
        msg: "{{ my_environments[newvar] }} "

The you can run it with:

ansible-playbook -ilocalhost,  playbook.yml -e "newvar=test"