cdkec2spotsimple

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 3, 2023 License: Apache-2.0 Imports: 11 Imported by: 0

README

cdk-ec2-spot-simple

CDK construct library to create EC2 Spot Instances simply.

Install

TypeScript/JavaScript
npm install cdk-ec2-spot-simple
Python
pip install cdk-ec2-spot-simple
.NET
dotnet add package TksSt.Cdk.Ec2SpotSimple
Java
<dependency>
    <groupId>st.tks.cdk</groupId>
    <artifactId>ec2-spot-simple</artifactId>
</dependency>
Go
go get github.com/tksst/cdk-ec2-spot-simple-go/

Usage

To set up a spot instance with default parameters, simply use "SpotInstance" instead of "ec2.Instance".

import { SpotInstance } from "cdk-ec2-spot-simple"
import * as ec2 from "aws-cdk-lib/ec2"

// Simple usage
new SpotInstance(this, "DefaultConfigSpotInstance", {
    // Required properties of "ec2.Instance"
    vpc: ec2.Vpc.fromLookup(this, "defaultVPC", { isDefault: true });,
    instanceType: ec2.InstanceType.of(ec2.InstanceClass.T3A, ec2.InstanceSize.NANO),
    machineImage: new ec2.AmazonLinuxImage(),
});

// Advanced usage
new SpotInstance(this, "StoppableSpotInstance", {
    // Required properties of "ec2.Instance"
    vpc: ec2.Vpc.fromLookup(this, "defaultVPC", { isDefault: true });,
    instanceType: ec2.InstanceType.of(ec2.InstanceClass.T3A, ec2.InstanceSize.NANO),
    machineImage: new ec2.AmazonLinuxImage(),
    // SpotInstance specific property
    spotOptions: {
        interruptionBehavior: ec2.SpotInstanceInterruption.STOP,
        requestType: ec2.SpotRequestType.PERSISTENT,
        maxPrice: 0.007,
    },
});

Background

The Instance construct in aws-cdk-lib/ec2 does not have any spot instance functionality.

This SpotInstance construct creates LaunchTemplate that is enabled spot request internally and associate with Instance.

Also, SpotInstance creates a Lambda-backed custom resource if the spot requiest type is PERSISTENT. That resource deletes the spot request when the stack is destroyed.

Documentation

Overview

CDK construct library to create EC2 Spot Instances simply.

CDK construct library to create EC2 Spot Instances simply.

CDK construct library to create EC2 Spot Instances simply.

CDK construct library to create EC2 Spot Instances simply.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewSpotInstance_Override

func NewSpotInstance_Override(s SpotInstance, scope constructs.Construct, id *string, props *SpotInstanceProps)

func SpotInstance_IsConstruct

func SpotInstance_IsConstruct(x interface{}) *bool

Checks if `x` is a construct.

Returns: true if `x` is an object created from a class which extends `Construct`. Deprecated: use `x instanceof Construct` instead.

func SpotInstance_IsResource

func SpotInstance_IsResource(construct constructs.IConstruct) *bool

Check whether the given construct is a Resource.

Types

type SpotInstance

type SpotInstance interface {
	awsec2.Instance
	// Allows specify security group connections for the instance.
	Connections() awsec2.Connections
	// The environment this resource belongs to.
	//
	// For resources that are created and managed by the CDK
	// (generally, those created by creating new class instances like Role, Bucket, etc.),
	// this is always the same as the environment of the stack they belong to;
	// however, for imported resources
	// (those obtained from static methods like fromRoleArn, fromBucketName, etc.),
	// that might be different than the stack they were imported into.
	Env() *awscdk.ResourceEnvironment
	// The principal to grant permissions to.
	GrantPrincipal() awsiam.IPrincipal
	// the underlying instance resource.
	Instance() awsec2.CfnInstance
	// The availability zone the instance was launched in.
	InstanceAvailabilityZone() *string
	// The instance's ID.
	InstanceId() *string
	// Private DNS name for this instance.
	InstancePrivateDnsName() *string
	// Private IP for this instance.
	InstancePrivateIp() *string
	// Publicly-routable DNS name for this instance.
	//
	// (May be an empty string if the instance does not have a public name).
	InstancePublicDnsName() *string
	// Publicly-routable IP  address for this instance.
	//
	// (May be an empty string if the instance does not have a public IP).
	InstancePublicIp() *string
	// The tree node.
	Node() constructs.Node
	// The type of OS the instance is running.
	OsType() awsec2.OperatingSystemType
	// Returns a string-encoded token that resolves to the physical name that should be passed to the CloudFormation resource.
	//
	// This value will resolve to one of the following:
	// - a concrete value (e.g. `"my-awesome-bucket"`)
	// - `undefined`, when a name should be generated by CloudFormation
	// - a concrete name generated automatically during synthesis, in
	//    cross-environment scenarios.
	PhysicalName() *string
	// The IAM role assumed by the instance.
	Role() awsiam.IRole
	// The stack in which this resource is defined.
	Stack() awscdk.Stack
	// UserData for the instance.
	UserData() awsec2.UserData
	// Add the security group to the instance.
	AddSecurityGroup(securityGroup awsec2.ISecurityGroup)
	// Adds a statement to the IAM role assumed by the instance.
	AddToRolePolicy(statement awsiam.PolicyStatement)
	// Add command to the startup script of the instance.
	//
	// The command must be in the scripting language supported by the instance's OS (i.e. Linux/Windows).
	AddUserData(commands ...*string)
	// Apply the given removal policy to this resource.
	//
	// The Removal Policy controls what happens to this resource when it stops
	// being managed by CloudFormation, either because you've removed it from the
	// CDK application or because you've made a change that requires the resource
	// to be replaced.
	//
	// The resource can be deleted (`RemovalPolicy.DESTROY`), or left in your AWS
	// account for data recovery and cleanup later (`RemovalPolicy.RETAIN`).
	ApplyRemovalPolicy(policy awscdk.RemovalPolicy)
	GeneratePhysicalName() *string
	// Returns an environment-sensitive token that should be used for the resource's "ARN" attribute (e.g. `bucket.bucketArn`).
	//
	// Normally, this token will resolve to `arnAttr`, but if the resource is
	// referenced across environments, `arnComponents` will be used to synthesize
	// a concrete ARN with the resource's physical name. Make sure to reference
	// `this.physicalName` in `arnComponents`.
	GetResourceArnAttribute(arnAttr *string, arnComponents *awscdk.ArnComponents) *string
	// Returns an environment-sensitive token that should be used for the resource's "name" attribute (e.g. `bucket.bucketName`).
	//
	// Normally, this token will resolve to `nameAttr`, but if the resource is
	// referenced across environments, it will be resolved to `this.physicalName`,
	// which will be a concrete name.
	GetResourceNameAttribute(nameAttr *string) *string
	// Returns a string representation of this construct.
	ToString() *string
}

This represents a single EC2 Spot instance and other necessary resources.

func NewSpotInstance

func NewSpotInstance(scope constructs.Construct, id *string, props *SpotInstanceProps) SpotInstance

type SpotInstanceProps

type SpotInstanceProps struct {
	// Type of instance to launch.
	InstanceType awsec2.InstanceType `field:"required" json:"instanceType" yaml:"instanceType"`
	// AMI to launch.
	MachineImage awsec2.IMachineImage `field:"required" json:"machineImage" yaml:"machineImage"`
	// VPC to launch the instance in.
	Vpc awsec2.IVpc `field:"required" json:"vpc" yaml:"vpc"`
	// Whether the instance could initiate connections to anywhere by default.
	//
	// This property is only used when you do not provide a security group.
	AllowAllOutbound *bool `field:"optional" json:"allowAllOutbound" yaml:"allowAllOutbound"`
	// In which AZ to place the instance within the VPC.
	AvailabilityZone *string `field:"optional" json:"availabilityZone" yaml:"availabilityZone"`
	// Specifies how block devices are exposed to the instance. You can specify virtual devices and EBS volumes.
	//
	// Each instance that is launched has an associated root device volume,
	// either an Amazon EBS volume or an instance store volume.
	// You can use block device mappings to specify additional EBS volumes or
	// instance store volumes to attach to an instance when it is launched.
	// See: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html
	//
	BlockDevices *[]*awsec2.BlockDevice `field:"optional" json:"blockDevices" yaml:"blockDevices"`
	// Whether "Detailed Monitoring" is enabled for this instance Keep in mind that Detailed Monitoring results in extra charges.
	// See: http://aws.amazon.com/cloudwatch/pricing/
	//
	DetailedMonitoring *bool `field:"optional" json:"detailedMonitoring" yaml:"detailedMonitoring"`
	// Apply the given CloudFormation Init configuration to the instance at startup.
	Init awsec2.CloudFormationInit `field:"optional" json:"init" yaml:"init"`
	// Use the given options for applying CloudFormation Init.
	//
	// Describes the configsets to use and the timeout to wait.
	InitOptions *awsec2.ApplyCloudFormationInitOptions `field:"optional" json:"initOptions" yaml:"initOptions"`
	// The name of the instance.
	InstanceName *string `field:"optional" json:"instanceName" yaml:"instanceName"`
	// Name of SSH keypair to grant access to instance.
	KeyName *string `field:"optional" json:"keyName" yaml:"keyName"`
	// Defines a private IP address to associate with an instance.
	//
	// Private IP should be available within the VPC that the instance is build within.
	PrivateIpAddress *string `field:"optional" json:"privateIpAddress" yaml:"privateIpAddress"`
	// Propagate the EC2 instance tags to the EBS volumes.
	PropagateTagsToVolumeOnCreation *bool `field:"optional" json:"propagateTagsToVolumeOnCreation" yaml:"propagateTagsToVolumeOnCreation"`
	// Whether IMDSv2 should be required on this instance.
	RequireImdsv2 *bool `field:"optional" json:"requireImdsv2" yaml:"requireImdsv2"`
	// The length of time to wait for the resourceSignalCount.
	//
	// The maximum value is 43200 (12 hours).
	ResourceSignalTimeout awscdk.Duration `field:"optional" json:"resourceSignalTimeout" yaml:"resourceSignalTimeout"`
	// An IAM role to associate with the instance profile assigned to this Auto Scaling Group.
	//
	// The role must be assumable by the service principal `ec2.amazonaws.com`:
	//
	// Example:
	//   const role = new iam.Role(this, 'MyRole', {
	//     assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com')
	//   });
	//
	Role awsiam.IRole `field:"optional" json:"role" yaml:"role"`
	// Security Group to assign to this instance.
	SecurityGroup awsec2.ISecurityGroup `field:"optional" json:"securityGroup" yaml:"securityGroup"`
	// Specifies whether to enable an instance launched in a VPC to perform NAT.
	//
	// This controls whether source/destination checking is enabled on the instance.
	// A value of true means that checking is enabled, and false means that checking is disabled.
	// The value must be false for the instance to perform NAT.
	SourceDestCheck *bool `field:"optional" json:"sourceDestCheck" yaml:"sourceDestCheck"`
	// Specific UserData to use.
	//
	// The UserData may still be mutated after creation.
	UserData awsec2.UserData `field:"optional" json:"userData" yaml:"userData"`
	// Changes to the UserData force replacement.
	//
	// Depending the EC2 instance type, changing UserData either
	// restarts the instance or replaces the instance.
	//
	// - Instance store-backed instances are replaced.
	// - EBS-backed instances are restarted.
	//
	// By default, restarting does not execute the new UserData so you
	// will need a different mechanism to ensure the instance is restarted.
	//
	// Setting this to `true` will make the instance's Logical ID depend on the
	// UserData, which will cause CloudFormation to replace it if the UserData
	// changes.
	UserDataCausesReplacement *bool `field:"optional" json:"userDataCausesReplacement" yaml:"userDataCausesReplacement"`
	// Where to place the instance within the VPC.
	VpcSubnets *awsec2.SubnetSelection `field:"optional" json:"vpcSubnets" yaml:"vpcSubnets"`
	// The options for the Spot instances.
	SpotOptions *awsec2.LaunchTemplateSpotOptions `field:"optional" json:"spotOptions" yaml:"spotOptions"`
	// Options related to Lambda functions to cancel spot requests.
	SpotReqCancelerOptions *SpotReqCancelerProps `field:"optional" json:"spotReqCancelerOptions" yaml:"spotReqCancelerOptions"`
}

Properties of `SpotInstance`.

type SpotReqCancelerProps

type SpotReqCancelerProps struct {
	// Internal Lambda functions execution role.
	LambdaExcecutionRole awsiam.IRole `field:"optional" json:"lambdaExcecutionRole" yaml:"lambdaExcecutionRole"`
	// Log retention period for internal Lambda functions logs kept in CloudWatch Logs.
	LambdaLogRetention awslogs.RetentionDays `field:"optional" json:"lambdaLogRetention" yaml:"lambdaLogRetention"`
	// Runtime environment for the internal Lambda function.
	//
	// If anything other than Node.js is specified, an error will occur.
	LambdaRuntime awslambda.Runtime `field:"optional" json:"lambdaRuntime" yaml:"lambdaRuntime"`
}

Options related to Lambda functions to cancel spot requests.

Directories

Path Synopsis
Package jsii contains the functionaility needed for jsii packages to initialize their dependencies and themselves.
Package jsii contains the functionaility needed for jsii packages to initialize their dependencies and themselves.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL