This command should work on any EC2. Then if it uses the instance ID, it should discover it.
            Asked
            
        
        
            Active
            
        
            Viewed 1,598 times
        
    2 Answers
5
            This is the AWS CLI command you have to use.
aws ec2 terminate-instances --instance-ids 'curl http://169.254.169.254/latest/meta-data/instance-id'
If you have Termination protection on you can disable it first from the command line and then use above command.
aws ec2-modify-instance-attribute --disable-api-termination false INSTANCEID
 
    
    
        Piyush Patil
        
- 14,512
- 6
- 35
- 54
- 
                    bare in mind that the instance need to have the termination protection off – sebamontini Sep 12 '16 at 15:29
- 
                    Can I use it to self terminate it? – Vitor Abella Sep 12 '16 at 15:35
- 
                    Self terminate? Means what you want to do? – Piyush Patil Sep 12 '16 at 15:36
- 
                    I'm using EC2. I write the script on EC2 and it terminates. – Vitor Abella Sep 12 '16 at 15:39
- 
                    You can create a bash script sh file. And then run that file when ever you want to terminate that instance. – Piyush Patil Sep 12 '16 at 15:41
- 
                    and how do I get the id from the EC2? – Vitor Abella Sep 12 '16 at 15:42
- 
                    Check my edited answer – Piyush Patil Sep 12 '16 at 15:43
- 
                    I think we are in the away. you understood that I want a one command to terminate it. but I get the error "You must specify a region. You can also configure your region by running "aws configure" – Vitor Abella Sep 12 '16 at 15:46
- 
                    @VitorAbella after you install the AWS CLI, just set the following 4 settings (Access key, secret key, region and output format) - see [here](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html) it only takes a minute. Then the AWS CLI is ready to go and the line of code in the answer will work! Very cool – stevec Jul 11 '19 at 05:32
- 
                    @error2007s are you able to explain ***why*** `aws ec2 terminate-instances --instance-ids 'curl http://169.254.169.254/latest/meta-data/instance-id'` works? What is the IP address in the curl request? – stevec Jul 11 '19 at 05:34
1
            
            
        you can curl the metadata of the instace to get the instanceId of itselff:
aws ec2 terminate-instances --instance-ids `curl http://169.254.169.254/latest/meta-data/instance-id`
PS:
bare in mind that the instance need to have the termination protection off
 
    
    
        sebamontini
        
- 360
- 2
- 10
- 
                    I did the aws configure but I got the error "An error occurred (UnauthorizedOperation) when calling the TerminateInstances operation: You are not authorized to perform this operation." – Vitor Abella Sep 12 '16 at 16:21
