@@ -3,12 +3,18 @@ $Token = (Invoke-WebRequest -UseBasicParsing -Method Put -Headers @{'X-aws-ec2-m
3
3
$InstanceId = (Invoke-WebRequest - UseBasicParsing - Headers @ {' X-aws-ec2-metadata-token' = $Token } http:// 169.254 .169.254 / latest/ meta- data/ instance- id).content
4
4
$Region = (Invoke-WebRequest - UseBasicParsing - Headers @ {' X-aws-ec2-metadata-token' = $Token } http:// 169.254 .169.254 / latest/ meta- data/ placement/ region).content
5
5
6
+ Write-Output " terminate-instance: disconnecting agent..."
7
+ nssm stop buildkite- agent
8
+
6
9
Write-Output " terminate-instance: requesting instance termination..."
7
10
aws autoscaling terminate- instance- in- auto- scaling- group -- region " $Region " -- instance- id " $InstanceId " " --should-decrement-desired-capacity" 2> $null
8
11
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..."
12
18
} else {
13
19
Write-Output " terminate-instance: ASG could not decrement (we're already at minSize)"
14
20
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
18
24
-- region " $Region " `
19
25
-- health- status Unhealthy `
20
26
-- no- should- respect- grace- period
27
+ } else {
28
+ Write-Output " terminate-instance: restarting agent..."
29
+ nssm start buildkite- agent
21
30
}
22
31
}
0 commit comments