0

I would like to (1) launch an AWS EC2 instance, (2) run a shell script (that sends output to an S3 bucket) and (3) terminate the instance automatically when the script terminates, all remotely without logging into the instance. I have managed to get parts (1) and (2) working using the AWS CLI commands aws ec2 run-instances and aws ssm send-command. I am struggling with part (3) - getting the instance to terminate automatically when the script completes.

I have seen in the AWS docs that you can use CloudWatch to monitor the SSM Run Command status, and I thought that this might be a solution - when the status changes, terminate the instance. Is this a feasible option? If so, how do you implement it using AWS CLI?

Miguel
  • 416
  • 3
  • 16
  • have you tried the `aws ec2 terminate-instances --instance-ids i-1234567890abcdef01` – error404 Nov 20 '19 at 13:58
  • Yes - but that doesn't terminate the instance _automatically_ when the script completes. You would need to check that the script has finished running, and then execute the command `aws ec2 terminate-instances`. If you run `aws ssm send-command` followed immediately by `aws ec2 terminate-instances`, I think you may end up terminating the instance before the job has completed, particularly if it's a long job. This is what I am trying to avoid. – Miguel Nov 20 '19 at 14:04
  • 1
    What are you actually trying to accomplish? There are far easier ways to perform an action than starting and terminating an EC2 instance. You could probably save money as well. – Mats Lannér Nov 20 '19 at 17:14
  • I agree with @MatsLannér If you can tell us what you are doing, there might be an easier way. Maybe even putting it up as a Lambda Function as it sounds like what you trying to do would work great there and save you money from having to spin up and down an instance. – DC.Skells Nov 20 '19 at 18:10

1 Answers1

2

Within the ssm script, you can issue a command to the operating system to shutdown the computer. If you launched the instance with a Shutdown behavior of Terminate, then this will terminate the instance.

Alternatively, the script can retrieve the Instance ID of the instance it is running on, and issue the aws ec2 terminate-instances command, specifying its own Instance ID.

See: Self-Terminating AWS EC2 Instance?

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470