Skip to main content

Overview

The EC2 Instance resource deploys a managed EC2 instance backed by an Auto Scaling Group, with security groups and optional SSH access. Use it for workloads that need direct server access or custom configuration. IMDSv2 is required by default, the root EBS volume is encrypted by default, and AZRebalance is suspended to keep instances pinned to their subnet.

Resource Class

Basic Usage

Configuration Options

Core Properties

Capacity Configuration

minCapacity and maxCapacity forward straight to the CDK Auto Scaling Group without a Fjall-supplied fallback. When both are omitted, CDK’s default of 1 applies to each.

Instance Configuration

Network Configuration

Machine Images

When machineImage is omitted, the construct uses MachineImage.latestAmazonLinux2023().

Amazon Linux 2023 (default)

Ubuntu

Custom AMI

User Data Configuration

Basic Script

Complex Setup

Storage Configuration

Additional EBS Volumes

RAID Configuration

Security Configuration

SSH Access

Custom Security Rules

IAM Role Configuration

The role prop accepts a standard CDK IAM Role from aws-cdk-lib/aws-iam.

Auto Scaling Configuration

Scaling Across AZs

Spot Instances

Methods

Get Security Group

Get Connections

Get VPC

Get Auto Scaling Group

The underlying ASG is private. Read it through getAutoScalingGroup(), for example to register it as a load balancer target.

Advanced Patterns

Web Server Fleet

Bastion Host

GPU Instance

Complete Example

Best Practices

  1. Use Systems Manager instead of SSH for production
  2. Enable IMDSv2 (enabled by default in this construct)
  3. Encrypt EBS volumes for sensitive data
  4. Use Auto Scaling even for single instances
  5. Apply least privilege IAM policies
  6. Monitor with CloudWatch and set alarms
  7. Use user data for repeatable configuration

Cost Optimisation

  • Use Spot instances for fault-tolerant workloads
  • Right-size instances based on CloudWatch metrics
  • Enable detailed monitoring only when needed
  • Use GP3 volumes instead of GP2 for better price/performance
  • Consider Savings Plans for predictable workloads

Next Steps

Compute Factory

Build EC2 and ECS compute through the Fjall compute factory pattern.

Security Group

Control inbound and outbound traffic for your instances.

VPC

Configure the network your EC2 instances run in.

IAM Role

Grant least-privilege AWS permissions to your instances.