Drift detection
CloudFormation as a service often refers to the term state. The state is basically inventory information that contains a pair of values: the logical resource name and the physical resource ID.
CloudFormation uses its state to understand which resources to create or update. If we create a stack with a resource with a logical name foo
, change the property of this resource (foo
) in a template, and run an update, then CloudFormation will change the corresponding physical resource in the account.
CloudFormation has a set of limitations. For example, it will not update the stack if we do not introduce changes to it. If we perform manual changes to the resource, then CloudFormation will change them only when we make changes to the template.
Developers had to rethink their way of managing the infrastructure once they started using CloudFormation, but we will get to that in the later chapters. For now, we would like to show you a feature that doesn't solve problems of manual intervention, but at least notifies us when they happen. This feature is called drift detection.
For this example, we will use the same template (Dummy IAM Role) as we did in the previous section:
$ aws cloudformation create-stack \ Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â --stack-name iamrole \ Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â --template-body file://IamRole.yaml \ Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â --capabilities CAPABILITY_IAM
After a while, we see our stack created:
Note the link on the right called Drifts. If we follow that link, we will see the Drifts menu and under that Drift status: NOT_CHECKED
. At the time of writing, we will have to run drift detection manually, so we need to run drift detection on our stack. After a while, we will see that everything is all right:
- I'm going to run
Detect stack drifts
and verify that my stack is compliant: - Now what we will do is add an extra policy to our role and rerun drift detection:
$ ROLENAME=$(aws cloudformation describe-stack-resources --stack-name iamrole --query "StackResources[0].PhysicalResourceId" --output text) $ aws iam attach-role-policy --role-name $ROLENAME --policy-arn "arn:aws:iam::aws:policy/AdministratorAccess"
- We can now detect drift again:
- If we check our IamRole resource and click on View drift details, we will see what exactly has been changed and differs from CloudFormation's state:
Now we have two options: either roll back the change to the resource manually or add any dummy property to the template and run update-stack
.
We've learned about CloudFormation drifts, how to run its drift detection, and the actions that must be taken afterward. But don't worry—we will revisit drifts again in the following chapters.