MrDuk
MrDuk

Reputation: 18322

What's the best way to populate variable files with hosts from groups?

In my all.yml file, I have some global variables that are used throughout my project. One of these is a list of redis hosts. My inventory files look like this:

[dev_redis]
host.abc.com

[prod_redis]
host.xyz.com

So what I'd like to do in my all.yml file is something like the following:

---
global__:
  app_user: root
  app_group: root

  redis_hosts: "{% for host in groups[{{env}}_redis] %}{{host}}:5544,{% endfor %}"

This doesn't work though -- I get an error: FAILED! => {"failed": true, "msg": "ERROR! template error while templating string: expected token ':', got '}'"}

My questions are:

(1) Why am I getting this error?

(2) Will I be able to do this if I'm not sourcing the inventory file which contains my redis nodes? For each run of the deploy scripts, I reference which inventory files to use for that service type (this all happens within a python wrapper) -- so if I'm deploying a service other than redis, can I still access the groups from the redis inventory file? Can I pass in multiple inventory files with -i?

Upvotes: 0

Views: 321

Answers (1)

Deepali Mittal
Deepali Mittal

Reputation: 1032

I see you have used loop in main yml whereas this way we define the loop when we need to access the vars in templates.

The hosts can be accessed as :

---
global__:
  app_user: root
  app_group: root

  redis_hosts: "{{[groups['dev_redis'][0]]}}:5544"

dev can be replaced with your variable {{env}}

Answers to your question:

  1. You are getting this error due to some syntax issue. In ansible when a variable is used it should be given in "{}" and at some places its a bare var. Depending on the usage of var if its not used correctly ansible throws this error.

  2. No thats not possible. You need to pass the inventory/variable file from which you want to use.

    • Yes you can access the groups from the redis inventory file even if you are deploying any other service but that should be passed

    • Multiple inventory files can be passed using -i in a way that you refer a folder. eg: ansible-playbook -i /home/ubuntu/inventory/ test.yml

And in inventory directory there can be multiple inventory files. like /home/ubuntu/inventory/host1,/home/ubuntu/inventory/host2,/home/ubuntu/inventory/var1 etc.

Upvotes: 0

Related Questions