本文整理汇总了Python中botocore.exceptions.ProfileNotFound方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.ProfileNotFound方法的具体用法?Python exceptions.ProfileNotFound怎么用?Python exceptions.ProfileNotFound使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类botocore.exceptions
的用法示例。
在下文中一共展示了exceptions.ProfileNotFound方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _make_boto3_athena_client
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ProfileNotFound [as 别名]
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')
示例2: _make_boto3_kinesis_client
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ProfileNotFound [as 别名]
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')
示例3: get_first_account_alias_or_account_id
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ProfileNotFound [as 别名]
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)
示例4: register_uri_param_handler
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ProfileNotFound [as 别名]
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)
示例5: _run_main
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ProfileNotFound [as 别名]
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)
示例6: inject_assume_role_provider_cache
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ProfileNotFound [as 别名]
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)
示例7: session
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ProfileNotFound [as 别名]
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
示例8: _get_account_info
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ProfileNotFound [as 别名]
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}
示例9: test_aws_instances_profile
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ProfileNotFound [as 别名]
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)
示例10: initialized
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ProfileNotFound [as 别名]
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
示例11: get_scoped_config
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ProfileNotFound [as 别名]
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]
示例12: _configure
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ProfileNotFound [as 别名]
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
示例13: sts_client
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ProfileNotFound [as 别名]
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))
示例14: main
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ProfileNotFound [as 别名]
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)
示例15: add_timestamp_parser
# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ProfileNotFound [as 别名]
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)