creating ec2 instance and adding new and existing security groups

579 Views Asked by At

I have some troposphere code that a) captures a list of security groups ids as a parameter using List b) creates a new security group

groups = template.add_parameter(Parameter(
  "securityGroups",
  Type="List<AWS::EC2::SecurityGroup::Id>",
  Description="Security Groups for EC2 Instance",
))


ec2_sg = template.add_resource(
  ec2.SecurityGroup(
    'sg',
    GroupName = 'sg_test_app',
    GroupDescription = 'Test SG',
    VpcId = Ref(vpcid),
    Tags=Tags( **tags )
  )  
)

If I create the EC2 with the following referring to (a), this works:

inst_ec2 = template.add_resource(
  ec2.Instance(
    "EC2Instance",
    ImageId = 'ami-8b8c57f8',
    InstanceType = Ref(Type),
    IamInstanceProfile=Ref(instance_profile),
    SubnetId = Ref(snid),
    Tags=Tags(**tags),
    SecurityGroupIds = [ GetAtt(csso_ec2_sg, "GroupId") ],
    DependsOn = [
      'EC2InstanceProfile',
      'sg'
    ]
  )
)

and if I refer to (b), this works:

inst_ec2 = template.add_resource(
  ec2.Instance(
    "EC2Instance",
    ImageId = 'ami-8b8c57f8',
    InstanceType = Ref(Type),
    IamInstanceProfile=Ref(instance_profile),
    SubnetId = Ref(snid),
    Tags=Tags(**tags),
    SecurityGroupIds = groups,
    DependsOn = [
      'EC2InstanceProfile',
      'sg'
    ]
  )
)

However, I can't work out how to add both - this doesn't work:

inst_ec2 = template.add_resource(
  ec2.Instance(
    "EC2Instance",
    ImageId = 'ami-8b8c57f8',
    InstanceType = Ref(Type),
    IamInstanceProfile=Ref(instance_profile),
    SubnetId = Ref(snid),
    Tags=Tags(**tags),
    SecurityGroupIds = [ GetAtt(csso_ec2_sg, "GroupId"), groups ],
    DependsOn = [
      'EC2InstanceProfile',
      'sg'
    ]
  )
)

Can anyone suggest how to do this?

1

There are 1 best solutions below

0
On

You can try joining and then splitting the lists. Something like this might work:

SecurityGroupIds = Split(",", Join(",", [Join(",", groups), GetAtt(csso_ec2_sg, "GroupId")]))