user5402945
user5402945

Reputation: 165

Create and delete EC2 instance with CloudFormation

I am quite new to AWS and want to know how to achieve following task with CloudFormation.

I want to spin up an EC2 instance with tomcat and deploy a java application on it. This java application will perform some operation. Once the operation is done, I want to delete all the resources created by this CloudFormation stack.

All these activities should be automatic. For example -- I will create the CloudFormation stack JSON file. At particular time of a day, a job should be kicked off (I don't know where in AWS to configure such job or how). But I know through Jenkins we can create a CloudFormation stack that will create all resources.

Then, after some time (lets say 2 hrs), another job should kick off and delete all resources created by CloudFormation.

Is this possible in AWS? If yes, any hints on how to do this?

Upvotes: 1

Views: 3617

Answers (3)

John Rotenstein
John Rotenstein

Reputation: 269340

If all you want is an EC2 instance, it's probably easier to simply create the EC2 instance rather than a CloudFormation stack.

  • Something (eg an AWS Lambda function triggered by Amazon CloudWatch Events) calls the EC2 API to create the instance
  • User Data is passed to the EC2 instance to install the desired software OR use a custom AMI with all software pre-installed
  • Have the instance terminate itself when it has finished processing -- this could be as simple as calling the Operating System to shutdown the machine, with the EC2 Shutdown Behavior set to Terminate.

Upvotes: 0

Miles
Miles

Reputation: 1732

Just to confirm, what you intend to do is have an EC2 instance get created on a schedule, and then have it shut down after 2 hours. The common way of accomplishing that is to use an Auto-Scaling Group (ASG) with a ScheduledAction to scale up and a ScheduledAction to scale down.

ASGs have a "desired capacity" (the number of instances in the ASG). You would want this to be "0" by default, change it to "1" at your desired time, and change it back to "0" two hours after that. What that will do is automatically start and subsequently terminate your EC2 instance on your schedule.

They also use a LaunchConfiguration, which is a template for your EC2 instances that will start on the schedule.

MyASG: 
  Type: AWS::AutoScaling::AutoScalingGroup
  Properties: 
    AvailabilityZones: !GetAZs !Ref "AWS::Region"
    LaunchConfigurationName: !Ref MyLaunchConfiguration
    MaxSize: 1
    MinSize: 0
    DesiredCapacity: 0

ScheduledActionUp: 
  Type: AWS::AutoScaling::ScheduledAction
  Properties:
    AutoScalingGroupName: !Ref MyASG
    DesiredCapacity: 1
    Recurrence: "0 7 * * *"

ScheduledActionDown: 
  Type: AWS::AutoScaling::ScheduledAction
  Properties:
    AutoScalingGroupName: !Ref MyASG
    DesiredCapacity: 0
    Recurrence: "0 9 * * *"

MyLaunchConfiguration:
  Type: AWS::AutoScaling::LaunchConfiguration
  Properties:
    ImageId:  ami-xxxxxxxxx # <-- Specify the AMI ID that you want
    InstanceType: t2.micro # <-- Chaneg the instance size if you want
    KeyName: my-key # <-- Change to the name of an EC2 SSH key that you've added
    UserData: 
      Fn::Base64: !Sub |
        #!/bin/bash
        yum install -y aws-cfn-bootstrap
        # ...
        # ... run some commands to set up the instance, if you need to
        # ...
  Metadata:
    AWS::CloudFormation::Init:
      config:
        files:
          "/etc/something/something.conf":
            mode: 000600
            owner: root
            group: root
            content: !Sub |
              #
              # Add the content of a config file, if you need to
              #

Depending on what you want your instances to interact with, you might also need to add a Security Group and/or an IAM Instance Profile along with an IAM Role.

If you're using Jenkins to deploy the program that will run, you would add a step to bake an AMI, build and push a docker image, or take whatever other action you need to deploy your application to the place that it will be used by your instance.

I note that in your question you say that you want to delete all of the resources created by CloudFormation. Usually, when you deploy a stack like this, the stack remains deployed. The ASG will remain there until you decide to remove the stack, but it won't cost anything when you're not running EC2 instances. I think I understand your intent here, so the advice that I'm giving aligns with that.

Upvotes: 2

jarmod
jarmod

Reputation: 78653

You can use Lambda to execute events on a regular schedule.

Write a Lambda function that calls CloudFormation to create your stack of resources. You might even consider including a termination Lambda function in your CloudFormation stack and configure it to run on a schedule (2 hours after the stack was created) to delete the stack that the termination Lambda function itself is part of (have not tried this, but believe that it will work). Or you could trigger stack deletion from cron on the EC2 instance running your Java app, of course).

Upvotes: 0

Related Questions