Esempio n. 1
0
def terminate(elastic_IP):
    global allocation_id

    ec2 = boto3.client('ec2')
    conn = boto.ec2.connect_to_region("us-east-1")

    filters = {"ip-address": elastic_IP}
    instances = conn.get_only_instances(filters=filters)

    filters = [{'Name': 'public-ip', 'Values': [elastic_IP]}]

    addresses = ec2.describe_addresses(Filters=filters)

    inst_id = str(instances[0].id)
    alloc_id = addresses['Addresses'][0]['AllocationId']

    ec2.release_address(AllocationId=alloc_id)
    conn.terminate_instances(instance_ids=[
        inst_id,
    ])

    while instances[0].update(
    ) != "terminated":  #wait until the instance has been terminated
        time.sleep(5)

    ec2.delete_security_group(GroupName='csc326-group23')
    ec2.delete_key_pair(KeyName='key')
Esempio n. 2
0
def create_keypair(econfig_file=None, region=None, keyname="bcbio"):
    """Create a bcbio keypair and import to ec2. Gives us access to keypair locally and at AWS.
    """
    import boto
    import boto.ec2
    if econfig_file:
        keypair_dir = os.path.dirname(econfig_file).replace("elasticluster", "aws_keypairs")
    else:
        keypair_dir = os.path.join(os.getcwd(), "aws_keypairs")
    if not os.path.exists(keypair_dir):
        os.makedirs(keypair_dir)
    private_key = os.path.join(os.path.join(keypair_dir, keyname))
    new_key = not os.path.exists(private_key)
    if new_key:
        cmd = ["ssh-keygen", "-t", "rsa", "-N", "", "-f", private_key, "-C", "bcbio_aws_keypair"]
        subprocess.check_call(cmd)
    public_key = private_key + ".pub"
    if region:
        ec2 = boto.ec2.connect_to_region(region)
    else:
        ec2 = boto.connect_ec2()
    key = ec2.get_key_pair(keyname)
    if key and new_key:
        print("Non matching key %s found in AWS, removing." % keyname)
        ec2.delete_key_pair(keyname)
        key = None
    if not key:
        print("Key %s not found in AWS, importing created key" % keyname)
        with open(public_key) as in_handle:
            ec2.import_key_pair(keyname, in_handle.read())
    return {"user_key_name": keyname, "user_key_private": private_key,
            "user_key_public": public_key}
Esempio n. 3
0
def wipe_account(args, dbh, iam, ec2, user_name):
    try:
        iam.remove_user_from_group(args.default_group, user_name) 
    except boto.exception.BotoServerError:
        pass

    try:
        iam.delete_login_profile(user_name) 
    except boto.exception.BotoServerError:
        pass

    try:
        iam.delete_user_policy(user_name, 'StartStopTaggedInstances-' + user_name)
    except boto.exception.BotoServerError:
        pass
    try:
        ec2.delete_key_pair(user_name)
        if os.path.exists(os.path.join(args.ssh_key_dir, user_name)):
            os.unlink(os.path.join(args.ssh_key_dir, user_name))
            os.unlink(os.path.join(args.ssh_key_dir, user_name + '.pub'))
    except boto.exception.BotoServerError:
        pass

    try:
        iam.delete_user(user_name) 
    except boto.exception.BotoServerError:
        pass

    dbh.execute("""
        DELETE FROM users WHERE user_name = :user_name
    """, {'user_name': user_name})
Esempio n. 4
0
def ec2_delete_keys(ec2):
	key = ec2.get_all_key_pairs()
	for k in key:
		try:
			print "---Deleting key: " + k.name
			ec2.delete_key_pair(k.name)
		except Exception, e:
			print(e)
Esempio n. 5
0
def create_keypair(source=KEYNAME):

    try:
        kp = ec2.delete_key_pair(source)
    except (boto.exception.EC2ResponseError):
        pass

    kp = ec2.create_key_pair(source)
    filename = os.environ.get(
        'EC2_KEY_PATH', './keys/ec2-{}.pem'.format(
            datetime.datetime.now().strftime('%Y-%m-%d_%H:%M')))
    latest_filename = os.environ.get('EC2_KEY_PATH', './latest.pem')
    kfile = open(filename, 'wb')
    latest_kfile = open(latest_filename, 'wb')

    def file_mode(user, group, other):
        return user * (8**2) + group * (8**1) + other * (8**0)

    kfile.write(kp.material)
    latest_kfile.write(kp.material)
    kfile.close()
    latest_kfile.close()
    os.chmod(filename, file_mode(7, 0, 0))
    os.chmod(latest_filename, file_mode(7, 0, 0))
    return filename
Esempio n. 6
0
    def _gen_key(self, aws_region='us-east-1', key_location= '/home/sgeadmin' ):
        ec2 = boto.ec2.connect_to_region( aws_region )
        key_name = 'sc-key-%s-%s' % (self._model.master_name, aws_region )
        k_file = '.'.join( [ key_name, 'pem' ])

        if os.path.isfile(os.path.join(key_location,k_file )) and \
                ec2.get_key_pair( key_name ):
            #we have a key and key_pair
            return key_name
        elif os.path.isfile(os.path.join(key_location, k_file )):
            #we have a key and no key pair
            os.remove( os.path.join(key_location, k_file) )
        elif ec2.get_key_pair( key_name ):
            #we have a key_pair, but no key
            ec2.delete_key_pair( key_name )
        key = ec2.create_key_pair( key_name )
        key.save( key_location )
        os.chmod( os.path.join( key_location, k_file ), 0600 )
        return (key_location , key_name)
Esempio n. 7
0
def createAllKP():
    """
	Create all key pairs in all regions
	"""
    if not os.path.exists(keysDir):
        os.makedirs(keysDir)
    for info in conf_HVM:
        keyName = 'Key-' + info['region'] + '-' + info['zone']
        try:
            os.remove(keysDir + '/' + keyName + '.pem')
        except OSError:
            pass
        print "Key creation :", keyName
        ec2 = boto.ec2.connect_to_region(info['region'] + '-' + info['zone'])
        # check if the key pair exists
        kps = [kp for kp in ec2.get_all_key_pairs() if kp.name == keyName]
        if kps:
            ec2.delete_key_pair(keyName)
        key = ec2.create_key_pair(keyName)
        key.save(keysDir)
Esempio n. 8
0
def createAllKP():
	"""
	Create all key pairs in all regions
	"""
	if not os.path.exists(keysDir):
		os.makedirs(keysDir)
	for info in conf_HVM:
		keyName = 'Key-'+info['region']+'-'+info['zone']
		try:
			os.remove(keysDir+'/'+keyName+'.pem')
		except OSError:
			pass
		print "Key creation :",keyName
		ec2 = boto.ec2.connect_to_region(info['region']+'-'+info['zone'])
		# check if the key pair exists
		kps = [kp for kp in ec2.get_all_key_pairs() if kp.name == keyName]
		if kps:
			ec2.delete_key_pair(keyName)	
		key = ec2.create_key_pair(keyName)
		key.save(keysDir)
Esempio n. 9
0
def create_key_pair():

    # if(os.path.exists('ec2-keypairv2.pem')):
    #     print("Key file already exists!")
    #     os.remove("ec2-keypairv2.pem")

    # create a file to store the key locally
    outfile = open('ec2-keypairv2.pem', 'w')

    if (check_key_pair_exists("ec2-keypairv2")):
        print("Key pair exists attached to ec2. deleting!")
        ec2.delete_key_pair("ec2-keypairv2")

    # call the boto ec2 function to create a key pair
    key_pair = ec2.create_key_pair(key_name='ec2-keypairv2')

    # capture the key and store it in a file
    key_pair_out = str(key_pair.material)
    outfile.write(key_pair_out)
    outfile.close()
Esempio n. 10
0
def create_keypair(source = KEYNAME):
    try:
        kp = ec2.delete_key_pair(source)
    except (boto.exception.EC2ResponseError):
        pass

    kp = ec2.create_key_pair(source)
    filename = os.environ.get('EC2_KEY_PATH', './keys/ec2-{}.pem'.format(datetime.datetime.now().strftime('%Y-%m-%d_%H:%M')))
    latest_filename = os.environ.get('EC2_KEY_PATH', './keys/latest.pem')
    kfile = open(filename, 'wb')
    latest_kfile = open(latest_filename, 'wb')
    def file_mode(user, group, other):
        return user*(8**2) + group*(8**1) + other*(8**0)
    kfile.write(kp.material)
    latest_kfile.write(kp.material)
    kfile.close()
    latest_kfile.close()
    os.chmod(filename, file_mode(7,0,0))
    os.chmod(latest_filename, file_mode(7,0,0))
    return filename
# configure command line argument parsing
parser = argparse.ArgumentParser(description='Deletes a key pair in all/some available EC2 regions')
parser.add_argument("key_name", help="A key pair name")
parser.add_argument("-r", "--region", help="A region substring selector (e.g. 'us-west')")
parser.add_argument("--access_key_id", dest='aws_access_key_id', help="Your AWS Access Key ID")
parser.add_argument("--secret_access_key", dest='aws_secret_access_key', help="Your AWS Secret Access Key")
args = parser.parse_args()

credentials = {'aws_access_key_id': args.aws_access_key_id, 'aws_secret_access_key': args.aws_secret_access_key}

def isSelected(region):
    return True if region.name.find(args.region) != -1 else False

# execute business logic
heading = "Deleting key pair named '" + args.key_name + "'"
regions = boto.ec2.regions()
if args.region:
    heading += " (filtered by region '" + args.region + "')"
    regions = filter(isSelected, regions)

print heading + ":"
for region in regions:
    pprint(region.name, indent=2)
    try:
        ec2 = boto.connect_ec2(region=region, **credentials)
        print 'Deleting key pair ' + args.key_name
        ec2.delete_key_pair(args.key_name)
    except boto.exception.BotoServerError, e:
        print e.error_message
Esempio n. 12
0
def delete_key(key_name=keyname):

    ec2 = conn_region 
    ec2.delete_key_pair(key_name)
    print "Success"    
Esempio n. 13
0
def delete_keys(ec2, keyname, dry_run):
    keys = ec2.get_all_key_pairs(filters={'key-name': keyname})
    for key in keys:
        print key.name
        if not dry_run:
            ec2.delete_key_pair(key.name)
Esempio n. 14
0
import boto
import boto.ec2
import botocross as bc
import logging

# configure command line argument parsing
parser = argparse.ArgumentParser(
    description='Deletes a key pair in all/some available EC2 regions',
    parents=[bc.build_region_parser(),
             bc.build_common_parser()])
parser.add_argument("key_name", help="A key pair name")
args = parser.parse_args()

# process common command line arguments
log = logging.getLogger('botocross')
bc.configure_logging(log, args.log_level)
credentials = bc.parse_credentials(args)
regions = bc.filter_regions(boto.ec2.regions(), args.region)

# execute business logic
log.info("Deleting key pair named '" + args.key_name + "':")

for region in regions:
    pprint(region.name, indent=2)
    try:
        ec2 = boto.connect_ec2(region=region, **credentials)
        print 'Deleting key pair ' + args.key_name
        ec2.delete_key_pair(args.key_name)
    except boto.exception.BotoServerError, e:
        log.error(e.error_message)
Esempio n. 15
0
def delete_key(key_name=keyname):

    ec2 = conn_region
    ec2.delete_key_pair(key_name)
    print("Success")
Esempio n. 16
0
def delete_keys(ec2, keyname, dry_run):
    keys = ec2.get_all_key_pairs(filters={'key-name': keyname})
    for key in keys:
        print key.name
        if not dry_run:
            ec2.delete_key_pair(key.name)
Esempio n. 17
0
def keyfile_delete(keyname, new_region):
    for conn_region in new_region:
        print "Deleting '%s' to '%s'" %  (keyname, conn_region) 
        ec2 = boto.ec2.connect_to_region(conn_region)
        ec2.delete_key_pair(keyname)