Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible, how to join multiple arrays in a single file?

Tags:

ansible

Using this as my boilerplate: https://github.com/modcloth/ansible-role-modcloth-sumologic-collector - It works great, but I'm looking for some suggestions on how to expand this for my intended needs. I need to be able to create a JSON file based on multiple arrays.

The following is the default array I need in the SumoLogic JSON source.

roles/sumologic/defaults/main.yml:

sumologic_collector_default_log_path:

- { name: "Auth Log", path: "/var/log/auth.log", use_multiline: false, category: "OS/Linux/Auth" }

Say I want to add an additional file to the SumoLogic JSON file from group_vars/app_server.yml:

- { name: "Package Log", path: "/var/log/nginx/access.log", use_multiline: fasle, category: "OS/Linux/Nginx" }

How would I combine the examples above using a template into the same destination file?

Happy to provide more details. Not entirely sure if my train of thought makes sense, though I think set_fact is one way of doing this and I haven't been able to understand that enough to figure out a way.

like image 650
wsani Avatar asked Jan 31 '15 02:01

wsani


1 Answers

Jinja2, the templating engine used by Ansible, gives you the option to easily merge lists:

array1 + array2

Here is a complete example playbook:

---

- name: Testing
  hosts: localhost
  gather_facts: no
  vars:
    array1:
      - a
      - b
      - c
    array2:
      - x
      - y
      - z
  tasks:
    - debug:
        msg: "{{ array1 + array2 }}"

...

Output:

PLAY [Testing] **************************************************************** 

TASK: [debug msg="{{ array1 + array2 }}"] ************************************* 
ok: [localhost] => {
    "msg": "['a', 'b', 'c', 'x', 'y', 'z']"
}

PLAY RECAP ******************************************************************** 
localhost                  : ok=1    changed=0    unreachable=0    failed=0
like image 57
udondan Avatar answered Oct 16 '22 22:10

udondan