|
| 1 | +import click |
| 2 | +from clickclick import fatal_error |
| 3 | +from senza.aws import resolve_security_groups |
| 4 | +from senza.components.elastic_load_balancer import get_load_balancer_name |
| 5 | + |
| 6 | +from ..cli import AccountArguments, TemplateArguments |
| 7 | +from ..manaus import ClientError |
| 8 | +from ..manaus.acm import ACM, ACMCertificate |
| 9 | +from ..manaus.iam import IAM, IAMServerCertificate |
| 10 | +from ..manaus.route53 import convert_domain_records_to_alias |
| 11 | + |
| 12 | +SENZA_PROPERTIES = frozenset(['Domains', 'HealthCheckPath', 'HealthCheckPort', 'HealthCheckProtocol', |
| 13 | + 'HTTPPort', 'Name', 'SecurityGroups', 'SSLCertificateId', 'Type']) |
| 14 | + |
| 15 | + |
| 16 | +def get_listeners(lb_name, target_group_name, subdomain, main_zone, configuration, |
| 17 | + account_info: AccountArguments): |
| 18 | + ssl_cert = configuration.get('SSLCertificateId') |
| 19 | + |
| 20 | + if ACMCertificate.arn_is_acm_certificate(ssl_cert): |
| 21 | + # check if certificate really exists |
| 22 | + try: |
| 23 | + ACMCertificate.get_by_arn(account_info.Region, ssl_cert) |
| 24 | + except ClientError as e: |
| 25 | + error_msg = e.response['Error']['Message'] |
| 26 | + fatal_error(error_msg) |
| 27 | + elif IAMServerCertificate.arn_is_server_certificate(ssl_cert): |
| 28 | + # TODO check if certificate exists |
| 29 | + pass |
| 30 | + elif ssl_cert is not None: |
| 31 | + certificate = IAMServerCertificate.get_by_name(account_info.Region, |
| 32 | + ssl_cert) |
| 33 | + ssl_cert = certificate.arn |
| 34 | + elif main_zone is not None: |
| 35 | + if main_zone: |
| 36 | + iam_pattern = main_zone.lower().rstrip('.').replace('.', '-') |
| 37 | + name = '{sub}.{zone}'.format(sub=subdomain, |
| 38 | + zone=main_zone.rstrip('.')) |
| 39 | + acm = ACM(account_info.Region) |
| 40 | + acm_certificates = sorted(acm.get_certificates(domain_name=name), |
| 41 | + reverse=True) |
| 42 | + else: |
| 43 | + iam_pattern = '' |
| 44 | + acm_certificates = [] |
| 45 | + iam = IAM(account_info.Region) |
| 46 | + iam_certificates = sorted(iam.get_certificates(name=iam_pattern)) |
| 47 | + if not iam_certificates: |
| 48 | + # if there are no iam certificates matching the pattern |
| 49 | + # try to use any certificate |
| 50 | + iam_certificates = sorted(iam.get_certificates(), reverse=True) |
| 51 | + |
| 52 | + # the priority is acm_certificate first and iam_certificate second |
| 53 | + certificates = (acm_certificates + |
| 54 | + iam_certificates) # type: List[Union[ACMCertificate, IAMServerCertificate]] |
| 55 | + try: |
| 56 | + certificate = certificates[0] |
| 57 | + ssl_cert = certificate.arn |
| 58 | + except IndexError: |
| 59 | + if main_zone: |
| 60 | + fatal_error('Could not find any matching ' |
| 61 | + 'SSL certificate for "{}"'.format(name)) |
| 62 | + else: |
| 63 | + fatal_error('Could not find any SSL certificate') |
| 64 | + return [{ |
| 65 | + 'Type': 'AWS::ElasticLoadBalancingV2::Listener', |
| 66 | + 'Properties': { |
| 67 | + "Certificates": [{'CertificateArn': ssl_cert}], |
| 68 | + "Protocol": "HTTPS", |
| 69 | + "DefaultActions": [{'Type': 'forward', 'TargetGroupArn': {'Ref': target_group_name}}], |
| 70 | + 'LoadBalancerArn': {'Ref': lb_name}, |
| 71 | + "Port": 443 |
| 72 | + } |
| 73 | + }] |
| 74 | + |
| 75 | + |
| 76 | +def component_elastic_load_balancer_v2(definition, |
| 77 | + configuration: dict, |
| 78 | + args: TemplateArguments, |
| 79 | + info: dict, |
| 80 | + force, |
| 81 | + account_info: AccountArguments): |
| 82 | + lb_name = configuration["Name"] |
| 83 | + # domains pointing to the load balancer |
| 84 | + subdomain = '' |
| 85 | + main_zone = None |
| 86 | + for name, domain in configuration.get('Domains', {}).items(): |
| 87 | + name = '{}{}'.format(lb_name, name) |
| 88 | + |
| 89 | + domain_name = "{0}.{1}".format(domain["Subdomain"], domain["Zone"]) |
| 90 | + |
| 91 | + convert_domain_records_to_alias(domain_name) |
| 92 | + |
| 93 | + properties = {"Type": "A", |
| 94 | + "Name": domain_name, |
| 95 | + "HostedZoneName": domain["Zone"], |
| 96 | + "AliasTarget": {"HostedZoneId": {"Fn::GetAtt": [lb_name, |
| 97 | + "CanonicalHostedZoneID"]}, |
| 98 | + "DNSName": {"Fn::GetAtt": [lb_name, "DNSName"]}}} |
| 99 | + definition["Resources"][name] = {"Type": "AWS::Route53::RecordSet", |
| 100 | + "Properties": properties} |
| 101 | + |
| 102 | + if domain["Type"] == "weighted": |
| 103 | + definition["Resources"][name]["Properties"]['Weight'] = 0 |
| 104 | + definition["Resources"][name]["Properties"]['SetIdentifier'] = "{0}-{1}".format(info["StackName"], |
| 105 | + info["StackVersion"]) |
| 106 | + subdomain = domain['Subdomain'] |
| 107 | + main_zone = domain['Zone'] # type: str |
| 108 | + |
| 109 | + target_group_name = lb_name + 'TargetGroup' |
| 110 | + listeners = configuration.get('Listeners') or get_listeners( |
| 111 | + lb_name, target_group_name, subdomain, main_zone, configuration, account_info) |
| 112 | + |
| 113 | + health_check_protocol = "HTTP" |
| 114 | + allowed_health_check_protocols = ("HTTP", "TCP", "UDP", "SSL") |
| 115 | + if "HealthCheckProtocol" in configuration: |
| 116 | + health_check_protocol = configuration["HealthCheckProtocol"] |
| 117 | + |
| 118 | + if health_check_protocol not in allowed_health_check_protocols: |
| 119 | + raise click.UsageError('Protocol "{}" is not supported for LoadBalancer'.format(health_check_protocol)) |
| 120 | + |
| 121 | + health_check_path = "/ui/" |
| 122 | + if "HealthCheckPath" in configuration: |
| 123 | + health_check_path = configuration["HealthCheckPath"] |
| 124 | + |
| 125 | + health_check_port = configuration["HTTPPort"] |
| 126 | + if "HealthCheckPort" in configuration: |
| 127 | + health_check_port = configuration["HealthCheckPort"] |
| 128 | + |
| 129 | + if configuration.get('NameSuffix'): |
| 130 | + version = '{}-{}'.format(info["StackVersion"], |
| 131 | + configuration['NameSuffix']) |
| 132 | + loadbalancer_name = get_load_balancer_name(info["StackName"], version) |
| 133 | + del(configuration['NameSuffix']) |
| 134 | + else: |
| 135 | + loadbalancer_name = get_load_balancer_name(info["StackName"], |
| 136 | + info["StackVersion"]) |
| 137 | + |
| 138 | + loadbalancer_scheme = "internal" |
| 139 | + allowed_loadbalancer_schemes = ("internet-facing", "internal") |
| 140 | + if "Scheme" in configuration: |
| 141 | + loadbalancer_scheme = configuration["Scheme"] |
| 142 | + else: |
| 143 | + configuration["Scheme"] = loadbalancer_scheme |
| 144 | + |
| 145 | + if loadbalancer_scheme == 'internet-facing': |
| 146 | + click.secho('You are deploying an internet-facing ELB that will be ' |
| 147 | + 'publicly accessible! You should have OAUTH2 and HTTPS ' |
| 148 | + 'in place!', bold=True, err=True) |
| 149 | + |
| 150 | + if loadbalancer_scheme not in allowed_loadbalancer_schemes: |
| 151 | + raise click.UsageError('Scheme "{}" is not supported for LoadBalancer'.format(loadbalancer_scheme)) |
| 152 | + |
| 153 | + if loadbalancer_scheme == "internal": |
| 154 | + loadbalancer_subnet_map = "LoadBalancerInternalSubnets" |
| 155 | + else: |
| 156 | + loadbalancer_subnet_map = "LoadBalancerSubnets" |
| 157 | + |
| 158 | + tags = [ |
| 159 | + # Tag "Name" |
| 160 | + { |
| 161 | + "Key": "Name", |
| 162 | + "Value": "{0}-{1}".format(info["StackName"], info["StackVersion"]) |
| 163 | + }, |
| 164 | + # Tag "StackName" |
| 165 | + { |
| 166 | + "Key": "StackName", |
| 167 | + "Value": info["StackName"], |
| 168 | + }, |
| 169 | + # Tag "StackVersion" |
| 170 | + { |
| 171 | + "Key": "StackVersion", |
| 172 | + "Value": info["StackVersion"] |
| 173 | + } |
| 174 | + ] |
| 175 | + |
| 176 | + # load balancer |
| 177 | + definition["Resources"][lb_name] = { |
| 178 | + "Type": "AWS::ElasticLoadBalancingV2::LoadBalancer", |
| 179 | + "Properties": { |
| 180 | + 'Name': loadbalancer_name, |
| 181 | + 'Scheme': loadbalancer_scheme, |
| 182 | + 'SecurityGroups': resolve_security_groups(configuration["SecurityGroups"], args.region), |
| 183 | + 'Subnets': {"Fn::FindInMap": [loadbalancer_subnet_map, {"Ref": "AWS::Region"}, "Subnets"]}, |
| 184 | + "Tags": tags |
| 185 | + } |
| 186 | + } |
| 187 | + definition["Resources"][target_group_name] = { |
| 188 | + 'Type': 'AWS::ElasticLoadBalancingV2::TargetGroup', |
| 189 | + 'Properties': { |
| 190 | + 'Name': loadbalancer_name, |
| 191 | + 'HealthCheckIntervalSeconds': '10', |
| 192 | + 'HealthCheckPath': health_check_path, |
| 193 | + 'HealthCheckPort': health_check_port, |
| 194 | + 'HealthCheckProtocol': health_check_protocol, |
| 195 | + 'HealthCheckTimeoutSeconds': '5', |
| 196 | + 'HealthyThresholdCount': '2', |
| 197 | + 'Port': configuration['HTTPPort'], |
| 198 | + 'Protocol': 'HTTP', |
| 199 | + 'UnhealthyThresholdCount': '2', |
| 200 | + 'VpcId': account_info.VpcID, # TODO: support multiple VPCs |
| 201 | + 'Tags': tags, |
| 202 | + 'TargetGroupAttributes': [{'Key': 'deregistration_delay.timeout_seconds', 'Value': '60'}] |
| 203 | + } |
| 204 | + } |
| 205 | + for i, listener in enumerate(listeners): |
| 206 | + if i == 0: |
| 207 | + suffix = '' |
| 208 | + else: |
| 209 | + suffix = str(i + 1) |
| 210 | + definition['Resources'][lb_name + 'Listener' + suffix] = listener |
| 211 | + for key, val in configuration.items(): |
| 212 | + # overwrite any specified properties, but |
| 213 | + # ignore our special Senza properties as they are not supported by CF |
| 214 | + if key not in SENZA_PROPERTIES: |
| 215 | + definition['Resources'][lb_name]['Properties'][key] = val |
| 216 | + |
| 217 | + return definition |
0 commit comments