Creating EC2 instance directly with serverless

Hey guys,

I was wondering if it is possible to create and deploy an EC2 instance directly via the serverless.yml file.

I tried looking for it online, but I haven’t found any resources for it. The only resource I found is: serverless.yml guide which doesn’t contain any info about this topic.

You should be able to create EC2 instances via resources. Here’s an example below:

# serverless.yml

service: usersCrud
provider: aws
functions:

resources: # CloudFormation template syntax
  Resources:
    YourEC2Instance:
      Type: AWS::EC2::Instance
      Properties: 
        ImageId: pickAnImageOrUseYourOwn
        KeyName: yourSshKeyName # This needs to be created manually. CloudFormation does not allow it
        InstanceType: t2.micro // pick whatever size you want
        SubnetId: // your subnetId
        SecurityGroupIds:
          - // your security group IDs

You can see the full documentation for all the options available to you here:
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html

Scroll down to the YAML section.

Hope this helps

Edit: Further, this is how you would define any resource that isn’t available to be created with the Serverless framework itself. Resources can be any AWS resource through raw Cloudformation.