AWS CloudFormation template: Is it possible to add many CidrIp as a list?
Unfortunately, there's no iteration available through CloudFormation's Intrinsic Functions, and as you pointed out the AWS::EC2::SecurityGroupIngress
resource itself only accepts a single String
for its CidrIp
property.
As an alternative, I would recommend choosing an intermediate format to compile down to CloudFormation template JSON using a preprocessor, if/when greater expressive power is needed. You can use a full-featured library like troposphere, but it's also easy enough to code up your own basic preprocessing layer to suit your use-case and programming-language/library preferences.
My current choice is a combination of YAML with embedded Ruby (ERB), mostly because I'm already familiar with them. Here's an example template.yml.erb
file that would generate the example JSON above:
SecurityGroupIngress:
<% ["100.10.77.66/32", "100.10.66.66/32" , "101.10.77.66/32"].each do |cidr| -%>
- IpProtocol: tcp
CidrIp: <%=cidr%>
FromPort: 3306
ToPort: 3306
<% end -%>
Here's a minimal preprocessor script, process_template.rb
:
require 'erb'
require 'yaml'
require 'json'
puts JSON.pretty_generate(YAML.load(ERB.new(ARGF.read, nil, '-').result))
Running ruby ./process_template.rb template.yml.erb
produces:
{
"SecurityGroupIngress": [
{
"IpProtocol": "tcp",
"CidrIp": "100.10.77.66/32",
"FromPort": 3306,
"ToPort": 3306
},
{
"IpProtocol": "tcp",
"CidrIp": "100.10.66.66/32",
"FromPort": 3306,
"ToPort": 3306
},
{
"IpProtocol": "tcp",
"CidrIp": "101.10.77.66/32",
"FromPort": 3306,
"ToPort": 3306
}
]
}
I am not sure why the prefix list has not been mentioned. You can create the prefix list with all the CIDR's and mention the prefix list id as the security group source in the CF template. Example
PrefixList:
Type: AWS::EC2::PrefixList
Properties:
PrefixListName: "Name of PL"
AddressFamily: "IPv4"
MaxEntries: 2 # the number of CIDR's you want to add
Entries:
- Cidr: "10.10.0.0/16"
Description: "CIDR1"
- Cidr: "10.100.0.0/16"
Description: "CIDR2"
Tags:
- Key: "Name"
Value: "PL
Please go through the link below.
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-prefixlist.html
Afraid not, as the documentation states it only accepts String and not List therefore multiple blocks are required.
Think of it the same way as ingress rules are created within the web console, one new rule for each CIDR.