sshcapistrano3ansible

Ansible copy ssh key from one host to another


I have 2 app servers with a loadbalancer in front of them and 1 database server in my system. I'm provisioning them using Ansible. App servers has Nginx + Passenger and running for a Rails app. Will use capistrano for deployment but I have an issue about ssh keys. My git repo is in another server and I have to generate ssh public keys on appservers and add them to the Git server(To authorized_keys file). How can I do this in ansible playbook?

PS: I may have more than 2 app servers.

enter image description here


Solution

  • Take a look to the authorized_key module for getting info on how to manage your public keys.

    The most straightforward solution I can think of would be to generate a fresh key pair for your application, to be shared accross all your app instances. This may have security implications (you are indeed sharing keys between all instances!), but it'll simplify a lot the provisioning process.

    You'll also require a deploy user on each app machine, to be used later on during deployment process. You'll need your public key (or jenkins one) on each deploy user's authorized_keys.

    A sketch playbook:

    ---
    - name: ensure app/deploy public key is present on git server
      hosts: gitserver
      tasks:
        - name: ensure app public key
          authorized_key: 
            user: "{{ git_user }}" 
            key: app_keys/id_dsa.pub 
            state: present
    
    - name: provision app servers
      hosts: appservers
      tasks:
        - name: ensure app/deploy user is present
          user: 
            name: "{{ deploy_user }}"
            state: present
    
        - name: ensure you'll be able to deploy later on
          authorized_key:
            user: "{{ deploy_user }}" 
            key: "{{ path_to_your_public_key }}" 
            state: present
    
        - name: ensure private key and public one are present
          copy: 
            src: keys/myapp.private 
            dest: "/home/{{ deploy_user }}/.ssh/{{ item }}" 
            mode: 0600
          with_items:
            - app_keys/id_dsa.pub
            - app_keys/id_dsa