Ansible group_vars

2019-08-09 10:52发布

问题:

I'm trying to automate the deployment of sensu checks to each role that a host plays.

I currently have a structure like

group_vars/
  nginx
  all

In each group_vars file, I have defined the following:

sensu_checks:
  - check_name
  - check_other_name

So for example, in group_vars/all I'd have:

sensu_checks:
  - check_raid
  - check_load
  - check_disk

In group_vars/nginx I'd have:

sensu_checks:
 - check_pid
 - check_http

What I would like to know if it's possible would be to get all the checks that a specific host should install, for example with:

- name: Print host sensu checks
  command: echo {{item}}
  with_flattened:
   - {{ sensu_checks }}

This doesn't work though, as it only gives me the group_vars of the last group the host name is defined in. Is there a way to get a flattened list the checks of all the groups the host is attached to?

In the previous example, I'd expect

 [ check_load, check_disk, check_raid, check_http, check_pid ] 

but instead I'm getting

[ check_http, check_pid ]

for an nginx host (which is part of both the 'all' and and 'nginx' groups)

回答1:

with_flattened doesn't do what you expect in this case - you're a victim of variable scoping.

The nginx group is the most specific, so ansible is using that variable definition - which explains why you're only getting the sensu_check defined in nginx.

You could rename the var in one of the two places (I recommend the nginx var, since that's the most specific one), and then use with_flattened to combine the two lists:

with_flattened: - {{ sensu_checks }} - {{ sensu_nginx_checks }}



回答2:

In your question the YAML format is incorrect for group_vars/all

It should look like:

sensu_checks:
  - check_raid
  - check_load
  - check_disk

If that is the code in your project you might want to fix it and see if you get the result you are expecting.