def keypair_setup(): """Creates keypair if necessary, saves private key locally, returns contents of private key file.""" os.system('mkdir -p ' + u.PRIVATE_KEY_LOCATION) keypair_name = u.get_keypair_name() keypair = u.get_keypair_dict().get(keypair_name, None) keypair_fn = u.get_keypair_fn() if keypair: print("Reusing keypair " + keypair_name) # check that local pem file exists and is readable assert os.path.exists( keypair_fn ), "Keypair %s exists, but corresponding .pem file %s is not found, delete keypair %s through console and run again to recreate keypair/.pem together" % ( keypair_name, keypair_fn, keypair_name) keypair_contents = open(keypair_fn).read() assert len(keypair_contents) > 0 else: print("Creating keypair " + keypair_name) ec2 = u.get_ec2_resource() assert not os.path.exists( keypair_fn ), "previous keypair exists, delete it with 'sudo rm %s' and also delete corresponding keypair through console" % ( keypair_fn) keypair = ec2.create_key_pair(KeyName=keypair_name) open(keypair_fn, 'w').write(keypair.key_material) os.system('chmod 400 ' + keypair_fn) return keypair
def delete_keypair(): keypairs = u.get_keypair_dict() keypair = keypairs.get(KEYPAIR_NAME, '') if keypair: try: sys.stdout.write("Deleting keypair %s (%s) ... " % (keypair.key_name, KEYPAIR_NAME)) sys.stdout.write(response_type(keypair.delete()) + '\n') except Exception as e: sys.stdout.write('failed\n') util.log_error(str(e) + '\n') keypair_fn = u.get_keypair_fn() if os.path.exists(keypair_fn): print("Deleting local keypair file %s" % (keypair_fn, )) os.system('rm -f ' + keypair_fn)