ALBでコードを作りました。
AWSTemplateFormatVersion: '2010-09-09'
Description: ALB and EC2 with CloudFormation
Parameters:
Subnet1:
Type: String
Description: Subnet 1 ID
Subnet2:
Type: String
Description: Subnet 2 ID
VpcId:
Type: String
Description: VPC ID
KeyName:
Type: String
Description: Name of an existing EC2 KeyPair for SSH access
Resources:
# Security Group for ALB and EC2
MySecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Security group for ALB and EC2
VpcId: !Ref VpcId
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: 0.0.0.0/0 # Restrict to your IP for SSH access
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0 # Allow HTTP traffic
# Load Balancer
MyLoadBalancer:
Type: AWS::ElasticLoadBalancingV2::LoadBalancer
Properties:
Name: MyLoadBalancer
Scheme: internet-facing
Subnets:
- !Ref Subnet1
- !Ref Subnet2
SecurityGroups:
- !Ref MySecurityGroup
# Target Group
MyTargetGroup:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Properties:
Name: MyTargetGroup
Port: 80
Protocol: HTTP
TargetType: instance
VpcId: !Ref VpcId
Targets:
- Id: !Ref MyEC2Instance
# EC2 Instance
MyEC2Instance:
Type: AWS::EC2::Instance
Properties:
ImageId: ami-08ce76bae392de7dc # Example: Amazon Linux 2 AMI
InstanceType: t2.micro
KeyName: !Ref KeyName
SecurityGroupIds:
- !Ref MySecurityGroup
SubnetId: !Ref Subnet1
# Listener for ALB
MyALBListener:
Type: AWS::ElasticLoadBalancingV2::Listener
Properties:
DefaultActions:
- Type: forward
TargetGroupArn: !Ref MyTargetGroup
LoadBalancerArn: !Ref MyLoadBalancer
Port: 80
Protocol: HTTP
これで構築完了。