Set variable based on group_names

1,273 views
Skip to first unread message

Jacek

unread,
Sep 17, 2014, 7:42:08 PM9/17/14
to ansible...@googlegroups.com
  Hi,

Perhaps it's an easy question but I cannot find a way to answer it myself.

More in details -- I have two groups in my inventory: clients (many hosts) and server (single host), and a template at the client which needs to use the server address. If it happens that a client host is also in the 'server' group, I wanted to set the address in the template to 'localhost'. Otherwise, the address should point to the server address as specified in the inventory. I guess it's quite easy to code it using jinja2 directly in the template but my template includes many places with such a reference, so I thought about first setting the server address variable, and then using this variable to evaluate the template. Is this correct way of thinking? How can I set a variable in a play before template evaluation? Otherwise, have you got any other ideas?

  Cheers,
  Jacek

James Cammarata

unread,
Sep 17, 2014, 8:41:55 PM9/17/14
to ansible...@googlegroups.com
Hi Jacek, this should work for you:

- set_fact: address_variable='localhost'
  when: 'server' in group_names
- set_fact: address_variable='server_address_here'
  when: 'server' not in group_names
- template: ...

The "group_names" variable is a special variable that contains a list of the groups the current host is in.

--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To post to this group, send email to ansible...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/b878ce70-0326-42a9-8f5a-25c3b9e3dd71%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Jacek

unread,
Sep 19, 2014, 9:06:25 AM9/19/14
to ansible...@googlegroups.com
Thanks James,

That's nice. One thing I'm not sure about is the 'server_address_here' which you wrote. Ideally, what I need there is the name/address of the first (and the only) host in the inventory group 'server'.
Is there a way to do this?

  Cheers,
  Jacek

Jacek

unread,
Sep 19, 2014, 10:59:46 AM9/19/14
to ansible...@googlegroups.com
Ok, after a little search I've got it; for anyone interested:

- set_fact: address_variable={{ item }}
  with_items: groups.server
  when: "'server' not in group_names"

  Cheers,
  Jacek

Tomasz Kontusz

unread,
Sep 22, 2014, 3:50:28 AM9/22/14
to ansible...@googlegroups.com
I think this would be even better:

- set_fact: address_variable={{ groups.server[0] }}

when: "'server' not in group_names"

Looks nicer both in code and in output ;-)

Jacek <jacek...@gmail.com> napisał:

--
Wysłane za pomocą K-9 Mail.
Reply all
Reply to author
Forward
0 new messages