def test_redirect_action(self): Action(Type='redirect', RedirectConfig=RedirectConfig( StatusCode='HTTP_301', Protocol='HTTPS', Host='api.troposphere.org', Path='redirect/#{path}')).to_dict()
def test_redirect_config_only_with_redirect(self): with self.assertRaises(ValueError): Action( Type='forward', RedirectConfig=RedirectConfig( StatusCode='HTTP_301', ) ).to_dict()
def test_redirect_action(self): Action( Type="redirect", RedirectConfig=RedirectConfig( StatusCode="HTTP_301", Protocol="HTTPS", Host="api.troposphere.org", Path="redirect/#{path}", ), ).to_dict()
def http_to_https_default(default_of_all=False) -> Action: """ Predefined rule to redirect HTTP to HTTPS """ return Action( RedirectConfig=RedirectConfig( Protocol="HTTPS", Port="443", Host="#{host}", Path="/#{path}", Query="#{query}", StatusCode=r"HTTP_301", ), Type="redirect", Order=Ref(AWS_NO_VALUE) if not default_of_all else 50000, )
def _add_service_listener(self, service_name, target_group_action, alb, internal): ssl_cert = Certificate(CertificateArn=self.ssl_certificate_arn) service_listener = Listener( "SslLoadBalancerListener" + service_name, Protocol="HTTPS", DefaultActions=[target_group_action], LoadBalancerArn=Ref(alb), Port=443, Certificates=[ssl_cert], SslPolicy="ELBSecurityPolicy-FS-1-2-Res-2019-08" ) self.template.add_resource(service_listener) if internal: # Allow HTTP traffic on internal services http_service_listener = Listener( "LoadBalancerListener" + service_name, Protocol="HTTP", DefaultActions=[target_group_action], LoadBalancerArn=Ref(alb), Port=80 ) self.template.add_resource(http_service_listener) else: # Redirect HTTP to HTTPS on external services redirection_config = RedirectConfig( StatusCode='HTTP_301', Protocol='HTTPS', Port='443' ) http_redirection_action = Action( RedirectConfig=redirection_config, Type="redirect" ) http_redirection_listener = Listener( "LoadBalancerRedirectionListener" + service_name, Protocol="HTTP", DefaultActions=[http_redirection_action], LoadBalancerArn=Ref(alb), Port=80 ) self.template.add_resource(http_redirection_listener) return service_listener
def test_redirect_action_config_one_of(self): with self.assertRaises(ValueError): RedirectConfig(StatusCode="HTTP_200").to_dict()
def __init__(self, prefix: str, lb_security_groups: List[SecurityGroup], subnets: List[Subnet], vpc: VPC, desired_domain_name: str, healthy_http_codes: Optional[List[int]] = None): """ Constructor. :param prefix: A prefix for resource names. :param lb_security_groups: Security groups to attach to a loadbalancer. NOTE! when passing loadbalancer security groups - make sure the loadbalancer can communicate through ci/cd blue/green deployments opened ports. Usually they are 8000 and 44300. :param subnets: Subnets in which loadbalancer can exist. :param vpc: Virtual private cloud in which target groups and a loadbalancer exist. :param desired_domain_name: Domain name for using https. :param healthy_http_codes: The deployed instance is constantly pinged to determine if it is available (healthy) or not. Specify a list of http codes that your service can return and should be treated as healthy. """ # By default a healthy http code is considered to be 200. healthy_http_codes = healthy_http_codes or [200] # If your service's task definition uses the awsvpc network mode # (which is required for the Fargate launch type), you must choose ip as the target type, # not instance, when creating your target groups because # tasks that use the awsvpc network mode are associated with an elastic network interface, # not an Amazon EC2 instance. self.target_type = 'ip' # Certificate so a loadbalancer could communicate via HTTPS. self.certificate = Certificate( prefix + 'FargateEcsCertificate', DomainName=desired_domain_name, ValidationMethod='DNS', ) # A main target group to which a loadbalancer forwards a HTTP traffic. # This is the main group with which our ecs container is associated. self.target_group_1_http = TargetGroup( prefix + 'FargateEcsTargetGroup1', Name=prefix + 'FargateEcsTargetGroup1', Matcher=Matcher( HttpCode=','.join([str(code) for code in healthy_http_codes])), Port=self.TARGET_GROUP_PORT, Protocol='HTTP', VpcId=Ref(vpc), TargetType=self.target_type) # Second target group is usd for Blue/Green deployments. A new container (that should be deployed) # is associated with the second target group. self.target_group_2_http = TargetGroup( prefix + 'FargateEcsTargetGroup2', Name=prefix + 'FargateEcsTargetGroup2', Matcher=Matcher( HttpCode=','.join([str(code) for code in healthy_http_codes])), Port=self.TARGET_GROUP_PORT, Protocol='HTTP', VpcId=Ref(vpc), TargetType=self.target_type) self.load_balancer = LoadBalancer( prefix + 'FargateEcsLoadBalancer', Subnets=[Ref(sub) for sub in subnets], SecurityGroups=[Ref(group) for group in lb_security_groups], Name=prefix + 'FargateEcsLoadBalancer', Scheme='internet-facing', ) self.load_balancer_output = Output( prefix + 'FargateEcsLoadBalancerUrl', Description='The endpoint url of a loadbalancer.', Value=GetAtt(self.load_balancer, 'DNSName')) # Listener that listens to HTTP incoming traffic and redirects to other HTTPS listener. self.listener_http_1 = Listener( prefix + 'FargateEcsHttpListener1', Port=self.LISTENER_HTTP_PORT_1, Protocol='HTTP', LoadBalancerArn=Ref(self.load_balancer), DefaultActions=[ # Redirect to https. Action(Type='redirect', RedirectConfig=RedirectConfig( Host='#{host}', Path='/#{path}', Port=str(self.LISTENER_HTTPS_PORT_1), Query='#{query}', StatusCode='HTTP_301', Protocol='HTTPS')) ]) # Listener that listens to HTTPS traffic and forwards to a target group. self.listener_https_1 = Listener( prefix + 'FargateEcsHttpsListener1', Certificates=[LBCertificate(CertificateArn=Ref(self.certificate))], Port=self.LISTENER_HTTPS_PORT_1, Protocol='HTTPS', LoadBalancerArn=Ref(self.load_balancer), DefaultActions=[ Action(Type='forward', TargetGroupArn=Ref(self.target_group_1_http)) ]) # Second listener is usd for Blue/Green deployments (testing new instance). Test HTTP traffic is # redirected to test HTTPS traffic. self.listener_http_2 = Listener( prefix + 'FargateEcsHttpListener2', Port=self.LISTENER_HTTP_PORT_2, Protocol='HTTP', LoadBalancerArn=Ref(self.load_balancer), DefaultActions=[ # Redirect to https. Action(Type='redirect', RedirectConfig=RedirectConfig( Host='#{host}', Path='/#{path}', Port=str(self.LISTENER_HTTPS_PORT_2), Query='#{query}', StatusCode='HTTP_301', Protocol='HTTPS')) ]) # Listener that listens to test HTTP traffic and forwards to a secondary target group (new container). self.listener_https_2 = Listener( prefix + 'FargateEcsHttpsListener2', Certificates=[LBCertificate(CertificateArn=Ref(self.certificate))], Port=self.LISTENER_HTTPS_PORT_2, Protocol='HTTPS', LoadBalancerArn=Ref(self.load_balancer), DefaultActions=[ Action(Type='forward', TargetGroupArn=Ref(self.target_group_2_http)) ])
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')) certificate = template.add_parameter( parameter=Parameter(title='Certificate', 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' }, { 'IpProtocol': 'tcp', 'FromPort': 443, 'ToPort': 443, 'CidrIp': '0.0.0.0/0' }], VpcId=Ref(vpc))) load_balancer = template.add_resource(resource=LoadBalancer( title='SampleLoadBalancer', Name='sample-alb-https', 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-https', Port=443, Protocol='HTTP', )) template.add_resource(resource=Listener( title='SampleListenerHttps', Certificates=[Certificate(CertificateArn=Ref(certificate))], DefaultActions=[ Action(TargetGroupArn=Ref(target_group), Type='forward') ], LoadBalancerArn=Ref(load_balancer), Port=443, Protocol='HTTPS', )) template.add_resource(resource=Listener( title='SampleListenerHttp', DefaultActions=[ Action( RedirectConfig=RedirectConfig( Host='#{host}', Path='/#{path}', Port='443', Protocol='HTTPS', Query='#{query}', StatusCode='HTTP_301', ), Type='redirect', ) ], LoadBalancerArn=Ref(load_balancer), Port=80, Protocol='HTTP', )) with open('./alb.yml', mode='w') as file: file.write(template.to_yaml())
] ) template.add_resource(origin_certificate), template.add_resource(origin_issued_certificate), template.add_resource(certificate_dns_record) template.add_resource(alb_record_set_group) http_listener = Listener( region.replace("-", "") + "ecslivehttplistener", DefaultActions = [ Action( region.replace("-", "") + "ecslivehttpredirectaction", RedirectConfig = RedirectConfig( region.replace("-", "") + "ecslivehttpredirectconfig", Port = "443", Protocol = "HTTPS", StatusCode = "HTTP_301" ), Type = "redirect" ) ], LoadBalancerArn = Ref(application_load_balancer), Port = 80, Protocol = "HTTP" ) https_listener = Listener( region.replace("-", "") + "ecslivehttpslistener", Certificates = [ Certificate( CertificateArn = Ref(origin_issued_certificate)
}, { "Key": "Project", "Value": Ref(parameters["Project"]) }])) ### Application Load Balancer Listeners ### resources["ALBHTTPlistener"] = template.add_resource( AppListener("ALBHTTPlistener", DependsOn=[resource for resource in ["ALB", "ALBTargetGroup"]], DefaultActions=[ Action(Type='redirect', RedirectConfig=RedirectConfig( Host="#{host}", Path="/#{path}", Port="443", Protocol="HTTPS", Query="#{query}", StatusCode="HTTP_301")) ], LoadBalancerArn=Ref(resources["ALB"]), Port=80, Protocol="HTTP")) resources["ALBHTTPSlistener"] = template.add_resource( AppListener("ALBHTTPSlistener", DependsOn=[resource for resource in ["ALB", "ALBTargetGroup"]], Certificates=[ Certificate("ALBCertificate", CertificateArn=Ref( parameters["SSLCertificateALB"]))