3

Is there a way to have multiple variable files append to an array?

The end goal is to have each file append an AWS security group for the launch configuration without the need to copy those groups into each file

ex:

group_vars/all.yml
group_vars/php.yml
group_vars/web.yml

all.yml:

aws_security_groups:
  - sg-ssh

php.yml

aws_security_groups:
  - sg-mysql

web.yml

aws_security_groups:
  - sg-http

Debugging aws_security_groups produces:

TASK [Debugging] ***************************************************************
ok: [XXX.XXX.XXX.XXX] => {
    "aws_security_groups": [
        "sg-mysql"
    ]
}

We have API servers and front-end servers which have different scaling polices. I would like the web servers to have the groups: sg-web and sg-ssh with the api servers to have: sg-web, sg-ssh and sg-mysql

MANCHUCK
  • 2,424
  • 1
  • 16
  • 22
  • I think you could structure your playbook much better, but I can't give better guidance on that without more context. – MillerGeek Sep 26 '16 at 19:04

1 Answers1

4

AFAIK there is no way to merge list variables during definition time in Ansible.
As a workaround, you can make a dict in your all.yml:

aws_security_groups:
  all:
    - sg-ssh
    - sg-all
  php:
    - sg-mysql
  web:
    - sg-http

Or define each subkey (all, php, web, etc.) in corresponding group vars file and use merge hash_behavior (but changing hash_behavior is not generally recommended).

And then use this magic to get a list of security groups:

- debug: msg="{{ (group_names + ['all']) | intersect(aws_security_groups.keys()) | map('extract', aws_security_groups) | sum(start=[]) }}"

This will make plain list of all security groups depending on groups for current host.

Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193
  • This is a good answer as it will merge in the keys together. What I am looking to do is based on tag for the instance, assign different groups without the need to copy the groups into each group file. The solution here means that all instances will get all the groups assigned to the. +1 for the all the filters – MANCHUCK Sep 26 '16 at 15:11