我尝试了下面的模板,但它给出了如下错误
这里我尝试启动 2 个实例 MyEC2Instance1 和 MyEC2Instance2 并创建一个允许从 MyEC2Instance2 访问的安全组
用于启动 EC2 实例和安全组的云形成模板:
AWSTemplateFormatVersion: '2010-09-09'
Parameters:
SourceAccountId:
Type: String
Description: "AWS Account ID where the AMIs are shared from"
SourceAmis:
Type: List<String>
Description: "List of shared encrypted AMI IDs"
VpcId:
Type: String
Description: "VPC ID where the security groups will be created."
Resources:
MyEC2Instance1:
Type: 'AWS::EC2::Instance'
Properties:
ImageId: !Select [0, !Ref SourceAmis] # Select the first AMI from the list
InstanceType: t2.micro
KeyName: New_Test_PIM
SubnetId: subnet-xxxxxxxxxxxx
Tags:
- Key: Name
Value: "Test_1_EC2"
MyEC2Instance2:
Type: 'AWS::EC2::Instance'
Properties:
ImageId: !Select [1, !Ref SourceAmis] # Select the second AMI from the list
InstanceType: t2.micro
KeyName: New_Test_PIM
SubnetId: subnet-xxxxxxxxxxxxx
Tags:
- Key: Name
Value: "Test_2_EC2"
MyEIP:
Type: 'AWS::EC2::EIP'
MySecurityGroup:
Type: 'AWS::EC2::SecurityGroup'
DependsOn: MyEC2Instance2
Properties:
GroupDescription: "Allow traffic from MyEC2Instance2s private IP"
VpcId: !Ref "VpcId"
MySecurityGroupIngress:
Type: 'AWS::EC2::SecurityGroupIngress'
DependsOn: MySecurityGroup
Properties:
GroupId: !GetAtt MySecurityGroup.GroupId
IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: !Sub "{{MyEC2Instance2.PrivateIpAddresses[0]}}/32"
Description: "Inbound Rule 1"
错误:
CIDR block {{MyEC2Instance2.PrivateIpAddresses[0]}}/32 is malformed (Service: AmazonEC2; Status Code: 400; Error Code: InvalidParameterValue; Request ID: dd12c2d9-fe00-481d-b267-d6ad355ab2b0; Proxy: null)
任何人都可以帮我解决如何将实例 IP 地址动态分配给安全组入站规则吗?
“更正确”的方法是创建两个单独的安全组:
SG1
对于MyEC2Instance1
SG2
对于MyEC2Instance2
然后,您可以在
SG1
上配置入站规则,以允许来自 SG2
的入站流量。与 SG2
关联的任何资源都将被授予对与 SG1
关联的任何资源的入站访问权限。在这种情况下,MyEC2Instance2
将被授予对 MyEC2Instance1
的入站访问权限。
引用其他安全组的好处是可以将各个实例替换为其他实例,而无需更改安全组中引用的 IP 地址。