Friday, September 4, 2015

Automatically (and hopefully securely) configure ansible-pull with a secure ssh git repository

    We are just starting to play around with using ansible to configure our systems.  Since we have a lot of laptops and other machines that shut themselves down when idle, we need to use ansible-pull to configure them.  I also use cobbler to provision our systems and wanted to be able to configure ansible-pull automatically as part of the install process.  The complicating factor is that since we do not want to have our playbooks public, we are using a ssh deployment key to get access to the git repository that ansible-pull will use.  So we needed a way to distribute the ansible private ssh key to the new systems.  Here is what I came up with:

* Create a ssh key pair for cobbler to use:

 
ssh-keygen -N '' -f ~/.ssh/id_rsa_cobbler


* Create a cobbler trigger to copy the ansible deployment key over to the newly installed system, in /var/lib/cobbler/triggers/install/post/ansible_key:

#!/bin/bash
[ "$1" = system ] &&
  /usr/bin/scp -i /root/.ssh/id_rsa_cobbler -o "StrictHostKeyChecking no" -p /root/.ssh/id_rsa_ansible ${2}:/root/.ssh/id_rsa_ansible

* In %post add the cobbler public key (id_rsa_cobbler.pub) to /root/.ssh/authorized_keys and only give it permission to scp to /root/.ssh/id_rsa_ansible:

cat >> /root/.ssh/authorized_keys <<EOF
command="scp -p -t /root/.ssh/id_rsa_ansible",no-pty,no-port-forwarding,no-X11-forwarding,no-agent-forwarding ssh-rsa AAAAB...==
EOF

* In %post, start up the sshd server so that cobbler can copy over the ssh key during the post install trigger:

/usr/sbin/sshd-keygen
/usr/sbin/sshd
 
* In %post, configure ansible-pull to run at each boot:

cat > /etc/systemd/system/ansible-pull.service <<EOF
[Unit]
Description=Run ansible-pull on boot
After=network-online.target
Wants=network-online.target
 
[Install]
WantedBy=multi-user.target
 
[Service]
Type=oneshot
ExecStart=/usr/bin/ansible-pull --url ssh://git@git.server.com/ansible-pull.git --key-file /root/.ssh/id_rsa_ansible
EOF
systemctl enable ansible-pull.service
echo localhost ansible_connection=local > /etc/ansible/inventory
 
* In %post, teach the machine about our git host:

echo [git.server.com]:51424,[10.10.10.10]:51424 ssh-rsa AAAA...== >> /root/.ssh/known_hosts

    This assumes we're using a local.yml playbook that has:

- hosts: localhost

No comments:

Post a Comment