我们从Python开源项目中,提取了以下18个代码示例,用于说明如何使用botocore.exceptions.NoCredentialsError()。
def list_ec2_snapshots_boto3(connection, module): if module.params.get("filters") is None: filters = [] else: filters = ansible_dict_to_boto3_filter_list(module.params.get("filters")) try: network_interfaces_result = connection.describe_network_interfaces(Filters=filters) except (ClientError, NoCredentialsError) as e: module.fail_json(msg=e.message) # Turn the boto3 result in to ansible_friendly_snaked_names snaked_network_interfaces_result = camel_dict_to_snake_dict(network_interfaces_result) for network_interfaces in snaked_network_interfaces_result['network_interfaces']: network_interfaces['tag_set'] = boto3_tag_list_to_ansible_dict(network_interfaces['tag_set']) module.exit_json(**snaked_network_interfaces_result)
def describe_services(self, cluster_name, service_name): if not self.access_key_id or not self.secret_access_key: raise NoCredentialsError() if cluster_name != u'test-cluster': error_response = {u'Error': {u'Code': u'ClusterNotFoundException', u'Message': u'Cluster not found.'}} raise ClientError(error_response, u'DescribeServices') if service_name != u'test-service': return {u'services': []} if self.deployment_errors: return { u"services": [PAYLOAD_SERVICE_WITH_ERRORS], u"failures": [] } return { u"services": [PAYLOAD_SERVICE], u"failures": [] }
def __init__(self, client, cluster_name, service_name): self._client = client self._cluster_name = cluster_name self._service_name = service_name try: if service_name: self._service = self.get_service() except IndexError: raise EcsConnectionError( u'An error occurred when calling the DescribeServices ' u'operation: Service not found.' ) except ClientError as e: raise EcsConnectionError(str(e)) except NoCredentialsError: raise EcsConnectionError( u'Unable to locate credentials. Configure credentials ' u'by running "aws configure".' )
def _perform(self, domain, validation_domain_name, validation): try: change_id = self._change_txt_record("UPSERT", validation_domain_name, validation) self._wait_for_change(change_id) except (NoCredentialsError, ClientError) as e: logger.debug('Encountered error during perform: %s', e, exc_info=True) raise errors.PluginError("\n".join([str(e), INSTRUCTIONS]))
def _cleanup(self, domain, validation_domain_name, validation): try: self._change_txt_record("DELETE", validation_domain_name, validation) except (NoCredentialsError, ClientError) as e: logger.debug('Encountered error during cleanup: %s', e, exc_info=True)
def test_perform_no_credentials_error(self): self.auth._change_txt_record = mock.MagicMock(side_effect=NoCredentialsError) self.assertRaises(errors.PluginError, self.auth.perform, [self.achall])
def test_cleanup_no_credentials_error(self): self.auth._attempt_cleanup = True self.auth._change_txt_record = mock.MagicMock(side_effect=NoCredentialsError) self.auth.cleanup([self.achall])
def call(session, operation_name, parameters, region_name=None, endpoint_url=None, verify=None): # We could get an error from get_endpoint() about not having # a region configured. Before this happens we want to check # for credentials so we can give a good error message. if session.get_credentials() is None: raise NoCredentialsError() client = session.create_client( 'emr', region_name=region_name, endpoint_url=endpoint_url, verify=verify) LOG.debug('Calling ' + str(operation_name)) return getattr(client, operation_name)(**parameters)
def list_ec2_vpc_nacls(connection, module): nacl_ids = module.params.get("nacl_ids") filters = ansible_dict_to_boto3_filter_list(module.params.get("filters")) try: nacls = connection.describe_network_acls(NetworkAclIds=nacl_ids, Filters=filters) except (ClientError, NoCredentialsError) as e: module.fail_json(msg=e.message, **camel_dict_to_snake_dict(e.response)) # Turn the boto3 result in to ansible_friendly_snaked_names snaked_nacls = [] for nacl in nacls['NetworkAcls']: snaked_nacls.append(camel_dict_to_snake_dict(nacl)) # Turn the boto3 result in to ansible friendly tag dictionary for nacl in snaked_nacls: if 'tags' in nacl: nacl['tags'] = boto3_tag_list_to_ansible_dict(nacl['tags']) if 'entries' in nacl: nacl['egress'] = [nacl_entry_to_list(e) for e in nacl['entries'] if e['rule_number'] != 32767 and e['egress']] nacl['ingress'] = [nacl_entry_to_list(e) for e in nacl['entries'] if e['rule_number'] != 32767 and not e['egress']] del nacl['entries'] if 'associations' in nacl: nacl['subnets'] = [a['subnet_id'] for a in nacl['associations']] del nacl['associations'] if 'network_acl_id' in nacl: nacl['nacl_id'] = nacl['network_acl_id'] del nacl['network_acl_id'] module.exit_json(nacls=snaked_nacls)
def load_tables(self, query, meta): """ Load necessary resources tables into db to execute given query. """ try: for table in meta.tables: self.load_table(table) except NoCredentialsError: help_link = 'http://boto3.readthedocs.io/en/latest/guide/configuration.html' raise QueryError('Unable to locate AWS credential. ' 'Please see {0} on how to configure AWS credential.'.format(help_link))
def test_anonymous_access(): with ignoring(NoCredentialsError): s3 = S3FileSystem(anon=True) assert s3.ls('') == [] ## TODO: public bucket doesn't work through moto with pytest.raises((OSError, IOError)): s3.mkdir('newbucket')
def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict( name=dict(required=True), description=dict(), value=dict(required=False), state=dict(default='present', choices=['present', 'absent']), string_type=dict(default='String', choices=['String', 'StringList', 'SecureString']), decryption=dict(default=True, type='bool'), key_id=dict(default="alias/aws/ssm"), overwrite=dict(default=True, type='bool'), region=dict(required=False), ) ) module = AnsibleModule(argument_spec=argument_spec) if not HAS_BOTO3: module.fail_json(msg='boto3 are required.') state = module.params.get('state') try: region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True) client = boto3_conn(module, conn_type='client', resource='ssm', region=region, endpoint=ec2_url, **aws_connect_kwargs) except NoCredentialsError as e: module.fail_json(msg="Can't authorize connection - %s" % str(e)) invocations = { "present": create_update_parameter, "absent": delete_parameter, } (changed, response) = invocations[state](client, module) module.exit_json(changed=changed, response=response)
def get_elb(connection, module): try: return connection.describe_load_balancers(Names=[module.params.get("name")])['LoadBalancers'][0] except (ClientError, NoCredentialsError) as e: if e.response['Error']['Code'] == 'LoadBalancerNotFound': return None else: module.fail_json(msg=e.message, **camel_dict_to_snake_dict(e.response))
def update_elb_attributes(connection, module, elb): """Update ELB attributes. Return true if changed, else false""" attribute_changed = False update_required = False params = dict() elb_attributes = connection.describe_load_balancer_attributes(LoadBalancerArn=elb['LoadBalancerArn']) if module.params.get("attributes"): params['Attributes'] = module.params.get("attributes") for new_attribute in params['Attributes']: for current_attribute in elb_attributes['Attributes']: if new_attribute['Key'] == current_attribute['Key']: if new_attribute['Value'] != current_attribute['Value']: update_required = True if update_required: attribute_changed = True try: connection.modify_load_balancer_attributes(LoadBalancerArn=elb['LoadBalancerArn'], Attributes=params['Attributes']) except (ClientError, NoCredentialsError) as e: module.fail_json(msg=e.message, **camel_dict_to_snake_dict(e.response)) return attribute_changed
def delete_elb(connection, module): changed = False elb = get_elb(connection, module) if elb: try: connection.delete_load_balancer(LoadBalancerArn=elb['LoadBalancerArn']) changed = True except (ClientError, NoCredentialsError) as e: module.fail_json(msg=e.message, **camel_dict_to_snake_dict(e.response)) module.exit_json(changed=changed)
def main(self, args=None): """ :param args: List of arguments, with the 'aws' removed. For example, the command "aws s3 list-objects --bucket foo" will have an args list of ``['s3', 'list-objects', '--bucket', 'foo']``. """ if args is None: args = sys.argv[1:] command_table = self._get_command_table() parser = self._create_parser(command_table) self._add_aliases(command_table, parser) parsed_args, remaining = parser.parse_known_args(args) try: # Because _handle_top_level_args emits events, it's possible # that exceptions can be raised, which should have the same # general exception handling logic as calling into the # command table. This is why it's in the try/except clause. self._handle_top_level_args(parsed_args) self._emit_session_event() return command_table[parsed_args.command](remaining, parsed_args) except UnknownArgumentError as e: sys.stderr.write("usage: %s\n" % USAGE) sys.stderr.write(str(e)) sys.stderr.write("\n") return 255 except NoRegionError as e: msg = ('%s You can also configure your region by running ' '"aws configure".' % e) self._show_error(msg) return 255 except NoCredentialsError as e: msg = ('%s. You can configure credentials by running ' '"aws configure".' % e) self._show_error(msg) return 255 except KeyboardInterrupt: # Shell standard for signals that terminate # the process is to return 128 + signum, in this case # SIGINT=2, so we'll have an RC of 130. sys.stdout.write("\n") return 128 + signal.SIGINT except Exception as e: LOG.debug("Exception caught in main()", exc_info=True) LOG.debug("Exiting with rc 255") err = get_stderr_text_writer() err.write("\n") err.write(six.text_type(e)) err.write("\n") return 255
def get_remote_host(remote_host, regions, spilo_stack_name): # We allow instance ids or stack names to be specified # If it looks like one, we will try to get a host and port using boto3 # Spilo member names replace - with _, so we accept instance id's with both match = re.match('^(i[_-])?([a-zA-Z0-9]+)$', remote_host) if match is None: return remote_host, None import boto3 from botocore.exceptions import NoCredentialsError, ClientError try: if match.group(1) is None: ec2_instance_id = None for region in regions: logging.debug("Trying to find Spilo {} in region {}".format(remote_host, region)) cf = boto3.client('cloudformation', region) elb = boto3.client('elb', region) ec2_instance_id = get_spilo_master(cf, elb, spilo_stack_name, remote_host) if ec2_instance_id is not None: break if ec2_instance_id is None: raise ClickException('Could not find a Cloud Formation stack for Spilo {}'.format(remote_host)) regions = [region] else: ec2_instance_id = re.sub('^i[-_]', 'i-', remote_host) logging.debug(regions) for region in regions: ec2 = boto3.client('ec2', region) ip = None try: logging.debug("Trying to find instance {} in region {}".format(ec2_instance_id, region)) ip = get_instance_ip(ec2, ec2_instance_id, region) if ip is not None: return ip, region except ClientError as ce: if ce.response['Error']['Code'] != 'InvalidInstanceID.NotFound': raise raise ClickException('Could not determine IP-address for instance {}'.format(ec2_instance_id)) except ClientError as ce: logging.warning(ce.response['Error']['Code']) if ce.response['Error']['Code'] in ['ExpiredToken', 'RequestExpired']: raise ClickException('\nAWS credentials have expired.\n' + 'Use the "zaws require" command line tool to get a new temporary access key.') else: raise ce except NoCredentialsError: raise ClickException('\nNo AWS credentials found.\n' + 'Use the "zaws require" command line tool to get a temporary access key\n')