def get_sts(duration, mfa_serial, mfa_device_name, long_term, short_term, assume_role_arn=None): if boto.config.get(long_term, 'aws_access_key_id') is None: logger.error('aws_access_key_id is missing from section %s' 'or config file is missing.' % (long_term,)) sys.exit(1) else: long_term_id = boto.config.get(long_term, 'aws_access_key_id') if boto.config.get(long_term, 'aws_secret_access_key') is None: logger.error('aws_secret_access_key is missing from section ' 'or config file is missing.' % (long_term,)) sys.exit(1) else: long_term_secret = boto.config.get(long_term, 'aws_secret_access_key') if boto.config.has_section(short_term): boto.config.remove_option(short_term, 'aws_security_token') mfa_TOTP = raw_input('Enter AWS MFA code for user %s ' '(renewing for %s seconds):' % (mfa_device_name, duration)) try: sts_connection = STSConnection(aws_access_key_id=long_term_id, aws_secret_access_key=long_term_secret) if assume_role_arn is None: tempCredentials = sts_connection.get_session_token( duration=duration, mfa_serial_number=mfa_serial, mfa_token=mfa_TOTP) assumed_role = 'False' else: role_session_name = assume_role_arn.split('/')[-1] assumedRole = sts_connection.assume_role( assume_role_arn, role_session_name, duration_seconds=duration, mfa_serial_number=mfa_serial, mfa_token=mfa_TOTP) tempCredentials = assumedRole.credentials assumed_role = 'True' default_options = [ ('aws_access_key_id', tempCredentials.access_key), ('aws_secret_access_key', tempCredentials.secret_key), ('aws_security_token', tempCredentials.session_token), ('expiration', tempCredentials.expiration), ('assumed_role', assumed_role) ] for option, value in default_options: boto.config.save_user_option( short_term, option, value ) except boto.exception.BotoServerError as e: message = '%s - Please try again.' % (e.message) logger.error(message) sys.exit(1)
def check_credentials(self): result = False if not self._role_arn: result = True else: try: if self._parameters.get('assumed_region_name', None): sts_connection = boto.sts.connect_to_region( self._parameters['assumed_region_name']) else: sts_connection = STSConnection() assumed_role_object = sts_connection.assume_role( role_arn=self._role_arn, role_session_name=self._role_session) self._parameters[ 'access_key'] = assumed_role_object.credentials.access_key self._parameters[ 'secret_key'] = assumed_role_object.credentials.secret_key self._parameters[ 'session_token'] = assumed_role_object.credentials.session_token result = True except: if self._log_file: log( "An error occured when creating connection, check the exception error message for more details", self._log_file) result = False raise return (result)
def get_conn(self): """ Returns the boto S3Connection object. """ if self._creds_in_config_file: a_key, s_key = _parse_s3_config(self.s3_config_file, self.s3_config_format, self.profile) else: a_key = self._a_key s_key = self._s_key if self._sts_conn_required: sts_connection = STSConnection(aws_access_key_id=a_key, aws_secret_access_key=s_key, profile_name=self.profile) assumed_role_object = sts_connection.assume_role( role_arn=self.role_arn, role_session_name="Airflow_" + self.s3_conn_id ) creds = assumed_role_object.credentials connection = S3Connection( aws_access_key_id=creds.access_key, aws_secret_access_key=creds.secret_key, security_token=creds.session_token ) else: connection = S3Connection(aws_access_key_id=a_key, aws_secret_access_key=s_key) return connection
def get_aws_credentials(self, account_alias, role): """Get temporary credentials from AWS""" self.check_user_permissions(account_alias, role) try: account_id = self.account_config[account_alias]['id'] except Exception: message = "No Configuration for account '{account}'." raise ConfigurationError(message.format(account=account_alias)) arn = "arn:aws:iam::{account_id}:role/{role}".format( account_id=account_id, role=role) key_id = self.application_config['aws']['access_key'] secret_key = self.application_config['aws']['secret_key'] try: sts_connection = STSConnection( aws_access_key_id=key_id, aws_secret_access_key=secret_key) assumed_role_object = sts_connection.assume_role( role_arn=arn, role_session_name=self.user) except Exception as error: if getattr(error, 'status', None) == 403: raise PermissionError(str(error)) self.logger.exception("AWS STS failed with: {exc_vars}".format( exc_vars=vars(error))) raise AWSError(str(error)) return assumed_role_object.credentials
def assume(self): """Assume a role a collect the AWS keys for that role. This will set the environment variables AND will print the results. It returns the credentials object from the assume_role function. """ self._clear_expired() try: sts = STSConnection() except boto.exception.NoAuthHandlerFound: sys.stderr.write( "Please ensure that your AWS keys can " "assume roles.\n" ) sys.exit(1) output = sts.assume_role(self.get_role_arn(), self.session_name) for source, dest in self.map_.items(): # SVC-4728 - Add security_token support if source is 'security_token': source = 'session_token' value = getattr(output.credentials, source) self.set_env(dest, value) self.credentials = output.credentials if self.save: self._save() return self.credentials
def oauth_authorized(resp): facebook_graph = facebook.GraphAPI(resp.get('access_token')) email = facebook_graph.get_object("me")['email'] sts_connection = STSConnection() role = sts_connection.assume_role( role_arn="arn:aws:iam::054060359478:role/facebook-login", role_session_name=email ) creds = { 'sessionId': role.credentials.access_key, 'sessionKey': role.credentials.secret_key, 'sessionToken': role.credentials.session_token } params = { 'Action': 'getSigninToken', 'Session': json.dumps(creds), } auth_url = "https://signin.aws.amazon.com/federation" r = requests.get(auth_url, params=params) signin_token = json.loads(r.text).get('SigninToken') params.update({ 'Action': 'login', 'Issuer': 'ranman.org', 'Destination': 'https://console.aws.amazon.com/', 'SigninToken': signin_token }) url = requests.Request('GET', auth_url, params=params).prepare().url return redirect(url)
def get_conn(self): """ Returns the boto S3Connection object. """ if self._default_to_boto: return S3Connection(profile_name=self.profile) a_key = s_key = None if self._creds_in_config_file: a_key, s_key = _parse_s3_config(self.s3_config_file, self.s3_config_format, self.profile) elif self._creds_in_conn: a_key = self._a_key s_key = self._s_key if self._sts_conn_required: sts_connection = STSConnection(aws_access_key_id=a_key, aws_secret_access_key=s_key, profile_name=self.profile) assumed_role_object = sts_connection.assume_role( role_arn=self.role_arn, role_session_name="Airflow_" + self.s3_conn_id) creds = assumed_role_object.credentials connection = S3Connection(aws_access_key_id=creds.access_key, aws_secret_access_key=creds.secret_key, security_token=creds.session_token) else: connection = S3Connection(aws_access_key_id=a_key, aws_secret_access_key=s_key, profile_name=self.profile) return connection
def make_aws_credentials(config, role_arn=None, role_name=None): if role_arn: try: sts_connection = STSConnection() assumedRoleObject = sts_connection.assume_role( role_arn=role_arn, role_session_name=role_name ) except: out("Oops! something went wrong trying to assume the specified role") else: # create credentials for switching roles aws = AwsCredentials( assumedRoleObject.credentials.access_key, assumedRoleObject.credentials.secret_key, assumedRoleObject.credentials.session_token, get(config, 'aws.region', os.environ.get('AWS_DEFAULT_REGION')), get(config, 'aws.bucket', os.environ.get('AWS_BEANSTALK_BUCKET_NAME')), get(config, 'aws.bucket_path', os.environ.get('AWS_BEANSTALK_BUCKET_NAME_PATH'))) out("Using Role: "+role_name) else: # create credentials aws = AwsCredentials( get(config, 'aws.access_key', os.environ.get('AWS_ACCESS_KEY_ID')), get(config, 'aws.secret_key', os.environ.get('AWS_SECRET_ACCESS_KEY')), get(config, 'aws.secret_token', os.environ.get('AWS_SECRET_TOKEN')), get(config, 'aws.region', os.environ.get('AWS_DEFAULT_REGION')), get(config, 'aws.bucket', os.environ.get('AWS_BEANSTALK_BUCKET_NAME')), get(config, 'aws.bucket_path', os.environ.get('AWS_BEANSTALK_BUCKET_NAME_PATH'))) return aws
def get_connection(self): ret = None if self._cross_account_number and self._cross_account_role: self._info( subject=_status.parse_status('cross_account_connect', (self._cross_account_number, self._cross_account_role, self._region)), src_account=self._cross_account_number, src_role=self._cross_account_role, category='connection') from boto.sts import STSConnection import boto try: role_arn = 'arn:aws:iam::%s:role/%s' % (self._cross_account_number, self._cross_account_role) sts = STSConnection() assumed_role = sts.assume_role(role_arn=role_arn, role_session_name='AssumeRoleSession') ret = ec2.connect_to_region( self._region, aws_access_key_id=assumed_role.credentials.access_key, aws_secret_access_key=assumed_role.credentials.secret_key, security_token=assumed_role.credentials.session_token ) except BotoServerError, e: raise BackupMonkeyException('%s: %s' % (_status.parse_status('cross_account_error'), e.message), subject=_status.parse_status('cross_account_error'), body=e.message, src_account=self._cross_account_number, src_role=self._cross_account_role, category='connection')
def conn_aws_arnrole_s3(aws_access_key, aws_access_secret, aws_arn_role, aws_arn_session_name, aws_arn_session_duration, aws_bucket): """ Makes connection to AWS S3 bucket with arn details. The connection details comes from extract_postgres.getawsarn(id) :return: Returns the bucket. If using boto3: sts_client = boto3.client('sts') assumedroleobject = sts_client.assume_role(RoleArn=aws_arn_role, RoleSessionName=aws_arn_session_name, DurationSeconds=aws_arn_session_duration) credentials = assumedroleobject['Credentials'] s3_resource = boto3.resource( 's3', aws_access_key_id=credentials['AccessKeyId'], aws_secret_access_key=credentials['SecretAccessKey'], aws_session_token=credentials['SessionToken']) return s3_resource.Bucket(aws_bucket) """ try: sts_connection = STSConnection(aws_access_key, aws_access_secret) tempCredentials = sts_connection.assume_role(role_arn=aws_arn_role, role_session_name=aws_arn_session_name, duration_seconds=aws_arn_session_duration) s3_connection = S3Connection(aws_access_key_id=tempCredentials.credentials.access_key, aws_secret_access_key=tempCredentials.credentials.secret_key, security_token=tempCredentials.credentials.session_token) return s3_connection.get_bucket(aws_bucket) except Exception as exn: print "The error is {} : {}".format(exn.__class__.__name__, exn)
def main(options): sts_connection = STSConnection() # conn = dynamodb.connect_to_region(options.region) assumedRoleObject = sts_connection.assume_role() conn = dynamodb.layer2.Layer2(region=options.region, aws_access_key_id=assumedRoleObject.credentials.access_key, aws_secret_access_key=assumedRoleObject.credentials.secret_key, security_token=assumedRoleObject.credentials.session_token) def create_table(name): table_schema = conn.create_schema( hash_key_name='Key', hash_key_proto_value=str ) table = conn.create_table( name=name, schema=table_schema, read_units=2, write_units=1 ) return table try: create_table(CONFIGURATION_TABLE_NAME) time.sleep(5) except: pass table = conn.get_table(CONFIGURATION_TABLE_NAME) availability_zones = ",".join([zone.name for zone in ec2.connect_to_region(options.region).get_all_zones()]) account_id = iam.connect_to_region(options.region).get_user().arn.split(':')[4] items = { 'account_name': options.account_name, 'account_environment': options.account_environment, 'availability_zones': availability_zones, 'account_id': account_id, 'output_path': options.output_path, 'output_path': options.output_path } if options.accounts: items['accounts'] = options.accounts if options.okta_credential: okta_config = json.load(open(options.okta_credential)) items['okta_credential'] = json.dumps(okta_config) for key, value in items.iteritems(): print key attrs = {'Key': key, 'Value': value} time.sleep(1) my_item = table.new_item(attrs=attrs) print my_item.put()
def _create_s3_connection_assuming_role(self): """Creates S3 connection by assuming the role necessary to read from the S3 bucket that contains the logs. """ JsonLogger.log_event('assuming_role', assumed_role_arn=self.role_arn) sts_connection = STSConnection() assumed_role = sts_connection.assume_role( role_arn=self.role_arn, role_session_name="AssumeRoleS3BucketRead") self.s3_connection = S3Connection( aws_access_key_id=assumed_role.credentials.access_key, aws_secret_access_key=assumed_role.credentials.secret_key, security_token=assumed_role.credentials.session_token)
def __init__(self): ''' Main execution path ''' # Inventory grouped by instance IDs, tags, security groups, regions, elbs and availability zones self.inventory = self._empty_inventory() # Index of hostname (address) to instance ID #self.index = {} # Read settings and parse CLI arguments self.read_settings() self.parse_cli_args() #Initiate the STS connection: sts_connection = STSConnection( ) data_to_print = {} for i in self.aws_creds.keys(): # Creating the object from the sts_connection assumedRoleObject = sts_connection.assume_role( role_arn=self.aws_creds[i]["arn"], role_session_name="AssumeRoleSession") # Index of hostname (address) to instance ID self.index = {} self.creds = self.aws_creds[i] # Cache Setup self.cache_path_cache = self.cache_dir + "/ansible-%s.cache" % i self.cache_path_index = self.cache_dir + "/ansible-%s.index" % i # Cache if self.args.refresh_cache: self.do_api_calls_update_cache(assumedRoleObject) elif not self.is_cache_valid(): self.do_api_calls_update_cache(assumedRoleObject) # Data to print if self.args.host: data_to_print = self.get_host_info() elif self.args.list: # Display list of instances for inventory if self.inventory == self._empty_inventory(): data_to_print = self.get_inventory_from_cache() else: data_to_print = self.json_format_dict(self.inventory, True) print(data_to_print)
def openConsole(): """ Get STS token and open AWS console. """ # Create an ARN out of the information provided by the user. role_arn = "arn:aws:iam::" + accountId() + ":role/" + getArgs().role_name # Connect to AWS STS and then call AssumeRole. # Returns temporary security credentials. sts_connection = STSConnection() assumed_role_object = sts_connection.assume_role( role_arn=role_arn, role_session_name="AssumeRoleSession") # Format resulting credentials into a JSON block. tmp_creds = { "sessionId": assumed_role_object.credentials.access_key, "sessionKey": assumed_role_object.credentials.secret_key, "sessionToken": assumed_role_object.credentials.session_token, } json_temp_credentials = json.dumps(tmp_creds) # Make a request to the AWS federation endpoint to get a sign-in # token, passing parameters in the query string. params = { "Action": "getSigninToken", "Session": json_temp_credentials, } request_url = "https://signin.aws.amazon.com/federation" r = requests.get(request_url, params=params) # The return value from the federation endpoint, the token. sign_in_token = json.loads(r.text)["SigninToken"] # Token is good for 15 minutes. # Create the URL to the console with token. params = { "Action": "login", "Issuer": "", "Destination": "https://console.aws.amazon.com/", "SigninToken": sign_in_token, } request_url = "https://signin.aws.amazon.com/federation?" request_url += urlencode(params) # Use the default browser to sign in to the console using the # generated URL. browser = webbrowser.get() if getArgs().incognito: webbrowser.Chromium.raise_opts = ["", "--incognito"] webbrowser.Chrome.raise_opts = ["", "--incognito"] webbrowser.Mozilla.remote_args = ['--private-window', '%s'] browser.open(request_url, new=1)
def get_session_token(sts_connection, role_arn, mfa_serial_number, role_session_name, project_name, environment_name, role_name, token_expiration, session_token_expiration): try: if not args.nomfa: mfa_token = raw_input("Enter the MFA code: ") sts_session = sts_connection.get_session_token( duration=session_token_expiration, mfa_serial_number=mfa_serial_number, mfa_token=mfa_token ) session_sts_connection = STSConnection(aws_access_key_id=sts_session.access_key, aws_secret_access_key=sts_session.secret_key, security_token=sts_session.session_token) if args.externalid: assumed_role_object = session_sts_connection.assume_role( role_arn=role_arn, role_session_name=role_session_name, duration_seconds=token_expiration, external_id=externalid ) else: assumed_role_object = session_sts_connection.assume_role( role_arn=role_arn, role_session_name=role_session_name, duration_seconds=token_expiration, ) else: colormsg ("When using get_session you must use MFA", "error") exit(1) except Exception, e: colormsg ("There was an error assuming role", "error") verbose(e) exit(1)
def get_session_token(sts_connection, role_arn, mfa_serial_number, role_session_name, project_name, environment_name, role_name, token_expiration, session_token_expiration): try: if not args.nomfa: mfa_token = raw_input("Enter the MFA code: ") sts_session = sts_connection.get_session_token( duration=session_token_expiration, mfa_serial_number=mfa_serial_number, mfa_token=mfa_token) session_sts_connection = STSConnection( aws_access_key_id=sts_session.access_key, aws_secret_access_key=sts_session.secret_key, security_token=sts_session.session_token) if args.externalid: assumed_role_object = session_sts_connection.assume_role( role_arn=role_arn, role_session_name=role_session_name, duration_seconds=token_expiration, external_id=externalid) else: assumed_role_object = session_sts_connection.assume_role( role_arn=role_arn, role_session_name=role_session_name, duration_seconds=token_expiration, ) else: colormsg("When using get_session you must use MFA", "error") exit(1) except Exception, e: colormsg("There was an error assuming role", "error") verbose(e) exit(1)
def get_session_token(sts_connection, role_arn, mfa_serial_number, role_session_name, project_name, environment_name, role_name, token_expiration, session_token_expiration): try: if not args.nomfa: mfa_token = input("Enter the MFA code: ") sts_session = sts_connection.get_session_token( duration=session_token_expiration, mfa_serial_number=mfa_serial_number, mfa_token=mfa_token ) session_sts_connection = STSConnection(aws_access_key_id=sts_session.access_key, aws_secret_access_key=sts_session.secret_key, security_token=sts_session.session_token) assumed_role_object = session_sts_connection.assume_role( role_arn=role_arn, role_session_name=role_session_name, duration_seconds=token_expiration, ) else: colormsg("When using get_session you must use MFA", "error") exit(1) except Exception as e: colormsg("There was an error assuming role", "error") verbose(e) exit(1) colormsg("Assumed the role successfully", "ok") access_key = sts_session.access_key session_key = sts_session.secret_key session_token = sts_session.session_token expiration = sts_session.expiration login_to_fedaccount(access_key, session_key, session_token, role_session_name) credential_profile = 'default' save_credentials(access_key, session_key, session_token, role_session_name, 'corp', 'session', credential_profile, region) save_cli_credentials(access_key, session_key, session_token, '-'.join(['corp', 'session', credential_profile]), region) return {'access_key': access_key, 'session_key': session_key, 'session_token': session_token, 'role_session_name': role_session_name}
def __init__(self): """ Virtually private constructor. """ if AssumeRole.__instance: raise Exception("This is a singleton class!") sts = STSConnection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY) self.credentials = sts.assume_role( role_arn=settings.ROLE_ARN, role_session_name='vem', duration_seconds=3600, mfa_serial_number=settings.MFA_SERIAL_NUMBER, mfa_token=settings.MFA_TOKEN).credentials.to_dict() AssumeRole.__instance = self
def get_conn(self): """ Returns the boto S3Connection object. """ if self._default_to_boto: return S3Connection(profile_name=self.profile) a_key = s_key = None if self._creds_in_config_file: a_key, s_key, calling_format = _parse_s3_config(self.s3_config_file, self.s3_config_format, self.profile) elif self._creds_in_conn: a_key = self._a_key s_key = self._s_key calling_format = self.calling_format s3_host = self.s3_host if calling_format is None: calling_format = 'boto.s3.connection.SubdomainCallingFormat' if s3_host is None: s3_host = NoHostProvided if self._sts_conn_required: sts_connection = STSConnection(aws_access_key_id=a_key, aws_secret_access_key=s_key, profile_name=self.profile) assumed_role_object = sts_connection.assume_role( role_arn=self.role_arn, role_session_name="Airflow_" + self.s3_conn_id ) creds = assumed_role_object.credentials connection = S3Connection( aws_access_key_id=creds.access_key, aws_secret_access_key=creds.secret_key, calling_format=calling_format, security_token=creds.session_token ) else: connection = S3Connection(aws_access_key_id=a_key, aws_secret_access_key=s_key, calling_format=calling_format, host=s3_host, profile_name=self.profile) return connection
def get_conn(self): """ Returns the boto S3Connection object. """ if self._default_to_boto: return S3Connection(profile_name=self.profile, host=self.s3_host) a_key = s_key = None if self._creds_in_config_file: a_key, s_key, calling_format = _parse_s3_config(self.s3_config_file, self.s3_config_format, self.profile) elif self._creds_in_conn: a_key = self._a_key s_key = self._s_key calling_format = self.calling_format s3_host = self.s3_host if calling_format is None: calling_format = 'boto.s3.connection.SubdomainCallingFormat' if s3_host is None: s3_host = NoHostProvided if self._sts_conn_required: sts_connection = STSConnection(aws_access_key_id=a_key, aws_secret_access_key=s_key, profile_name=self.profile) assumed_role_object = sts_connection.assume_role( role_arn=self.role_arn, role_session_name="Airflow_" + self.s3_conn_id ) creds = assumed_role_object.credentials connection = S3Connection( aws_access_key_id=creds.access_key, aws_secret_access_key=creds.secret_key, calling_format=calling_format, security_token=creds.session_token ) else: connection = S3Connection(aws_access_key_id=a_key, aws_secret_access_key=s_key, calling_format=calling_format, host=s3_host, profile_name=self.profile) return connection
def assumeRole(credentials, arn): sts_connection = STSConnection( aws_access_key_id=credentials['AWS_ACCESS_KEY_ID'], aws_secret_access_key=credentials['AWS_SECRET_ACCESS_KEY']) sessionName = "awsudo-%08x" % (random.randint(0, 0xffffffff),) response = sts_connection.assume_role( role_arn=arn, role_session_name=sessionName) credentials = response.credentials return { 'AWS_ACCESS_KEY_ID': credentials.access_key, 'AWS_SECRET_ACCESS_KEY': credentials.secret_key, 'AWS_SESSION_TOKEN': credentials.session_token, }
def get_connection(self): ret = None if self._cross_account_number and self._cross_account_role: from boto.sts import STSConnection import boto try: role_arn = 'arn:aws:iam::%s:role/%s' % (self._cross_account_number, self._cross_account_role) sts = STSConnection() assumed_role = sts.assume_role(role_arn=role_arn, role_session_name='AssumeRoleSession') ret = ec2.connect_to_region( self._region, aws_access_key_id=assumed_role.credentials.access_key, aws_secret_access_key=assumed_role.credentials.secret_key, security_token=assumed_role.credentials.session_token ) except Exception,e: print e raise BackupMonkeyException('Cannot complete cross account access')
def get_connection(self): ret = None if self._cross_account_number and self._cross_account_role: from boto.sts import STSConnection import boto try: role_arn = 'arn:aws:iam::%s:role/%s' % ( self._cross_account_number, self._cross_account_role) sts = STSConnection() assumed_role = sts.assume_role( role_arn=role_arn, role_session_name='AssumeRoleSession') ret = ec2.connect_to_region( self._region, aws_access_key_id=assumed_role.credentials.access_key, aws_secret_access_key=assumed_role.credentials.secret_key, security_token=assumed_role.credentials.session_token) except Exception, e: print e raise BackupMonkeyException( 'Cannot complete cross account access')
def get_aws_credentials(self, account_alias, role): """Get temporary credentials from AWS""" self.check_user_permissions(account_alias, role) try: account_id = self.account_config[account_alias]['id'] except Exception: message = "No Configuration for account '{account}'." raise ConfigurationError(message.format(account=account_alias)) arn = "arn:aws:iam::{account_id}:role/{role}".format( account_id=account_id, role=role) key_id = self.application_config['aws']['access_key'] secret_key = self.application_config['aws']['secret_key'] try: sts_connection = STSConnection(aws_access_key_id=key_id, aws_secret_access_key=secret_key) assumed_role_object = sts_connection.assume_role( role_arn=arn, role_session_name=self.user) except Exception as error: if getattr(error, 'status', None) == 403: raise PermissionError(str(error)) self.logger.exception( "AWS STS failed with: {exc_vars}".format(exc_vars=vars(error))) raise AWSError(str(error)) return assumed_role_object.credentials
def make_aws_credentials(config, role_arn=None, role_name=None): if role_arn: try: sts_connection = STSConnection() assumedRoleObject = sts_connection.assume_role( role_arn=role_arn, role_session_name=role_name) except: out("Oops! something went wrong trying to assume the specified role" ) else: # create credentials for switching roles aws = AwsCredentials( assumedRoleObject.credentials.access_key, assumedRoleObject.credentials.secret_key, assumedRoleObject.credentials.session_token, get(config, 'aws.region', os.environ.get('AWS_DEFAULT_REGION')), get(config, 'aws.bucket', os.environ.get('AWS_BEANSTALK_BUCKET_NAME')), get(config, 'aws.bucket_path', os.environ.get('AWS_BEANSTALK_BUCKET_NAME_PATH'))) out("Using Role: " + role_name) else: # create credentials aws = AwsCredentials( get(config, 'aws.access_key', os.environ.get('AWS_ACCESS_KEY_ID')), get(config, 'aws.secret_key', os.environ.get('AWS_SECRET_ACCESS_KEY')), get(config, 'aws.secret_token', os.environ.get('AWS_SECRET_TOKEN')), get(config, 'aws.region', os.environ.get('AWS_DEFAULT_REGION')), get(config, 'aws.bucket', os.environ.get('AWS_BEANSTALK_BUCKET_NAME')), get(config, 'aws.bucket_path', os.environ.get('AWS_BEANSTALK_BUCKET_NAME_PATH'))) return aws
def get_session_token(sts_connection, role_arn, mfa_serial_number, role_session_name, project_name, environment_name, role_name, token_expiration, session_token_expiration, args): global access_key global session_key global session_token try: if not args.nomfa: mfa_token = input("Enter the MFA code: ") sts_session = sts_connection.get_session_token( duration=session_token_expiration, mfa_serial_number=mfa_serial_number, mfa_token=mfa_token ) session_sts_connection = STSConnection(aws_access_key_id=sts_session.access_key, aws_secret_access_key=sts_session.secret_key, security_token=sts_session.session_token) if args.externalid: assumed_role_object = session_sts_connection.assume_role( role_arn=role_arn, role_session_name=role_session_name, duration_seconds=token_expiration, external_id=externalid ) else: assumed_role_object = session_sts_connection.assume_role( role_arn=role_arn, role_session_name=role_session_name, duration_seconds=token_expiration, ) else: colormsg("When using get_session you must use MFA", "error") exit(1) except Exception as e: colormsg("There was an error assuming role", "error") verbose(str(e)) exit(1) colormsg ("Assumed the role successfully", "ok") # Format resulting temporary credentials into a JSON block using # known field names. access_key = sts_session.access_key session_key = sts_session.secret_key session_token = sts_session.session_token expiration = sts_session.expiration login_to_fedaccount(access_key, session_key, session_token, role_session_name, args=args) if not args.profile: credential_profile = 'default' else: credential_profile = args.profile save_credentials(access_key, session_key, session_token, role_session_name, 'corp', 'session', credential_profile, region) # save_credentials(access_key, session_key, session_token, role_session_name, project_name, environment_name, role_name, region) # and save them on the CLI config file .aws/credentials save_cli_credentials(access_key, session_key, session_token, '-'.join(['corp','session',credential_profile]), region) if args.stdout: print("") print("If you want to use your credentials from the environment with an external Tool (for instance, Terraform), you can use the following instructions:") print("WARNING: If you use it in the same shell as anwbis exported variables takes precedence over the .aws/credentials, so use it carefully") print("") print("export AWS_ACCESS_KEY_ID='%s'" % access_key) print("export AWS_SECRET_ACCESS_KEY='%s'" % session_key) print("export AWS_SESSION_TOKEN='%s'" % session_token) print("export AWS_DEFAULT_REGION='%s'" % region) print("Expiration='%s'" % expiration) print("") return {'access_key': access_key, 'session_key': session_key, 'session_token': session_token, 'role_session_name': role_session_name}
# ] # } # And appropriate IAM policy roleArn = "arn:aws:iam::<YOUR_ACCOUNT_ID>:role/<NAME_OF_EXISTING_ROLE>" ########################################### ### Create preSigned URL ########################################### # Taken from : http://docs.aws.amazon.com/STS/latest/UsingSTS/STSMgmtConsole-manualURL.html#STSConsoleLink_programPython sts_connection = STSConnection() assumed_role_object = sts_connection.assume_role( role_arn=roleArn, role_session_name="ConsoleSSOSession", duration_seconds=1800 ) # Step 3: Format resulting temporary credentials into JSON json_string_with_temp_credentials = '{' json_string_with_temp_credentials += '"sessionId":"' + assumed_role_object.credentials.access_key + '",' json_string_with_temp_credentials += '"sessionKey":"' + assumed_role_object.credentials.secret_key + '",' json_string_with_temp_credentials += '"sessionToken":"' + assumed_role_object.credentials.session_token + '"' json_string_with_temp_credentials += '}' # Step 4. Make request to AWS federation endpoint to get sign-in token. Pass # the action and JSON document with temporary credentials as parameters. request_parameters = "?Action=getSigninToken" request_parameters += "&Session=" + urllib.quote_plus(json_string_with_temp_credentials) request_url = "https://signin.aws.amazon.com/federation" + request_parameters
def get_aws_connection_info(module): ec2_url = module.params.get('ec2_url') access_key = module.params.get('aws_access_key') secret_key = module.params.get('aws_secret_key') security_token = module.params.get('security_token') region = module.params.get('region') aws_profile = module.params.get('aws_profile') validate_certs = module.params.get('validate_certs') profile_dict = {} if not ec2_url: if 'EC2_URL' in os.environ: ec2_url = os.environ['EC2_URL'] elif 'AWS_URL' in os.environ: ec2_url = os.environ['AWS_URL'] if not region: if 'EC2_REGION' in os.environ: region = os.environ['EC2_REGION'] elif 'AWS_REGION' in os.environ: region = os.environ['AWS_REGION'] else: # boto.config.get returns None if config not found region = boto.config.get('Boto', 'aws_region') if not region: region = boto.config.get('Boto', 'ec2_region') if aws_profile: # sanity checks if aws_profile != "default": if "HOME" not in os.environ: module.fail_json( msg= "No $HOME environment variable could be detected. Do you even UNIX bro?" ) aws_config_file = os.path.join(os.environ["HOME"], ".aws/config") if not os.path.exists(aws_config_file): module.fail_json(msg="Does $HOME/aws/.config even exist?") config = ConfigParser.ConfigParser() config.read(aws_config_file) sections = config.sections() if 'profile ' + aws_profile not in sections: module.fail_json(msg="AWS profile: %s was not found" % aws_profile) profile_dict = config_section_map(config, 'profile ' + aws_profile) else: aws_profile = None if profile_dict and 'role_arn' in profile_dict: role_arn = profile_dict['role_arn'] source_profile = profile_dict['source_profile'] role_session_name = 'CustomAnsibleSession' # get creds by following source_profile aws_credentials_file = os.path.join(os.environ["HOME"], ".aws/credentials") if not os.path.exists(aws_credentials_file): module.fail_json(msg="Does $HOME/aws/.credentials even exist?") config.read(aws_credentials_file) source_profile_dict = config_section_map(config, source_profile) aws_access_key = source_profile_dict['aws_access_key_id'] aws_secret_key = source_profile_dict['aws_secret_access_key'] sts_connection = STSConnection(aws_access_key_id=aws_access_key, aws_secret_access_key=aws_secret_key) assumedRoleObject = sts_connection.assume_role( role_arn=role_arn, role_session_name=role_session_name) access_key = assumedRoleObject.credentials.access_key secret_key = assumedRoleObject.credentials.secret_key security_token = assumedRoleObject.credentials.session_token else: if not access_key: if 'EC2_ACCESS_KEY' in os.environ: access_key = os.environ['EC2_ACCESS_KEY'] elif 'AWS_ACCESS_KEY_ID' in os.environ: access_key = os.environ['AWS_ACCESS_KEY_ID'] elif 'AWS_ACCESS_KEY' in os.environ: access_key = os.environ['AWS_ACCESS_KEY'] else: # in case access_key came in as empty string access_key = None if not secret_key: if 'EC2_SECRET_KEY' in os.environ: secret_key = os.environ['EC2_SECRET_KEY'] elif 'AWS_SECRET_ACCESS_KEY' in os.environ: secret_key = os.environ['AWS_SECRET_ACCESS_KEY'] elif 'AWS_SECRET_KEY' in os.environ: secret_key = os.environ['AWS_SECRET_KEY'] else: # in case secret_key came in as empty string secret_key = None if not security_token: if 'AWS_SECURITY_TOKEN' in os.environ: security_token = os.environ['AWS_SECURITY_TOKEN'] else: # in case security_token came in as empty string security_token = None boto_params = dict(aws_access_key_id=access_key, aws_secret_access_key=secret_key, profile_name=aws_profile, security_token=security_token) return region, ec2_url, boto_params
# Step 1: Authenticate user in your own identity system. # Step 2: Using the access keys for an IAM user in your AWS account, # call "AssumeRole" to get temporary access keys for the federated user # Note: Calls to AWS STS AssumeRole must be signed using the access key ID # and secret access key of an IAM user or using existing temporary credentials. # The credentials can be in EC2 instance metadata, in environment variables, # or in a configuration file, and will be discovered automatically by the # STSConnection() function. For more information, see the Python SDK docs: # http://boto.readthedocs.org/en/latest/boto_config_tut.html sts_connection = STSConnection() assumed_role_object = sts_connection.assume_role( role_arn="arn:aws:iam::348107122702:role/Test", role_session_name="AssumeRoleSession") # Step 3: Format resulting temporary credentials into JSON json_string_with_temp_credentials = '{' json_string_with_temp_credentials += '"sessionId":"' + assumed_role_object.credentials.access_key + '",' json_string_with_temp_credentials += '"sessionKey":"' + assumed_role_object.credentials.secret_key + '",' json_string_with_temp_credentials += '"sessionToken":"' + assumed_role_object.credentials.session_token + '"' json_string_with_temp_credentials += '}' # Step 4. Make request to AWS federation endpoint to get sign-in token. Pass # the action and JSON document with temporary credentials as parameters. request_parameters = "?Action=getSigninToken" request_parameters += "&Session=" + urllib.quote_plus( json_string_with_temp_credentials) request_url = "https://signin.aws.amazon.com/federation" + request_parameters
def get_aws_connection_info(module): ec2_url = module.params.get('ec2_url') access_key = module.params.get('aws_access_key') secret_key = module.params.get('aws_secret_key') security_token = module.params.get('security_token') region = module.params.get('region') aws_profile = module.params.get('aws_profile') validate_certs = module.params.get('validate_certs') profile_dict = {} if not ec2_url: if 'EC2_URL' in os.environ: ec2_url = os.environ['EC2_URL'] elif 'AWS_URL' in os.environ: ec2_url = os.environ['AWS_URL'] if not region: if 'EC2_REGION' in os.environ: region = os.environ['EC2_REGION'] elif 'AWS_REGION' in os.environ: region = os.environ['AWS_REGION'] else: # boto.config.get returns None if config not found region = boto.config.get('Boto', 'aws_region') if not region: region = boto.config.get('Boto', 'ec2_region') if aws_profile: # sanity checks if aws_profile != "default": if "HOME" not in os.environ: module.fail_json(msg="No $HOME environment variable could be detected. Do you even UNIX bro?") aws_config_file = os.path.join(os.environ["HOME"], ".aws/config") if not os.path.exists(aws_config_file): module.fail_json(msg="Does $HOME/aws/.config even exist?") config = ConfigParser.ConfigParser() config.read(aws_config_file) sections = config.sections() if 'profile ' + aws_profile not in sections: module.fail_json(msg="AWS profile: %s was not found" % aws_profile) profile_dict = config_section_map(config, 'profile ' + aws_profile) else: aws_profile = None if profile_dict and 'role_arn' in profile_dict: role_arn = profile_dict['role_arn'] source_profile = profile_dict['source_profile'] role_session_name = 'CustomAnsibleSession' # get creds by following source_profile aws_credentials_file = os.path.join(os.environ["HOME"], ".aws/credentials") if not os.path.exists(aws_credentials_file): module.fail_json(msg="Does $HOME/aws/.credentials even exist?") config.read(aws_credentials_file) source_profile_dict = config_section_map(config, source_profile) aws_access_key = source_profile_dict['aws_access_key_id'] aws_secret_key = source_profile_dict['aws_secret_access_key'] sts_connection = STSConnection(aws_access_key_id=aws_access_key, aws_secret_access_key=aws_secret_key) assumedRoleObject = sts_connection.assume_role( role_arn=role_arn, role_session_name=role_session_name ) access_key = assumedRoleObject.credentials.access_key secret_key = assumedRoleObject.credentials.secret_key security_token = assumedRoleObject.credentials.session_token else: if not access_key: if 'EC2_ACCESS_KEY' in os.environ: access_key = os.environ['EC2_ACCESS_KEY'] elif 'AWS_ACCESS_KEY_ID' in os.environ: access_key = os.environ['AWS_ACCESS_KEY_ID'] elif 'AWS_ACCESS_KEY' in os.environ: access_key = os.environ['AWS_ACCESS_KEY'] else: # in case access_key came in as empty string access_key = None if not secret_key: if 'EC2_SECRET_KEY' in os.environ: secret_key = os.environ['EC2_SECRET_KEY'] elif 'AWS_SECRET_ACCESS_KEY' in os.environ: secret_key = os.environ['AWS_SECRET_ACCESS_KEY'] elif 'AWS_SECRET_KEY' in os.environ: secret_key = os.environ['AWS_SECRET_KEY'] else: # in case secret_key came in as empty string secret_key = None if not security_token: if 'AWS_SECURITY_TOKEN' in os.environ: security_token = os.environ['AWS_SECURITY_TOKEN'] else: # in case security_token came in as empty string security_token = None boto_params = dict(aws_access_key_id=access_key, aws_secret_access_key=secret_key, profile_name=aws_profile, security_token=security_token) return region, ec2_url, boto_params
import json import boto import boto3 import os import commands import boto.ec2 from boto import ec2 from boto.sts import STSConnection import sys arn=str(sys.argv[1]) print arn sts_connection = STSConnection() assumed_role_object = sts_connection.assume_role( role_arn=arn, role_session_name="run-script" ) os.environ["AWS_ACCESS_KEY_ID"] =assumed_role_object.credentials.access_key os.environ["AWS_SECRET_ACCESS_KEY"] = assumed_role_object.credentials.secret_key os.environ["AWS_SESSION_TOKEN"] = assumed_role_object.credentials.session_token ############ Get Account name & ID ############################################# accountname=commands.getoutput("aws iam list-account-aliases | awk {'print $2'}") accountid=(boto3.client('sts').get_caller_identity()['Account']) print accountname f1=open('/tmp/email_output.html', 'a') f1.write("<h2 style='color:#0066cc;'>"+accountname+" ["+accountid+"]</h2><hr>\n<h4>Security Group Ports Summary for EC2 Instances</h4>\n<table style=\'width:100%\', border=\'1\'>\n<thead><th>Instance Name</th><th>Instance Type</th><th>VPC</th><th>Security Group</th><th>Ports Opened</th></thead>\n<tbody>\n") ############# EC2 instance INFo with attached security group name/ID ########### def get_name(instance): if instance.tags:
# Step 1: Authenticate user in your own identity system. # Step 2: Using the access keys for an IAM user in your AWS account, # call "AssumeRole" to get temporary access keys for the federated user # Note: Calls to AWS STS AssumeRole must be signed using the access key ID # and secret access key of an IAM user or using existing temporary credentials. # The credentials can be in EC2 instance metadata, in environment variables, # or in a configuration file, and will be discovered automatically by the # STSConnection() function. For more information, see the Python SDK docs: # http://boto.readthedocs.org/en/latest/boto_config_tut.html sts_connection = STSConnection() assumed_role_object = sts_connection.assume_role( role_arn="arn:aws:iam::ACCOUNT-ID-WITHOUT-HYPHENS:role/ROLE-NAME", role_session_name="AssumeRoleSession") # Step 3: Format resulting temporary credentials into JSON json_string_with_temp_credentials = '{' json_string_with_temp_credentials += '"sessionId":"' + assumed_role_object.credentials.access_key + '",' json_string_with_temp_credentials += '"sessionKey":"' + assumed_role_object.credentials.secret_key + '",' json_string_with_temp_credentials += '"sessionToken":"' + assumed_role_object.credentials.session_token + '"' json_string_with_temp_credentials += '}' # Step 4. Make request to AWS federation endpoint to get sign-in token. Construct the parameter string with # the sign-in action request, a 12-hour session duration, and the JSON document with temporary credentials # as parameters. request_parameters = "?Action=getSigninToken" request_parameters += "&SessionDuration=43200" request_parameters += "&Session=" + urllib.quote_plus(
# The calls to AWS STS AssumeRole must be signed with the access key ID and secret # access key of an IAM user. (The AssumeRole API operation can also be called using temporary # credentials, but this example does not show that scenario.) # The IAM user credentials can be in environment variables or in # a configuration file and will be discovered automatically # by the STSConnection() function. For more information, see the Python SDK # documentation: http://boto.readthedocs.org/en/latest/boto_config_tut.html sts_connection = STSConnection() # Use appropriate device ID (serial number for hardware device or ARN for virtual device) # Replace ACCOUNT-NUMBER-WITHOUT-HYPHENS, ROLE-NAME, and MFA-DEVICE-ID with appropriate values tempCredentials = sts_connection.assume_role( role_arn="arn:aws:iam::ACCOUNT-NUMBER-WITHOUT-HYPHENS:role/ROLE-NAME", role_session_name="AssumeRoleSession1", mfa_serial_number="arn:aws:iam::ACCOUNT-NUMBER-WITHOUT-HYPHENS:mfa/MFA-DEVICE-ID", mfa_token=mfa_TOTP ) # Use the temporary credentials to list the contents of an S3 bucket s3_connection = S3Connection( aws_access_key_id=tempCredentials.credentials.access_key, aws_secret_access_key=tempCredentials.credentials.secret_key, security_token=tempCredentials.credentials.session_token ) # Replace BUCKET-NAME with a real bucket name bucket = s3_connection.get_bucket(bucket_name="BUCKET-NAME") objectlist = bucket.list() for obj in objectlist: print(obj.name)
mfa_serial_number="arn:aws:iam::186502235371:mfa/sthathamsetty", mfa_token=mfa_TOTP) print(tempCredentials.access_key) print(tempCredentials.secret_key) print("\n" + tempCredentials.session_token) sts_connection1 = STSConnection( aws_access_key_id=tempCredentials.access_key, aws_secret_access_key=tempCredentials.secret_key, security_token=tempCredentials.session_token) # Call the assume_role method of the STSConnection object and pass the role # ARN and a role session name. assumedRoleObject = sts_connection1.assume_role( role_arn= "arn:aws:iam::981284651061:role/CredibilityDataDevPowerUserCrossAccountSignin", role_session_name="session") # From the response that contains the assumed role, get the temporary # credentials that can be used to make subsequent API calls #credentials = assumedRoleObject s3_connection = S3Connection( aws_access_key_id=assumedRoleObject.credentials.access_key, aws_secret_access_key=assumedRoleObject.credentials.secret_key, security_token=assumedRoleObject.credentials.session_token, is_secure=False) bucket = s3_connection.get_bucket("capzones-dev") for key in bucket.list(): print(key.name.encode('utf-8'))
def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs): try: args = {} if complex_args: args.update(complex_args) args.update(parse_kv(module_args)) # get starting credentials # from environment: # AWS_ACCESS_KEY_ID # AWS_SECRET_ACCESS_KEY # use get started credentials to do the roles dance and obtain # temporary credentials in target account #target_role_name = 'init-test3-shoppertrak-NucleatorCageBuilder-1I5ZOAYRJLS8Z' data = {} data.update(inject) # TODO use nucleator facts instead source_role_name = data[ 'nucleator_builder_role_name'] # TODO - RHS var here could have names in better alignment with current conventions target_role_name = data[ 'cage_builder_role_name'] # TODO - RHS var here could have names in better alignment with current conventions print "Target Role Name: ", target_role_name print "Source Role Name: ", source_role_name source_account_id = data['source_account_number'] target_account_id = data['target_account_number'] print "Target Account Number: ", target_account_id print "Source Account Number: ", source_account_id try: envdict = {} if self.runner.environment: env = template.template(self.runner.basedir, self.runner.environment, inject, convert_bare=True) env = utils.safe_eval(env) aws_access_key_id = env.get("AWS_ACCESS_KEY_ID") aws_secret_access_key = env.get("AWS_SECRET_ACCESS_KEY") security_token = env.get("AWS_SECURITY_TOKEN") aws_access_key_id = aws_access_key_id if aws_access_key_id else None aws_secret_access_key = aws_secret_access_key if aws_secret_access_key else None security_token = security_token if security_token else None sts_connection = STSConnection( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, security_token=security_token) source_role = sts_connection.assume_role( role_arn='arn:aws:iam::{0}:role/{1}'.format( source_account_id, source_role_name), role_session_name='SourceRoleSession') vv("Successfully assumed {0} role in account {1}".format( source_role_name, source_account_id)) except Exception, e: result = dict( failed=True, msg=type(e).__name__ + ": Failed to obtain temporary credentials for role " + source_role_name + " in target account " + source_account_id + ", message: '" + str(e)) return ReturnData(conn=conn, comm_ok=False, result=result) try: sts_connection = STSConnection( aws_access_key_id=source_role.credentials.access_key, aws_secret_access_key=source_role.credentials.secret_key, security_token=source_role.credentials.session_token) target_role = sts_connection.assume_role( role_arn='arn:aws:iam::{0}:role/{1}'.format( target_account_id, target_role_name), role_session_name='TargetRoleSession') vv("Successfully assumed {0} role in account {1}".format( target_role_name, target_account_id)) except Exception, e: # deal with failure gracefully result = dict( failed=True, msg=type(e).__name__ + ": Failed to obtain temporary credentials for role " + target_role_name + " in target account " + target_account_id + ", message: '" + str(e) + " Security_Token: " + source_role.credentials.session_token) return ReturnData(conn=conn, comm_ok=False, result=result)
import boto from boto.sts import STSConnection from boto.s3.connection import S3Connection print ('Assuming role to access S3 on a different account') ROLE_ARN = os.environ['ROLE_ARN'] ROLE_SESS_NAME = os.environ['ROLE_SESS_NAME'] FILE_ROOT = os.environ['WORKSPACE'] + '/project/deploy/' BUCKET_PARAM = os.environ['BUCKET_NAME'] CF_DIST_ID = os.environ['CF_DIST_ID'] sts_connection = STSConnection() assumedRoleObject = sts_connection.assume_role( role_arn=ROLE_ARN, role_session_name=ROLE_SESS_NAME ) ACCESS_KEY = assumedRoleObject.credentials.access_key SECRET_KEY = assumedRoleObject.credentials.secret_key TOKEN = assumedRoleObject.credentials.session_token # Use the temporary credentials returned by AssumeRole to call Amazon S3 connection = S3Connection( aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, security_token=TOKEN, calling_format=boto.s3.connection.OrdinaryCallingFormat() ) print('File Root: ', FILE_ROOT)
import hashlib import sys import boto from boto.sts import STSConnection from boto.s3.connection import S3Connection print('Assuming role to access S3 on a different account') ROLE_ARN = os.environ['ROLE_ARN'] ROLE_SESS_NAME = os.environ['ROLE_SESS_NAME'] FILE_ROOT = os.environ['WORKSPACE'] + '/project/deploy/' BUCKET_PARAM = os.environ['BUCKET_NAME'] CF_DIST_ID = os.environ['CF_DIST_ID'] sts_connection = STSConnection() assumedRoleObject = sts_connection.assume_role( role_arn=ROLE_ARN, role_session_name=ROLE_SESS_NAME) ACCESS_KEY = assumedRoleObject.credentials.access_key SECRET_KEY = assumedRoleObject.credentials.secret_key TOKEN = assumedRoleObject.credentials.session_token # Use the temporary credentials returned by AssumeRole to call Amazon S3 connection = S3Connection( aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, security_token=TOKEN, calling_format=boto.s3.connection.OrdinaryCallingFormat()) print('File Root: ', FILE_ROOT) print('Bucket Name ', BUCKET_PARAM) bucket = connection.get_bucket(BUCKET_PARAM, validate=False)
account_id_from_user = sys.argv[1] role_name_from_user = sys.argv[2] else: print "\n\tUsage: ", print os.path.basename(sys.argv[0]), # script name print " <account_id> <role_name>" exit(0) # Create an ARN out of the information provided by the user. role_arn = "arn:aws:iam::" + account_id_from_user + ":role/" role_arn += role_name_from_user # Step 2: Connect to AWS STS and then call AssumeRole. This returns # temporary security credentials. sts_connection = STSConnection() assumed_role_object = sts_connection.assume_role( role_arn=role_arn, role_session_name="AssumeRoleSession") # Step 3: Format resulting temporary credentials into a JSON block using # known field names. access_key = assumed_role_object.credentials.access_key session_key = assumed_role_object.credentials.secret_key session_token = assumed_role_object.credentials.session_token json_temp_credentials = '{' json_temp_credentials += '"sessionId":"' + access_key + '",' json_temp_credentials += '"sessionKey":"' + session_key + '",' json_temp_credentials += '"sessionToken":"' + session_token + '"' json_temp_credentials += '}' # Step 4. Make a request to the AWS federation endpoint to get a sign-in # token, passing parameters in the query string. The call requires an # Action parameter ('getSigninToken') and a Session parameter (the
def get_sts(duration, mfa_serial, mfa_device_name, long_term, short_term, assume_role_arn=None): if boto.config.get(long_term, 'aws_access_key_id') is None: logger.error('aws_access_key_id is missing from section %s' 'or config file is missing.' % (long_term, )) sys.exit(1) else: long_term_id = boto.config.get(long_term, 'aws_access_key_id') if boto.config.get(long_term, 'aws_secret_access_key') is None: logger.error('aws_secret_access_key is missing from section ' 'or config file is missing.' % (long_term, )) sys.exit(1) else: long_term_secret = boto.config.get(long_term, 'aws_secret_access_key') if boto.config.has_section(short_term): boto.config.remove_option(short_term, 'aws_security_token') mfa_TOTP = raw_input('Enter AWS MFA code for user %s ' '(renewing for %s seconds):' % (mfa_device_name, duration)) try: sts_connection = STSConnection(aws_access_key_id=long_term_id, aws_secret_access_key=long_term_secret) if assume_role_arn is None: tempCredentials = sts_connection.get_session_token( duration=duration, mfa_serial_number=mfa_serial, mfa_token=mfa_TOTP) assumed_role = 'False' else: role_session_name = assume_role_arn.split('/')[-1] assumedRole = sts_connection.assume_role( assume_role_arn, role_session_name, duration_seconds=duration, mfa_serial_number=mfa_serial, mfa_token=mfa_TOTP) tempCredentials = assumedRole.credentials assumed_role = 'True' default_options = [ ('aws_access_key_id', tempCredentials.access_key), ('aws_secret_access_key', tempCredentials.secret_key), ('aws_security_token', tempCredentials.session_token), ('expiration', tempCredentials.expiration), ('assumed_role', assumed_role) ] for option, value in default_options: boto.config.save_user_option(short_term, option, value) except boto.exception.BotoServerError as e: message = '%s - Please try again.' % (e.message) logger.error(message) sys.exit(1)
import uuid import boto.ec2 from boto.ec2.connection import EC2Connection from boto.sts import STSConnection from sys import argv script_name, account_id_from_user, role_name_from_user, my_region = argv theregion = boto.ec2.get_region(my_region) role_arn = "arn:aws:iam::" + account_id_from_user + ":role/" role_arn += role_name_from_user sts_connection = STSConnection() assumed_role_object = sts_connection.assume_role( role_arn=role_arn, role_session_name="AssumeRoleSession" ) access = assumed_role_object.credentials.access_key secret = assumed_role_object.credentials.secret_key token = assumed_role_object.credentials.session_token myimages = EC2Connection(region=theregion) listims = myimages.get_all_images(owners='self') ec2conn = EC2Connection(aws_access_key_id=access,aws_secret_access_key=secret,security_token=token,region=theregion) for x in listims: theimage = str([x]) theimage = theimage.replace('Image:','') theimage = theimage.replace('[','') theimage = theimage.replace(']','') myimages.modify_image_attribute(theimage, attribute='launchPermission', operation='add', user_ids=account_id_from_user)
appId ="{{ priam_cluster_name }}" def put_record(domain, prop, val): print"Inserting into %s: %s -> %s" % (domain, prop, val) itemname ="%s.%s" % (appId, prop) sdb.put_attributes(domain, itemname, {"appId" : appId,"property" : prop,"value" : val}) return roleArn = '{{ priam_assume_role_arn|default('None') }}' if roleArn == 'None': sdb = boto.sdb.connect_to_region("us-east-1") else: sts = STSConnection() assumed = sts.assume_role(roleArn, 'sdb_script') sdb = boto.sdb.connect_to_region('us-east-1', aws_access_key_id=assumed.credentials.access_key, aws_secret_access_key=assumed.credentials.secret_key, security_token=assumed.credentials.session_token) ii = sdb.lookup("InstanceIdentity", validate=True) if ii is None: print"No InstanceIdentity, creating." ii = sdb.create_domain("InstanceIdentity") pp = sdb.lookup("PriamProperties", validate=True) if pp is None: print"No PriamProperties, creating." pp = sdb.create_domain("PriamProperties") put_record("PriamProperties","priam.s3.bucket","{{ priam_s3_bucket }}") put_record("PriamProperties","priam.s3.base_dir","{{ priam_s3_base_dir }}") put_record("PriamProperties","priam.clustername","{{ priam_cluster_name }}")