Skip to content

Instantly share code, notes, and snippets.

@kencoba
Created September 22, 2024 08:01
Show Gist options
  • Save kencoba/9691c9874e940fe9729e233560e080a9 to your computer and use it in GitHub Desktop.
Save kencoba/9691c9874e940fe9729e233560e080a9 to your computer and use it in GitHub Desktop.
AWS CloudFormation template that launch EC2 instance with Docker.
AWSTemplateFormatVersion: '2010-09-09'
Description: CloudFormation template to launch an EC2 instance with User Data, using Instance Profile for SSM Session Manager access.
Parameters:
Prefix:
Type: String
Default: MyApp
Description: Prefix for all resource names
InstanceType:
Description: EC2 instance type
Type: String
Default: t3.micro
AllowedValues:
- t3.micro
- t2.small
- t2.medium
ConstraintDescription: Must be a valid EC2 instance type.
AmiId:
Description: AMI ID for the instance
Type: AWS::EC2::Image::Id
Default: ami-0f75d1a8c9141bd00 # Amazon Linux 2023 AMI
SecurityGroupId:
Description: The security group to associate with the EC2 instance
Type: AWS::EC2::SecurityGroup::Id
ConstraintDescription: Must be the ID of an existing security group.
SubnetId:
Description: Subnet ID to launch the instance into
Type: AWS::EC2::Subnet::Id
ConstraintDescription: Must be an existing subnet in the VPC.
InstanceProfileName:
Description: IAM InstanceProfile
Type: String
ConstraintDescription: Must be the name of an existing IAM Role.
Resources:
# Create EC2 Instance with User Data
EC2Instance:
Type: AWS::EC2::Instance
Properties:
InstanceType: !Ref InstanceType
ImageId: !Ref AmiId
IamInstanceProfile: !Ref InstanceProfileName # Use Instance Profile for SSM access
NetworkInterfaces:
- AssociatePublicIpAddress: false # No public IP
DeviceIndex: 0
SubnetId: !Ref SubnetId
GroupSet:
- !Ref SecurityGroupId
Tags:
- Key: Name
Value: !Sub "${Prefix}-EC2Instance"
UserData:
Fn::Base64: |
#!/bin/bash
dnf update
dnf install -y docker
systemctl start docker
gpasswd -a ssm-user docker
chgrp docker /var/run/docker.sock
chmod 666 /var/run/docker.sock
service docker restart
systemctl enable docker
curl -L "https://github.com/docker/compose/releases/download/v2.29.6/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose
ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
Outputs:
InstanceId:
Description: The Instance ID of the EC2 instance
Value: !Ref EC2Instance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment