Ejemplo n.º 1
0
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
Ejemplo n.º 2
0
def security_group_egress(name, desc, ip_protocol, from_port, to_port, group_id, cidr):
    """
    Returns a security group egress rule resource
    """
    resource_name = '{}SGEgress'.format(sanitize_resource_name(name))
    return SecurityGroupEgress(
        resource_name,
        Description=desc,
        IpProtocol=ip_protocol,
        FromPort=from_port,
        ToPort=to_port,
        GroupId=group_id,
        CidrIp=cidr,
    )
Ejemplo n.º 3
0
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_nat_sg_rules(self):
     '''
     Add the security group rules necessary for the NAT to operate
     For now, this is opening all ingress from the VPC and all egress to the internet
     '''
     self.add_resource(
         SecurityGroupIngress("Nat%sIngress" % str(self.subnet_index),
                              ToPort="-1",
                              FromPort="-1",
                              IpProtocol="-1",
                              GroupId=Ref(self.sg),
                              CidrIp=self.vpc_cidr))
     self.add_resource(
         SecurityGroupEgress("Nat%sEgress" % str(self.subnet_index),
                             ToPort="-1",
                             FromPort="-1",
                             IpProtocol="-1",
                             GroupId=Ref(self.sg),
                             CidrIp='0.0.0.0/0'))
Ejemplo n.º 5
0
    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
Ejemplo n.º 6
0
Archivo: stack.py Proyecto: jpza/ekscli
    def _create_cfn_template(self):
        self.tpl = Template()
        self.tpl.add_version('2010-09-09')
        self.tpl.add_description('CFN template to create an EKS node group and affiliated resources.')

        eks_tag = 'kubernetes.io/cluster/{}'.format(self.cluster.name)

        r = self.resources.get(self.RESOURCE_NG_ROLE.name)
        if self.role:
            profile = InstanceProfile(
                self.RESOURCE_NG_PROFILE.name, InstanceProfileName=self.tag_name, Path='/', Roles=[self.role])
            account_id = boto3.session.Session().client('sts').get_caller_identity().get('Account')
            role_arn = 'arn:aws:iam::{}:role/{}'.format(account_id, self.role)
            self.tpl.add_output(
                Output(self.RESOURCE_NG_ROLE.name, Value=role_arn, Description='Node group role'))
            r.status = Status.provided
            r.resource_id = role_arn
        else:
            role = Role(
                self.RESOURCE_NG_ROLE.name, RoleName=self.tag_name,
                AssumeRolePolicyDocument=Policy(Statement=[
                    Statement(Effect=Allow, Action=[AssumeRole],
                              Principal=Principal('Service', ['ec2.amazonaws.com'])), ], ),
                ManagedPolicyArns=['arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy',
                                   'arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy',
                                   'arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly']
            )
            self.tpl.add_resource(role)
            profile = InstanceProfile(
                self.RESOURCE_NG_PROFILE.name, InstanceProfileName=self.tag_name, Path='/', Roles=[Ref(role)])
            self.tpl.add_output(
                Output(self.RESOURCE_NG_ROLE.name, Value=GetAtt(role, 'Arn'), Description='Node group role'))

        self.tpl.add_resource(profile)

        if self.sg_igresses:
            sg = SecurityGroup(
                self.RESOURCE_NG_SG.name, VpcId=self.cluster.vpc, Tags=Tags({'Name': self.tag_name, eks_tag: 'owned'}),
                GroupDescription='Security Group applied to the EKS node group',
                SecurityGroupIngress=[SecurityGroupRule(IpProtocol=r.protocol, FromPort=r.from_port, ToPort=r.to_port,
                                                        CidrIp=r.cidr) for r in self.sg_igresses]
            )
        else:
            sg = SecurityGroup(
                self.RESOURCE_NG_SG.name, VpcId=self.cluster.vpc, Tags=Tags({'Name': self.tag_name, eks_tag: 'owned'}),
                GroupDescription='Security Group applied to the EKS node group',
            )
        self.tpl.add_resource(sg)

        self.tpl.add_resource(SecurityGroupIngress(
            self.RESOURCE_NG_SG_INGRESS.name, DependsOn=sg, Description='Allow node to communicate with each other',
            GroupId=Ref(sg), SourceSecurityGroupId=Ref(sg), IpProtocol='-1', FromPort=0, ToPort=65535
        ))

        self.tpl.add_resource(SecurityGroupIngress(
            self.RESOURCE_NG_SG_CP_INGRESS.name, DependsOn=sg,
            Description='Allow kubelet and pods on the nodes to receive communication from the cluster control plane',
            GroupId=Ref(sg), SourceSecurityGroupId=self.cluster.sg, IpProtocol='tcp', FromPort=1025, ToPort=65535
        ))

        self.tpl.add_resource(SecurityGroupEgress(
            self.RESOURCE_CP_EGRESS_TO_NG.name, DependsOn=sg,
            Description='Allow the cluster control plane to communicate with nodes kubelet and pods',
            GroupId=self.cluster.sg, DestinationSecurityGroupId=Ref(sg), IpProtocol='tcp', FromPort=1025, ToPort=65535
        ))

        self.tpl.add_resource(SecurityGroupIngress(
            self.RESOURCE_CP_SG_INGRESS.name, DependsOn=sg,
            Description='Allow pods to communicate with the cluster API Server',
            GroupId=self.cluster.sg, SourceSecurityGroupId=Ref(sg), IpProtocol='tcp', FromPort=443, ToPort=443
        ))

        # keypair
        ec2 = boto3.session.Session().resource('ec2')
        r = self.resources.get(self.RESOURCE_NG_KEYPAIR.name)
        if not self.keypair:
            keyname = 'eks{}'.format(''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(5)))
            with open(self.ssh_public_key, 'rb') as f:
                ec2.import_key_pair(KeyName=keyname, PublicKeyMaterial=f.read())
            self.keypair = keyname
            self.keypair_imported = True
            self.tpl.add_output(Output(self.OUTPUT_KEYNAME, Value=self.keypair, Description='Imported kaypair name'))
            r.status = Status.created
        else:
            r.status = Status.provided

        r.resource_id = self.keypair

        # auto-scaling group and launch configuration
        if self.no_user_data:
            lc = LaunchConfiguration(
                self.RESOURCE_NG_ASG_LC.name, AssociatePublicIpAddress=self.use_public_ip,
                IamInstanceProfile=Ref(profile),
                ImageId=self.ami, InstanceType=self.instance, KeyName=self.keypair, SecurityGroups=[Ref(sg)])
        else:
            user_data = Base64(
                Join('', [line + '\n' for line in
                          Environment().from_string(self.USER_DATA).render(
                              ci=self.cluster, ng_asg=self.RESOURCE_NG_ASG.name, stack_name=self.stack_name,
                              max_pods=self.MAX_PODS.get(self.instance), region=self.region).split('\n')]))
            lc = LaunchConfiguration(
                self.RESOURCE_NG_ASG_LC.name, AssociatePublicIpAddress=self.use_public_ip,
                IamInstanceProfile=Ref(profile),
                ImageId=self.ami, InstanceType=self.instance, KeyName=self.keypair, SecurityGroups=[Ref(sg)],
                UserData=user_data)

        self.tpl.add_resource(lc)
        self.tpl.add_resource(AutoScalingGroup(
            self.RESOURCE_NG_ASG.name, DesiredCapacity=self.desired, MinSize=self.min, MaxSize=self.max,
            LaunchConfigurationName=Ref(lc), VPCZoneIdentifier=self.subnets,
            Tags=[Tag('Name', self.tag_name, True), Tag(eks_tag, 'owned', True)],
            UpdatePolicy=UpdatePolicy(
                AutoScalingRollingUpdate=AutoScalingRollingUpdate(MinInstancesInService=1, MaxBatchSize=1))))
Ejemplo n.º 7
0
))

ec2_ssh_ingress = t.add_resource(SecurityGroupIngress(
    'Ec2SshIngress',
    DependsOn='Ec2SecurityGroup',
    ToPort='22',
    FromPort='22',
    IpProtocol='tcp',
    GroupId=Ref(ec2_security_group),
    CidrIp=c.QUAD_ZERO,
))

ec2_egress = t.add_resource(SecurityGroupEgress(
    'Ec2Egress',
    DependsOn='Ec2SecurityGroup',
    ToPort='-1',
    IpProtocol='-1',
    GroupId=Ref(ec2_security_group),
    CidrIp=c.QUAD_ZERO,
))

###########################################
#             EC2 Instance
###########################################

server_instance = t.add_resource(Instance(
    'ServerInstance',
    DependsOn=['Ec2SecurityGroup'],
    SourceDestCheck='false',
    SecurityGroupIds=[Ref(ec2_security_group)],
    ImageId=FindInMap(
        'InstanceAmiMap',
Ejemplo n.º 8
0
AppStreamSGIngress01 = t.add_resource(
    SecurityGroupIngress(
        "AppStreamSGIngress01",
        GroupId=Ref("AppStreamSG"),
        CidrIp=Ref(AllowedIP),
        FromPort="443",
        ToPort="443",
        IpProtocol="tcp",
        Description="Allow HTTPS for Access to the Image Builder",
    ))

AppStreamEgress = t.add_resource(
    SecurityGroupEgress("AppStreamEgress",
                        GroupId=Ref("AppStreamSG"),
                        IpProtocol="-1",
                        FromPort="0",
                        ToPort="65535",
                        CidrIp="0.0.0.0/0"))

AppStreamImageBuilder = t.add_resource(
    appstr.ImageBuilder(
        "AppStreamImageBuilder",
        Description="Image Builder",
        EnableDefaultInternetAccess="true",
        ImageArn=Ref(AppStreamImageArn),
        InstanceType=Ref(InstanceType),
        Name="ImageBuilder",
        Tags=Tags(Name="Image Builder"),
        VpcConfig=appstr.VpcConfig(
            SecurityGroupIds=[Ref("AppStreamSG")],
            SubnetIds=[Ref("SubnetId")],
Ejemplo n.º 9
0
        LoadBalancerSG.title
        ],
    GroupId=Ref("instanceSecurityGroup"),
    IpProtocol='tcp',
    FromPort='80',
    ToPort='80',
    SourceSecurityGroupId=Ref("LoadBalancerSG")
))

SGBaseEgress = t.add_resource(SecurityGroupEgress(
    "SGBaseEgress",
    Description="Secures traffic to be allowed out of the LoadBalancerSG to the InstanceSecurityGroup",
    DependsOn=[
        instanceSecurityGroup.title,
        LoadBalancerSG.title
        ],
    GroupId=Ref("LoadBalancerSG"),
    IpProtocol='tcp',
    FromPort='80',
    ToPort='80',
    DestinationSecurityGroupId=Ref("instanceSecurityGroup")
))


LoadBalancer = t.add_resource(LoadBalancer(
    "LoadBalancer",
    Name="QAAppLoadBalancerTrop",
    Scheme="internet-facing",
    Subnets=[
        Ref("DMZSubnet1a"),
        Ref("DMZSubnet1b"),
Ejemplo n.º 10
0
                         GroupId=Ref("CustomSg"),
                         IpProtocol="tcp",
                         FromPort="22",
                         ToPort="22",
                         SourceSecurityGroupId=Ref("CustomSg")),
    SecurityGroupIngress('SgRuleSshIBS',
                         DependsOn="CustomSg",
                         GroupId=Ref("CustomSg"),
                         IpProtocol="tcp",
                         FromPort="22",
                         ToPort="22",
                         CidrIp="203.122.24.146/32"),
    SecurityGroupEgress('SgRuleAllTraffic',
                        DependsOn="CustomSg",
                        GroupId=Ref("CustomSg"),
                        IpProtocol="-1",
                        FromPort="0",
                        ToPort="0",
                        CidrIp="0.0.0.0/0")
])

for _ in range(subnetcount):
    if _ % 2 is 0:
        typ = "Public"
    else:
        typ = "Private"
    t.add_resource(
        Subnet(F"S{_}",
               AvailabilityZone=fazes[_],
               CidrBlock=Select(_, Cidr(cidr, subnetcount, subnetmask)),
               VpcId=Ref("vpc"),