【发布时间】:2021-03-12 04:08:50
【问题描述】:
我正在尝试构建一个包含多个具有不同安全组的 EC2 实例的堆栈。
如果我可以提前创建我的安全组并在我的 EC2 堆栈中引用它们,那对我来说会很容易。
有没有办法在 CF 堆栈中引用现有的安全组资源?
提前感谢您的帮助!
【问题讨论】:
标签: amazon-web-services amazon-ec2 amazon-cloudformation
我正在尝试构建一个包含多个具有不同安全组的 EC2 实例的堆栈。
如果我可以提前创建我的安全组并在我的 EC2 堆栈中引用它们,那对我来说会很容易。
有没有办法在 CF 堆栈中引用现有的安全组资源?
提前感谢您的帮助!
【问题讨论】:
标签: amazon-web-services amazon-ec2 amazon-cloudformation
是的,这完全可以通过标准 Cloudformation 模板实现。 您可以通过多种方式解决此问题。
如果您使用嵌套堆栈,您可以在一个子堆栈中创建您需要的所有安全组。该堆栈应该具有您创建的每个安全组 ID 的输出。
Outputs:
SecurityGroup1Id:
Description: Security Group 1 ID
Value: !Ref SecurityGroup1
在随后创建您的 EC2 实例的堆栈中,您可以为每个安全组定义 Parameters。它可以是一个数组,也可以是每个组的一个参数,具体取决于您的用例。
单一模板
如果 EC2 实例和安全组是在同一个模板中定义的,那么您可以使用简单的 Ref 来访问已创建的安全组的 ID。即:!Ref SecurityGroup1Name
【讨论】:
如果您已经部署了一个安全组并且您知道它的 ID,您可以在属性下像这样引用它。
您可以引用多个安全组,因为它是一个列表
SecurityGroupIds:
- <the id of the security group>
- <another security group ID>
【讨论】:
如果安全组是在 CloudFormation(控制台/CLI)之外创建的,或者 CloudFormation 堆栈未通过 nesting 或 exports 链接,您应该将它们定义为参数,然后在模板中引用该参数名称:
Parameters:
MySecurityGroup:
Type: String
Description: ID of an existing VPC security group (sg-xxxxxx)
Resources:
MyInstance:
Type: AWS::EC2::Instance
Properties:
# All of your other properties
SecurityGroupIds:
- !Ref MySecurityGroup
如果安全组 ID 是您要经常引用的东西,请将其放入 SSM Parameter Store 并按照此博文中的步骤链接两者:https://aws.amazon.com/blogs/mt/integrating-aws-cloudformation-with-aws-systems-manager-parameter-store/
【讨论】:
是的,您可以提前创建一个安全组并将其引用到新堆栈中。 在下面的示例中,我们通过 cloudformation 模板创建一个安全组,以允许用户(用户名为 User1)的 3389/RDP 协议并导出安全组 名字。
在 EC2 CloudFormation 堆栈中,我们正在导入安全组 CloudFormation 堆栈的导出值(sg 名称)。
AWSTemplateFormatVersion: 2010-09-09
Description: CloudFormation template for Security Group definitions
Parameters:
User1:
Description: Public IP OF Deven .
Type: String
Default: 106.209.184.29/32
AllowedPattern: (\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/(\d{1,2})
ConstraintDescription: Must be valid IP Range.
Resources:
MySG:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Common Jenkins SG.
VpcId: vpc-8587d522
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 3389
ToPort: 3389
CidrIp: !Ref User1
Description: User1 - RDP access .
- Key: Name
Value: test-security-group
SecurityGroupEgress: []
Outputs:
Ec2SecurityGroup:
Description: Security Group ID for EC2
Value: !Ref MySG
Export:
Name: !Sub "${AWS::StackName}-testapplication"
在 Youe EC2 实例模板中导入值。以下是相同的示例。
Type: 'AWS::EC2::Instance'
Properties:
.
.
(your other parameters mentioned in 'AWS::EC2::Instance' )
.
.
KeyName: !Ref Key
SubnetId: !Ref SubnetA
SecurityGroups:
Fn::ImportValue:
!Sub "${SGStackName}-RenderEngine" ##### SGStackName is Security group CloudFormation Stack name
.
.
(your other parameters mentioned in 'AWS::EC2::Instance' )
.
.
更多详情请咨询官方link
【讨论】: