Python botocore.exceptions.ProfileNotFound() Examples
The following are 30
code examples of botocore.exceptions.ProfileNotFound().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
botocore.exceptions
, or try the search function
.
Example #1
Source File: test_aws.py From bridgy with MIT License | 6 votes |
def test_aws_instances_profile(mocker): test_dir = os.path.dirname(os.path.abspath(__file__)) cache_dir = os.path.join(test_dir, 'aws_stubs') config_dir = os.path.join(test_dir, 'aws_configs') aws_obj = AwsInventory(cache_dir=cache_dir, profile='somewhere', region='region', config_path=config_dir) instances = aws_obj.instances() expected_instances = [Instance(name='test-forms', address='devbox', aliases=('devbox', 'ip-172-31-8-185.us-west-2.compute.internal', 'i-e54cbaeb'), source='aws', container_id=None, type='VM'), Instance(name='devlab-forms', address='devbox', aliases=('devbox', 'ip-172-31-0-138.us-west-2.compute.internal', 'i-f7d726f9'), source='aws', container_id=None, type='VM'), Instance(name='test-account-svc', address='devbox', aliases=('devbox', 'ip-172-31-0-139.us-west-2.compute.internal', 'i-f4d726fa'), source='aws', container_id=None, type='VM'), Instance(name='devlab-pubsrv', address='devbox', aliases=('devbox', 'ip-172-31-0-142.us-west-2.compute.internal', 'i-f5d726fb'), source='aws', container_id=None, type='VM'), Instance(name='devlab-game-svc', address='devbox', aliases=('devbox', 'ip-172-31-0-140.us-west-2.compute.internal', 'i-f2d726fc'), source='aws', container_id=None, type='VM'), Instance(name='test-game-svc', address='devbox', aliases=('devbox', 'ip-172-31-0-141.us-west-2.compute.internal', 'i-f3d726fd'), source='aws', container_id=None, type='VM'), Instance(name='test-pubsrv', address='devbox', aliases=('devbox', 'ip-172-31-2-38.us-west-2.compute.internal', 'i-0f500447384e95942'), source='aws', container_id=None, type='VM'), Instance(name='test-pubsrv', address='devbox', aliases=('devbox', 'ip-172-31-2-39.us-west-2.compute.internal', 'i-0f500447384e95943'), source='aws', container_id=None, type='VM')] assert set(instances) == set(expected_instances) from botocore.exceptions import ProfileNotFound with pytest.raises(ProfileNotFound): aws_obj = AwsInventory(cache_dir=cache_dir, profile='some-unconfigured-profile', region='region', config_path=config_dir)
Example #2
Source File: _client_factory.py From taskcat with Apache License 2.0 | 6 votes |
def session(self, profile: str = "default", region: str = None) -> boto3.Session: region = self._get_region(region, profile) try: session = self._cache_lookup( self._session_cache, [profile, region], self._boto3.Session, [], {"region_name": region, "profile_name": profile}, ) except ProfileNotFound: if profile != "default": raise session = self._boto3.Session(region_name=region) self._cache_set(self._session_cache, [profile, region], session) return session
Example #3
Source File: assumerole.py From bash-lambda-layer with MIT License | 6 votes |
def inject_assume_role_provider_cache(session, **kwargs): try: cred_chain = session.get_component('credential_provider') except ProfileNotFound: # If a user has provided a profile that does not exist, # trying to retrieve components/config on the session # will raise ProfileNotFound. Sometimes this is invalid: # # "ec2 describe-instances --profile unknown" # # and sometimes this is perfectly valid: # # "configure set region us-west-2 --profile brand-new-profile" # # Because we can't know (and don't want to know) whether # the customer is trying to do something valid, we just # immediately return. If it's invalid something else # up the stack will raise ProfileNotFound, otherwise # the configure (and other) commands will work as expected. LOG.debug("ProfileNotFound caught when trying to inject " "assume-role cred provider cache. Not configuring " "JSONFileCache for assume-role.") return provider = cred_chain.get_provider('assume-role') provider.cache = JSONFileCache(CACHE_DIR)
Example #4
Source File: _client_factory.py From taskcat with Apache License 2.0 | 6 votes |
def _get_account_info(self, profile): partition, region = self._get_partition(profile) session = self.session(profile, region) sts_client = session.client("sts", region_name=region) try: account_id = sts_client.get_caller_identity()["Account"] except ClientError as e: if e.response["Error"]["Code"] == "AccessDenied": raise TaskCatException( f"Not able to fetch account number from {region} using profile " f"{profile}. {str(e)}" ) raise except NoCredentialsError as e: raise TaskCatException( f"Not able to fetch account number from {region} using profile " f"{profile}. {str(e)}" ) except ProfileNotFound as e: raise TaskCatException( f"Not able to fetch account number from {region} using profile " f"{profile}. {str(e)}" ) return {"partition": partition, "account_id": account_id}
Example #5
Source File: configure.py From bash-lambda-layer with MIT License | 6 votes |
def _run_main(self, parsed_args, parsed_globals): # Called when invoked with no args "aws configure" new_values = {} # This is the config from the config file scoped to a specific # profile. try: config = self._session.get_scoped_config() except ProfileNotFound: config = {} for config_name, prompt_text in self.VALUES_TO_PROMPT: current_value = config.get(config_name) new_value = self._prompter.get_value(current_value, config_name, prompt_text) if new_value is not None and new_value != current_value: new_values[config_name] = new_value config_filename = os.path.expanduser( self._session.get_config_variable('config_file')) if new_values: profile = self._session.profile self._write_out_creds_file_values(new_values, profile) if profile is not None: section = profile_to_section(profile) new_values['__section__'] = section self._config_writer.update_config(new_values, config_filename)
Example #6
Source File: paramfile.py From bash-lambda-layer with MIT License | 6 votes |
def register_uri_param_handler(session, **kwargs): prefix_map = copy.deepcopy(LOCAL_PREFIX_MAP) try: fetch_url = session.get_scoped_config().get( 'cli_follow_urlparam', 'true') == 'true' except ProfileNotFound: # If a --profile is provided that does not exist, loading # a value from get_scoped_config will crash the CLI. # This function can be called as the first handler for # the session-initialized event, which happens before a # profile can be created, even if the command would have # successfully created a profile. Instead of crashing here # on a ProfileNotFound the CLI should just use 'none'. fetch_url = True if fetch_url: prefix_map.update(REMOTE_PREFIX_MAP) handler = URIArgumentHandler(prefix_map) session.register('load-cli-arg', handler)
Example #7
Source File: session.py From awscli-keyring with MIT License | 6 votes |
def initialized(session, **kwargs): session.session_var_map["keyring"] = ("keyring", None, False, cast_bool) try: if session.get_config_variable("keyring") != False: if session.profile is not None: profile = session.profile else: profile = "default" key, secret = persistence.get_credentials(profile) session.set_credentials(key, secret) except (ConfigNotFound, ProfileNotFound): pass
Example #8
Source File: cli.py From cfn-sphere with Apache License 2.0 | 6 votes |
def get_first_account_alias_or_account_id(): try: return boto3.client('iam').list_account_aliases()["AccountAliases"][0] except IndexError: return boto3.client('sts').get_caller_identity()["Arn"].split(":")[4] except ProfileNotFound: LOGGER.error( "The AWS_PROFILE env var is set to '{0}' but this profile is not found in your ~/.aws/config".format( os.environ.get("AWS_PROFILE"))) sys.exit(1) except (BotoCoreError, ClientError) as e: LOGGER.error(e) sys.exit(1) except Exception as e: LOGGER.error("Unknown error occurred loading users account alias") LOGGER.exception(e) LOGGER.info("Please report at https://github.com/cfn-sphere/cfn-sphere/issues!") sys.exit(1)
Example #9
Source File: services.py From streamalert with Apache License 2.0 | 6 votes |
def _make_boto3_kinesis_client(container): region = container.get_parameter('aws_region') logger = container.get('logger') config = botocore_client.Config( connect_timeout=5, read_timeout=5, region_name=region ) session_kwargs = {} try: session = boto3.Session(**session_kwargs) return session.client('kinesis', config=config) except ProfileNotFound: logger.error('AWS Kinesis Connection via Profile Failed')
Example #10
Source File: services.py From streamalert with Apache License 2.0 | 6 votes |
def _make_boto3_athena_client(container): region = container.get_parameter('aws_region') logger = container.get('logger') config = botocore_client.Config( connect_timeout=5, read_timeout=5, region_name=region ) session_kwargs = {} try: session = boto3.Session(**session_kwargs) return session.client( 'athena', config=config, ) except ProfileNotFound: logger.error('AWS Athena Connection via Profile Failed')
Example #11
Source File: session.py From aws-extender with MIT License | 5 votes |
def get_scoped_config(self): """ Returns the config values from the config file scoped to the current profile. The configuration data is loaded **only** from the config file. It does not resolve variables based on different locations (e.g. first from the session instance, then from environment variables, then from the config file). If you want this lookup behavior, use the ``get_config_variable`` method instead. Note that this configuration is specific to a single profile (the ``profile`` session variable). If the ``profile`` session variable is set and the profile does not exist in the config file, a ``ProfileNotFound`` exception will be raised. :raises: ConfigNotFound, ConfigParseError, ProfileNotFound :rtype: dict """ profile_name = self.get_config_variable('profile') profile_map = self._build_profile_map() # If a profile is not explicitly set return the default # profile config or an empty config dict if we don't have # a default profile. if profile_name is None: return profile_map.get('default', {}) elif profile_name not in profile_map: # Otherwise if they specified a profile, it has to # exist (even if it's the default profile) otherwise # we complain. raise ProfileNotFound(profile=profile_name) else: return profile_map[profile_name]
Example #12
Source File: session.py From AWS-Transit-Gateway-Demo-MultiAccount with MIT License | 5 votes |
def get_scoped_config(self): """ Returns the config values from the config file scoped to the current profile. The configuration data is loaded **only** from the config file. It does not resolve variables based on different locations (e.g. first from the session instance, then from environment variables, then from the config file). If you want this lookup behavior, use the ``get_config_variable`` method instead. Note that this configuration is specific to a single profile (the ``profile`` session variable). If the ``profile`` session variable is set and the profile does not exist in the config file, a ``ProfileNotFound`` exception will be raised. :raises: ConfigNotFound, ConfigParseError, ProfileNotFound :rtype: dict """ profile_name = self.get_config_variable('profile') profile_map = self._build_profile_map() # If a profile is not explicitly set return the default # profile config or an empty config dict if we don't have # a default profile. if profile_name is None: return profile_map.get('default', {}) elif profile_name not in profile_map: # Otherwise if they specified a profile, it has to # exist (even if it's the default profile) otherwise # we complain. raise ProfileNotFound(profile=profile_name) else: return profile_map[profile_name]
Example #13
Source File: session.py From AWS-Transit-Gateway-Demo-MultiAccount with MIT License | 5 votes |
def get_scoped_config(self): """ Returns the config values from the config file scoped to the current profile. The configuration data is loaded **only** from the config file. It does not resolve variables based on different locations (e.g. first from the session instance, then from environment variables, then from the config file). If you want this lookup behavior, use the ``get_config_variable`` method instead. Note that this configuration is specific to a single profile (the ``profile`` session variable). If the ``profile`` session variable is set and the profile does not exist in the config file, a ``ProfileNotFound`` exception will be raised. :raises: ConfigNotFound, ConfigParseError, ProfileNotFound :rtype: dict """ profile_name = self.get_config_variable('profile') profile_map = self._build_profile_map() # If a profile is not explicitly set return the default # profile config or an empty config dict if we don't have # a default profile. if profile_name is None: return profile_map.get('default', {}) elif profile_name not in profile_map: # Otherwise if they specified a profile, it has to # exist (even if it's the default profile) otherwise # we complain. raise ProfileNotFound(profile=profile_name) else: return profile_map[profile_name]
Example #14
Source File: session.py From aws-builders-fair-projects with Apache License 2.0 | 5 votes |
def get_scoped_config(self): """ Returns the config values from the config file scoped to the current profile. The configuration data is loaded **only** from the config file. It does not resolve variables based on different locations (e.g. first from the session instance, then from environment variables, then from the config file). If you want this lookup behavior, use the ``get_config_variable`` method instead. Note that this configuration is specific to a single profile (the ``profile`` session variable). If the ``profile`` session variable is set and the profile does not exist in the config file, a ``ProfileNotFound`` exception will be raised. :raises: ConfigNotFound, ConfigParseError, ProfileNotFound :rtype: dict """ profile_name = self.get_config_variable('profile') profile_map = self._build_profile_map() # If a profile is not explicitly set return the default # profile config or an empty config dict if we don't have # a default profile. if profile_name is None: return profile_map.get('default', {}) elif profile_name not in profile_map: # Otherwise if they specified a profile, it has to # exist (even if it's the default profile) otherwise # we complain. raise ProfileNotFound(profile=profile_name) else: return profile_map[profile_name]
Example #15
Source File: test_client_factory.py From taskcat with Apache License 2.0 | 5 votes |
def test_session_no_profile( self, mock_boto3, mock_cache_lookup, mock_cache_set, mock_get_partition ): mock_get_partition.return_value = (None, "us-east-1") mock_cache_lookup.side_effect = ProfileNotFound(profile="non-existent-profile") Boto3Cache().session() # default value should be "default" profile self.assertEqual(mock_boto3.called, True) self.assertEqual(mock_cache_lookup.called, True) self.assertEqual(mock_cache_set.called, True)
Example #16
Source File: test_client_factory.py From taskcat with Apache License 2.0 | 5 votes |
def test_session_invalid_profile(self, mock_cache_lookup, mock_cache_set): mock_cache_lookup.side_effect = ProfileNotFound(profile="non-existent-profile") cache = Boto3Cache() with self.assertRaises(ProfileNotFound): cache.session(profile="non-existent-profile") self.assertEqual(mock_cache_lookup.called, False) cache._get_region = mock.Mock(return_value="us-east-1") with self.assertRaises(ProfileNotFound): cache.session(profile="non-existent-profile") self.assertEqual(mock_cache_lookup.called, True)
Example #17
Source File: _client_factory.py From taskcat with Apache License 2.0 | 5 votes |
def get_default_region(self, profile_name="default") -> str: try: region = self._boto3.session.Session(profile_name=profile_name).region_name except ProfileNotFound: if profile_name != "default": raise region = self._boto3.session.Session().region_name if not region: _, region = self._get_partition(profile_name) LOG.warning( "Region not set in credential chain, defaulting to {}".format(region) ) return region
Example #18
Source File: session.py From faces with GNU General Public License v2.0 | 5 votes |
def get_scoped_config(self): """ Returns the config values from the config file scoped to the current profile. The configuration data is loaded **only** from the config file. It does not resolve variables based on different locations (e.g. first from the session instance, then from environment variables, then from the config file). If you want this lookup behavior, use the ``get_config_variable`` method instead. Note that this configuration is specific to a single profile (the ``profile`` session variable). If the ``profile`` session variable is set and the profile does not exist in the config file, a ``ProfileNotFound`` exception will be raised. :raises: ConfigNotFound, ConfigParseError, ProfileNotFound :rtype: dict """ profile_name = self.get_config_variable('profile') profile_map = self._build_profile_map() # If a profile is not explicitly set return the default # profile config or an empty config dict if we don't have # a default profile. if profile_name is None: return profile_map.get('default', {}) elif profile_name not in profile_map: # Otherwise if they specified a profile, it has to # exist (even if it's the default profile) otherwise # we complain. raise ProfileNotFound(profile=profile_name) else: return profile_map[profile_name]
Example #19
Source File: scalarparse.py From bash-lambda-layer with MIT License | 5 votes |
def add_timestamp_parser(session): factory = session.get_component('response_parser_factory') try: timestamp_format = session.get_scoped_config().get( 'cli_timestamp_format', 'none') except ProfileNotFound: # If a --profile is provided that does not exist, loading # a value from get_scoped_config will crash the CLI. # This function can be called as the first handler for # the session-initialized event, which happens before a # profile can be created, even if the command would have # successfully created a profile. Instead of crashing here # on a ProfileNotFound the CLI should just use 'none'. timestamp_format = 'none' if timestamp_format == 'none': # For backwards compatibility reasons, we replace botocore's timestamp # parser (which parses to a datetime.datetime object) with the # identity function which prints the date exactly the same as it comes # across the wire. timestamp_parser = identity elif timestamp_format == 'iso8601': timestamp_parser = iso_format else: raise ValueError('Unknown cli_timestamp_format value: %s, valid values' ' are "none" or "iso8601"' % timestamp_format) factory.set_parser_defaults(timestamp_parser=timestamp_parser)
Example #20
Source File: session.py From bash-lambda-layer with MIT License | 5 votes |
def get_scoped_config(self): """ Returns the config values from the config file scoped to the current profile. The configuration data is loaded **only** from the config file. It does not resolve variables based on different locations (e.g. first from the session instance, then from environment variables, then from the config file). If you want this lookup behavior, use the ``get_config_variable`` method instead. Note that this configuration is specific to a single profile (the ``profile`` session variable). If the ``profile`` session variable is set and the profile does not exist in the config file, a ``ProfileNotFound`` exception will be raised. :raises: ConfigNotFound, ConfigParseError, ProfileNotFound :rtype: dict """ profile_name = self.get_config_variable('profile') profile_map = self._build_profile_map() # If a profile is not explicitly set return the default # profile config or an empty config dict if we don't have # a default profile. if profile_name is None: return profile_map.get('default', {}) elif profile_name not in profile_map: # Otherwise if they specified a profile, it has to # exist (even if it's the default profile) otherwise # we complain. raise ProfileNotFound(profile=profile_name) else: return profile_map[profile_name]
Example #21
Source File: __init__.py From ssh2ec2 with MIT License | 5 votes |
def main(): args = parse_args() try: boto3.setup_default_session(profile_name=args.profile, region_name=args.region) conn = boto3.client('ec2') except ProfileNotFound as e: print(e) sys.exit(1) # Retrieve a list of instances that match the filters reservations = conn.describe_instances(Filters=get_filters(args)) if len(reservations['Reservations']) == 0: print('No instances matching criteria') sys.exit(1) instance_dns_names = [ instance['PublicDnsName'] for reservation in reservations['Reservations'] for instance in reservation['Instances']] if args.all_matching_instances: pass else: # Pick a random instance from the results instance_dns_names = [instance_dns_names[random.randrange(0, len(instance_dns_names))]] if args.command: remote_command = ' '.join(args.command) else: remote_command = '' for dns_name in instance_dns_names: if args.ssh_user: dns_name = '%s@%s' % (args.ssh_user, dns_name) ssh_cmd = 'ssh %s %s %s' % (args.ssh_args, dns_name, remote_command) os.system(ssh_cmd)
Example #22
Source File: amazon.py From aws-google-auth with MIT License | 5 votes |
def sts_client(self): try: profile = os.environ.get('AWS_PROFILE') if profile is not None: del os.environ['AWS_PROFILE'] client = boto3.client('sts', region_name=self.config.region) if profile is not None: os.environ['AWS_PROFILE'] = profile return client except ProfileNotFound as ex: raise ExpectedGoogleException("Error : {}.".format(ex))
Example #23
Source File: configure.py From python-aada with MIT License | 5 votes |
def _configure(self, parsed_args): new_values = {} try: config = self._session.get_scoped_config() except ProfileNotFound: config = {} for config_name, prompt_text in self.PROMPT_VALUES: current_value = config.get(config_name) new_value = self._get_value(current_value, prompt_text) if new_value is not None and new_value != current_value: new_values[config_name] = new_value config_filename = os.path.expanduser( self._session.get_config_variable('config_file')) if KEYRING and config.get('use_keyring'): updatepwd = input('Update Azure password in keyring? (yes/no)') if updatepwd.upper() in ['Y', 'YES']: azure_pass = getpass.getpass('Azure password ') keyring.set_password('aada', config.get('azure_username'), azure_pass) if new_values: self._write_credentials(new_values, parsed_args.profile) if parsed_args.profile is not None: new_values['__section__'] = ('profile {}'.format( parsed_args.profile)) self._config_writer.update_config(new_values, config_filename) return 0
Example #24
Source File: session.py From deepWordBug with Apache License 2.0 | 5 votes |
def get_scoped_config(self): """ Returns the config values from the config file scoped to the current profile. The configuration data is loaded **only** from the config file. It does not resolve variables based on different locations (e.g. first from the session instance, then from environment variables, then from the config file). If you want this lookup behavior, use the ``get_config_variable`` method instead. Note that this configuration is specific to a single profile (the ``profile`` session variable). If the ``profile`` session variable is set and the profile does not exist in the config file, a ``ProfileNotFound`` exception will be raised. :raises: ConfigNotFound, ConfigParseError, ProfileNotFound :rtype: dict """ profile_name = self.get_config_variable('profile') profile_map = self._build_profile_map() # If a profile is not explicitly set return the default # profile config or an empty config dict if we don't have # a default profile. if profile_name is None: return profile_map.get('default', {}) elif profile_name not in profile_map: # Otherwise if they specified a profile, it has to # exist (even if it's the default profile) otherwise # we complain. raise ProfileNotFound(profile=profile_name) else: return profile_map[profile_name]
Example #25
Source File: session.py From faces with GNU General Public License v2.0 | 5 votes |
def get_scoped_config(self): """ Returns the config values from the config file scoped to the current profile. The configuration data is loaded **only** from the config file. It does not resolve variables based on different locations (e.g. first from the session instance, then from environment variables, then from the config file). If you want this lookup behavior, use the ``get_config_variable`` method instead. Note that this configuration is specific to a single profile (the ``profile`` session variable). If the ``profile`` session variable is set and the profile does not exist in the config file, a ``ProfileNotFound`` exception will be raised. :raises: ConfigNotFound, ConfigParseError, ProfileNotFound :rtype: dict """ profile_name = self.get_config_variable('profile') profile_map = self._build_profile_map() # If a profile is not explicitly set return the default # profile config or an empty config dict if we don't have # a default profile. if profile_name is None: return profile_map.get('default', {}) elif profile_name not in profile_map: # Otherwise if they specified a profile, it has to # exist (even if it's the default profile) otherwise # we complain. raise ProfileNotFound(profile=profile_name) else: return profile_map[profile_name]
Example #26
Source File: mturk_utils.py From neural_chat with MIT License | 4 votes |
def setup_aws_credentials(): try: # Use existing credentials boto3.Session(profile_name=aws_profile_name) except ProfileNotFound: # Setup new credentials print( 'AWS credentials not found. Please create an IAM user with ' 'programmatic access and AdministratorAccess policy at ' 'https://console.aws.amazon.com/iam/ (On the "Set permissions" ' 'page, choose "Attach existing policies directly" and then select ' '"AdministratorAccess" policy). After creating the IAM user, ' 'please enter the user\'s Access Key ID and Secret Access ' 'Key below:' ) aws_access_key_id = input('Access Key ID: ') aws_secret_access_key = input('Secret Access Key: ') if not os.path.exists(os.path.expanduser('~/.aws/')): os.makedirs(os.path.expanduser('~/.aws/')) aws_credentials_file_path = '~/.aws/credentials' aws_credentials_file_string = None expanded_aws_file_path = os.path.expanduser(aws_credentials_file_path) if os.path.exists(expanded_aws_file_path): with open(expanded_aws_file_path, 'r') as aws_credentials_file: aws_credentials_file_string = aws_credentials_file.read() with open(expanded_aws_file_path, 'a+') as aws_credentials_file: # Clean up file if aws_credentials_file_string: if aws_credentials_file_string.endswith("\n\n"): pass elif aws_credentials_file_string.endswith("\n"): aws_credentials_file.write("\n") else: aws_credentials_file.write("\n\n") # Write login details aws_credentials_file.write('[{}]\n'.format(aws_profile_name)) aws_credentials_file.write( 'aws_access_key_id={}\n'.format(aws_access_key_id) ) aws_credentials_file.write( 'aws_secret_access_key={}\n'.format(aws_secret_access_key) ) print( 'AWS credentials successfully saved in {} file.\n'.format( aws_credentials_file_path ) ) os.environ['AWS_PROFILE'] = aws_profile_name
Example #27
Source File: mturk_utils.py From neural_chat with MIT License | 4 votes |
def setup_aws_credentials(): try: # Use existing credentials boto3.Session(profile_name=aws_profile_name) except ProfileNotFound: # Setup new credentials print( 'AWS credentials not found. Please create an IAM user with ' 'programmatic access and AdministratorAccess policy at ' 'https://console.aws.amazon.com/iam/ (On the "Set permissions" ' 'page, choose "Attach existing policies directly" and then select ' '"AdministratorAccess" policy). After creating the IAM user, ' 'please enter the user\'s Access Key ID and Secret Access ' 'Key below:' ) aws_access_key_id = input('Access Key ID: ') aws_secret_access_key = input('Secret Access Key: ') if not os.path.exists(os.path.expanduser('~/.aws/')): os.makedirs(os.path.expanduser('~/.aws/')) aws_credentials_file_path = '~/.aws/credentials' aws_credentials_file_string = None expanded_aws_file_path = os.path.expanduser(aws_credentials_file_path) if os.path.exists(expanded_aws_file_path): with open(expanded_aws_file_path, 'r') as aws_credentials_file: aws_credentials_file_string = aws_credentials_file.read() with open(expanded_aws_file_path, 'a+') as aws_credentials_file: # Clean up file if aws_credentials_file_string: if aws_credentials_file_string.endswith("\n\n"): pass elif aws_credentials_file_string.endswith("\n"): aws_credentials_file.write("\n") else: aws_credentials_file.write("\n\n") # Write login details aws_credentials_file.write('[{}]\n'.format(aws_profile_name)) aws_credentials_file.write( 'aws_access_key_id={}\n'.format(aws_access_key_id) ) aws_credentials_file.write( 'aws_secret_access_key={}\n'.format(aws_secret_access_key) ) print( 'AWS credentials successfully saved in {} file.\n'.format( aws_credentials_file_path ) ) os.environ['AWS_PROFILE'] = aws_profile_name
Example #28
Source File: mturk_utils.py From neural_chat with MIT License | 4 votes |
def setup_aws_credentials(): try: # Use existing credentials boto3.Session(profile_name=aws_profile_name) except ProfileNotFound: # Setup new credentials print( 'AWS credentials not found. Please create an IAM user with ' 'programmatic access and AdministratorAccess policy at ' 'https://console.aws.amazon.com/iam/ (On the "Set permissions" ' 'page, choose "Attach existing policies directly" and then select ' '"AdministratorAccess" policy). After creating the IAM user, ' 'please enter the user\'s Access Key ID and Secret Access ' 'Key below:' ) aws_access_key_id = input('Access Key ID: ') aws_secret_access_key = input('Secret Access Key: ') if not os.path.exists(os.path.expanduser('~/.aws/')): os.makedirs(os.path.expanduser('~/.aws/')) aws_credentials_file_path = '~/.aws/credentials' aws_credentials_file_string = None expanded_aws_file_path = os.path.expanduser(aws_credentials_file_path) if os.path.exists(expanded_aws_file_path): with open(expanded_aws_file_path, 'r') as aws_credentials_file: aws_credentials_file_string = aws_credentials_file.read() with open(expanded_aws_file_path, 'a+') as aws_credentials_file: # Clean up file if aws_credentials_file_string: if aws_credentials_file_string.endswith("\n\n"): pass elif aws_credentials_file_string.endswith("\n"): aws_credentials_file.write("\n") else: aws_credentials_file.write("\n\n") # Write login details aws_credentials_file.write('[{}]\n'.format(aws_profile_name)) aws_credentials_file.write( 'aws_access_key_id={}\n'.format(aws_access_key_id) ) aws_credentials_file.write( 'aws_secret_access_key={}\n'.format(aws_secret_access_key) ) print( 'AWS credentials successfully saved in {} file.\n'.format( aws_credentials_file_path ) ) os.environ['AWS_PROFILE'] = aws_profile_name
Example #29
Source File: mturk_utils.py From ParlAI with MIT License | 4 votes |
def setup_aws_credentials(): try: # Use existing credentials boto3.Session(profile_name=aws_profile_name) except ProfileNotFound: # Setup new credentials print( 'AWS credentials not found. Please create an IAM user with ' 'programmatic access and AdministratorAccess policy at ' 'https://console.aws.amazon.com/iam/ (On the "Set permissions" ' 'page, choose "Attach existing policies directly" and then select ' '"AdministratorAccess" policy). After creating the IAM user, ' 'please enter the user\'s Access Key ID and Secret Access ' 'Key below:' ) aws_access_key_id = input('Access Key ID: ') aws_secret_access_key = input('Secret Access Key: ') if not os.path.exists(os.path.expanduser('~/.aws/')): os.makedirs(os.path.expanduser('~/.aws/')) aws_credentials_file_path = '~/.aws/credentials' aws_credentials_file_string = None expanded_aws_file_path = os.path.expanduser(aws_credentials_file_path) if os.path.exists(expanded_aws_file_path): with open(expanded_aws_file_path, 'r') as aws_credentials_file: aws_credentials_file_string = aws_credentials_file.read() with open(expanded_aws_file_path, 'a+') as aws_credentials_file: # Clean up file if aws_credentials_file_string: if aws_credentials_file_string.endswith("\n\n"): pass elif aws_credentials_file_string.endswith("\n"): aws_credentials_file.write("\n") else: aws_credentials_file.write("\n\n") # Write login details aws_credentials_file.write('[{}]\n'.format(aws_profile_name)) aws_credentials_file.write( 'aws_access_key_id={}\n'.format(aws_access_key_id) ) aws_credentials_file.write( 'aws_secret_access_key={}\n'.format(aws_secret_access_key) ) print( 'AWS credentials successfully saved in {} file.\n'.format( aws_credentials_file_path ) ) os.environ['AWS_PROFILE'] = aws_profile_name
Example #30
Source File: mturk_utils.py From ParlAI with MIT License | 4 votes |
def setup_aws_credentials(): try: # Use existing credentials boto3.Session(profile_name=aws_profile_name) except ProfileNotFound: # Setup new credentials print( 'AWS credentials not found. Please create an IAM user with ' 'programmatic access and AdministratorAccess policy at ' 'https://console.aws.amazon.com/iam/ (On the "Set permissions" ' 'page, choose "Attach existing policies directly" and then select ' '"AdministratorAccess" policy). After creating the IAM user, ' 'please enter the user\'s Access Key ID and Secret Access ' 'Key below:' ) aws_access_key_id = input('Access Key ID: ') aws_secret_access_key = input('Secret Access Key: ') if not os.path.exists(os.path.expanduser('~/.aws/')): os.makedirs(os.path.expanduser('~/.aws/')) aws_credentials_file_path = '~/.aws/credentials' aws_credentials_file_string = None expanded_aws_file_path = os.path.expanduser(aws_credentials_file_path) if os.path.exists(expanded_aws_file_path): with open(expanded_aws_file_path, 'r') as aws_credentials_file: aws_credentials_file_string = aws_credentials_file.read() with open(expanded_aws_file_path, 'a+') as aws_credentials_file: # Clean up file if aws_credentials_file_string: if aws_credentials_file_string.endswith("\n\n"): pass elif aws_credentials_file_string.endswith("\n"): aws_credentials_file.write("\n") else: aws_credentials_file.write("\n\n") # Write login details aws_credentials_file.write('[{}]\n'.format(aws_profile_name)) aws_credentials_file.write( 'aws_access_key_id={}\n'.format(aws_access_key_id) ) aws_credentials_file.write( 'aws_secret_access_key={}\n'.format(aws_secret_access_key) ) print( 'AWS credentials successfully saved in {} file.\n'.format( aws_credentials_file_path ) ) os.environ['AWS_PROFILE'] = aws_profile_name