1

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.

0

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"
0

Try lookup vars

- name: debug
  debug:
    msg: "{{ lookup('vars', newvar) }}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.