Exemplo n.º 1
0
def main():
    try:
        if len(config.templateParameterValues['SubnetAD']) > 2:
            action = {}
            action["statusCode"] = "400"
            action["body"] = config.json.dumps(
                'Simple AD Allow only 2 subnets!')
            return action
        else:
            name = {'Ref': 'SimpleADName'}
            if config.templateParameterValues['Alias'] != '':
                alias = {'Ref': 'Alias'}
            else:
                alias = ''
            recname = config.templateParameterValues['NetbiosNm']
            desc = {'Ref': 'DescAD'}
            sso = {'Ref': 'SSO'}
            pwd = {'Ref': 'SimpleADPwd'}
            netb = {'Ref': 'NetbiosNm'}
            size = {'Ref': 'Size'}
            subad = {'Ref': 'SubnetAD'}
            vpc = {'Ref': 'VPC'}
            r53endname = config.templateParameterValues['R53EndPtName']
            subr53end = config.templateParameterValues['SubnetR53End']
            sgr53end = config.templateParameterValues['SecGR53End']
            sgr53endact = config.templateParameterValues['SecGR53EndAct']
            sgr53endsrc = config.templateParameterValues['SecGR53EndSrc']
            config.fragment['Resources'] = {}
            config.fragment['Outputs'] = {}
            action = simpleAD.create(recname, name, alias, desc, sso, pwd,
                                     netb, size, subad, vpc, '')
            config.logger.info('Response: {}'.format(action))
            netsrc = []
            if ',' in sgr53endsrc:
                netsrc = list(sgr53endsrc.split(','))
            else:
                netsrc.append(sgr53endsrc)
            if sgr53endact == 'Create SG':
                action = securitygroup.create(vpc, r53endname)
                config.logger.info('Response: {}'.format(action))
                for src in netsrc:
                    if src.startswith('pl-'):
                        action = securitygroup.addingress(
                            'SecG' + r53endname, src, 'SourcePrefixListId',
                            '-1', '', '', '')
                        config.logger.info('Response: {}'.format(action))
                    elif src == 'zoneprefix':
                        with open('zonemap.cfg') as zonefile:
                            zonemap = config.json.load(zonefile)
                            srcprefix = zonemap['Mappings']['RegionMap'][
                                config.region]['PREFIXLIST']
                            action = securitygroup.addingress(
                                'SecG' + r53endname, srcprefix,
                                'SourcePrefixListId', '-1', '', '', '')
                            config.logger.info('Response: {}'.format(action))
                    else:
                        ip = config.IPNetwork(src)
                        if ip.version == 4:
                            action = securitygroup.addingress(
                                'SecG' + r53endname, str(ip), 'CidrIp', '-1',
                                '', '', '')
                            config.logger.info('Response: {}'.format(action))
                        if ip.version == 6:
                            action = securitygroup.addingress(
                                'SecG' + r53endname, str(ip), 'CidrIpv6', '-1',
                                '', '', '')
                sg = [{'Ref': 'SecG' + r53endname}]
                action = r53resolver.createendpoint(r53endname, 'OUTBOUND', sg,
                                                    subr53end,
                                                    'SimpleAD' + recname)
                config.logger.info('Response: {}'.format(action))
            elif sgr53endact == 'Update SG':
                for src in netsrc:
                    if src.startswith('pl-'):
                        action = securitygroup.addingress(
                            sgr53end[0], src, 'SourcePrefixListId', '-1', '',
                            '', '')
                        config.logger.info('Response: {}'.format(action))
                    elif src == 'zoneprefix':
                        with open('zonemap.cfg') as zonefile:
                            zonemap = config.json.load(zonefile)
                            srcprefix = zonemap['Mappings']['RegionMap'][
                                config.region]['PREFIXLIST']
                            action = securitygroup.addingress(
                                sgr53end[0], srcprefix, 'SourcePrefixListId',
                                '-1', '', '', '')
                            config.logger.info('Response: {}'.format(action))
                    else:
                        ip = config.IPNetwork(src)
                        if ip.version == 4:
                            action = securitygroup.addingress(
                                sgr53end[0], ip, 'CidrIp', '-1', '', '', '')
                            config.logger.info('Response: {}'.format(action))
                        if ip.version == 6:
                            action = securitygroup.addingress(
                                sgr53end[0], ip, 'CidrIpv6', '-1', '', '', '')
                            config.logger.info('Response: {}'.format(action))
                sg = sgr53end
                action = r53resolver.createendpoint(r53endname, 'OUTBOUND', sg,
                                                    subr53end,
                                                    'SimpleAD' + recname)
                config.logger.info('Response: {}'.format(action))
            else:
                sg = sgr53end
                action = r53resolver.createendpoint(r53endname, 'OUTBOUND', sg,
                                                    subr53end,
                                                    'SimpleAD' + recname)
                config.logger.info('Response: {}'.format(action))
            dep = ['SimpleAD' + recname]
            keylist = {
                'Version': 'V0.0.1',
                'DirectoryId': {
                    'Ref': 'SimpleAD' + recname
                }
            }
            action = customresource.create(
                'namesrv',
                'arn:aws:lambda:eu-west-1:778501541840:function:CloudFormationCustomResources-CustResFunc-242OKZQ449P0',
                dep, keylist)
            config.logger.info('Response: {}'.format(action))
            dep = ['SimpleAD' + recname, 'R53ResEnd' + r53endname]
            dns = {"Fn::GetAtt": ["namesrv", "DnsIpAddrs"]}
            res = {'Ref': 'R53ResEnd' + r53endname}
            action = r53resolver.createrule(r53endname + recname, name, res,
                                            'FORWARD', dns, dep)
            config.logger.info('Response: {}'.format(action))
            assname = recname + 'vpc'
            if '-' in assname:
                assname = assname.replace('-', '')
            if '.' in assname:
                assname = assname.replace('.', '')
            if ' ' in assname:
                assname = assname.replace(' ', '')
            resruleid = {'Ref': 'R53ResRule' + r53endname + recname}
            dep = ['R53ResRule' + r53endname + recname]
            action = r53resolver.assocrule(assname, resruleid, vpc, dep)
            config.logger.info('Response: {}'.format(action))
            action = {}
            action["statusCode"] = "200"
            action["body"] = config.json.dumps('Template Update Success!')
            config.logger.info('Response: {}'.format(action))
    except Exception as e:
        action = {}
        config.logger.error('ERROR: {}'.format(e))
        config.traceback.print_exc()
        action["statusCode"] = "500"
        action["body"] = str(e)
        config.logger.info('Response: {}'.format(action))
    return action
Exemplo n.º 2
0
def main():
    try:
        VPC = config.templateParameterValues['VPC']
        Subnet = config.templateParameterValues['Subnet']
        SecurityGroup = config.templateParameterValues['SecurityGroup']
        SGAction = config.templateParameterValues['SGAction']
        ASGAction = config.templateParameterValues['ASGAction']
        SGSRC = config.templateParameterValues['SGSRC']
        PublicIP = config.templateParameterValues['PublicIP']
        UpdateDNS = config.templateParameterValues['UpdateDNS']
        HostedZones = config.templateParameterValues['HostedZones']
        InstType = {'Ref': 'InstType'}
        InstNumb = {'Ref': 'InstNumb'}
        InstMin = {'Ref': 'InstMin'}
        InstMax = {'Ref': 'InstMax'}
        Hostname = config.templateParameterValues['Hostname']
        LatestAmiId = {'Ref': 'LatestAmiId'}
        InstProfAct = config.templateParameterValues['InstProfAct']
        MgtPol = config.templateParameterValues['MgtPol']
        Keyname = config.templateParameterValues['Keyname']
        usrdata = config.templateParameterValues['usrdata']
        config.fragment['Resources'] = {}
        config.fragment['Outputs'] = {}
        netsrc = []
        if ',' in SGSRC:
            netsrc = list(SGSRC.split(','))
        else:
            netsrc.append(SGSRC)
        if SGAction == 'Create SG':
            action = securitygroup.create(VPC,Hostname)
            config.logger.info('Response: {}'.format(action))
            for src in netsrc:
                if src.startswith('pl-'):
                    action = securitygroup.addingress('SecG' + Hostname,src,'SourcePrefixListId','-1','','','')
                    config.logger.info('Response: {}'.format(action))
                elif src == 'zoneprefix':
                    with open('zonemap.cfg') as zonefile:
                        zonemap = config.json.load(zonefile)
                        srcprefix = zonemap['Mappings']['RegionMap'][config.region]['PREFIXLIST']
                        action = securitygroup.addingress('SecG' + Hostname,srcprefix,'SourcePrefixListId','-1','','','')
                        config.logger.info('Response: {}'.format(action))
                else:
                    ip = config.IPNetwork(src)
                    if ip.version == 4:
                        action = securitygroup.addingress('SecG' + Hostname,str(ip),'CidrIp','-1','','','')
                        config.logger.info('Response: {}'.format(action))
                    if ip.version == 6:
                        action = securitygroup.addingress('SecG' + Hostname,str(ip),'CidrIpv6','-1','','','')
            srcsg = {'Ref': 'SecG' + Hostname}
            action = securitygroup.addingress('SecG' + Hostname,srcsg,'SourceSecurityGroupId','-1','','','')
            sg = [ { 'Fn::GetAtt' : [ 'SecG' + Hostname, 'GroupId' ] } ]
        elif SGAction == 'Update SG':
            for src in netsrc:
                if src.startswith('pl-'):
                    action = securitygroup.addingress(SecurityGroup[0],src,'SourcePrefixListId','-1','','','')
                    config.logger.info('Response: {}'.format(action))
                elif src == 'zoneprefix':
                    with open('zonemap.cfg') as zonefile:
                        zonemap = config.json.load(zonefile)
                        srcprefix = zonemap['Mappings']['RegionMap'][config.region]['PREFIXLIST']
                        action = securitygroup.addingress(SecurityGroup[0],srcprefix,'SourcePrefixListId','-1','','','')
                        config.logger.info('Response: {}'.format(action))
                else:
                    ip = config.IPNetwork(src)
                    if ip.version == 4:
                        action = securitygroup.addingress(SecurityGroup[0],ip,'CidrIp','-1','','','')
                        config.logger.info('Response: {}'.format(action))
                    if ip.version == 6:
                        action = securitygroup.addingress(SecurityGroup[0],ip,'CidrIpv6','-1','','','')
                        config.logger.info('Response: {}'.format(action))
            sg = {'Ref': 'SecurityGroup'}
        elif SGAction == 'Use SG with no change':
            sg = {'Ref': 'SecurityGroup'}
        if InstProfAct == 'No Role':
            InstProfName = ''
        elif InstProfAct == 'Create New Role':
            action = createiamrole.manag('IAMRole' + Hostname,'ec2.amazonaws.com',MgtPol)
            config.logger.info('Response: {}'.format(action))
            action = createinstprof.main('InstProf' + Hostname,'IAMRole' + Hostname,'yes')
            config.logger.info('Response: {}'.format(action))
            InstProfName = {'Ref': 'InstProf' + Hostname}
        elif InstProfAct == 'Use Existent Role':
            InstProfName = {'Ref': 'InstProfName'}
        action = launchtemplate.create(Hostname,InstType,LatestAmiId,sg,InstProfName,Keyname,usrdata,PublicIP,'')
        config.logger.info('Response: {}'.format(action))
        ltemp = 'LT' + Hostname
        dep = ['LT' + Hostname]
        action = autoscalegroup.create(Hostname,'',InstNumb,'',ltemp,'',InstMin,InstMax,Subnet,dep)
        config.logger.info('Response: {}'.format(action))
        if ASGAction == 'Yes':
            asgname = 'ASG' + Hostname
            ncapac = config.templateParameterValues['InstNumb']
            capac = 'DesiredCapacity:' + ncapac
            recr = {'Ref': 'AsgActStartRec'}
            dep = [asgname]
            action = autoscalegroup.schdact('startday',asgname,capac,'','',recr,dep)
            config.logger.info('Response: {}'.format(action))
            mincapac = config.templateParameterValues['InstMin']
            capac = 'DesiredCapacity:' + mincapac
            recr = {'Ref': 'AsgActStopRec'}
            action = autoscalegroup.schdact('stopday',asgname,capac,'','',recr,dep)
            config.logger.info('Response: {}'.format(action))
        action = {}
        action["statusCode"] = "200"
        action["body"] = config.json.dumps('Template Update Success!')
        config.logger.info('Response: {}'.format(action))
        return action
    except Exception as e:
        action = {}
        config.logger.error('ERROR: {}'.format(e))
        config.traceback.print_exc()
        action["statusCode"] = "500"
        action["body"] = str(e)
        config.logger.info('Response: {}'.format(action))
    return action
Exemplo n.º 3
0
def vpc(UpdateDNS, PrivHZ, vpcname, DualStack, VpcCidr, PubSub, PubSize,
        PubSubAZs, PrivSub, PrivSize, PrivSubAZs, NatGW):
    try:
        config.logger.info('Create VPC ' + vpcname +
                           ' : {0}\nDualStack: {1}'.format(VpcCidr, UpdateDNS))
        action = createvpc.main(vpcname, VpcCidr, UpdateDNS, PrivHZ)
        config.logger.info('Response: {}'.format(action))
        cidrvpc = config.IPNetwork(VpcCidr)
        if DualStack == 'Yes':
            action = createvpc6.main(vpcname)
            config.logger.info('Response: {}'.format(action))
        if UpdateDNS == 'Yes':
            action = createdhcpoptions.main(vpcname, PrivHZ)
            config.logger.info('Response: {}'.format(action))
        if PubSub == 'Yes':
            action = createinternetgw.main(vpcname, DualStack)
            config.logger.info('Response: {}'.format(action))
            action = createroutetable.main(vpcname, 'Pub', DualStack)
            config.logger.info('Response: {}'.format(action))
            action = route.addv4('PubDefaultIpv4', '0.0.0.0/0',
                                 'RTPub' + vpcname, 'GatewayId',
                                 'IGW' + vpcname)
            config.logger.info('Response: {}'.format(action))
            if DualStack == 'Yes':
                action = route.addv6('PubDefaultIpv6', '::/0',
                                     'RTPub' + vpcname, 'GatewayId',
                                     'IGW' + vpcname)
                config.logger.info('Response: {}'.format(action))
            subnets = list(cidrvpc.subnet(PubSize))
            maxsub = len(subnets)
            i = 0  # Counter to be used in iterations
            #cidrblock=VpcCidr.split('/',2)[1]
            #ipbits=32-int(PubSize)
            #ipaddr=(2**ipbits)
            for id in PubSubAZs:
                if DualStack == 'Yes':
                    action = createsubnet.main(vpcname, 'Pub' + vpcname,
                                               str(subnets[i]), id, DualStack,
                                               'IPv6', i, 'RTPub' + vpcname)
                    config.logger.info('Response: {}'.format(action))
                else:
                    action = createsubnet.main(vpcname, 'Pub' + vpcname,
                                               str(subnets[i]), id, DualStack,
                                               'Pub', i, 'RTPub' + vpcname)
                    config.logger.info('Response: {}'.format(action))
                i = i + 1
        if PrivSub == 'Yes':
            subnets = list(cidrvpc.subnet(PrivSize))
            maxsub = len(subnets)
            if DualStack == 'Yes':
                action = createegressgw.main(vpcname)
                config.logger.info('Response: {}'.format(action))
            if NatGW == 'Single' and PubSub == 'Yes':
                i = maxsub - 1
                i6 = 255
                action = createroutetable.main(vpcname, 'Priv', DualStack)
                config.logger.info('Response: {}'.format(action))
                action = createnatinstance.main(vpcname, 'Pub' + vpcname,
                                                PubSubAZs[0])
                config.logger.info('Response: {}'.format(action))
                action = route.addv4('PrivDefaultIpv4' + vpcname, '0.0.0.0/0',
                                     'RTPriv' + vpcname, 'NatGatewayId',
                                     'NATgwAZ' + vpcname + PubSubAZs[0][-2:])
                config.logger.info('Response: {}'.format(action))
                if DualStack == 'Yes':
                    action = route.addv6('PrivDefaultIpv6' + vpcname, '::/0',
                                         'RTPriv' + vpcname,
                                         'EgressOnlyInternetGatewayId',
                                         'EgressGW' + vpcname)
                    config.logger.info('Response: {}'.format(action))
                for id in PrivSubAZs:
                    if DualStack == 'Yes':
                        action = createsubnet.main(vpcname, 'Priv' + vpcname,
                                                   str(subnets[i]), id,
                                                   DualStack, 'IPv6', i6,
                                                   'RTPriv' + vpcname)
                        config.logger.info('Response: {}'.format(action))
                    else:
                        action = createsubnet.main(vpcname, 'Priv' + vpcname,
                                                   str(subnets[i]), id,
                                                   DualStack, 'None', i6,
                                                   'RTPriv' + vpcname)
                        config.logger.info('Response: {}'.format(action))
                    i = i - 1
                    i6 = i6 - 1
            elif NatGW == 'PerAz' and PubSub == 'Yes':
                i = maxsub - 1
                i6 = 255
                for id in PrivSubAZs:
                    action = createroutetable.main(vpcname, 'Priv' + id[-2:],
                                                   DualStack)
                    config.logger.info('Response: {}'.format(action))
                    action = createnatinstance.main(vpcname, 'Pub' + vpcname,
                                                    id)
                    config.logger.info('Response: {}'.format(action))
                    action = route.addv4(
                        'Priv' + vpcname + id[-2:] + 'DefaultIpv4',
                        '0.0.0.0/0', 'RTPriv' + id[-2:] + vpcname,
                        'NatGatewayId', 'NATgwAZ' + vpcname + id[-2:])
                    config.logger.info('Response: {}'.format(action))
                    if DualStack == 'Yes':
                        action = route.addv6(
                            'PrivDefaultIpv6' + vpcname + id[-2:], '::/0',
                            'RTPriv' + id[-2:] + vpcname,
                            'EgressOnlyInternetGatewayId',
                            'EgressGW' + vpcname)
                        config.logger.info('Response: {}'.format(action))
                        action = createsubnet.main(
                            vpcname, 'Priv' + vpcname, str(subnets[i]), id,
                            DualStack, 'IPv6', i6,
                            'RTPriv' + id[-2:] + vpcname)
                        config.logger.info('Response: {}'.format(action))
                    else:
                        action = createsubnet.main(
                            vpcname, 'Priv' + vpcname, str(subnets[i]), id,
                            DualStack, 'None', i6,
                            'RTPriv' + id[-2:] + vpcname)
                        config.logger.info('Response: {}'.format(action))
                    i = i - 1
                    i6 = i6 - 1
            else:
                i = maxsub - 1
                i6 = 255
                for id in PrivSubAZs:
                    if DualStack == 'Yes':
                        action = createsubnet.main(vpcname, 'Priv' + vpcname,
                                                   str(subnets[i]), id,
                                                   DualStack, 'IPv6', i6,
                                                   'None')
                        config.logger.info('Response: {}'.format(action))
                    else:
                        action = createsubnet.main(vpcname, 'Priv' + vpcname,
                                                   str(subnets[i]), id,
                                                   DualStack, 'None', i6,
                                                   'None')
                        config.logger.info('Response: {}'.format(action))
                    i = i - 1
                    i6 = i6 - 1
        action = {}
        action["statusCode"] = "200"
        action["body"] = config.json.dumps('VPC Template' + vpcname +
                                           ' Update Success!')
        config.logger.info('Response: {}'.format(action))
        return action
    except Exception as e:
        action = {}
        config.logger.error('ERROR: {}'.format(e))
        config.traceback.print_exc()
        action["statusCode"] = "500"
        action["body"] = str(e)
        config.logger.info('Response: {}'.format(action))
    return action
Exemplo n.º 4
0
def main():
    try:
        config.fragment['Resources'] = {}
        config.fragment['Outputs'] = {}
        UpdateDNS = 'No'
        PrivHZ = ''
        # create GW VPC 
        vpcname = config.templateParameterValues['VpcName']
        DualStack = config.templateParameterValues['DualStack']
        VpcCidr = config.templateParameterValues['VpcCidr']
        PubSub = config.templateParameterValues['PubSub']
        PubSize = int(config.templateParameterValues['PubSize'])
        PubSubAZs = config.templateParameterValues['PubSubAZs']
        PrivSub = config.templateParameterValues['PrivSub']
        PrivSize = int(config.templateParameterValues['PrivSize'])
        PrivSubAZs = config.templateParameterValues['PrivSubAZs']
        NatGW = config.templateParameterValues['NatGW']
        SecurityGroup = config.templateParameterValues['SecurityGroup']
        SGAction = config.templateParameterValues['SGAction']
        ASGAction = config.templateParameterValues['ASGAction']
        SGSRC = config.templateParameterValues['SGSRC']
        PublicIP = config.templateParameterValues['PublicIP']
        UpdateDNS = config.templateParameterValues['UpdateDNS']
        HostedZones = config.templateParameterValues['HostedZones']
        InstType = {'Ref': 'InstType'}
        InstNumb = {'Ref': 'InstNumb'}
        InstMin = {'Ref': 'InstMin'}
        InstMax = {'Ref': 'InstMax'}
        Hostname = config.templateParameterValues['Hostname']
        LatestAmiId = {'Ref': 'LatestAmiId'}
        InstProfAct = config.templateParameterValues['InstProfAct']
        MgtPol = config.templateParameterValues['MgtPol']
        Keyname = config.templateParameterValues['Keyname']
        usrdata = config.templateParameterValues['usrdata']
        action = stack.vpc(UpdateDNS,PrivHZ,vpcname,DualStack,VpcCidr,PubSub,PubSize,PubSubAZs,PrivSub,PrivSize,PrivSubAZs,NatGW)
        config.logger.info('Response: {}'.format(action))
        # find subnets to deploy GW
        Subnet = []
        for id in PubSubAZs:
            sub.append("Ref" : vpcname + name + 'SubAZ' + AZ[-2:])
        # create GWLB
        action = elbv2.lb('GWLB','dualstack','gateway',Subnet,'','','')
        config.logger.info('Response: {}'.format(action))
        netsrc = []
        if ',' in SGSRC:
            netsrc = list(SGSRC.split(','))
        else:
            netsrc.append(SGSRC)
        # create Security Group for GW
        if SGAction == 'Create SG':
            vpcid = {"Ref" : 'Vpc' + vpcname }
            sgname = 'SGGW' + vpcname
            action = securitygroup.create(vpcid,sgname)
            config.logger.info('Response: {}'.format(action))
            for src in netsrc:
                # create Rules for adm GW
                if src.startswith('pl-'):
                    action = securitygroup.addingress(sgname,src,'SourcePrefixListId','-1','','','')
                    config.logger.info('Response: {}'.format(action))
                elif src == 'zoneprefix':
                    with open('zonemap.cfg') as zonefile:
                        zonemap = config.json.load(zonefile)
                        srcprefix = zonemap['Mappings']['RegionMap'][config.region]['PREFIXLIST']
                        action = securitygroup.addingress(sgname,srcprefix,'SourcePrefixListId','-1','','','')
                        config.logger.info('Response: {}'.format(action))
                else:
                    ip = config.IPNetwork(src)
                    if ip.version == 4:
                        action = securitygroup.addingress(sgname,str(ip),'CidrIp','-1','','','')
                        config.logger.info('Response: {}'.format(action))
                    if ip.version == 6:
                        action = securitygroup.addingress(sgname,str(ip),'CidrIpv6','-1','','','')
            srcsg = {'Ref': sgname}
            # create Rules for GW works
            action = securitygroup.addingress(sgname,VpcCidr,'CidrIp','udp','6081','6081','Geneve')
            sg = [ { 'Fn::GetAtt' : [ sgname, 'GroupId' ] } ]
        elif SGAction == 'Update SG':
            for src in netsrc:
                if src.startswith('pl-'):
                    # create Rules for GW
                    action = securitygroup.addingress(SecurityGroup[0],src,'SourcePrefixListId','-1','','','')
                    config.logger.info('Response: {}'.format(action))
                elif src == 'zoneprefix':
                    with open('zonemap.cfg') as zonefile:
                        zonemap = config.json.load(zonefile)
                        srcprefix = zonemap['Mappings']['RegionMap'][config.region]['PREFIXLIST']
                        action = securitygroup.addingress(SecurityGroup[0],srcprefix,'SourcePrefixListId','-1','','','')
                        config.logger.info('Response: {}'.format(action))
                else:
                    ip = config.IPNetwork(src)
                    if ip.version == 4:
                        action = securitygroup.addingress(SecurityGroup[0],ip,'CidrIp','-1','','','')
                        config.logger.info('Response: {}'.format(action))
                    if ip.version == 6:
                        action = securitygroup.addingress(SecurityGroup[0],ip,'CidrIpv6','-1','','','')
                        config.logger.info('Response: {}'.format(action))
            sg = {'Ref': 'SecurityGroup'}
        elif SGAction == 'Use SG with no change':
            sg = {'Ref': 'SecurityGroup'}
        if InstProfAct == 'No Role':
            InstProfName = ''
        elif InstProfAct == 'Create New Role':
            # create Instance Profile
            action = createiamrole.manag('IAMRole' + Hostname,'ec2.amazonaws.com',MgtPol)
            config.logger.info('Response: {}'.format(action))
            action = createinstprof.main('InstProf' + Hostname,'IAMRole' + Hostname,'yes')
            config.logger.info('Response: {}'.format(action))
            InstProfName = {'Ref': 'InstProf' + Hostname}
        elif InstProfAct == 'Use Existent Role':
            InstProfName = {'Ref': 'InstProfName'}
        # create GW Launch Template
        action = launchtemplate.create(Hostname,InstType,LatestAmiId,sg,InstProfName,Keyname,usrdata,PublicIP,'')
        config.logger.info('Response: {}'.format(action))
        ltemp = 'LT' + Hostname
        dep = ['LT' + Hostname]
        # create GW Target Group
        hcmatch = { "HttpCode" : "200–399" }
        hcheltc = 3
        hcunheltc = 3
        hctout = 5
        hcintv = 10
        hctgatt =''
        hctarg = ''
        dep = ['Vpc' + vpcname]
        action = elbv2.tgrp(Hostname,vpcid,'instance','GENEVE',6081,'HTTP','80','/',hcmatch,hcheltc,hcunheltc,hctout,hcintv,hctgatt,hctarg,dep)
        config.logger.info('Response: {}'.format(action))
        # create GW Auto Scale Group
        LB = { "Fn::GetAtt" : [ 'TGRP' + name, LoadBalancerArns ]  }
        dep = ['Vpc' + vpcname,'TGRP' + name]
        action = autoscalegroup.create(Hostname,'',InstNumb,'',ltemp,LB,InstMin,InstMax,Subnet,dep)
        config.logger.info('Response: {}'.format(action))
        if ASGAction == 'Yes':
            asgname = 'ASG' + Hostname
            ncapac = config.templateParameterValues['InstNumb']
            capac = 'DesiredCapacity:' + ncapac
            recr = {'Ref': 'AsgActStartRec'}
            dep = [asgname]
            action = autoscalegroup.schdact('startday',asgname,capac,'','',recr,dep)
            config.logger.info('Response: {}'.format(action))
            mincapac = config.templateParameterValues['InstMin']
            capac = 'DesiredCapacity:' + mincapac
            recr = {'Ref': 'AsgActStopRec'}
            action = autoscalegroup.schdact('stopday',asgname,capac,'','',recr,dep)
            config.logger.info('Response: {}'.format(action))
        # create LB Listener
        act = [ { "Type" : "forward" } ]
        action = elbv2.lst(Hostname,'','',act,LB,'','','','TGRP' + name)
        config.logger.info('Response: {}'.format(action))


        vpcname = config.templateParameterValues['VpcName1']
        DualStack = config.templateParameterValues['DualStack1']
        VpcCidr = config.templateParameterValues['VpcCidr1']
        PubSub = config.templateParameterValues['PubSub1']
        PubSize = int(config.templateParameterValues['PubSize1'])
        PubSubAZs = config.templateParameterValues['PubSubAZs1']
        PrivSub = config.templateParameterValues['PrivSub1']
        PrivSize = int(config.templateParameterValues['PrivSize1'])
        PrivSubAZs = config.templateParameterValues['PrivSubAZs1']
        NatGW = config.templateParameterValues['NatGW1']
        action = stack.vpc(UpdateDNS,PrivHZ,vpcname,DualStack,VpcCidr,PubSub,PubSize,PubSubAZs,PrivSub,PrivSize,PrivSubAZs,NatGW)
        config.logger.info('Response: {}'.format(action))

        vpcname = config.templateParameterValues['VpcName2']
        DualStack = config.templateParameterValues['DualStack2']
        VpcCidr = config.templateParameterValues['VpcCidr2']
        PubSub = config.templateParameterValues['PubSub2']
        PubSize = int(config.templateParameterValues['PubSize2'])
        PubSubAZs = config.templateParameterValues['PubSubAZs2']
        PrivSub = config.templateParameterValues['PrivSub2']
        PrivSize = int(config.templateParameterValues['PrivSize2'])
        PrivSubAZs = config.templateParameterValues['PrivSubAZs2']
        NatGW = config.templateParameterValues['NatGW2']
        action = stack.vpc(UpdateDNS,PrivHZ,vpcname,DualStack,VpcCidr,PubSub,PubSize,PubSubAZs,PrivSub,PrivSize,PrivSubAZs,NatGW)
        config.logger.info('Response: {}'.format(action))

        del config.fragment['Outputs']
        action = {}
        action["statusCode"] = "200"
        action["body"] = config.json.dumps('Template Update Success!')
        return action
    except Exception as e:
        action = {}
        config.logger.error('ERROR: {}'.format(e))
        config.traceback.print_exc()
        action["statusCode"] = "500"
        action["body"] = str(e)
        config.logger.info('Response: {}'.format(action))
    return action
Exemplo n.º 5
0
def main():
    try:
        vpntype = config.templateParameterValues['vpntype']
        gwid = config.templateParameterValues['gwid']
        peerip = config.templateParameterValues['peerip']
        peercert = config.templateParameterValues['peercert']
        peername = config.templateParameterValues['peername']
        vpnopt = config.templateParameterValues['vpnopt']
        peerregion = {'Ref': 'peerregion'}
        localasn = {'Ref': 'localasn'}
        peerasn = {'Ref': 'peerasn'}
        InstNumb = {'Ref': 'InstNumb'}
        tgwdesc = {'Ref': 'tgwdesc'}
        autoacceptshrdattach = {'Ref': 'autoacceptshrdattach'}
        defrtassoc = {'Ref': 'defrtassoc'}
        defrtprop = {'Ref': 'defrtprop'}
        dnssup = {'Ref': 'dnssup'}
        multicastsup = {'Ref': 'multicastsup'}
        ecmpsup = {'Ref': 'ecmpsup'}
        VPC = config.templateParameterValues['VPC']
        Subnet = config.templateParameterValues['Subnet']
        SecurityGroup = config.templateParameterValues['SecurityGroup']
        SGAction = config.templateParameterValues['SGAction']
        ASGAction = config.templateParameterValues['ASGAction']
        SGSRC = config.templateParameterValues['SGSRC']
        InstType = {'Ref': 'InstType'}
        InstNumb = {'Ref': 'InstNumb'}
        InstMin = {'Ref': 'InstMin'}
        InstMax = {'Ref': 'InstMax'}
        Hostname = config.templateParameterValues['Hostname']
        LatestAmiId = {'Ref': 'LatestAmiId'}
        InstProfAct = config.templateParameterValues['InstProfAct']
        MgtPol = config.templateParameterValues['MgtPol']
        Keyname = config.templateParameterValues['Keyname']
        usrdata = config.templateParameterValues['usrdata']
        config.fragment['Resources'] = {}
        config.fragment['Outputs'] = {}
        netsrc = []
        if ',' in SGSRC:
            netsrc = list(SGSRC.split(','))
        else:
            netsrc.append(SGSRC)
        if config.templateParameterValues[
                'localasn'] != 0 and config.templateParameterValues[
                    'localasn'] != 0:
            bgp = 1
        if vpntype != 'Software VPN':
            if peerip.startswith('cgw-'):
                cgw = {'Ref': peerip}
                dep = [peerip]
            elif peercert != '' and peerip == 'New':
                keylist = {
                    'Version': 'V0.0.4',
                    'CustomerGatewayCert': {
                        'CGWName': peername,
                        'Region': config.region,
                        'CGWASN': peerasn,
                        'CertificateArn': peercert
                    }
                }
                action = customresource.create(
                    'CustomerGatewayCert',
                    'arn:aws:lambda:eu-west-1:778501541840:function:CloudFormationCustomResources-CustResFunc-242OKZQ449P0',
                    '', keylist)
                cgw = {"Fn::GetAtt": ["CustomerGatewayCert", "CGWID"]}
                dep = ['CustomerGatewayCert']
            elif peerip == 'New' and peercert == '':
                cgw = {'Ref': peerip}
                dep = [peerip]
                keylist = {
                    'Version': 'V0.0.2',
                    'AllocateAddress': {
                        'Region': peerregion,
                        'Domain': 'vpc'
                    }
                }
                action = customresource.create(
                    'CGWAddr',
                    'arn:aws:lambda:eu-west-1:778501541840:function:CloudFormationCustomResources-CustResFunc-242OKZQ449P0',
                    '', keylist)
                cgwip = {"Fn::GetAtt": ["CGWAddr", "PublicIp"]}
                dep = ['CGWAddr']
                action = gateway.cgw('CGW', peerasn, cgwip, 'ipsec.1', bgp,
                                     dep)
                cgw = {'Ref': 'CGW'}
                dep = ['CGW']
            else:
                action = gateway.cgw('CGW', peerasn, peerip, 'ipsec.1', bgp,
                                     dep)
                cgw = {'Ref': 'CGW'}
                dep = ['CGW']
            if vpntype == 'VGW' and gwid == 'New':
                action = gateway.vgw('VGW', localasn, tgwdesc, 'ipsec.1', bgp,
                                     '')
                mygw = {'Ref': 'VGW'}
                dep.append('VGW')
            if vpntype == 'TGW' and gwid == 'New':
                action = gateway.tgw('TGW', localasn, tgwdesc, bgp,
                                     autoacceptshrdattach, defrtassoc,
                                     defrtprop, dnssup, multicastsup, ecmpsup,
                                     '')
                mygw = {'Ref': 'TGW'}
                dep.append('TGW')
            if gwid.startswith('vgw-') or gwid.startswith('tgw-'):
                mygw = {'Ref': gwid}
                dep.append(mygw)
            if vpnopt == 'default':
                action = gateway.vpn('VPN', cgw, bgp, mygw, vpntype, dep)
            else:
                myvpnopts = {}
                vpnaccel = config.templateParameterValues['vpnaccel']
                vpnipfamily = config.templateParameterValues['vpnipfamily']
                myvpnopts['EnableAcceleration'] = {}
                myvpnopts['EnableAcceleration'] = vpnaccel
                myvpnopts['StaticRoutesOnly'] = {}
                if bgp == 0:
                    myvpnopts['StaticRoutesOnly'] = True
                else:
                    myvpnopts['StaticRoutesOnly'] = False
                if vpntype == 'TGW':
                    myvpnopts['TunnelInsideIpVersion'] = {}
                    myvpnopts['TunnelInsideIpVersion'] = vpnipfamily
#                if vpnipfamily == 'ipv4' and vpntype == 'TGW':
#                    myvpnopts['LocalIpv4NetworkCidr'] = {}
#                    myvpnopts['LocalIpv4NetworkCidr'] = '0.0.0.0/0'
#                    myvpnopts['RemoteIpv4NetworkCidr'] = {}
#                    myvpnopts['RemoteIpv4NetworkCidr'] = '0.0.0.0/0'
#                if vpnipfamily == 'ipv6' and vpntype == 'TGW':
#                    myvpnopts['LocalIpv6NetworkCidr'] = {}
#                    myvpnopts['LocalIpv6NetworkCidr'] = '::/0'
#                    myvpnopts['RemoteIpv6NetworkCidr'] = {}
#                    myvpnopts['RemoteIpv6NetworkCidr'] = '::/0'
                myvpnopts['TunnelOptions'] = []
                for i in range(2):
                    myvpnopts['TunnelOptions'].append({})
                    if config.templateParameterValues['tunnel' + str(i) +
                                                      'insidecidrv4'] != '':
                        myvpnopts['TunnelOptions'][i]['TunnelInsideCidr'] = {}
                        myvpnopts['TunnelOptions'][i]['TunnelInsideCidr'] = {
                            'Ref': 'tunnel' + str(i) + 'insidecidrv4'
                        }
                    if config.templateParameterValues['tunnel' + str(i) +
                                                      'insidecidrv6'] != '':
                        myvpnopts['TunnelOptions'][i][
                            'TunnelInsideIpv6Cidr'] = {}
                        myvpnopts['TunnelOptions'][i][
                            'TunnelInsideIpv6Cidr'] = {
                                'Ref': 'tunnel' + str(i) + 'insidecidrv6'
                            }
                    if config.templateParameterValues['tunnel' + str(i) +
                                                      'sharedkey'] != '':
                        myvpnopts['TunnelOptions'][i]['PreSharedKey'] = {}
                        myvpnopts['TunnelOptions'][i]['PreSharedKey'] = {
                            'Ref': 'tunnel' + str(i) + 'sharedkey'
                        }
                    if config.templateParameterValues[
                            'tunnelph1lifetime'] != '':
                        myvpnopts['TunnelOptions'][i][
                            'Phase1LifetimeSeconds'] = {}
                        myvpnopts['TunnelOptions'][i][
                            'Phase1LifetimeSeconds'] = {
                                'Ref': 'tunnelph1lifetime'
                            }
                    if config.templateParameterValues[
                            'tunnelph2lifetime'] != '':
                        myvpnopts['TunnelOptions'][i][
                            'Phase2LifetimeSeconds'] = {}
                        myvpnopts['TunnelOptions'][i][
                            'Phase2LifetimeSeconds'] = {
                                'Ref': 'tunnelph2lifetime'
                            }
                    if config.templateParameterValues['tunnelrekeymarg'] != '':
                        myvpnopts['TunnelOptions'][i][
                            'RekeyMarginTimeSeconds'] = {}
                        myvpnopts['TunnelOptions'][i][
                            'RekeyMarginTimeSeconds'] = {
                                'Ref': 'tunnelrekeymarg'
                            }
                    if config.templateParameterValues['tunnelrekeyfuzz'] != '':
                        myvpnopts['TunnelOptions'][i][
                            'RekeyFuzzPercentage'] = {}
                        myvpnopts['TunnelOptions'][i][
                            'RekeyFuzzPercentage'] = {
                                'Ref': 'tunnelrekeyfuzz'
                            }
                    if config.templateParameterValues['tunnelreplaywin'] != '':
                        myvpnopts['TunnelOptions'][i]['ReplayWindowSize'] = {}
                        myvpnopts['TunnelOptions'][i]['ReplayWindowSize'] = {
                            'Ref': 'tunnelreplaywin'
                        }
                    if config.templateParameterValues['tunneldpdtimeout'] != '':
                        myvpnopts['TunnelOptions'][i]['DPDTimeoutSeconds'] = {}
                        myvpnopts['TunnelOptions'][i]['DPDTimeoutSeconds'] = {
                            'Ref': 'tunneldpdtimeout'
                        }
#                    if config.templateParameterValues['tunneldpdact'] != '' and vpntype == 'TGW':
#                        myvpnopts['TunnelOptions'][i]['DPDTimeoutAction'] = {}
#                        myvpnopts['TunnelOptions'][i]['DPDTimeoutAction'] = {'Ref' : 'tunneldpdact'}
                    if config.templateParameterValues['tunnelencalg'] != '':
                        myvpnopts['TunnelOptions'][i][
                            'Phase1EncryptionAlgorithms'] = []
                        myvpnopts['TunnelOptions'][i][
                            'Phase1EncryptionAlgorithms'].append(
                                {'Value': {
                                    'Ref': 'tunnelencalg'
                                }})
                        myvpnopts['TunnelOptions'][i][
                            'Phase2EncryptionAlgorithms'] = []
                        myvpnopts['TunnelOptions'][i][
                            'Phase2EncryptionAlgorithms'].append(
                                {'Value': {
                                    'Ref': 'tunnelencalg'
                                }})
                    if config.templateParameterValues['tunnelintalg'] != '':
                        myvpnopts['TunnelOptions'][i][
                            'Phase1IntegrityAlgorithms'] = []
                        myvpnopts['TunnelOptions'][i][
                            'Phase1IntegrityAlgorithms'].append(
                                {'Value': {
                                    'Ref': 'tunnelintalg'
                                }})
                        myvpnopts['TunnelOptions'][i][
                            'Phase2IntegrityAlgorithms'] = []
                        myvpnopts['TunnelOptions'][i][
                            'Phase2IntegrityAlgorithms'].append(
                                {'Value': {
                                    'Ref': 'tunnelintalg'
                                }})
                    if config.templateParameterValues['tunneldhg'] != '':
                        myvpnopts['TunnelOptions'][i][
                            'Phase1DHGroupNumbers'] = []
                        myvpnopts['TunnelOptions'][i][
                            'Phase1DHGroupNumbers'].append(
                                {'Value': {
                                    'Ref': 'tunneldhg'
                                }})
                        myvpnopts['TunnelOptions'][i][
                            'Phase2DHGroupNumbers'] = []
                        myvpnopts['TunnelOptions'][i][
                            'Phase2DHGroupNumbers'].append(
                                {'Value': {
                                    'Ref': 'tunneldhg'
                                }})
                    if config.templateParameterValues['tunnelikev'] != '':
                        myvpnopts['TunnelOptions'][i]['IKEVersions'] = []
                        myvpnopts['TunnelOptions'][i]['IKEVersions'].append(
                            {'Value': {
                                'Ref': 'tunnelikev'
                            }})
#                   if config.templateParameterValues['tunnelstartact'] != '' and vpntype == 'TGW':
#                       myvpnopts['TunnelOptions'][i]['StartupAction'] = {}
#                       myvpnopts['TunnelOptions'][i]['StartupAction'] = {'Ref' : 'tunnelstartact'}
                keylist = {
                    'Version': 'V0.0.3',
                    'VPNConn': {
                        'Customer-Gateway-Id': cgw,
                        'Gateway-Type': vpntype,
                        'Gateway-Id': mygw,
                        'VPNOptions': myvpnopts
                    }
                }
                action = customresource.create(
                    'VPNConn',
                    'arn:aws:lambda:eu-west-1:778501541840:function:CloudFormationCustomResources-CustResFunc-242OKZQ449P0',
                    '', keylist)
        else:
            if SGAction == 'Create SG':
                action = securitygroup.create(VPC, Hostname)
                config.logger.info('Response: {}'.format(action))
                for src in netsrc:
                    if src.startswith('pl-'):
                        action = securitygroup.addingress(
                            'SecG' + Hostname, src, 'SourcePrefixListId', '-1',
                            '', '', '')
                        config.logger.info('Response: {}'.format(action))
                    elif src == 'zoneprefix':
                        with open('zonemap.cfg') as zonefile:
                            zonemap = config.json.load(zonefile)
                            srcprefix = zonemap['Mappings']['RegionMap'][
                                config.region]['PREFIXLIST']
                            action = securitygroup.addingress(
                                'SecG' + Hostname, srcprefix,
                                'SourcePrefixListId', '-1', '', '', '')
                            config.logger.info('Response: {}'.format(action))
                    else:
                        ip = config.IPNetwork(src)
                        if ip.version == 4:
                            action = securitygroup.addingress(
                                'SecG' + Hostname, str(ip), 'CidrIp', '-1', '',
                                '', '')
                            config.logger.info('Response: {}'.format(action))
                        if ip.version == 6:
                            action = securitygroup.addingress(
                                'SecG' + Hostname, str(ip), 'CidrIpv6', '-1',
                                '', '', '')
                srcsg = {'Ref': 'SecG' + Hostname}
                action = securitygroup.addingress('SecG' + Hostname, srcsg,
                                                  'SourceSecurityGroupId',
                                                  '-1', '', '', '')
                sg = [{'Fn::GetAtt': ['SecG' + Hostname, 'GroupId']}]
            elif SGAction == 'Update SG':
                for src in netsrc:
                    if src.startswith('pl-'):
                        action = securitygroup.addingress(
                            SecurityGroup[0], src, 'SourcePrefixListId', '-1',
                            '', '', '')
                        config.logger.info('Response: {}'.format(action))
                    elif src == 'zoneprefix':
                        with open('zonemap.cfg') as zonefile:
                            zonemap = config.json.load(zonefile)
                            srcprefix = zonemap['Mappings']['RegionMap'][
                                config.region]['PREFIXLIST']
                            action = securitygroup.addingress(
                                SecurityGroup[0], srcprefix,
                                'SourcePrefixListId', '-1', '', '', '')
                            config.logger.info('Response: {}'.format(action))
                    else:
                        ip = config.IPNetwork(src)
                        if ip.version == 4:
                            action = securitygroup.addingress(
                                SecurityGroup[0], ip, 'CidrIp', '-1', '', '',
                                '')
                            config.logger.info('Response: {}'.format(action))
                        if ip.version == 6:
                            action = securitygroup.addingress(
                                SecurityGroup[0], ip, 'CidrIpv6', '-1', '', '',
                                '')
                            config.logger.info('Response: {}'.format(action))
                sg = [{'Ref': 'SecurityGroup'}]
            elif SGAction == 'Use SG with no change':
                sg = [{'Ref': 'SecurityGroup'}]
            if InstProfAct == 'No Role':
                InstProfName = ''
            elif InstProfAct == 'Create New Role':
                action = createiamrole.manag('IAMRole' + Hostname,
                                             'ec2.amazonaws.com', MgtPol)
                config.logger.info('Response: {}'.format(action))
                action = createinstprof.main('InstProf' + Hostname,
                                             'IAMRole' + Hostname, 'yes')
                config.logger.info('Response: {}'.format(action))
                InstProfName = {'Ref': 'InstProf' + Hostname}
            elif InstProfAct == 'Use Existent Role':
                InstProfName = {'Ref': 'InstProfName'}
            action = launchtemplate.create(Hostname, InstType, LatestAmiId, sg,
                                           InstProfName, Keyname, usrdata,
                                           'No', '')
            config.logger.info('Response: {}'.format(action))
            ltemp = 'LT' + Hostname
            dep = ['LT' + Hostname]
            action = autoscalegroup.create(Hostname, '', InstNumb, '', ltemp,
                                           '', InstMin, InstMax, Subnet, dep)
            config.logger.info('Response: {}'.format(action))
            if ASGAction == 'Yes':
                asgname = 'ASG' + Hostname
                ncapac = config.templateParameterValues['InstNumb']
                capac = 'DesiredCapacity:' + ncapac
                recr = {'Ref': 'AsgActStartRec'}
                dep = [asgname]
                action = autoscalegroup.schdact('startday', asgname, capac, '',
                                                '', recr, dep)
                config.logger.info('Response: {}'.format(action))
                mincapac = config.templateParameterValues['InstMin']
                capac = 'DesiredCapacity:' + mincapac
                recr = {'Ref': 'AsgActStopRec'}
                action = autoscalegroup.schdact('stopday', asgname, capac, '',
                                                '', recr, dep)
                config.logger.info('Response: {}'.format(action))
        action = {}
        action["statusCode"] = "200"
        action["body"] = config.json.dumps('Template Update Success!')
        config.logger.info('Response: {}'.format(action))
        return action
    except Exception as e:
        action = {}
        config.logger.error('ERROR: {}'.format(e))
        config.traceback.print_exc()
        action["statusCode"] = "500"
        action["body"] = str(e)
        config.logger.info('Response: {}'.format(action))
    return action