ng1404
ng1404

Reputation: 81

Cannot Delete Amazon ECS Cluster using CloudFormation

I am using the following CloudFormation template to create ECS Cluster.

AWSTemplateFormatVersion: '2010-09-09'
Description: 'AWS Cloudformation Template to create the Infrastructure'
Resources:
  ECSCluster:
    Type: AWS::ECS::Cluster
    Properties:
    ClusterName: 'Blog-iac-test-1'
  EC2InstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
    Path: /
    Roles: [!Ref 'EC2Role']
  ECSAutoScalingGroup:
    Type: AWS::AutoScaling::AutoScalingGroup
  Properties:
    VPCZoneIdentifier:
    - subnet-****
    LaunchConfigurationName: !Ref 'ECSAutoscalingLC'
    MinSize: '1'
    MaxSize: '2'
    DesiredCapacity: '1'
 ECSAutoscalingLC:
    Type: AWS::AutoScaling::LaunchConfiguration
    Properties:
      AssociatePublicIpAddress: true
      ImageId: 'ami-b743bed1'
      SecurityGroups:
      - sg-****
      InstanceType: 't2.micro'
      IamInstanceProfile: !Ref 'EC2InstanceProfile'
      KeyName: 'test'
      UserData:
        Fn::Base64: !Sub |
        #!/bin/bash -xe
        echo ECS_CLUSTER=Blog-iac-test-1 >> /etc/ecs/ecs.config
  EC2Role:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
      Statement:
      - Effect: Allow
      Principal:
        Service: [ec2.amazonaws.com]
        Action: ['sts:AssumeRole']
      Path: /
  ECSServicePolicy:
    Type: "AWS::IAM::Policy"
    Properties: 
      PolicyName: "root"
      PolicyDocument: 
        Version: "2012-10-17"
        Statement: 
        - Effect: Allow
        Action: ['ecs:*', 'logs:*', 'ecr:*', 's3:*']
        Resource: '*'
    Roles: [!Ref 'EC2Role']

The stack is created successfully, but while destroying, I am getting the following error:
The Cluster cannot be deleted while Container Instances are active or draining.

I was able to delete the stack earlier, this issue started to occur recently. What could be a workaround to avoid this issue ? Should I need to add some dependencies ?

Upvotes: 7

Views: 2545

Answers (1)

st_rt_dl_8
st_rt_dl_8

Reputation: 317

As mentioned in this AWS Documentation Link, have you tried deregistering the instances as well?:

Deregister Container Instances: Before you can delete a cluster, you must deregister the container instances inside that cluster. For each container instance inside your cluster, follow the procedures in Deregister a Container Instance to deregister it.

Alternatively, you can use the following AWS CLI command to deregister your container instances. Be sure to substitute the Region, cluster name, and container instance ID for each container instance that you are deregistering.

aws ecs deregister-container-instance --cluster default --container-instance container_instance_id --region us-west-2 --force

Upvotes: 5

Related Questions