Created
January 13, 2012 18:16
-
-
Save pcn/1607864 to your computer and use it in GitHub Desktop.
Code to upload an ssh public key to aws when we need a keypair with a different name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# To create a cluster using cluster_chef, an ssh key must exist with | |
# that cluster name in EC2/AWS. Since we use generic keys, it makes | |
# sense to continue to use a per-account key, but to upload that key | |
# to AWS as needed. | |
# | |
# E.g. .ssh/FOO-utility.pub can be uploaded to EC2 as UtilityCluster | |
# to enable a cluster called UtilityCluster to be bootstrapped. | |
import os | |
import sys | |
import boto | |
import os.path | |
import base64 | |
# Don't guess the region | |
def main(argv=sys.argv[:]): | |
if os.environ['EC2_URL'] is None: | |
print "Cowardly refusing to run without $EC2_URL being set" | |
sys.exit(2) | |
else: | |
print "Using {0} to connect".format(os.environ['EC2_URL']) | |
if not os.path.exists(sys.argv[1]): | |
print """ | |
ERROR: Can't find the public key at "{0}"! | |
Pass in the path to the public key (if the private" | |
key is passed in, we'll try to find the public key). | |
The public key is determined by the name of the file | |
ending in ".pub" | |
""".format(sys.argv[1]) | |
sys.exit(2) | |
try: | |
upload_name = sys.argv[2] | |
except IndexError: | |
print """As the second argument, pass in the name that will be used to reference the key when it is uploaded to AWS.""" | |
sys.exit(2) | |
if os.path.exists("{0}.pub".format(sys.argv[1])): | |
ssh_keyfile = "{0}.pub".format(sys.argv[1]) | |
print "Found {0}".format(ssh_keyfile) | |
else: | |
ssh_keyfile = sys.argv[1] | |
print "Using {0}".format(ssh_keyfile) | |
try: | |
pubkey = base64.b64encode(open(ssh_keyfile).read()) | |
except IOError as e: | |
print "Couldn't open {0} because {1}".format(ssh_keyfile, e) | |
upload_to_aws(pubkey, upload_name) | |
def upload_to_aws(pubkey, upload_name): | |
e = boto.connect_ec2() | |
rv = e.import_key_pair(upload_name, pubkey) | |
print rv | |
if __name__ == '__main__': | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment