Search code examples
amazon-web-servicesamazon-ec2amazon-ami

Replace username/password authentication with keypair on an existing Linux AMI


I have a ami which need username/password for login via ssh. I want to create new amis from this, in which I can login from any newly created keypairs.

Any suggestions?


Solution

  • The simplest way is to do this is by adding the following snippet in to the /etc/rc.local or its equivalent.

    #!/bin/sh
    #
    # This script will be executed *after* all the other init scripts.
    # You can put your own initialization stuff in here if you don't
    # want to do the full Sys V style init stuff.
    
    touch /var/lock/subsys/local
    if [ ! -d /root/.ssh ] ; then
        mkdir -p /root/.ssh
        chmod 0700 /root/.ssh
    fi
    
    # Fetch public key using HTTP
    curl -f http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key > /tmp/aws-key 2>/dev/null
    if [ $? -eq 0 ] ; then
        cat /tmp/aws-key >> /root/.ssh/authorized_keys
        chmod 0600 /root/.ssh/authorized_keys
    fi
    rm -f /tmp/aws-key
    
    # or fetch public key using the file in the ephemeral store:
    if [ -e /mnt/openssh_id.pub ] ; then
        cat /mnt/openssh_id.pub >> /root/.ssh/authorized_keys
        chmod 0600 /root/.ssh/authorized_keys
    fi