Playbook acting on multiple hosts

Hi there,

I’ve recently fallen in love with Ansible and I’m “playbook’ing” all my install scripts. I’m currently stuck on a problem for a ninjabackup setup playbook.

Let’s consider server A that will store its backups to server B. I would like the playbook to do the following:

  • set up ninjabackup on server A
  • create a user “backup” on server B
  • copy A’s root public ssh key to B’s backup user authorized_keys.

I also would like B to be defined as a variable that is specific to A in order to write a generic playbook that could be used to setup cross-backup between servers A and B (and C, D…) using a host-specific variable file, e.g. “vars/A_backup.yml”

Can a playbook have sub-playbooks allowing to specifiy a “hosts” directive containing variables defined by the parent playbook?

I am going the wrong way, having missed the obvious to achieve this?

Thanks,
Sylvain

So if you are looking at doing one thing on one host on behalf on other hosts, you need to read up on “delegation” in the Advanced Playbook section of the manual.
This allows you to do one thing on a server not in the host loop with a reference to the name of the other server in the host loop.

You should also lookup “hostvars” which explains how to get variable information about other hosts.

Thanks a lot Michael, “delegate_to” is indeed what I was looking for!

When writing the task to copy the ssh pub key from server A to server B, I encountered what seems to be https://github.com/ansible/ansible/pull/2981 (null MD5 returned on fetch used with sudo). I found this workaround using a registered variable :

  • name: Backupninja | Fetch public ssh key
    command: cat /root/.ssh/id_rsa.pub
    register: root_pub_key

  • name: Backupninja | Add public ssh key to backup account
    delegate_to: $backup_host
    authorized_key: user=$backup_user key=“{{root_pub_key.stdout}}”

I also added this task to add server B’s public ssh key to server A’s known_host file:

  • name: Backupninja | Add backup host to known_keys
    shell:
    touch ~/.ssh/known_hosts &&
    ssh-keygen -R {{ backup_host }} &&
    ssh-keyscan -H {{ backup_host }} >> ~/.ssh/known_hosts

Works like a charm!

Sylvain

Excellent, getting fetch to work with sudo is on our list of things to do!

–Michael

Let us say, I have four servers. A,B,C and D. I want to deploy SSH public keys from A to C and also from C to D. How can I do with ansible playbook ?