Exemplo n.º 1
0
def sync_keypairs(keypair_name, public_key_file):
    """
    Synchronize SSH keypairs across all EC2 regions.

    keypair_name    The name of the keypair.
    public_key_file The path to the file containing the
                    public key portion of the keypair.
    """
    fp = open(public_key_file)
    material = fp.read()
    fp.close()

    for region in boto.ec2.regions():
        ec2 = region.connect()
        # Try to list the keypair.  If it doesn't exist
        # in this region, then import it.
        try:
            key = ec2.get_all_key_pairs(keynames=[keypair_name])[0]
            print 'Keypair(%s) already exists in %s' % (keypair_name,
                                                        region.name)
        except ec2.ResponseError, e:
            if e.code == 'InvalidKeyPair.NotFound':
                print 'Importing keypair(%s) to %s' % (keypair_name,
                                                       region.name)
                ec2.import_key_pair(keypair_name, material)
Exemplo 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}
Exemplo n.º 3
0
def sync_keypairs(keypair_name, public_key_file):
    """
    Synchronize SSH keypairs across all EC2 regions.

    keypair_name    The name of the keypair.
    public_key_file The path to the file containing the
                    public key portion of the keypair.
    """
    fp = open(public_key_file)
    material = fp.read()
    fp.close()
    
    for region in boto.ec2.regions():
        ec2 = region.connect()
        # Try to list the keypair.  If it doesn't exist
        # in this region, then import it.
        try:
            key = ec2.get_all_key_pairs(keynames=[keypair_name])[0]
            print 'Keypair(%s) already exists in %s' % (keypair_name,
                                                        region.name)
        except ec2.ResponseError, e:
            if e.code == 'InvalidKeyPair.NotFound':
                print 'Importing keypair(%s) to %s' % (keypair_name,
                                                       region.name)
                ec2.import_key_pair(keypair_name, material)
Exemplo n.º 4
0
def create_account(args, dbh, iam, ec2, user_name, name, note=''):
    response = iam.create_user(user_name)
    user = response.user
    password = generate_password(args)
    response = iam.create_login_profile(user_name, password)
    iam.add_user_to_group(args.default_group, user_name)
    public_key = _generate_keypair(args, user_name)
    _put_user_policy(args, iam, user_name)
    ec2.import_key_pair(user_name, public_key)
    dbh.execute("""
        INSERT INTO users (user_name, name, note, password)
        VALUES (:user_name, :name, :note, :password)
    """, {'user_name': user_name, 'name': name, 'note': note, 'password': password})
Exemplo n.º 5
0
 def checkKeyPair(self, keypair_name, public_key_file):
     fp = open(public_key_file)
     material = fp.read()
     fp.close()
     for region in boto.ec2.regions():
         ec2 = region.connect()
         try:
             key = ec2.get_all_key_pairs(keynames=[keypair_name])[0]
             print 'Keypair(%s) already exists in %s' % \
                    (keypair_name, region.name)
         except ec2.ResponseError, e:
             if e.code == 'InvalidKeyPair.NotFound':
                 print 'Importing keypair(%s) to %s' % \
                       (keypair_name, region.name)
         ec2.import_key_pair(keypair_name, material)
Exemplo n.º 6
0
def main(key, secret, ssh_key_name, ssh_key_dir, config_path):
    ssh_key_dir = os.path.abspath(ssh_key_dir)

    cer = ssh_key_name + ".cer"
    pem = ssh_key_name + ".pem"

    cer_path = os.path.join(ssh_key_dir, cer)
    pem_path = os.path.join(ssh_key_dir, pem)

    config = {
        "access_key_id": key,
        "secret_access_key": secret,
        "certificate_path": pem_path,
    }

    generate_client_cert(pem_path)
    generate_server_cert(pem_path, cer_path)

    all_regions = boto.ec2.regions(
        aws_access_key_id=key,
        aws_secret_access_key=secret)

    with open(cer_path, 'rb') as f:
        cert_data = f.read()

    for region in all_regions:
        print "---"
        print "Importing to:", region.name
        print "---"
        try:
            ec2 = boto.ec2.connect_to_region(
                region.name,
                aws_access_key_id=key,
                aws_secret_access_key=secret)

            ec2.import_key_pair(
                    ssh_key_name,
                    cert_data)

        except Exception as e:
            sys.stderr.write(
                "Unable to import {} to {}: {}\n".format(
                    ssh_key_name, region.name, e))

    with open(config_path, 'w') as f:
        json.dump(config, f, indent=2)
Exemplo n.º 7
0
            if key_material:
                # EC2's fingerprints are non-trivial to generate, so push this key 
                # to a temporary name and make ec2 calculate the fingerprint for us.
                #
                # http://blog.jbrowne.com/?p=23
                # https://forums.aws.amazon.com/thread.jspa?messageID=352828

                # find an unused name
                test = 'empty'
                while test:
                    randomchars = [random.choice(string.ascii_letters + string.digits) for x in range(0,10)]
                    tmpkeyname = "ansible-" + ''.join(randomchars)
                    test = ec2.get_key_pair(tmpkeyname)

                # create tmp key
                tmpkey = ec2.import_key_pair(tmpkeyname, key_material)
                # get tmp key fingerprint
                tmpfingerprint = tmpkey.fingerprint
                # delete tmp key
                tmpkey.delete()

                if key.fingerprint != tmpfingerprint:
                    if not module.check_mode:
                        key.delete()
                        key = ec2.import_key_pair(name, key_material)    

                        if wait:
                            start = time.time()
                            action_complete = False
                            while (time.time() - start) < wait_timeout:
                                if ec2.get_key_pair(name):
Exemplo n.º 8
0
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(
            name=dict(required=True),
            key_material=dict(required=False),
            force=dict(required=False, type='bool', default=True),
            state=dict(default='present', choices=['present', 'absent']),
            wait=dict(type='bool', default=False),
            wait_timeout=dict(default=300),
        ))
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    if not HAS_BOTO:
        module.fail_json(msg='boto required for this module')

    name = module.params['name']
    state = module.params.get('state')
    key_material = module.params.get('key_material')
    force = module.params.get('force')
    wait = module.params.get('wait')
    wait_timeout = int(module.params.get('wait_timeout'))

    changed = False

    ec2 = ec2_connect(module)

    # find the key if present
    key = ec2.get_key_pair(name)

    # Ensure requested key is absent
    if state == 'absent':
        if key:
            '''found a match, delete it'''
            if not module.check_mode:
                try:
                    key.delete()
                    if wait:
                        start = time.time()
                        action_complete = False
                        while (time.time() - start) < wait_timeout:
                            if not ec2.get_key_pair(name):
                                action_complete = True
                                break
                            time.sleep(1)
                        if not action_complete:
                            module.fail_json(
                                msg=
                                "timed out while waiting for the key to be removed"
                            )
                except Exception as e:
                    module.fail_json(
                        msg="Unable to delete key pair '%s' - %s" % (key, e))
            key = None
            changed = True

    # Ensure requested key is present
    elif state == 'present':
        if key:
            # existing key found
            if key_material and force:
                # EC2's fingerprints are non-trivial to generate, so push this key
                # to a temporary name and make ec2 calculate the fingerprint for us.
                #
                # http://blog.jbrowne.com/?p=23
                # https://forums.aws.amazon.com/thread.jspa?messageID=352828

                # find an unused name
                test = 'empty'
                while test:
                    randomchars = [
                        random.choice(string.ascii_letters + string.digits)
                        for x in range(0, 10)
                    ]
                    tmpkeyname = "ansible-" + ''.join(randomchars)
                    test = ec2.get_key_pair(tmpkeyname)

                # create tmp key
                tmpkey = ec2.import_key_pair(tmpkeyname, key_material)
                # get tmp key fingerprint
                tmpfingerprint = tmpkey.fingerprint
                # delete tmp key
                tmpkey.delete()

                if key.fingerprint != tmpfingerprint:
                    if not module.check_mode:
                        key.delete()
                        key = ec2.import_key_pair(name, key_material)

                        if wait:
                            start = time.time()
                            action_complete = False
                            while (time.time() - start) < wait_timeout:
                                if ec2.get_key_pair(name):
                                    action_complete = True
                                    break
                                time.sleep(1)
                            if not action_complete:
                                module.fail_json(
                                    msg=
                                    "timed out while waiting for the key to be re-created"
                                )

                    changed = True
            pass

        # if the key doesn't exist, create it now
        else:
            '''no match found, create it'''
            if not module.check_mode:
                if key_material:
                    '''We are providing the key, need to import'''
                    key = ec2.import_key_pair(name, key_material)
                else:
                    '''
                    No material provided, let AWS handle the key creation and
                    retrieve the private key
                    '''
                    key = ec2.create_key_pair(name)

                if wait:
                    start = time.time()
                    action_complete = False
                    while (time.time() - start) < wait_timeout:
                        if ec2.get_key_pair(name):
                            action_complete = True
                            break
                        time.sleep(1)
                    if not action_complete:
                        module.fail_json(
                            msg=
                            "timed out while waiting for the key to be created"
                        )

            changed = True

    if key:
        data = {'name': key.name, 'fingerprint': key.fingerprint}
        if key.material:
            data.update({'private_key': key.material})

        module.exit_json(changed=changed, key=data)
    else:
        module.exit_json(changed=changed, key=None)
parser.add_argument("public_key", help="The key pair's public key file (e.g. ~/.ssh/my-key.pub)")
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 = "Importing key pair named '" + args.key_name + "'"
regions = boto.ec2.regions()
if args.region:
    heading += " (filtered by region '" + args.region + "')"
    regions = filter(isSelected, regions)

public_key_file = open(args.public_key, 'r')
public_key_body = public_key_file.read()

print heading + ":"
for region in regions:
    pprint(region.name, indent=2)
    try:
        ec2 = boto.connect_ec2(region=region, **credentials)
        print 'Importing key pair ' + args.key_name
        ec2.import_key_pair(args.key_name, public_key_body)
    except boto.exception.BotoServerError, e:
        print e.error_message
Exemplo n.º 10
0
parser = argparse.ArgumentParser(
    description='Imports 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")
parser.add_argument(
    "public_key",
    help="The key pair's public key file (e.g. ~/.ssh/my-key.pub)")
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("Importing key pair named '" + args.key_name + "':")

public_key_file = open(args.public_key, 'r')
public_key_body = public_key_file.read()

for region in regions:
    pprint(region.name, indent=2)
    try:
        ec2 = boto.connect_ec2(region=region, **credentials)
        print 'Importing key pair ' + args.key_name
        ec2.import_key_pair(args.key_name, public_key_body)
    except boto.exception.BotoServerError, e:
        log.error(e.error_message)
Exemplo n.º 11
0
print args.keypair_name
print args.public_key_file

"""
Synchronize SSH keypairs across all EC2 regions.

keypair_name    The name of the keypair.
public_key_file The path to the file containing the
								public key portion of the keypair.
"""
fp = open(args.public_key_file)
material = fp.read()
fp.close()

for region in boto.ec2.regions():
  print 'Importing key to %s region' %region.name
  ec2 = region.connect()

  # Try to list the keypair.  If it doesn't exist
  # in this region, then import it.
  try:
    key = ec2.get_all_key_pairs(keynames=[args.keypair_name])[0]
    print 'Keypair(%s) already exists in %s' % (args.keypair_name,
																										region.name)
  except ec2.ResponseError, e:
    if e.code == 'InvalidKeyPair.NotFound':
      print 'Importing keypair(%s) to %s' % (args.keypair_name,
																									 region.name)
      ec2.import_key_pair(args.keypair_name, material)
Exemplo n.º 12
0
def keyfile_import(keyname, new_region):
    file = open(os.path.expanduser('~')+'/.ssh/test').readline()
    for conn_region in new_region:
        print "Importing '%s' to '%s'" % (keyname, conn_region) 
        ec2 = boto.ec2.connect_to_region(conn_region)
        ec2.import_key_pair(keyname, file)