Skip to content

Instantly share code, notes, and snippets.

@kszarek
Created December 25, 2017 18:06
Show Gist options
  • Save kszarek/11544ee5196ca9a7609fba403a0382c0 to your computer and use it in GitHub Desktop.
Save kszarek/11544ee5196ca9a7609fba403a0382c0 to your computer and use it in GitHub Desktop.
Terraform - graceful shutdown on AWS
resource "aws_sqs_queue" "graceful_termination_queue" {
name = "graceful_termination_queue"
}
resource "aws_iam_role" "autoscaling_role" {
name = "autoscaling_role"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "autoscaling.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
EOF
}
resource "aws_iam_role_policy" "lifecycle_hook_autoscaling_policy" {
name = "lifecycle_hook_autoscaling_policy"
role = "${aws_iam_role.autoscaling_role.id}"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt1436380187000",
"Effect": "Allow",
"Action": [
"sqs:GetQueueUrl",
"sqs:SendMessage"
],
"Resource": [
"*"
]
}
]
}
EOF
}
resource "aws_autoscaling_lifecycle_hook" "graceful_shutdown_asg_hook" {
name = "graceful_shutdown_asg"
autoscaling_group_name = "${aws_autoscaling_group.builder_asg.name}"
default_result = "CONTINUE"
hearbeat_timeout = 3600
lifecycle_transition = "autoscaling:EC2_INSTANCE_TERMINATING"
notification_target_arn = "${aws_sqs_queue.graceful_termination_queue.arn}"
role_arn = "${aws_iam_role.autoscaling_role.arn}"
}
output "sqs_queue_arn" {
value = "${aws_sqs_queue.graceful_termination_queue.arn}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment