Reputation: 81
I Know that terraform does remove the default behavior of AWS.But is it possible to do that with the cloudformation ?
Upvotes: 7
Views: 3092
Reputation: 441
I have the same requirement that need to remove the inbound and outbound rules for the Default SG that created from CFN when create a VPC.
There has an open issue in GitHub but it still not provide any solution on it.
As the link mentioned, there only able to remove the inbound and outbound rules using CFN Custom Resources and AWS CLI, I will provide these 2 work a round here.
AWS CLI way:
# aws ec2 revoke-security-group-egress --group-id "<default-sg-id>" --protocol all --port all --cidr 0.0.0.0/0
# aws ec2 revoke-security-group-ingress --group-id "<default-sg-id>" --protocol all --port all --source-group <default-sg-id>
Custom Reources:
Resources:
VPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: !Ref VpcCIDR
EnableDnsSupport: true
EnableDnsHostnames: true
Tags:
- Key: Name
Value: !Ref EnvironmentName
LambdaBasicExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
Path: /
Policies:
- PolicyName: yliu-custom-resource-lambda
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action: '*'
Resource: '*'
CustomSGResource:
Type: AWS::CloudFormation::CustomResource
Properties:
ServiceToken: !GetAtt 'CustomFunction.Arn'
GroupIds: !GetAtt VPC.DefaultSecurityGroup
CustomFunction:
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Description: "Retrieves EC2 Security group name"
Timeout: 30
Role: !GetAtt 'LambdaBasicExecutionRole.Arn'
Runtime: python3.7
Code:
ZipFile: |
import json
import logging
import cfnresponse
import boto3
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
logger.info('got event {}'.format(event))
try:
responseData = {}
if event['RequestType'] == 'Delete':
logger.info('Incoming RequestType: Delete operation')
cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
if event['RequestType'] in ["Create", "Update"]:
# 1. retrieve resource reference ID or Name
GroupId=event['ResourceProperties']['GroupIds']
# 2. retrieve boto3 client
ec2_client = boto3.client('ec2')
# 3. Invoke describe/retrieve function using ResourceRef
ec2_client.revoke_security_group_egress(
GroupId=GroupId,
IpPermissions=[{
'IpProtocol': '-1',
'IpRanges': [
{
'CidrIp': '0.0.0.0/0',
},]
}]
)
ec2_client.revoke_security_group_ingress(
GroupId=GroupId,
IpPermissions=[{
'IpProtocol': '-1',
'UserIdGroupPairs': [
{
'GroupId': GroupId,
},]
}]
)
responseData = {}
logger.info('Remove Defefault Security group inbound and outbound rules')
responseData['message']= 'Remove Defefault Security group inbound and outbound rules'
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
else:
logger.info('Unexpected RequestType!')
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
except Exception as err:
logger.error(err)
responseData = {"Data": str(err)}
cfnresponse.send(event,context,cfnresponse.FAILED,responseData)
return
I hope the information is helpful.
Upvotes: 0
Reputation: 76
That should work when you need custom traffic.
ProjectABuildSecurityGroup:
Type: 'AWS::EC2::SecurityGroup'
Properties:
GroupDescription: Security group
VpcId: vpc-<id>
SecurityGroupEgress:
- Description: Allow to 443
IpProtocol: tcp
FromPort: 443
ToPort: 443
CidrIp: 0.0.0.0/0
- Description: Allow to 80
IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
Upvotes: 0
Reputation: 238527
The CloudFormation documentation has a dedicated section for that:
When you specify a VPC security group, Amazon EC2 creates a default egress rule that allows egress traffic on all ports and IP protocols to any location. The default rule is removed only when you specify one or more egress rules. If you want to remove the default rule and limit egress traffic to just the localhost (127.0.0.1/32), use the following example.
sgwithoutegress:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Limits security group egress traffic
SecurityGroupEgress:
- CidrIp: 127.0.0.1/32
IpProtocol: "-1"
VpcId:
Ref: myVPC
Not that this does not remove physically the egress rule from the security group. This will lead to the following egress rule being created:
Instead of the default one:
Upvotes: 8