当前位置: 首页>>代码示例>>Python>>正文


Python exceptions.ClientError方法代码示例

本文整理汇总了Python中botocore.exceptions.ClientError方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.ClientError方法的具体用法?Python exceptions.ClientError怎么用?Python exceptions.ClientError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在botocore.exceptions的用法示例。


在下文中一共展示了exceptions.ClientError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: watch

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ClientError [as 别名]
def watch(args):
    logger.info("Watching task %s (%s)", args.task_id, args.cluster)
    last_status, events_received = None, 0
    log_reader = CloudwatchLogReader("/".join([args.task_name, args.task_name, os.path.basename(args.task_id)]),
                                     log_group_name=args.task_name)
    while last_status != "STOPPED":
        res = clients.ecs.describe_tasks(cluster=args.cluster, tasks=[args.task_id])
        if len(res["tasks"]) == 1:
            task_desc = res["tasks"][0]
            if task_desc["lastStatus"] != last_status:
                logger.info("Task %s %s", args.task_id, format_task_status(task_desc["lastStatus"]))
                last_status = task_desc["lastStatus"]
        try:
            for event in log_reader:
                print_event(event)
                events_received += 1
        except ClientError as e:
            expect_error_codes(e, "ResourceNotFoundException")
        if last_status is None and events_received > 0:
            break  # Logs retrieved successfully but task record is no longer in ECS
        time.sleep(1) 
开发者ID:kislyuk,项目名称:aegea,代码行数:23,代码来源:ecs.py

示例2: grant

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ClientError [as 别名]
def grant(args):
    """
    Given an IAM role or instance name, attach an IAM policy granting
    appropriate permissions to subscribe to deployments. Given a
    GitHub repo URL, create and record deployment keys for the repo
    and any of its private submodules, making the keys accessible to
    the IAM role.
    """
    try:
        role = resources.iam.Role(args.iam_role_or_instance)
        role.load()
    except ClientError:
        role = get_iam_role_for_instance(args.iam_role_or_instance)
    role.attach_policy(PolicyArn=ensure_deploy_iam_policy().arn)
    for private_repo in [args.repo] + list(private_submodules(args.repo)):
        gh_owner_name, gh_repo_name = parse_repo_name(private_repo)
        secret = secrets.put(argparse.Namespace(secret_name="deploy.{}.{}".format(gh_owner_name, gh_repo_name),
                                                iam_role=role.name,
                                                instance_profile=None,
                                                iam_group=None,
                                                iam_user=None,
                                                generate_ssh_key=True))
        get_repo(private_repo).create_key(__name__ + "." + role.name, secret["ssh_public_key"])
        logger.info("Created deploy key %s for IAM role %s to access GitHub repo %s",
                    secret["ssh_key_fingerprint"], role.name, private_repo) 
开发者ID:kislyuk,项目名称:aegea,代码行数:27,代码来源:deploy.py

示例3: ls

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ClientError [as 别名]
def ls(args):
    bucket = resources.s3.Bucket(args.billing_reports_bucket.format(account_id=ARN.get_account_id()))
    now = datetime.utcnow()
    year = args.year or now.year
    month = str(args.month or now.month).zfill(2)
    next_year = year + ((args.month or now.month) + 1) // 12
    next_month = str(((args.month or now.month) + 1) % 12).zfill(2)
    manifest_name = "aegea/{report}/{yr}{mo}01-{next_yr}{next_mo}01/{report}-Manifest.json"
    manifest_name = manifest_name.format(report=__name__, yr=year, mo=month, next_yr=next_year, next_mo=next_month)
    try:
        manifest = json.loads(bucket.Object(manifest_name).get().get("Body").read())
        for report_key in manifest["reportKeys"]:
            report = BytesIO(bucket.Object(report_key).get().get("Body").read())
            with gzip.GzipFile(fileobj=report) as fh:
                reader = csv.DictReader(fh)
                for line in reader:
                    page_output(tabulate(filter_line_items(reader, args), args))
    except ClientError as e:
        msg = 'Unable to get report {} from {}: {}. Run "aegea billing configure" to enable reports.'
        raise AegeaException(msg.format(manifest_name, bucket, e)) 
开发者ID:kislyuk,项目名称:aegea,代码行数:22,代码来源:billing.py

示例4: create

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ClientError [as 别名]
def create(args):
    if args.resource and args.resource.startswith("vpc-"):
        resource_type = "VPC"
    elif args.resource and args.resource.startswith("subnet-"):
        resource_type = "Subnet"
    elif args.resource and args.resource.startswith("eni-"):
        resource_type = "NetworkInterface"
    elif args.resource:
        raise AegeaException('Unrecognized resource type: "{}"'.format(args.resource))
    else:
        args.resource = ensure_vpc().id
        resource_type = "VPC"
    flow_logs_iam_role = ensure_iam_role(__name__,
                                         policies=["service-role/AmazonAPIGatewayPushToCloudWatchLogs"],
                                         trust=["vpc-flow-logs"])
    try:
        return clients.ec2.create_flow_logs(ResourceIds=[args.resource],
                                            ResourceType=resource_type,
                                            TrafficType=args.traffic_type,
                                            LogGroupName=__name__,
                                            DeliverLogsPermissionArn=flow_logs_iam_role.arn)
    except ClientError as e:
        expect_error_codes(e, "FlowLogAlreadyExists")
        return dict(FlowLogAlreadyExists=True) 
开发者ID:kislyuk,项目名称:aegea,代码行数:26,代码来源:flow_logs.py

示例5: ensure_security_group

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ClientError [as 别名]
def ensure_security_group(name, vpc, tcp_ingress=frozenset()):
    try:
        security_group = resolve_security_group(name, vpc)
    except (ClientError, KeyError):
        logger.info("Creating security group %s for %s", name, vpc)
        security_group = vpc.create_security_group(GroupName=name, Description=name)
        for i in range(90):
            try:
                clients.ec2.describe_security_groups(GroupIds=[security_group.id])
            except ClientError:
                time.sleep(1)
    for rule in tcp_ingress:
        source_security_group_id = None
        if "source_security_group_name" in rule:
            source_security_group_id = resolve_security_group(rule["source_security_group_name"], vpc).id
        ensure_ingress_rule(security_group, IpProtocol="tcp", FromPort=rule["port"], ToPort=rule["port"],
                            CidrIp=rule.get("cidr"), SourceSecurityGroupId=source_security_group_id)
    return security_group 
开发者ID:kislyuk,项目名称:aegea,代码行数:20,代码来源:__init__.py

示例6: ensure_s3_bucket

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ClientError [as 别名]
def ensure_s3_bucket(name=None, policy=None, lifecycle=None):
    if name is None:
        name = "aegea-assets-{}".format(ARN.get_account_id())
    bucket = resources.s3.Bucket(name)
    try:
        clients.s3.head_bucket(Bucket=bucket.name)
    except ClientError as e:
        logger.debug(e)
        if ARN.get_region() == "us-east-1":
            bucket.create()
        else:
            bucket.create(CreateBucketConfiguration=dict(LocationConstraint=ARN.get_region()))
    bucket.wait_until_exists()
    if policy:
        bucket.Policy().put(Policy=str(policy))
    if lifecycle:
        bucket.LifecycleConfiguration().put(LifecycleConfiguration=dict(lifecycle))
    return bucket 
开发者ID:kislyuk,项目名称:aegea,代码行数:20,代码来源:__init__.py

示例7: ensure_ssh_key

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ClientError [as 别名]
def ensure_ssh_key(name=None, base_name=__name__, verify_pem_file=True):
    if name is None:
        from getpass import getuser
        from socket import gethostname
        name = base_name + "." + getuser() + "." + gethostname().split(".")[0]

    try:
        ec2_key_pairs = list(resources.ec2.key_pairs.filter(KeyNames=[name]))
        if verify_pem_file and not os.path.exists(get_ssh_key_path(name)):
            msg = "Key {} found in EC2, but not in ~/.ssh."
            msg += " Delete the key in EC2, copy it to {}, or specify another key."
            raise KeyError(msg.format(name, get_ssh_key_path(name)))
    except ClientError as e:
        expect_error_codes(e, "InvalidKeyPair.NotFound")
        ec2_key_pairs = None

    if not ec2_key_pairs:
        ssh_key = ensure_local_ssh_key(name)
        resources.ec2.import_key_pair(KeyName=name,
                                      PublicKeyMaterial=get_public_key_from_pair(ssh_key))
        logger.info("Imported SSH key %s", get_ssh_key_path(name))
    add_ssh_key_to_agent(name)
    return name 
开发者ID:kislyuk,项目名称:aegea,代码行数:25,代码来源:crypto.py

示例8: lambda_handler

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ClientError [as 别名]
def lambda_handler(event, context):
    print(event)
    if 'SecurityGroupId' in event and 'IpRanges' in event and 'IpProtocol' in event and 'FromPort' in event:
        try:
            data = ec2.authorize_security_group_ingress(
                GroupId= event['SecurityGroupId'],
                IpPermissions=[
                    {'IpProtocol': event['IpProtocol'],
                    'FromPort': event['FromPort'],
                    'ToPort': event['ToPort'],
                    'IpRanges': event['IpRanges']
                    }
                ])
            print('Ingress Successfully Set %s' % data)
        except ClientError as e:
            print(e)
    else:
        print("One or more parameters are missing. Nothing to do.") 
开发者ID:Optum,项目名称:ChaoSlingr,代码行数:20,代码来源:PortChange_Slingr.py

示例9: s3_request

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ClientError [as 别名]
def s3_request(func: Callable):
    """
    Wrapper function for s3 requests in order to create more helpful error
    messages.
    """

    @wraps(func)
    def wrapper(url: str, *args, **kwargs):
        try:
            return func(url, *args, **kwargs)
        except ClientError as exc:
            if int(exc.response["Error"]["Code"]) == 404:
                raise FileNotFoundError("file {} not found".format(url))
            else:
                raise

    return wrapper 
开发者ID:ymcui,项目名称:cmrc2019,代码行数:19,代码来源:file_utils.py

示例10: get_create_queue

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ClientError [as 别名]
def get_create_queue(self):
        if not self._queue:
            try:
                q = self._sqs.get_queue_by_name(QueueName=self._queue_name)
            except ClientError as e:
                if e.response['Error']['Code'] == 'AWS.SimpleQueueService.NonExistentQueue':
                    q = None
                else:
                    raise e
            if not q:
                LOGGER.info('Creating queue {}'.format(self._queue_name))
                q = self._create_queue_with_pushback(
                    self._queue_name,
                    {'MessageRetentionPeriod': str(self.TWO_WEEKS)}
                )

            self._queue = q
        return self._queue 
开发者ID:ellimilial,项目名称:sqs-s3-logger,代码行数:20,代码来源:environment.py

示例11: test_delete

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ClientError [as 别名]
def test_delete(self, s3_client):
        # given
        s3_client.boto.put_object(
            Bucket=s3_client.bucket,
            Key=os.path.join(s3_client.prefix, "war.png"),
            Body="bang",
        )

        # when
        assert s3_client.delete("war.png") is True

        # then
        assert s3_client.get("war.png") is None
        with pytest.raises(ClientError) as exc:
            s3_client.boto.head_object(
                Bucket=s3_client.bucket, Key=os.path.join(s3_client.prefix, "war.png")
            )
        assert exc.value.response["Error"]["Code"] == "404" 
开发者ID:MichaelAquilina,项目名称:S4,代码行数:20,代码来源:test_s3.py

示例12: s3_request

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ClientError [as 别名]
def s3_request(func):
    """
    Wrapper function for s3 requests in order to create more helpful error
    messages.
    """

    @wraps(func)
    def wrapper(url, *args, **kwargs):
        try:
            return func(url, *args, **kwargs)
        except ClientError as exc:
            if int(exc.response["Error"]["Code"]) == 404:
                raise EnvironmentError(f"file {url} not found")
            else:
                raise

    return wrapper 
开发者ID:huggingface,项目名称:neuralcoref,代码行数:19,代码来源:file_utils.py

示例13: delete_subs

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ClientError [as 别名]
def delete_subs(ec2, args):
  """
  Delete the subnets
  """

  try:
    subs = ec2.describe_subnets(**args)['Subnets']
  except ClientError as e:
    print(e.response['Error']['Message'])

  if subs:
    for sub in subs:
      sub_id = sub['SubnetId']

      try:
        result = ec2.delete_subnet(SubnetId=sub_id)
      except ClientError as e:
        print(e.response['Error']['Message'])

  return 
开发者ID:toddm92,项目名称:vpc-delete,代码行数:22,代码来源:remove_vpc.py

示例14: delete_rtbs

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ClientError [as 别名]
def delete_rtbs(ec2, args):
  """
  Delete the route tables
  """

  try:
    rtbs = ec2.describe_route_tables(**args)['RouteTables']
  except ClientError as e:
    print(e.response['Error']['Message'])

  if rtbs:
    for rtb in rtbs:
      main = 'false'
      for assoc in rtb['Associations']:
        main = assoc['Main']
      if main == True:
        continue
      rtb_id = rtb['RouteTableId']
        
      try:
        result = ec2.delete_route_table(RouteTableId=rtb_id)
      except ClientError as e:
        print(e.response['Error']['Message'])

  return 
开发者ID:toddm92,项目名称:vpc-delete,代码行数:27,代码来源:remove_vpc.py

示例15: delete_acls

# 需要导入模块: from botocore import exceptions [as 别名]
# 或者: from botocore.exceptions import ClientError [as 别名]
def delete_acls(ec2, args):
  """
  Delete the network access lists (NACLs)
  """

  try:
    acls = ec2.describe_network_acls(**args)['NetworkAcls']
  except ClientError as e:
    print(e.response['Error']['Message'])

  if acls:
    for acl in acls:
      default = acl['IsDefault']
      if default == True:
        continue
      acl_id = acl['NetworkAclId']

      try:
        result = ec2.delete_network_acl(NetworkAclId=acl_id)
      except ClientError as e:
        print(e.response['Error']['Message'])

  return 
开发者ID:toddm92,项目名称:vpc-delete,代码行数:25,代码来源:remove_vpc.py


注:本文中的botocore.exceptions.ClientError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。