Eugen Konkov
Eugen Konkov

Reputation: 25223

How to terminate EC2 instance if `user-data` script exits with not-zero status code?

So EC2 was created but user-data failed, eg. syntax error, some command failed etc.

How to terminate such instance automatically if a user-data run was not successful?

Upvotes: 0

Views: 231

Answers (1)

The DevOps Dude
The DevOps Dude

Reputation: 1937

If I were to come up with a solution to automatically terminate an EC2 instance if its user-data script fails, I’ll add error handling in the user-data script to terminate the instance using AWS CLI if any command fails. Something like this :

#!/bin/bash
set -e  # to stop script execution on any error

# Example command that might fail
let’s-assume-your-command-is-here || { 
    echo "Command failed"; 
    aws ec2 terminate-instances --instance-ids $(curl http://169.254.169.254/latest/meta-data/instance-id) --region $(curl http://169.254.169.254/latest/meta-data/placement/region); 
    exit 1; 
}

If you want to explore this approach, make sure to ensure the EC2 instance has an IAM role with permissions to terminate itself. It’ll need a policy like this:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "ec2:TerminateInstances",
            "Resource": "*" # you can make this more specific
        }
    ]
}

I’ll also suggest you test by simulating failures to ensure it terminates as expected.

  • Make sure AWS CLI is installed in the instance.
  • Consider implementing logging (to say S3 or CloudWatch) before termination for debugging purposes.

This is how I’ll approach this scenario. Hope it helps.

Upvotes: 2

Related Questions