public
Created

EC2 environment switcher script

  • Download Gist
ec2env.sh
Shell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
#!/bin/sh
 
#
# ec2env.sh
# mnmldave
#
# Switch between EC2_PRIVATE_KEY and EC2_CERT environment variables. Licensed under
# WTFPL v2.0.
#
# Installation (you'll have to open a new terminal after installing):
#
# $ mkdir ~/.ec2
# $ curl -L https://raw.github.com/gist/2990031/ > ~/.ec2/ec2env.sh
# $ echo "source ~/.ec2/ec2env.sh" >> ~/.bashrc # or ~/.zshrc or whatever
#
# Usage:
#
# $ ec2mkenv myec2 private_key.pem cert.pem # create a new "myec2" environment
# $ ec2workon myec2 # activates your "myec2" environment
#
 
function ec2workon {
typeset env_name="$1"
if [ "$env_name" = "" ]; then
echo "Please specify an EC2 environment name:"
find ~/.ec2/* -type d | xargs -n1 basename
return 1
fi
env_dir="$HOME/.ec2/$env_name"
if [ ! -d "$env_dir" ]; then
echo "No such environment: $env_name"
return 1
fi
 
env_private_key="$(/bin/ls "$env_dir"/pk-*.pem | /usr/bin/head -1)"
if [ ! -f "$env_private_key" ]; then
echo "Private key not found in directory: $env_dir"
return 1
fi
env_cert="$(/bin/ls "$env_dir"/cert-*.pem | /usr/bin/head -1)"
if [ ! -f "$env_cert" ]; then
echo "Certificate not found in directory: $env_dir"
return 1
fi
 
export EC2_PRIVATE_KEY="$env_private_key"
export EC2_CERT="$env_cert"
echo "Activated environment: $env_name"
}
 
function ec2mkenv {
typeset env_name="$1"
typeset env_pk="$2"
typeset env_cert="$3"
if [ -z "$env_name" -o -z "$env_pk" -o -z "$env_cert" ]; then
echo "Usage: ec2mkenv env_name pk cert"
return 1
fi
env_dir="$HOME/.ec2/$env_name"
if [ -d "$env_dir" ]; then
echo "Environment already exists: $env_name"
return 1
fi
if [ ! -f "$env_pk" ]; then
echo "Private key does not exist: $env_pk"
return 1
fi
if [ ! -f "$env_cert" ]; then
echo "Certificate does not exist: $env_cert"
return 1
fi
mkdir -p "$env_dir"
cp "$env_pk" "$env_dir/pk-$env_name.pem"
cp "$env_cert" "$env_dir/cert-$env_name.pem"
 
echo "Created environment in: $env_dir"
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.