Trifo
Trifo

Reputation: 71

Ansible: selecting dict element by extra var

I am trying to create a playbook to set up log collecting daemons. I have a dict with the parameters to set up (used in templates). Someting like this

logservers:
  prod:
    ipaddress: 10.10.44.79
    envname: "Productive servers"
    other_data: "important prod data"
  test:
    ipaddress: 10.20.44.79
    envname: "Testing servers"
    other_data: "data for testing"
  dev:
    ipaddress: 10.30.44.79
    envname: "Developement servers"
    other_data: "developers data"

Is it possible to use an extra var, like -e env=prod on running the playbook and use this tho select "prod" element from the dict when templating?

Or, what is the method to achieve this in Ansible?

And a last bit: I would need this for a fairly old dist of Ansible to work on (2.4)

Upvotes: 1

Views: 749

Answers (1)

Frenchy
Frenchy

Reputation: 16997

there are lot of ways to do that:

one way is to use a new variable server which has the data wanted following the extra var:

- name: configure app servers
  hosts: localhost
  vars:
    logservers:
      prod:
        ipaddress: 10.10.44.79
        envname: "Productive servers"
        other_data: "important prod data"
      test:
        ipaddress: 10.20.44.79
        envname: "Testing servers"
        other_data: "data for testing"
      dev:
        ipaddress: 10.30.44.79
        envname: "Developement servers"
        other_data: "developers data"

    server: "{{ logservers[env] }}"

  tasks:
    - name: display "{{ env }}"
      debug:
        msg: "{{ server }}"

you launch the playbook:

ansible-playbook play.yml -e env=dev

result:

TASK [display "dev"] ****************************************************************
ok: [localhost] => {
    "msg": {
        "envname": "Developement servers",
        "ipaddress": "10.30.44.79"
        "other_data": "developers data"
    }
}

you launch the playbook:

ansible-playbook play.yml -e env=prod

result:

TASK [display "prod"] ***************************************************************
ok: [localhost] => {
    "msg": {
        "envname": "Productive servers",
        "ipaddress": "10.10.44.79"
        "other_data": "important prod data"
    }
}

Upvotes: 2

Related Questions