Documenting this here, as I often forget (what I have found) is the best way to do this at the moment.
For example, you have a list of two existing security groups given to a stack and wish to create (and use) a third - attaching all to an ALB:
AWSTemplateFormatVersion: '2010-09-09'
Description: Example template
Parameters:
VPC:
Type: AWS::EC2::VPC::Id
ALBSubnetList:
Type: List<AWS::EC2::Subnet::Id>
securityGroupIdList:
Type: List<AWS::EC2::SecurityGroup::Id>
Resources:
ALBInstance:
Type: AWS::ElasticLoadBalancingV2::LoadBalancer
Properties:
Name: My ALB
Scheme: internal
SecurityGroups: !Split
- ','
- !Sub
- ${idList},${ALBSecurityGroup}
- idList: !Join [',', !Ref securityGroupIdList]
Subnets: !Ref ALBSubnetList
ALBSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: My new ALB security group
SecurityGroupIngress:
- CidrIp: 0.0.0.0/0
FromPort: 443
IpProtocol: tcp
ToPort: 443
VpcId: !Ref VPCWhat's happening here:
- Taking given
securityGroupIdListlist of strings and using!Jointo create a single string delimited with commas. - Next, using
!Subwe join this string (with a comma) to our new group resource ID ofALBSecurityGroup. - Finally, re-split via
!Splitthe complete string on commas, returning result as a list of strings passed toSecurityGroups.
@iDVB - look here: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html
!Suboffers a second form where you can define one or more name/value pairs - which can then be used in the substitution string - rather than trying to inline everything into a${STATEMENT}block - which is often messy to debug/work with.So here I'm creating a single named value of
idList- which is then used by the sub in it's opening argument.