Skip to content

Instantly share code, notes, and snippets.

@huevos-y-bacon
Last active August 7, 2024 10:32
Show Gist options
  • Save huevos-y-bacon/54c80333d73449bbffbf8e595e03e30c to your computer and use it in GitHub Desktop.
Save huevos-y-bacon/54c80333d73449bbffbf8e595e03e30c to your computer and use it in GitHub Desktop.
AWS EC2 - Enable or disable EC2 instance "Termination Protection" via AWS CLI (shell)

Loop through all EC2 instances (excluding terminated and spot) and enable termination protection

for I in $(aws ec2 describe-instances --query \
  'Reservations[].Instances[?(InstanceLifecycle!=`spot` && InstanceState!=`terminated`)].[InstanceId]' \
  --output text); do
  aws ec2 modify-instance-attribute --disable-api-termination --instance-id $I;
done

Loop through all EC2 instances (excluding terminated and spot) and disable termination protection

for I in $(aws ec2 describe-instances --query \
  'Reservations[].Instances[?(InstanceLifecycle!=`spot` && InstanceState!=`terminated`)].[InstanceId]' \
  --output text); do
  aws ec2 modify-instance-attribute --no-disable-api-termination --instance-id $I;
done
@ystoneman
Copy link

It seems like disable-api-termination does not support spot and terminated instances, which makes sense. So for me, the following ensured no errors:

for I in $(aws ec2 describe-instances --query 'Reservations[*].Instances[?(InstanceLifecycle!=`spot` && InstanceState!=terminated)].[InstanceId]' --output text);
  do aws ec2 modify-instance-attribute --no-disable-api-termination --instance-id $I;
done

@huevos-y-bacon
Copy link
Author

Thanks for the comment!

I would assume that, if disable-api-termination doesn't work for spot|terminated instances, the same would go for no-disable-api-termination.

I'll update the gist

@douglaz
Copy link

douglaz commented Sep 27, 2023

missing backticks on terminated:

for I in $(aws ec2 describe-instances --query \
  'Reservations[].Instances[?(InstanceLifecycle!=`spot` && InstanceState!=`terminated`)].[InstanceId]' \
  --output text); do
  aws ec2 modify-instance-attribute --disable-api-termination --instance-id $I;
done

@TingyuShare
Copy link

TingyuShare commented May 8, 2024

great comment list

@huevos-y-bacon
Copy link
Author

missing backticks on terminated:

for I in $(aws ec2 describe-instances --query \
  'Reservations[].Instances[?(InstanceLifecycle!=`spot` && InstanceState!=`terminated`)].[InstanceId]' \
  --output text); do
  aws ec2 modify-instance-attribute --disable-api-termination --instance-id $I;
done

Missed this comment! Thanks, updated now

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment