我正在尝试使用具有不同安全组的多个EC2实例构建堆栈。
如果我能提前创建我的安全组并在我的EC2堆栈中引用它们,对我来说会很容易。
有没有办法在CF堆栈中引用现有的安全组资源?
提前感谢您的帮助!
答案 0 :(得分:1)
是的,使用标准的Cloudformation模板完全可以实现这一点。 您可以通过几种方式解决此问题。
如果使用嵌套堆栈,则可以在一个子堆栈中创建所需的所有安全组。该堆栈应该为您创建的每个安全组ID都有输出。
Outputs:
SecurityGroup1Id:
Description: Security Group 1 ID
Value: !Ref SecurityGroup1
在随后创建EC2实例的堆栈中,您可以为每个安全组定义Parameters。它可以是每个组的数组或一个参数,具体取决于您的用例。
单一模板
如果在同一模板中定义了EC2实例和安全组,则可以使用简单的Ref访问已创建的安全组的ID。即:!Ref SecurityGroup1Name
答案 1 :(得分:1)
如果您已经部署了一个安全组并且您知道它的 ID,则可以在“属性”下像这样引用它。
您可以引用多个安全组,因为它是一个列表
SecurityGroupIds:
- <the id of the security group>
- <another security group ID>
答案 2 :(得分:0)
是的,您可以在另一个堆栈中交叉引用输出。
以下是AWS官方文档的演练。
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/walkthrough-crossstackref.html
答案 3 :(得分:0)
如果安全组是在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参数存储中,并按照此博客文章中的步骤链接两者:https://aws.amazon.com/blogs/mt/integrating-aws-cloudformation-with-aws-systems-manager-parameter-store/
答案 4 :(得分:0)
是的,您可以提前创建一个安全组并将它们引用到新堆栈中。 在下面的例子中,我们通过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