You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用AWS Boto3调用create_vpc_attachment传参合法仍报输入错误

AWS CreateVpcAttachment ValidationException 输入错误排查

使用Boto3调用create_vpc_attachment API将VPC附加到核心网络时,持续收到错误:

调用CreateVpcAttachment操作时出现ValidationException错误:输入不正确。

已验证CoreNetworkId、子网ARN(通过API获取)均正确,仅VPC ARN为代码生成。

代码实现

def create_vpc_attachment(network_manager_client, core_network_id, vpc_id, subnet_arns, region, account_id, poll_interval=60, max_retries=20):
    retries = 0
    try:
        # Ensure the correct ARN format for VPC
        vpc_arn = f'arn:aws:ec2:{region}:{account_id}:vpc/{vpc_id}'
        
        # Fetch existing VPC attachments for the specified region
        existing_attachments = network_manager_client.list_attachments(
            CoreNetworkId=core_network_id,
            AttachmentType='VPC',
            EdgeLocation=region
        )

        match_found = False 

        # Check if any existing attachments are found
        if existing_attachments.get('Attachments'):

            for attachment in existing_attachments['Attachments']:
                if attachment['ResourceArn'] == vpc_arn:
                    match_found = True
                    attachment_id = attachment['AttachmentId']
                    state = attachment['State']

                    # If VPC is already attached and available, return the state
                    if state == 'AVAILABLE':
                        logger.info(f"VPC {vpc_id} is already attached with ID: {attachment_id} in state {state}.")
                        return state
                    else:
                        logger.info(f"VPC {vpc_id} is  {state}.")
                        return state
                    
            if not match_found:
                logger.info(f"No matching attachment found for VPC {vpc_id}. Proceeding to create a new attachment.")

        if not match_found:
            # No existing attachment found, proceed to create a new one
            try:
                logger.info("Creating a VPC attachment.")

                # Log all the input parameters to ensure they are correct
                logger.info(f"CoreNetworkId: {core_network_id}")
                logger.info(f"VpcArn: {vpc_arn}")
                logger.info(f"SubnetArns: {subnet_arns}")

                response = network_manager_client.create_vpc_attachment(
                    CoreNetworkId=core_network_id,
                    VpcArn=vpc_arn,
                    SubnetArns=subnet_arns,
                    Options={'Ipv6Support': False},
                    Tags=[
                        {'Key': 'Env', 'Value': 'prod'},
                        {'Key': 'Name', 'Value': f'{account_id}-attachment-{vpc_id}'}
                    ]
                )

                # Extract the newly created VPC attachment details
                vpc_attachment = response.get('VpcAttachment', {})
                attachment = vpc_attachment.get('Attachment', {})
                attachment_id = attachment.get('AttachmentId')
                state = attachment.get('State')

            except Exception as e:
                logger.error(f"Error creating VPC attachment: {e}")
                sys.exit(1)

            while retries < max_retries:
                try:
                    # Fetch the current VPC attachment status
                    response = network_manager_client.get_vpc_attachment(AttachmentId=attachment_id)
                    attachment = response['VpcAttachment']['Attachment']
                    state = attachment.get('State')

                    logger.info(f"Current attachment state: {state}")

                    if state == 'AVAILABLE':
                        logger.info(f"VPC {attachment_id} is now AVAILABLE.")
                        return state  # Return the successful attachment details
                    elif state == 'FAILED':
                        logger.error(f"VPC {attachment_id} failed. Exiting.")
                        sys.exit(1)

                    # Sleep for the specified poll interval before checking again
                    time.sleep(poll_interval)
                    retries += 1

                except Exception as e:
                    logger.error(f"Error while checking attachment state: {e}")
                    sys.exit(1)

            logger.error(f"Max retries reached. VPC Attachment {attachment_id} is still not 'AVAILABLE'.")
            sys.exit(1)

    except Exception as e:
        logger.error(f"Error creating VPC attachment: {e}")
        logger.error(f"Full exception: {str(e)}")
        sys.exit(1)

日志输出

INFO - CoreNetworkId: core-network-*
INFO - VpcArn: arn:aws:ec2:myregion:*:vpc/vpc-*
INFO - SubnetArns: ['arn:aws:ec2:myregion:*:subnet/subnet-1*',  'arn:aws:ec2:myregion:*:subnet/subnet-2*','arn:aws:ec2:myregion:*:subnet/subnet-3*']
ERROR - Error creating VPC attachment: An error occurred (ValidationException) when calling the CreateVpcAttachment operation: Incorrect input.

排查方向

  • VPC ARN有效性:日志中VPC ARN的账号部分为*,确认实际传入的account_id是12位有效数字,若为空或占位符会导致ARN无效。
  • 子网一致性:确保所有子网ARN属于目标VPC,且子网处于可用状态,不存在跨VPC的子网传入。
  • 跨账号/区域限制:若Core Network与VPC不在同一账号,需配置资源共享授权;Core Network边缘位置必须覆盖VPC所在区域。
  • 参数格式检查:确认Options中的Ipv6Support是布尔值而非字符串;Tags的Value长度不超过256字符,无非法特殊字符。
  • 附件状态冲突:扩展现有附件检查逻辑,过滤CREATING/UPDATING等非终态的附件,避免重复创建请求触发错误。
  • IAM权限:验证SDK使用的角色拥有networkmanager:CreateVpcAttachment权限,以及对目标VPC、子网的访问权限。

内容的提问来源于stack exchange,提问作者Palma palermo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 13:10:55