Skip to content

Commit 3f84270

Browse files
committed
fix: force asg to scale down, target instances via asg tag
1 parent 4b17154 commit 3f84270

File tree

1 file changed

+35
-27
lines changed

1 file changed

+35
-27
lines changed

templates/aws-stack.yml

Lines changed: 35 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1769,6 +1769,14 @@ Resources:
17691769
Action:
17701770
- "autoscaling:DescribeAutoScalingGroups"
17711771
Resource: "*"
1772+
- PolicyName: ModifyASGs
1773+
PolicyDocument:
1774+
Version: 2012-10-17
1775+
Statement:
1776+
- Effect: Allow
1777+
Action:
1778+
- "autoscaling:UpdateAutoScalingGroup"
1779+
Resource: !Sub arn:${AWS::Partition}:autoscaling:${AWS::Region}:${AWS::AccountId}:autoScalingGroup:*:autoScalingGroupName/${AWS::StackName}-AgentAutoScaleGroup-*
17721780
- PolicyName: RunStopBuildkiteDocument
17731781
PolicyDocument:
17741782
Version: 2012-10-17
@@ -1810,23 +1818,19 @@ Resources:
18101818
18111819
def handler(event, context):
18121820
logger.info(f"Received event: {event}")
1813-
1821+
18141822
# only trigger on update upon replacement events
18151823
if event["RequestType"] == "Update":
18161824
try:
18171825
props = event["OldResourceProperties"]
18181826
autoscaling_group_name = props["AutoScalingGroupName"]
18191827
1820-
# Get all instances in the Auto Scaling group
1821-
instances = get_autoscaling_instances(autoscaling_group_name)
1822-
1823-
# Stop the Buikdite agent on each instance
1824-
if len(instances) == 0:
1825-
logger.info("No instances found in the Auto Scaling group.")
1826-
else:
1827-
logger.info(f"Stopping Buildkite agents on instances: {instances}")
1828-
stop_bk_agents(instances)
1829-
1828+
# Scale ASG down to zero, to allow Buildkite agents to terminate
1829+
force_instance_termination(autoscaling_group_name)
1830+
1831+
# Stop all Buildkite agents in the old ASG
1832+
stop_bk_agents(autoscaling_group_name)
1833+
18301834
# Send success response to CloudFormation
18311835
cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, "CustomResourcePhysicalID")
18321836
except Exception as e:
@@ -1836,25 +1840,29 @@ Resources:
18361840
# For Create and Delete events, just send success response
18371841
cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, "CustomResourcePhysicalID")
18381842
1839-
def get_autoscaling_instances(autoscaling_group_name):
1840-
"""Retrieve all instance IDs in the specified Auto Scaling group."""
1841-
logger.info(f"Retrieving instances in Auto Scaling group: {autoscaling_group_name}")
1842-
response = autoscaling_client.describe_auto_scaling_groups(
1843-
AutoScalingGroupNames=[autoscaling_group_name],
1844-
MaxRecords=1
1843+
def force_instance_termination(autoscaling_group_name):
1844+
"""Forces all EC2 instances to terminate in the specified Auto Scaling group by setting the desired capacity to zero."""
1845+
logger.info(f"Setting the desired capacity of {autoscaling_group_name} to zero")
1846+
autoscaling_client.update_auto_scaling_group(
1847+
AutoScalingGroupName=autoscaling_group_name,
1848+
MinSize=0,
1849+
DesiredCapacity=0
18451850
)
1846-
instances = []
1847-
for instance in response["AutoScalingGroups"][0]["Instances"]:
1848-
instances.append(instance["InstanceId"])
1849-
logger.info(f"Instances in Auto Scaling group {autoscaling_group_name}: {instances}")
1850-
return instances
1851-
1852-
def stop_bk_agents(instances):
1853-
"""Gracefully terminates the Buildkite agent running on the given instances."""
1854-
logger.info(f"Running agent termination command on {instances}")
1851+
1852+
def stop_bk_agents(autoscaling_group_name):
1853+
"""Gracefully terminates Buildkite agents running in the given Auto Scaling Group."""
1854+
stack_name = autoscaling_group_name.split("-AgentAutoScaleGroup")[0]
1855+
1856+
logger.info(f"Stopping BK agents in {stack_name}")
18551857
response = ssm_client.send_command(
1856-
InstanceIds=instances,
1858+
Targets=[
1859+
{
1860+
"Key": "tag:aws:autoscaling:groupName",
1861+
"Values": [autoscaling_group_name]
1862+
}
1863+
],
18571864
DocumentName="AWS-RunShellScript",
1865+
Comment=f"Stopping BK agents in {stack_name}",
18581866
Parameters={
18591867
"commands": ["sudo kill -s SIGTERM $(/bin/pidof buildkite-agent)"]
18601868
}

0 commit comments

Comments
 (0)