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.