How to do an array or hash merge in Ansible

ansible

An ansible-sensu-plugin-install role has been created in order to install sensu-plugins using this code:

- name: be sure sensu-plugins-{{ item.name }} is installed
  command: sensu-install -p {{ item.name }}:{{ item.version }}
  when: "'sensu-plugins-{{ item.name }} ({{ item.version }})' not in installed_plugins.stdout"
  with_items: "{{ sensu_plugin_install }}" 

There a two other roles that require sensu-plugins. The first role requires the mailer plugin:

sensu_plugin_install:
  - name: mailer
    version: 1.0.0

and the second one requires multiple plugins:

sensu_plugin_install:
  - name: cpu-checks
    version: 1.0.0
  - name: disk-checks
    version: 2.0.1
  - name: http
    version: 1.0.0
  - name: memory-checks
    version: 1.0.2
  - name: ntp
    version: 1.0.0

Role one and two have been included in one playbook.

Current outcome

Either the mailer defined in role one or the plugins defined in role two will be installed. Commenting out one of the sensu_plugin_install declarations will install plugins related to role one or two, e.g. only the mailer plugin will be installed:

TASK [030.sensu-plugin-install : be sure sensu-plugins-{{ item.name }} is
    installed] ***
    changed: [host.example.com] => (item={u'version': u'1.0.0', u'name':
    u'mailer'}) => {"changed": true, 

if the sensu_plugin_install of the second role has been commented out.

Expected outcome

The expected outcome is that all plugins will be installed, i.e. six in this case instead of one, i.e. mailer or five.

Discussion

It looks like that the arrays will not be merged as either one or five plugins will be installed instead of six and one of the two needs to be commented out in order to force the installation of a plugin.

One option to solve this issue is to merge these arrays, i.e. sensu_plugin_install + sensu_plugin_install. For example, in Puppet it is possible to merge arrays using hiera_array. How could this be done in Ansible?

Using Two different variables in order to solve the issue is not an option as the functionality of one role is used and it is not preferred to add another variable to this role if another role would like to install sensu plugins.

Best Answer

First of all I had to define two different variables rather than using the same one, e.g. sensu_plugin_install. After giving the second dict a different name like sensu_plugin_install_other, the two arrays were able to merge:

 with_items: "{{ sensu_plugin_install }} + {{ sensu_plugin_install_other }}"