【问题标题】:CloudFormation stack deletion failing to remove VPCCloudFormation 堆栈删除无法删除 VPC
【发布时间】:2019-09-01 14:56:21
【问题描述】:

我通过 CLOUDFORMATION 创建了包含 EC2、Redshift、VPC 等集合的 aws 基础架构。现在我想以相反的顺序删除它。例。所有资源都依赖于 VPC。最后应该删除 VPC。但不知何故,每个堆栈都在删除,但 VPC 堆栈没有通过 python BOTO3 删除。它显示了一些子网或网络接口依赖错误。但是当我尝试通过控制台删除时,它会成功删除它。 有没有人遇到过这个问题?

我试图删除附加到它的负载均衡器之类的所有内容。但 VPC 仍然没有删除。

【问题讨论】:

  • AWS 控制台会为您完成删除依赖项的工作。您能否解释一下,“我已尝试删除附加到它的负载均衡器之类的所有内容。但是它没有删除” - 负载均衡器没有删除或 VPC 是什么意思?
  • 我认为您可能有一些虚拟机,其 NIC 位于该 VPC 的子网中。尝试找出该 VPC 中的 NIC。 Cloudformation 删除通常会为您处理依赖项跟踪,因此它可能在您的 cloudformation 堆栈之外。
  • @gp42 我已经更新了问题。 VPC 没有删除
  • 您是否有在 VPC 中运行的 lambda?如果是,那么我可以为您提供一个 lambda,它可以清理所有关联的网络接口。我有一个类似的问题,我创建了使用自定义资源触发的 lambda
  • 是的@Biplob,我有在 VPC 中运行的 lambda。你能和我分享那个脚本吗?也许我可以试试。

标签: python-3.x amazon-web-services amazon-cloudformation boto3 amazon-vpc


【解决方案1】:

AWS CloudFormation 根据模板中的DependsOn 引用和资源之间的引用创建资源之间的依赖关系图。

然后它会尝试并行部署资源,但会考虑依赖关系。

例如,子网可能定义为:

Subnet1:
    Type: AWS::EC2::Subnet
    Properties:
      CidrBlock: 10.0.0.0/24
      VpcId: !Ref ProdVPC

在这种情况下,会显式引用ProdVPC,因此 CloudFormation 只会在创建ProdVPC 之后创建Subnet1。

当 CloudFormation 堆栈被删除时,会应用相反的逻辑。在这种情况下,Subnet1 将在ProdVPC 被删除之前被删除。

但是,CloudFormation 不知道在堆栈外部创建的资源。这意味着如果在子网内创建资源(例如 Amazon EC2 实例),则堆栈删除将失败,因为当有 EC2 实例使用子网时(或者更准确地说,附加了一个 ENI),子网不能被删除。

在这种情况下,您需要手动删除导致“删除失败”的资源,然后再次尝试删除命令。

查找此类资源的一个好方法是查看 EC2 管理控制台的网络接口部分。确保没有接口连接到 VPC。

【讨论】:

  • +1 约翰。所以,假设我删除了使用 VPC 的资源。那么,通过具有此类依赖关系的 python boto3 删除 VPC 的正确方法是什么。
  • 您应该可以再次尝试删除堆栈。那应该删除 VPC。但是,如果在未移除 VPC 的情况下删除了堆栈,您可以发出 delete_subnet() 和 delete_vpc() 命令。 AWS CloudFormation 只是调用普通 API 来创建/删除资源,因此您可以做同样的事情。
  • 感谢@John 的回复。问题已经解决了。首先,我删除了所有负载均衡器,然后删除了安全组规则和组。然后我将 time.sleep 设置为 300 秒以自动分离网络接口。之后就可以成功删除VPC了。
【解决方案2】:

正如您指定的那样,您在删除包含 lambdas 的堆栈中的 VPC 时遇到问题,这些 lambdas 本身就在 VPC 中,这很可能是因为 lambdas 生成的网络接口连接到 VPC 中的其他资源。

从技术上讲,当从堆栈中取消部署 lambda 时,应该自动删除这些网络接口,但根据我的经验,我观察到孤立的 ENI,它不允许取消部署 VPC。

出于这个原因,我创建了一个自定义资源支持的 lambda,它在取消部署 VPC 中的所有 lambda 后清理 ENI。

这是您设置自定义资源并传递 VPC ID 的云形成部分

##############################################
#                                            #
#  Custom resource deleting net interfaces   #
#                                            #
##############################################

  NetInterfacesCleanupFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src
      Handler: cleanup/network_interfaces.handler
      Role: !GetAtt BasicLambdaRole.Arn
      DeploymentPreference:
        Type: AllAtOnce
      Timeout: 900

  PermissionForNewInterfacesCleanupLambda:
    Type: AWS::Lambda::Permission
    Properties:
      Action: lambda:invokeFunction
      FunctionName:
        Fn::GetAtt: [ NetInterfacesCleanupFunction, Arn ]
      Principal: lambda.amazonaws.com

  InvokeLambdaFunctionToCleanupNetInterfaces:
    DependsOn: [PermissionForNewInterfacesCleanupLambda]
    Type: Custom::CleanupNetInterfacesLambda
    Properties:
      ServiceToken: !GetAtt NetInterfacesCleanupFunction.Arn
      StackName: !Ref AWS::StackName
      VPCID:
        Fn::ImportValue: !Sub '${MasterStack}-Articles-VPC-Ref'
      Tags:
        'owner': !Ref StackOwner
        'task': !Ref Task

这是对应的 lambda。此 lambda 尝试 3 次分离和删除孤立的网络接口,如果不能,则失败,这意味着仍有一个 lambda 正在生成新的网络接口,您需要为此进行调试。

import boto3
from botocore.exceptions import ClientError
from time import sleep

# Fix this wherever your custom resource handler code is
from common import cfn_custom_resources as csr
import sys

MAX_RETRIES = 3
client = boto3.client('ec2')


def handler(event, context):

    vpc_id = event['ResourceProperties']['VPCID']

    if not csr.__is_valid_event(event, context):
        csr.send(event, context, FAILED, validate_response_data(result))
        return
    elif event['RequestType'] == 'Create' or event['RequestType'] == 'Update':
        result = {'result': 'Don\'t trigger the rest of the code'}
        csr.send(event, context, csr.SUCCESS, csr.validate_response_data(result))
        return
    try:
        # Get all network intefaces for given vpc which are attached to a lambda function
        interfaces = client.describe_network_interfaces(
            Filters=[
                {
                    'Name': 'description',
                    'Values': ['AWS Lambda VPC ENI*']
                },
                {
                    'Name': 'vpc-id',
                    'Values': [vpc_id]
                },
            ],
        )

        failed_detach = list()
        failed_delete = list()

        # Detach the above found network interfaces
        for interface in interfaces['NetworkInterfaces']:
            detach_interface(failed_detach, interface)

        # Try detach a second time and delete each simultaneously
        for interface in interfaces['NetworkInterfaces']:
            detach_and_delete_interface(failed_detach, failed_delete, interface)

        if not failed_detach or not failed_delete:
            result = {'result': 'Network interfaces detached and deleted successfully'}
            csr.send(event, context, csr.SUCCESS, csr.validate_response_data(result))
        else:
            result = {'result': 'Network interfaces couldn\'t be deleted completely'}
            csr.send(event, context, csr.FAILED, csr.validate_response_data(result))
            # print(response)
    except Exception:
        print("Unexpected error:", sys.exc_info())
        result = {'result': 'Some error with the process of detaching and deleting the network interfaces'}
        csr.send(event, context, csr.FAILED, csr.validate_response_data(result))


def detach_interface(failed_detach, interface):
    try:

        if interface['Status'] == 'in-use':
            detach_response = client.detach_network_interface(
                AttachmentId=interface['Attachment']['AttachmentId'],
                Force=True
            )

            # Sleep for 1 sec after every detachment
            sleep(1)

            print(f"Detach response for {interface['NetworkInterfaceId']}- {detach_response}")

            if 'HTTPStatusCode' not in detach_response['ResponseMetadata'] or \
                    detach_response['ResponseMetadata']['HTTPStatusCode'] != 200:
                failed_detach.append(detach_response)
    except ClientError as e:
        print(f"Exception details - {sys.exc_info()}")


def detach_and_delete_interface(failed_detach, failed_delete, interface, retries=0):

    detach_interface(failed_detach, interface)

    sleep(retries + 1)

    try:
        delete_response = client.delete_network_interface(
            NetworkInterfaceId=interface['NetworkInterfaceId'])

        print(f"Delete response for {interface['NetworkInterfaceId']}- {delete_response}")
        if 'HTTPStatusCode' not in delete_response['ResponseMetadata'] or \
                delete_response['ResponseMetadata']['HTTPStatusCode'] != 200:
            failed_delete.append(delete_response)
    except ClientError as e:
        print(f"Exception while deleting - {str(e)}")
        print()
        if retries <= MAX_RETRIES:
            if e.response['Error']['Code'] == 'InvalidNetworkInterface.InUse' or \
                    e.response['Error']['Code'] == 'InvalidParameterValue':
                retries = retries + 1
                print(f"Retry {retries} : Interface in use, deletion failed, retrying to detach and delete")
                detach_and_delete_interface(failed_detach, failed_delete, interface, retries)
            else:
                raise RuntimeError("Code not found in error")
        else:
            raise RuntimeError("Max Number of retries exhausted to remove the interface")

指向 lambda 的链接是 https://gist.github.com/revolutionisme/8ec785f8202f47da5517c295a28c7cb5

有关在 VPC 中配置 lambda 的更多信息 - https://docs.aws.amazon.com/lambda/latest/dg/vpc.html

【讨论】:

  • 感谢@Biplob 的回复。问题已经解决了。首先,我删除了所有负载均衡器,然后删除了安全组规则和组。然后我将 time.sleep 设置为 300 秒以自动分离网络接口。之后就可以成功删除VPC了。
猜你喜欢
  • 2018-11-23
  • 2021-03-15
  • 1970-01-01
  • 2020-10-15
  • 1970-01-01
  • 2018-03-24
  • 2021-12-18
  • 1970-01-01
  • 2018-08-07
相关资源
最近更新 更多