I am creating AWS stack with cloudformation. I am creating EBS volumes as part of the Cloud Formation and attaching them to EC2 in bootstrap.
The creation part works fine. However, while deleting the stack, Cloudformation is trying to delete the EBS volumes first. As the volumes are already attached, it is failing to delete and deleting remaining resources.
Because of this, EBS volumes are staying there unless delete manually or use delete stack again.
Is there a way i can specify the order when Deletion(only) for the resources in cloudformation template.?
The only mechanism you have to control the order of CloudFormation operations is using DependsOn. But that won't solve this particular problem.
The problem you describe here occurs because CloudFormation doesn't know that the volume is attached: you attached it through a separate mechanism (as you described, using EC2 bootstrap, which I assume would be something like an aws command on the EC2 Instance User Data script, for example).
What you could do, instead, is have CloudFormation attach the volume for you. That way, CloudFormation knows that the volume has been attached, and it knows that it has to detach the volume, too.
To do that, you need to use a resource of type AWS::EC2::VolumeAttachment. A YAML snippet for that would be something like:
Resources:
MyInstance:
Type: AWS::EC2::Instance
Properties:
...
MyVolume:
Type: AWS::EC2::Volume
Properties:
...
MyVolumeAttachment:
Type: AWS::EC2::VolumeAttachment
Properties:
Device: /dev/sdf
InstanceId: !Ref MyInstance
VolumeId: !Ref MyVolume
There are quite a few *Attachment resource types on CFN, for this exact purpose: you let CFN attach the resource to you, you specify a Ref to the resources that participate in the attachment, so CFN knows the "order" (ie, it first create the 2 resources, then attach them, or when deleting, it first detaches, then deletes both resources) and CFN can then handle the entire process for your.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With