The following assumes:
- Your servers are launched using an Auto Scaling Group and are auto joined to an Active Directory domain using the AWS Instance Id as its hostname. Please see this post for details on how to accomplish this - Auto Join EC2 instances to domain
- An EC2 windows instance that has
- An IAM role assigned to the instance
- The AWS CLI installed on the instance
- Access to the Active Directory domain
1. Create the SQS queueWithin AWS, create a new SQS queue. Be sure to set the message retention period to a value greater than how often you plan to run the scheduled powershell script. We will set the permissions in a later step, after we've created the SNS topic.
2. Create the SNS topic
Create a new SNS topic in AWS and add a subscription to the SNS topic selecting 'Amazon SQS' as the endpoint, ie: arn:aws:sqs:us-east-1:123456789012:SQS-InstanceTerminations
3. Configure the SQS queue permissionsReturn to the SQS created in the prior step and select the Permissions tab. Add/Modify the permissions to allow SQS:SendMessage from the SNS topic you just created. Modify the below policy to use your SNS ARN and the SQS ARN resource.
4. Configure the notification for the Auto Scaling GroupSelect your Auto Scaling Group and choose the 'Notifications' tab and then 'Create notification'.
For the notification choose the option 'terminate' and select the SNS topic created earlier.
5. Configure the IAM roleThe EC2 instance that will be running our Powershell cleanup script requires permissions to access the SQS queue. To allow this, configure a security policy for the IAM role that is attached to the instance. Modify the policy below for the Resource ARN to match your SQS ARN.
6. Create the Powershell script to retrieve the SQS messagesPowershell is used to obtain the SQS messages of the terminated instances and then removes the terminated servers from Active Directory. Save the script on the server that will run the scheduled task.
Here is the script for the complete process. Modify this script to use your SQS queue name.