AWS SDK (Boto3) create_vpc_attachment` 传递有效参数时调用失败并显示“输入错误”

问题描述 投票:0回答:1

我正在使用 AWS SDK (Boto3) 通过 create_vpc_attachment API 创建到核心网络的 VPC 连接。但是,我不断收到以下错误:

创建VPC附件时出错:调用CreateVpcAttachment操作时发生错误(ValidationException):输入错误。

这是我的代码:

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)

我已经测试了所有变量和arns,输出示例是:

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.

我在代码的很多地方使用了 corenetwork id - 这个值 100% 正确。 从 api 调用检索子网,这不应该是问题。 只有一件事是 - 我在代码中生成了 vpc arn。

python amazon-web-services boto3
1个回答
0
投票

在故障排除过程中,我注意到使用 AWS CLI 而不是 Boto3 的输出略有不同。我尝试在 EC2 客户端和网络管理器的同一帐户中运行该脚本,并且它有效。 Boto3 似乎正在执行检查以确保核心网络和 VPC 位于同一帐户中,但它抛出了一个不正确的错误,表明“输入错误”。

© www.soinside.com 2019 - 2024. All rights reserved.