Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: Appending to list with variable files

Tags:

ansible

jinja2

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

like image 493
MANCHUCK Avatar asked Oct 19 '25 02:10

MANCHUCK


1 Answers

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.

like image 129
Konstantin Suvorov Avatar answered Oct 22 '25 05:10

Konstantin Suvorov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!