def create_sg(t, vpc): sglocal = t.add_resource( SecurityGroup( "VPCAccess", GroupDescription="VPC Access Only", SecurityGroupIngress=[ SecurityGroupRule( IpProtocol='-1', CidrIp=Join( '', [vpc["vpcenvcidr"], '.', vpc["service_id"], '.0/24']), FromPort='-1', ToPort='-1') ], VpcId=vpc['vpc'])) sgtrusted = t.add_resource( SecurityGroup( "TrustedAccess", GroupDescription="Access From Trusted Locations", SecurityGroupIngress=[ # ECS Offices SecurityGroupRule(IpProtocol='-1', CidrIp=Join('', ['0.0.0.0/0']), FromPort='-1', ToPort='-1') ], VpcId=vpc['vpc'])) output_sg = {} output_sg["sgtrusted"] = GetAtt(sgtrusted, "GroupId") output_sg["sglocal"] = GetAtt(sglocal, "GroupId") return t, output_sg
def _add_autopush_security_group(self): self.InternalRouterSG = self.add_resource( SecurityGroup("AutopushInternalRouter", GroupDescription="Internal Routing SG")) self.EndpointSG = self.add_resource( SecurityGroup( "AutopushEndpointNode", SecurityGroupIngress=[ allow_tcp(8082), allow_tcp(22), ], GroupDescription="Allow HTTP traffic to autoendpoint node", )) self.ConnectionSG = self.add_resource( SecurityGroup( "AutopushConnectionNode", SecurityGroupIngress=[ allow_tcp(8080), allow_tcp(22), SecurityGroupRule(IpProtocol="tcp", FromPort=8081, ToPort=8081, SourceSecurityGroupName=Ref( self.InternalRouterSG)) ], GroupDescription=("Allow Websocket traffic to autopush node")))
def taskmanager(location, vpc=None): properties = dict( GroupDescription="Enable accesses to TaskManager", SecurityGroupIngress=[] ) if vpc: properties["VpcId"] = Ref(vpc) sg = SecurityGroup("None", GroupDescription="None") return sg.from_dict("TaskManagerSecurityGroup", properties)
def ssh(location, vpc=None): properties = dict( GroupDescription="Enable SSH access via port 22", SecurityGroupIngress=[ SecurityGroupRule(IpProtocol="tcp", CidrIp=Ref(location), FromPort="22", ToPort="22") ] ) if vpc: properties["VpcId"] = Ref(vpc) sg = SecurityGroup("None", GroupDescription="None") return sg.from_dict("SSHSecurityGroup", properties)
def generate_env_template(app_env, env_dict): sg_name = env_dict['sg_name'] vpc_id = 'vpc-a1d187c4' # query for this! logger.debug('generating template for %s' % vpc_id) t = Template() t.add_version('2010-09-09') t.add_description('env template for %s' % app_env) app_sg = SecurityGroup('TestAppSecurityGroup') app_sg.VpcId = vpc_id app_sg.GroupDescription = 'testing' app_sg.Tags = name_tag(sg_name) t.add_resource(app_sg) return t.to_json()
def jobmanager(location, vpc=None): properties = dict( GroupDescription="Enable accesses to JobManager", SecurityGroupIngress=[ SecurityGroupRule(IpProtocol="tcp", CidrIp="0.0.0.0/0", FromPort="6123", ToPort="6123"), SecurityGroupRule(IpProtocol="tcp", CidrIp=Ref(location), FromPort="8081", ToPort="8081") ] ) if vpc: properties["VpcId"] = Ref(vpc) sg = SecurityGroup("None", GroupDescription="None") return sg.from_dict("JobManagerSecurityGroup", properties)
def create_security_group(stack, name, rules=()): """Add EC2 Security Group Resource.""" ingress_rules = [] for rule in rules: ingress_rules.append( SecurityGroupRule( '{0}'.format(rule['name']), CidrIp=rule['cidr'], FromPort=rule['from_port'], ToPort=rule['to_port'], IpProtocol=rule['protocol'], )) return stack.stack.add_resource( SecurityGroup( '{0}SecurityGroup'.format(name), GroupDescription='{0} Security Group'.format(name), SecurityGroupIngress=ingress_rules, SecurityGroupEgress=[ SecurityGroupRule('{0}egress'.format(name.replace('-', '')), CidrIp='0.0.0.0/0', IpProtocol='-1') ], VpcId=Ref(stack.vpc), ))
def create_cache_cluster(stack, name, cache_type, vpc, cidrs, subnet_ids, instance_type, num_cache_clusters): """Add Elasticache Cache cluster Resource.""" ports = {'redis': 6379, 'memcached': 11211} ingress = [] for idx, cidr in enumerate(cidrs): ingress.append( SecurityGroupRule( '{0}{1}{2}'.format(name.replace('-', ''), cache_type, idx), CidrIp=cidr, FromPort=ports[cache_type], ToPort=ports[cache_type], IpProtocol='tcp', )) secgroup = stack.stack.add_resource( SecurityGroup( '{0}{1}SecurityGroup'.format(name.replace('-', ''), cache_type), GroupDescription='{0} {1} Security Group'.format(name, cache_type), SecurityGroupIngress=ingress, SecurityGroupEgress=[ SecurityGroupRule('{0}egress'.format(name.replace('-', '')), CidrIp='0.0.0.0/0', IpProtocol='-1') ], VpcId=vpc, )) subnet_group = stack.stack.add_resource( elasticache.SubnetGroup( '{0}{1}cache'.format(name.replace('-', ''), cache_type), Description='{0}{1} cache'.format(name, cache_type), SubnetIds=subnet_ids, )) if num_cache_clusters > 1: stack.stack.add_resource( elasticache.ReplicationGroup( '{0}CacheCluster'.format(name.replace('-', '')), ReplicationGroupId='{0}'.format(name), ReplicationGroupDescription='{0}cluster'.format(name), Engine='{0}'.format(cache_type), EngineVersion='3.2.6', CacheNodeType=instance_type, NumCacheClusters=num_cache_clusters, CacheSubnetGroupName=Ref(subnet_group), SecurityGroupIds=[Ref(secgroup)], AtRestEncryptionEnabled=True)) else: stack.stack.add_resource( elasticache.CacheCluster('{0}CacheCluster'.format( name.replace('-', '')), ClusterName='{0}'.format(name), Engine='{0}'.format(cache_type), EngineVersion='3.2.10', CacheNodeType=instance_type, NumCacheNodes=num_cache_clusters, VpcSecurityGroupIds=[Ref(secgroup)], CacheSubnetGroupName=Ref(subnet_group)))
def custom_security_group(vpc_stack, region, request, cfn_stacks_factory): template = Template() template.set_version("2010-09-09") template.set_description("custom security group stack for testing additional_sg and vpc_security_group_id") security_group = template.add_resource( SecurityGroup( "SecurityGroupResource", GroupDescription="custom security group for testing additional_sg and vpc_security_group_id", VpcId=vpc_stack.cfn_outputs["VpcId"], ) ) template.add_resource( SecurityGroupIngress( "SecurityGroupIngressResource", IpProtocol="-1", FromPort=0, ToPort=65535, SourceSecurityGroupId=Ref(security_group), GroupId=Ref(security_group), ) ) stack = CfnStack( name=generate_stack_name("integ-tests-custom-sg", request.config.getoption("stackname_suffix")), region=region, template=template.to_json(), ) cfn_stacks_factory.create_stack(stack) yield stack if not request.config.getoption("no_delete"): cfn_stacks_factory.delete_stack(stack.name, region)
def add_security_group(family) -> None: """ Creates a new EC2 SecurityGroup and assigns to ecs_service.network_settings Adds the security group to the family template resources. :param ecs_composex.ecs.ecs_family.ComposeFamily family: """ family.service_networking.security_group = SecurityGroup( SG_T, GroupDescription=Sub( f"SG for ${{{SERVICE_NAME.title}}} - ${{STACK_NAME}}", STACK_NAME=define_stack_name(), ), Tags=Tags({ "Name": Sub( f"${{{SERVICE_NAME.title}}}-${{STACK_NAME}}", STACK_NAME=define_stack_name(), ), "StackName": StackName, "MicroserviceName": Ref(SERVICE_NAME), }), VpcId=Ref(VPC_ID), ) add_resource(family.template, family.service_networking.security_group)
def gen_sg(): sg = SecurityGroup("DBSecurityGroup", GroupDescription="Enable Postgres on the inbound port", VpcId=ImportValue( Sub("${NetworkName}-network-vpc-VpcId"))) self_sg_rule = SecurityGroupIngress( "IngressFromSelfRule", GroupId=Ref("DBSecurityGroup"), IpProtocol="tcp", FromPort="5432", ToPort="5432", SourceSecurityGroupId=Ref("DBSecurityGroup"), ) lambda_sg_rule = SecurityGroupIngress( "IngressFromLambdaRule", Condition="InstallPostgis", GroupId=Ref("DBSecurityGroup"), IpProtocol="tcp", FromPort="5432", ToPort="5432", SourceSecurityGroupId=ImportValue( Sub("${ProvisionerStackName}-SecurityGroup")), ) return [sg, self_sg_rule, lambda_sg_rule]
def add_alb_secuirty_group(self): ''' Add security group to load balancer ''' self.cfn_template.add_resource(SecurityGroup( title=constants.ALB_SG, GroupDescription='Load balancer security group', SecurityGroupIngress=[ SecurityGroupRule( IpProtocol='tcp', FromPort=int('8228'), ToPort=int('8228'), CidrIp=Ref('CIDRBLK'), ), SecurityGroupRule( IpProtocol='-1', FromPort=int('-1'), ToPort=int('-1'), SourceSecurityGroupId=ImportValue(Sub('${Environment}-AppSecurityGroup')), ) ], SecurityGroupEgress=[ SecurityGroupRule( IpProtocol='-1', CidrIp='0.0.0.0/0' ) ], VpcId=ImportValue(Sub('${Environment}-${VpcId}')) )) return self.cfn_template
def add_service_default_sg(self): """ Adds a default security group for the microservice. """ sg = self.template.add_resource( SecurityGroup( SG_T, GroupDescription=If( USE_STACK_NAME_CON_T, Sub(f"SG for ${{{SERVICE_NAME_T}}} - ${{AWS::StackName}}"), Sub(f"SG for ${{{SERVICE_NAME_T}}} - ${{{ROOT_STACK_NAME_T}}}" ), ), Tags=Tags({ "Name": If( USE_STACK_NAME_CON_T, Sub(f"${{{SERVICE_NAME_T}}}-${{AWS::StackName}}"), Sub(f"${{{SERVICE_NAME_T}}}-${{{ROOT_STACK_NAME_T}}}"), ), "StackName": Ref(AWS_STACK_NAME), "MicroserviceName": Ref(SERVICE_NAME), }), VpcId=Ref(VPC_ID), )) return sg
def add_vpnSecurityGroup(self): t = self.template self.openVPNSecurityGroup = t.add_resource( SecurityGroup( "OpenVPNSecurityGroup", VpcId=Ref(self.vpcIdParam), SecurityGroupIngress=[{ "ToPort": "443", "IpProtocol": "tcp", "CidrIp": "0.0.0.0/0", "FromPort": "443" }, { "ToPort": "943", "IpProtocol": "tcp", "CidrIp": "0.0.0.0/0", "FromPort": "943" }, { "ToPort": "1194", "IpProtocol": "udp", "CidrIp": "0.0.0.0/0", "FromPort": "1194" }, { "ToPort": "22", "IpProtocol": "tcp", "CidrIp": "0.0.0.0/0", "FromPort": "22" }], GroupDescription="Controls access to the OpenVPN server", Tags=self.defaultTags + [ Tag('Name', Join("", [self.namePrefix, 'OpenVPNSecurityGroup'])) ]))
def _create_eks_control_plane(self): account_id = boto3.client('sts').get_caller_identity().get('Account') r = copy(self.RESOURCE_CP_ROLE) if self.role: role_arn = 'arn:aws:iam::{}:role/{}'.format(account_id, self.role) r.status = Status.provided r.resource_id = role_arn else: role = self.tpl.add_resource( Role(self.RESOURCE_CP_ROLE.name, RoleName=self.tag_name, AssumeRolePolicyDocument=Policy(Statement=[ Statement(Effect=Allow, Action=[AssumeRole], Principal=Principal('Service', ['eks.amazonaws.com'])), Statement(Effect=Allow, Action=[AssumeRole], Principal=Principal('AWS', ['arn:aws:iam::{}:root'.format(account_id)])), ], ), ManagedPolicyArns=['arn:aws:iam::aws:policy/AmazonEKSClusterPolicy', 'arn:aws:iam::aws:policy/AmazonEKSServicePolicy'] )) role_arn = GetAtt(role, 'Arn') cp_sg = self.tpl.add_resource(SecurityGroup( self.RESOURCE_CP_SG.name, GroupDescription='Security Group applied to EKS cluster', VpcId=self.tpl.outputs.get(self.OUTPUT_VPC).resource.get('Value'), Tags=Tags(Name=self.tag_name) )) self.tpl.add_output(Output(self.OUTPUT_CP_SG, Value=Ref(self.OUTPUT_CP_SG))) self._create_eks_cluster_template(cp_sg, role_arn) self.resources.extend([r, copy(self.RESOURCE_CP_SG), copy(self.RESOURCE_EKS_CLUSTER)])
def create_efs_stack(settings, new_resources): """ Function to create the root stack and add EFS FS. :param ecs_composex.common.settings.ComposeXSettings settings: :param list new_resources: :return: Root template for EFS :rtype: troposphere.Template """ template = build_template("Root for EFS built by ECS Compose-X", [FS_PORT]) for res in new_resources: res_cfn_props = import_record_properties(res.properties, FileSystem) res.cfn_resource = FileSystem(res.logical_name, **res_cfn_props) res.db_sg = SecurityGroup( f"{res.logical_name}SecurityGroup", GroupName=Sub(f"{res.logical_name}EfsSg"), GroupDescription=Sub(f"SG for EFS {res.cfn_resource.title}"), VpcId=Ref(VPC_ID), ) template.add_resource(res.cfn_resource) template.add_resource(res.db_sg) res.init_outputs() res.generate_outputs() template.add_output(res.outputs) return template
def __init__(self, title, template, *args, **kwargs): self.props['PeerCidrBlock'] = (str, True) super().__init__(title, template, *args, **kwargs) for index in list(template.resources): resource = template.resources[index] if isinstance(resource, RouteTable): Route(index + 'to' + title + 'route', template, DestinationCidrBlock=kwargs['PeerCidrBlock'], RouteTableId=Ref(resource), VpcPeeringConnectionId=Ref(self)) SecurityGroup(title + "securitygroup", template, GroupDescription="Allow SSH & ICMP from " + title, VpcId=kwargs['VpcId']) SecurityGroupIngress(title + "sshingress", template, GroupId=Ref(title + "securitygroup"), CidrIp=kwargs['PeerCidrBlock'], IpProtocol="tcp", FromPort="22", ToPort="22") SecurityGroupIngress(title + "icmpingress", template, GroupId=Ref(title + "securitygroup"), CidrIp=kwargs['PeerCidrBlock'], IpProtocol="icmp", FromPort="-1", ToPort="-1") self.props.pop('PeerCidrBlock') self.properties.pop('PeerCidrBlock')
def add_nat_sg(self): ''' Create the NAT security group and add the ingress/egress rules ''' self.sg = self.add_resource( SecurityGroup("Nat%sSG" % str(self.subnet_index), VpcId=Ref(self.vpc_id), GroupDescription="Security group for NAT host.")) self.add_nat_sg_rules()
def security_group(name, desc, vpc_id): """ Returns a security group """ resource_name = '{}SG'.format(sanitize_resource_name(name)) return SecurityGroup( resource_name, GroupDescription=desc, VpcId=vpc_id, Tags=tags(name) )
def create_alb_template(): template = Template() vpc = template.add_parameter( parameter=Parameter(title='Vpc', Type='String')) subnet_a = template.add_parameter( parameter=Parameter(title='SubnetA', Type='String')) subnet_b = template.add_parameter( parameter=Parameter(title='SubnetB', Type='String')) ec2_instance = template.add_parameter( parameter=Parameter(title='Ec2Instance', Type='String')) security_group = template.add_resource( resource=SecurityGroup(title='SampleSecurityGroup', GroupDescription='sample-security-group', SecurityGroupIngress=[{ 'IpProtocol': 'tcp', 'FromPort': 80, 'ToPort': 80, 'CidrIp': '0.0.0.0/0' }], VpcId=Ref(vpc))) load_balancer = template.add_resource(resource=LoadBalancer( title='SampleLoadBalancer', Name='sample-alb', Subnets=[Ref(subnet_a), Ref(subnet_b)], SecurityGroups=[Ref(security_group)], )) target_group = template.add_resource(resource=TargetGroup( title='SampleTargetGroup', Targets=[TargetDescription( Id=Ref(ec2_instance), Port=80, )], VpcId=Ref(vpc), Name='sample-target-group', Port=80, Protocol='HTTP', )) template.add_resource(resource=Listener( title='SampleListener', DefaultActions=[ Action(TargetGroupArn=Ref(target_group), Type='forward') ], LoadBalancerArn=Ref(load_balancer), Port=80, Protocol='HTTP', )) with open('./alb.yml', mode='w') as file: file.write(template.to_yaml())
def attach_security_group(template, vpc): secgroup = SecurityGroup("sgdemosecuritygroup", GroupDescription = "sgdemosecuritygroup", VpcId = Ref(vpc)) template.add_resource(secgroup) ingress = SecurityGroupIngress("sgdemoingressssh", GroupId = Ref(secgroup), IpProtocol = "tcp", FromPort = "22", ToPort = "22", CidrIp = "0.0.0.0/0") template.add_resource(ingress) ingress = SecurityGroupIngress("sgdemoingresses", GroupId = Ref(secgroup), IpProtocol = "tcp", FromPort = "9200", ToPort = "9399", CidrIp = "0.0.0.0/0") template.add_resource(ingress) ingress = SecurityGroupIngress("sgdemoingresskibana", GroupId = Ref(secgroup), IpProtocol = "tcp", FromPort = "5601", ToPort = "5601", CidrIp = "0.0.0.0/0") template.add_resource(ingress) egress = SecurityGroupEgress("sgdemoegress", GroupId = Ref(secgroup), IpProtocol = "-1", FromPort = "-1", ToPort = "-1", CidrIp = "0.0.0.0/0") template.add_resource(egress) return secgroup
def get_vdcm_management_security_group(template, vpc, sg_name='vdcmmanagementsecuritygroup', cidr=CISCO_CIDR): """Get a vdcm security group containing the vdcm rules for management :param name: unique name of the security group. :param template: the template to add this subnet too. :param vpc: the vpc to add this subnet too. :param cidr: the cidr to use to create this security group rule. Defaults to the CISCO_CIDR. :return: security_group """ sg = SecurityGroup(sg_name, template=template) sg.Tags = Tags(Name=aws_name(sg.title)) sg.GroupDescription = 'vdcm security group for management' sg.VpcId = Ref(vpc) rules = Rules() rs = [ rules.ssh, rules.http, rules.https, rules.influxdb, rules.vnc, rules.rest, rules.graphana, rules.all_icmp, rules.abr2ts ] if cidr: rs = [rules.override_cidr(rule=r, cidr=cidr) for r in rs] rs.append(rules.all_sn) sg.SecurityGroupIngress = rs return sg
def __create_security_group(): template = Template() alb_security_group = template.add_resource(resource=SecurityGroup( title='SampleAlbSecurityGroup', GroupDescription='sample-fargate', SecurityGroupIngress=[{ 'IpProtocol': 'tcp', 'ToPort': 80, 'FromPort': 80, 'CidrIp': '0.0.0.0/0' }], VpcId=ImportValue(CommonResource.ExportName.VPC_ID.value))) template.add_output( output=Output(title=alb_security_group.title, Value=Ref(alb_security_group), Export=Export(name=ExportName.ALB_SECURITY_GROUP.value))) task_security_group = template.add_resource(resource=SecurityGroup( title='SampleTaskSecurityGroup', GroupDescription='sample-fargate', SecurityGroupIngress=[ { 'IpProtocol': 'tcp', 'ToPort': 80, 'FromPort': 80, 'CidrIp': '0.0.0.0/0' }, ], VpcId=ImportValue(CommonResource.ExportName.VPC_ID.value))) template.add_output( output=Output(title=task_security_group.title, Value=Ref(task_security_group), Export=Export( name=ExportName.TASK_SECURITY_GROUP.value))) output_template_file(template, 'sg.yml') return alb_security_group, task_security_group
def _add_processor_databases(self): # Add the security group for Redis access self.LambdaProcessorSG = self.add_resource( SecurityGroup( "LambdaProcessorSG", GroupDescription="Lambda Message Processor", VpcId=Ref(self.ProcessorVPCId), )) self.RedisClusterSG = self.add_resource( SecurityGroup( "RedisClusterSG", SecurityGroupIngress=[ SecurityGroupRule(IpProtocol="tcp", FromPort=6379, ToPort=6379, SourceSecurityGroupId=GetAtt( self.LambdaProcessorSG, "GroupId")) ], GroupDescription="Allow HTTP traffic to redis", VpcId=Ref(self.ProcessorVPCId), )) self.RedisClusterSubnetGroup = self.add_resource( SubnetGroup( "RedisClusterSubnetGroup", Description="Subnet group for Redis Cluster", SubnetIds=[Ref(self.MessageAPISubnetId)], )) self.RedisCluster = self.add_resource( CacheCluster( "RedisPushMessages", Engine="redis", CacheNodeType="cache.m3.medium", NumCacheNodes=1, CacheSubnetGroupName=Ref(self.RedisClusterSubnetGroup), VpcSecurityGroupIds=[ GetAtt(self.RedisClusterSG, "GroupId"), ], Tags=self._instance_tags("push-messages", "push-messages"), ))
def create_security_groups(self, vpc_param): elb_sg = self.t.add_resource( SecurityGroup( "ElbSg", GroupDescription= "Allows inbound connection from from everywhere on port 80", VpcId=Ref(vpc_param), SecurityGroupIngress=[ SecurityGroupRule( IpProtocol="tcp", FromPort="80", ToPort="80", CidrIp="0.0.0.0/0", ) ])) autoscaling_sg = self.t.add_resource( SecurityGroup("AutoscalingSG", GroupDescription= "Allows inbound connection from elb sg on port 80", VpcId=Ref(vpc_param), SecurityGroupIngress=[ SecurityGroupRule( IpProtocol="tcp", FromPort="80", ToPort="80", SourceSecurityGroupId=Ref(elb_sg), ) ])) self.t.add_resource( SecurityGroupEgress("ELBegress", DestinationSecurityGroupId=Ref(autoscaling_sg), GroupId=Ref(elb_sg), IpProtocol="-1", FromPort="-1", ToPort="-1")) return elb_sg, autoscaling_sg
def gen_sg(): sg = SecurityGroup( "PostGisProvisionerSg", GroupDescription="Allow PostGis Provisioner access to Postgres", VpcId=ImportValue(Sub("${NetworkName}-network-vpc-VpcId"))) sg_rule = SecurityGroupEgress( "EgressToPrivateSubnets", GroupId=Ref("PostGisProvisionerSg"), IpProtocol="tcp", FromPort="5432", ToPort="5432", CidrIp=ImportValue(Sub("${NetworkName}-network-vpc-PrivateCIDR")), ) return [sg, sg_rule]
def add_db_sg(template, db_name): """ Function to add a Security group for the database :param str db_name: Name of the database as defined in compose file :param troposphere.Template template: template to add the sg to """ return SecurityGroup( f"{db_name}Sg", template=template, GroupName=Sub(f"${{{ROOT_STACK_NAME_T}}}-{db_name}"), GroupDescription=Sub(f"${{{ROOT_STACK_NAME_T}}} ${db_name}"), VpcId=Ref(VPC_ID), )
def add_security_groups(self): t = self.template self.asgSg = t.add_resource( SecurityGroup( 'AsgSg', VpcId=Ref(self.vpcIdParam), GroupDescription='Security group for ASG.', SecurityGroupIngress=[ SecurityGroupRule(ToPort='80', FromPort='80', IpProtocol='tcp', SourceSecurityGroupId=Ref(self.elbSg)), SecurityGroupRule(ToPort='22', FromPort='22', IpProtocol='tcp', SourceSecurityGroupId=Ref( self.vpnSgIdParam)) #TODO HTTPS ], Tags=self.defaultTags + [Tag('Name', Join("", [self.namePrefix, 'AsgSg']))])) self.rdsSg = t.add_resource( SecurityGroup('RdsSg', VpcId=Ref(self.vpcIdParam), GroupDescription='Security group for RDS.', SecurityGroupIngress=[ SecurityGroupRule(ToPort='3306', FromPort='3306', IpProtocol='tcp', SourceSecurityGroupId=Ref( self.asgSg)) ], Tags=self.defaultTags + [Tag('Name', Join("", [self.namePrefix, 'RdsSg']))])) return 0
def add_security_group(self): t = self.template self.security_group = t.add_resource( SecurityGroup( "SecurityGroup", GroupDescription="Security Group", SecurityGroupIngress=[ SecurityGroupRule(IpProtocol="tcp", FromPort="80", ToPort="80", CidrIp=Ref(self.whitelist_ip_param)) ], VpcId=Ref(self.vpc_id_param), ))
def sort_sg(self): if self.is_nlb(): self.lb_sg = Ref(AWS_NO_VALUE) elif self.is_alb(): self.lb_sg = SecurityGroup( f"{self.logical_name}SecurityGroup", GroupDescription=Sub( f"SG for LB {self.logical_name} in ${{{AWS_STACK_NAME}}}"), GroupName=Sub( f"{self.logical_name}-{self.lb_type}-sg-${{{AWS_STACK_NAME}}}" ), VpcId=Ref(VPC_ID), Tags=Tags(Name=Sub( f"elbv2-{self.logical_name}-${{{AWS_STACK_NAME}}}")), )
def add_WebSecurityGroup(self): self.WebSecurityGroup = self.template.add_resource( SecurityGroup( "WebSecurityGroup", SecurityGroupIngress=[ { "ToPort": "80", "IpProtocol": "tcp", "CidrIp": "0.0.0.0/0", "FromPort": "80" }, ], VpcId=self.sceptre_user_data.get("VpcId"), GroupDescription="WEBsg", ))
def add_elb(self): t = self.template self.elbSg = t.add_resource( SecurityGroup( 'ElbSecurityGroup', VpcId=Ref(self.vpcIdParam), GroupDescription='Security group for ELB.', SecurityGroupIngress=[ SecurityGroupRule(ToPort='80', FromPort='80', IpProtocol='tcp', CidrIp="0.0.0.0/0") #TODO HTTPS ], Tags=self.defaultTags + [Tag('Name', Join("", [self.namePrefix, 'ElbSecurityGroup'])) ])) self.elbListener = Listener('ElbListener', LoadBalancerPort="80", InstancePort="80", Protocol="HTTP", InstanceProtocol="HTTP") self.elbHealthCheck = HealthCheck(Target="TCP:80", Timeout="2", Interval="5", HealthyThreshold="2", UnhealthyThreshold="2") publicSubnetIds = [ self.sceptreUserData['subnets']['publicInfraAZ1Id'], self.sceptreUserData['subnets']['publicInfraAZ2Id'], self.sceptreUserData['subnets']['publicInfraAZ3Id'] ] self.elb = t.add_resource( LoadBalancer('Elb', Listeners=[self.elbListener], Scheme='internet-facing', HealthCheck=self.elbHealthCheck, CrossZone=True, Subnets=publicSubnetIds, SecurityGroups=[Ref(self.elbSg)], Tags=self.defaultTags + [Tag('Name', Join("", [self.namePrefix, 'Elb']))])) return 0
def add_hosts_security_group(template): """ Function to add a security group for the host :parm template: EC2 Cluster template to add the SG to :type template: troposphere.Template :returns: troposphere IAM Role for EC2 hosts :rtype: troposphere.ec2.SecurityGroup """ return SecurityGroup( NODES_SG_T, template=template, GroupDescription=Sub(f"Group for hosts in ${{{CLUSTER_NAME_T}}}"), VpcId=Ref(vpc_params.VPC_ID), )
def add_security_group(self): t = self.template self.security_group = t.add_resource( SecurityGroup( self.sceptre_user_data['sg_name'] + 'SecurityGroup', VpcId=self.sceptre_user_data['vpc_id'], GroupDescription='Security Group.', SecurityGroupIngress=self.create_rules( self.sceptre_user_data['rules']), Tags=self.DEFAULT_TAGS + [ Tag( 'Name', self.sceptre_user_data['application'] + self.sceptre_user_data['sg_name'] + 'SG') ])) return 0
# route table associations need to be handled per subnet rta = SubnetRouteTableAssociation(config['name'] + 'Rta' + subnet[0]) rta.RouteTableId = Ref(route_table) rta.SubnetId = Ref(sub) t.add_resource(rta) route_table_associations.append(rta) # security group addresses # list of tuples # [('cidr block', 'cloudformation resource name')] home_egress_ips = [ ('68.193.66.133/32', 'home') ] # security groups home_ssh = SecurityGroup(config['name'] + 'homeSsh') home_ssh.GroupDescription = 'home SSH in' home_ssh.VpcId = Ref(vpc) home_ssh.Tags = Tags(Name = config['name'] + '-home-ssh') t.add_resource(home_ssh) consul_sg = SecurityGroup('consul') consul_sg.GroupDescription = 'consul cluster' consul_sg.VpcId = Ref(vpc) consul_sg.Tags = Tags(Name = config['name'] + '-consul') t.add_resource(consul_sg) # consul ports consul_ports = [ 8300, 8301,