Skip to content

Commit c3ebaa5

Browse files
committed
Modify terminate-instance on windows to stop the agent earlier, but restart it if needed
1 parent d2927cf commit c3ebaa5

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

packer/windows/conf/buildkite-agent/scripts/terminate-instance.ps1

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,18 @@ $Token = (Invoke-WebRequest -UseBasicParsing -Method Put -Headers @{'X-aws-ec2-m
33
$InstanceId = (Invoke-WebRequest -UseBasicParsing -Headers @{'X-aws-ec2-metadata-token' = $Token} http://169.254.169.254/latest/meta-data/instance-id).content
44
$Region = (Invoke-WebRequest -UseBasicParsing -Headers @{'X-aws-ec2-metadata-token' = $Token} http://169.254.169.254/latest/meta-data/placement/region).content
55

6+
Write-Output "terminate-instance: disconnecting agent..."
7+
nssm stop buildkite-agent
8+
69
Write-Output "terminate-instance: requesting instance termination..."
710
aws autoscaling terminate-instance-in-auto-scaling-group --region "$Region" --instance-id "$InstanceId" "--should-decrement-desired-capacity" 2> $null
811

9-
if ($lastexitcode -eq 0) { # If autoscaling request was successful, we will terminate
10-
Write-Output "terminate-instance: disabling buildkite-agent service"
11-
nssm stop buildkite-agent
12+
# If autoscaling request was successful, we will terminate the instance, otherwise, if
13+
# BuildkiteTerminateInstanceAfterJob is set to true, we will mark the instance as unhealthy
14+
# so that the ASG will terminate it despite scale-in protection. Otherwise, we should not
15+
# terminate the instance, so we need to retart the agent.
16+
if ($lastexitcode -eq 0) {
17+
Write-Output "terminate-instance: terminating instance..."
1218
} else {
1319
Write-Output "terminate-instance: ASG could not decrement (we're already at minSize)"
1420
if ($Env:BUILDKITE_TERMINATE_INSTANCE_AFTER_JOB -eq "true") {
@@ -18,5 +24,8 @@ if ($lastexitcode -eq 0) { # If autoscaling request was successful, we will term
1824
--region "$Region" `
1925
--health-status Unhealthy `
2026
--no-should-respect-grace-period
27+
} else {
28+
Write-Output "terminate-instance: restarting agent..."
29+
nssm start buildkite-agent
2130
}
2231
}

0 commit comments

Comments
 (0)