1

this is a tricky theoretical question, even the explanation itself.

I will use Bacula (server backup software) as an example here to make it more clear.

Bacula has a server and a client component. Adding a new client requires a config file on the server and on the client. So what I want to do in my role is:

Bacula server role:

  1. Setup the bacula server on one host
  2. [for every client] Copy client config file for the server to the server
  3. [for every client] Copy client config file for the client to the client

Now the problem I have is with host_vars and group_vars. I want to be able to have this role used by all my [debian] hosts (this is a group). So my playbook looks like this:

- hosts: debian
  roles:
    - bacula
  tags:
    - bacula

So when this role is triggered it should do the following:

  1. One host must obviously the server, so this one will get a complete bacula server provision if it is played out on the server host.
  2. If this role is applied to all other clients the following should happen:
    1. (current host debian-client): copy config to debian-client
    2. (current host debian-client): copy config to debian-server

Any idea how I could do that?


For me it is really hard to explain, so if anything about the above is unclear, please let me know so i can make it clearer.

Update:

Thanks to @Konstantin Suvorov delegate_to answered it: https://docs.ansible.com/ansible/playbooks_delegation.html#delegation

cytopia
  • 177
  • 1
  • 12

1 Answers1

2

Something like this, for example:

inventory:

[debian]
host1
host2
host3 bacula_role=server
host4
host5

play:

- hosts: debian
  vars:
    bacula_server: "{{ (ansible_play_hosts | map('extract',hostvars) | selectattr('bacula_role','defined') | selectattr('bacula_role','equalto','server') | first).inventory_hostname }}"
  tasks:
    - debug: msg="Install server"
      when: inventory_hostname == bacula_server

      # client block
    - block:
        - debug: msg="Template server-side client config"
          delegate_to: bacula_server

        - debug: msg="Template client config"

      when: inventory_hostname != bacula_server
      # end of block

Replace debug statements with some real module (e.g. apt/template) and add some error handling if not hosts with bacula_role=server exist.

If you have many tasks to install server/client, you may split them into bacula_server.yml and bacula_client.yml without when statements but include them with:

- include: "bacula_{{ bacula_role | default('client') }}.yml"
Konstantin Suvorov
  • 3,836
  • 1
  • 11
  • 13
  • Thank you, that solved it. The thing I was looking for and could not really describe was `delegate_to`. Maybe you could add this link to your answer for others to find: https://docs.ansible.com/ansible/playbooks_delegation.html#delegation – cytopia Feb 11 '17 at 10:46