VpcId=ImportValue( Join( "-", [Select(0, Split("-", Ref("AWS::StackName"))), "cluster-vpc-id"] ) ), )) t.add_resource(elb.Listener( "Listener", Port="3000", Protocol="HTTP", LoadBalancerArn=Ref("LoadBalancer"), DefaultActions=[elb.Action( Type="forward", TargetGroupArn=Ref("TargetGroup") )] )) t.add_output(Output( "TargetGroup", Description="TargetGroup", Value=Ref("TargetGroup"), Export=Export(Sub("${AWS::StackName}-target-group")), )) t.add_output(Output( "URL", Description="Helloworld URL", Value=Join("", ["http://", GetAtt("LoadBalancer", "DNSName"), ":3000"]) ))
HealthCheckProtocol='HTTP', HealthCheckTimeoutSeconds='5', HealthyThresholdCount='3', UnhealthyThresholdCount='5', Matcher=elbv2.Matcher(HttpCode='200'), TargetGroupAttributes=[ elbv2.TargetGroupAttribute( Key='deregistration_delay.timeout_seconds', Value='20') ])) http_listener = t.add_resource( elbv2.Listener( 'HttpListener', DefaultActions=[ elbv2.Action(TargetGroupArn=Ref(targetgroup), Type='forward') ], LoadBalancerArn=Ref(load_balancer), Port='80', Protocol='HTTP', )) https_listener = t.add_resource( elbv2.Listener('HttpsListener', DefaultActions=[ elbv2.Action(TargetGroupArn=Ref(targetgroup), Type='forward') ], LoadBalancerArn=Ref(load_balancer), Port='443', Protocol='HTTPS',
HealthCheckPath="/", Matcher=elb.Matcher(HttpCode="200"), Port=3000, Protocol="HTTP", UnhealthyThresholdCount="3", VpcId=ImportValue(Join("-", [e, "cluster-vpc-id"])), )) t.add_resource( elb.Listener("{}Listener".format(e), Port="80", Protocol="HTTP", LoadBalancerArn=Ref("{}LoadBalancer".format(e)), DefaultActions=[ elb.Action(Type="forward", TargetGroupArn=Ref( "{}{}TargetGroup".format( e, services[0]))) ])) for s in services: # Set an integer for the rule priority. This assumes the list of # services is ordered by priority. priority = services.index(s) + 1 # Set a URL extension for non-prod environments if e == "prod": URLPathMod = "" else: URLPathMod = "{}.".format(e) t.add_resource(
# # LoadBalancerArn=Ref(app_lb), # LoadBalancerArn=ImportValue(Sub("${AlbStack}-AppLb")), # DefaultActions=[elasticloadbalancingv2.Action( # Type="forward", # TargetGroupArn=Ref(target_group) # )] # )) """ Add the TargetGroup to a Listener on the ALB - path-pattern is given as a Parameter to this stack """ listener_rule1 = t.add_resource( elasticloadbalancingv2.ListenerRule( "ListenerRule1", Actions=[ elasticloadbalancingv2.Action(TargetGroupArn=Ref(target_group), Type="forward") ], Conditions=[ elasticloadbalancingv2.Condition(Field="path-pattern", Values=[Ref(service_path)]), If( service_host_condition, elasticloadbalancingv2.Condition(Field="host-header", Values=[Ref(service_host)]), Ref("AWS::NoValue")) ], # ListenerArn=Ref(app_lb_listener), ListenerArn=ImportValue(Sub("${AlbStack}-AlbPublicListener80")), Priority=Ref(listener_priority))) listener_rule2 = t.add_resource(
Port=3000, Protocol="HTTP", UnhealthyThresholdCount="3", VpcId=ImportValue( Join("-", [ Select(0, Split("-", Ref("AWS::StackName"))), "cluster-vpc-id" ])), )) t.add_resource( elb.Listener("Listener", Port="3000", Protocol="HTTP", LoadBalancerArn=Ref("LoadBalancer"), DefaultActions=[ elb.Action(Type="forward", TargetGroupArn=Ref("TargetGroup")) ])) t.add_output( Output( "TargetGroup", Description="TargetGroup", Value=Ref("TargetGroup"), Export=Export(Sub("${AWS::StackName}-helloworld-target-group")), )) t.add_output( Output("URL", Description="Helloworld URL", Value=Join("", ["http://",
HealthyThresholdCount="4", Matcher=elasticloadbalancingv2.Matcher(HttpCode="200,301"), Port=2368, Protocol="HTTP", UnhealthyThresholdCount="3", TargetType="ip", VpcId=Ref(db_vpc))) Listener = t.add_resource( elasticloadbalancingv2.Listener( "Listener", Port="80", Protocol="HTTP", LoadBalancerArn=Ref(GhostALB), DefaultActions=[ elasticloadbalancingv2.Action(Type="forward", TargetGroupArn=Ref(GhostTargetGroup)) ])) dbinit = t.add_resource( CustomDBInit("DBInit", ServiceToken=GetAtt(DBInitFunction, 'Arn'), Password=Ref(dbpassword), DBHost=GetAtt(ghost_db, "Endpoint.Address"), DependsOn=ghost_db)) # Create the required Outputs # Output the Task Role Arn t.add_output( Output("TaskRoleArn", Value=GetAtt(TaskRole, "Arn"),
def main(): template = Template() template.add_version("2010-09-09") template.set_description( "AWS CloudFormation Sample Template: NLB with 1 EC2 instance") AddAMI(template) # Add the Parameters keyname_param = template.add_parameter( Parameter( "KeyName", Type="String", Default="mark", Description="Name of an existing EC2 KeyPair to " "enable SSH access to the instance", )) template.add_parameter( Parameter( "InstanceType", Type="String", Description="WebServer EC2 instance type", Default="m1.small", AllowedValues=[ "t1.micro", "m1.small", "m1.medium", "m1.large", "m1.xlarge", "m2.xlarge", "m2.2xlarge", "m2.4xlarge", "c1.medium", "c1.xlarge", "cc1.4xlarge", "cc2.8xlarge", "cg1.4xlarge" ], ConstraintDescription="must be a valid EC2 instance type.", )) webport_param = template.add_parameter( Parameter( "WebServerPort", Type="String", Default="8888", Description="TCP/IP port of the web server", )) subnetA = template.add_parameter( Parameter("subnetA", Type="String", Default="subnet-096fd06d")) subnetB = template.add_parameter( Parameter("subnetB", Type="String", Default="subnet-1313ef4b")) VpcId = template.add_parameter( Parameter("VpcId", Type="String", Default="vpc-82c514e6")) # Define the instance security group instance_sg = template.add_resource( ec2.SecurityGroup( "InstanceSecurityGroup", GroupDescription="Enable SSH and HTTP access on the inbound port", SecurityGroupIngress=[ ec2.SecurityGroupRule( IpProtocol="tcp", FromPort="22", ToPort="22", CidrIp="0.0.0.0/0", ), ec2.SecurityGroupRule( IpProtocol="tcp", FromPort=Ref(webport_param), ToPort=Ref(webport_param), CidrIp="0.0.0.0/0", ), ])) eipA = template.add_resource(ec2.EIP( 'eipA', Domain='vpc', )) eipB = template.add_resource(ec2.EIP( 'eipB', Domain='vpc', )) # Add the web server instance WebInstance = template.add_resource( ec2.Instance( "WebInstance", SecurityGroups=[Ref(instance_sg)], KeyName=Ref(keyname_param), InstanceType=Ref("InstanceType"), ImageId=FindInMap("RegionMap", Ref("AWS::Region"), "AMI"), UserData=Base64(Ref(webport_param)), )) # Add the network LB NetworkLB = template.add_resource( elb.LoadBalancer( "NetworkLB", Name="NetworkLB", Scheme="internet-facing", SubnetMappings=[ elb.SubnetMapping(AllocationId=GetAtt(eipA, 'AllocationId'), SubnetId=Ref(subnetA)), elb.SubnetMapping(AllocationId=GetAtt(eipB, 'AllocationId'), SubnetId=Ref(subnetB)) ], Type='network')) TargetGroupWeb = template.add_resource( elb.TargetGroup("TargetGroupWeb", HealthCheckIntervalSeconds="30", HealthCheckProtocol="HTTP", HealthCheckTimeoutSeconds="10", HealthyThresholdCount="4", Matcher=elb.Matcher(HttpCode="200"), Name="WebTarget", Port=Ref(webport_param), Protocol="HTTP", Targets=[ elb.TargetDescription(Id=Ref(WebInstance), Port=Ref(webport_param)) ], UnhealthyThresholdCount="3", VpcId=Ref(VpcId))) template.add_resource( elb.Listener("Listener", Port="80", Protocol="HTTP", LoadBalancerArn=Ref(NetworkLB), DefaultActions=[ elb.Action(Type="forward", TargetGroupArn=Ref(TargetGroupWeb)) ])) template.add_output( Output("URL", Description="URL of the sample website", Value=Join("", ["http://", GetAtt(NetworkLB, "DNSName")]))) print(template.to_json())
Priority='1', ListenerArn= 'arn:aws:elasticloadbalancing:us-east-2:445114057331:listener/app/my-service-lb/39baed772591d6c0/930c98eb2dcb4690', Conditions=[ elasticloadbalancingv2.Condition( Field='path-pattern', Values=['/api/currency-exchange-microservice/*']) ], Actions=[ elasticloadbalancingv2.Action( Type='forward', TargetGroupArn= 'arn:aws:elasticloadbalancing:us-east-2:445114057331:targetgroup/currencyexchangeservicetg/1d71df4075d5ad16', ForwardConfig={ "TargetGroups": [{ 'TargetGroupArn': 'arn:aws:elasticloadbalancing:us-east-2:445114057331:targetgroup/currencyexchangeservicetg/1d71df4075d5ad16', 'Weight': 1 }], "TargetGroupStickinessConfig": { 'Enabled': False } }) ])) ElasticLoadBalancingV2ListenerRule2 = template.add_resource( elasticloadbalancingv2.ListenerRule( 'ElasticLoadBalancingV2ListenerRule2', Priority='2', ListenerArn= 'arn:aws:elasticloadbalancing:us-east-2:445114057331:listener/app/my-service-lb/39baed772591d6c0/930c98eb2dcb4690', Conditions=[
HealthyThresholdCount="4", Matcher=elb.Matcher(HttpCode="200"), Name="WebTarget", Port="80", Protocol="HTTP", UnhealthyThresholdCount="3", VpcId=myvpc, )) Listener = template.add_resource( elb.Listener("Listener", Port="80", Protocol="HTTP", LoadBalancerArn=Ref(FrontendAlb), DefaultActions=[ elb.Action(Type="forward", TargetGroupArn=Ref(WebTargets)) ])) template.add_resource( elb.ListenerRule( "ListenerRule", ListenerArn=Ref(Listener), Conditions=[elb.Condition(Field="path-pattern", Values=["/*"])], Actions=[elb.Action(Type="forward", TargetGroupArn=Ref(WebTargets))], Priority="1")) lcf = template.add_resource( LaunchConfiguration( "lcf", AssociatePublicIpAddress=False, ImageId='ami-63d53204',
HealthyThresholdCount=5, UnhealthyThresholdCount=5, )) keycloakListenerRule = t.add_resource( elasticloadbalancingv2.ListenerRule( 'KeycloakListenerRule', ListenerArn=ImportValue(Sub('${CoreStack}-ALB-Web-Listener')), Priority=10, Conditions=[ elasticloadbalancingv2.Condition(Field='path-pattern', Values=['/auth', '/auth*']) ], Actions=[ elasticloadbalancingv2.Action( Type='forward', TargetGroupArn=keycloakTargetGroup.Ref(), ) ])) keycloakTask = t.add_resource( ecs.TaskDefinition( 'KeycloakTask', ContainerDefinitions=[ ecs.ContainerDefinition( 'KeycloakContainer', Name='keycloak', Image=Ref('KeycloakImage'), Environment=[ ecs.Environment(Name='KEYCLOAK_USER', Value=Ref('KeycloakUser')), ecs.Environment(Name='KEYCLOAK_PASSWORD',
StorReduceNLBTargetsPort9200 = t.add_resource( elb.TargetGroup( "StorReduceNLBTargetsPort9200", Name="StorReduceNLBTargetsPort9200", Port=9200, Protocol="TCP", Targets=[elb.TargetDescription(Id=Ref(monitor_instance), Port=9200)], VpcId=Ref(VpcIdParam))) t.add_resource( elb.Listener("StorReduceNLBPort80Listener", Port="80", Protocol="TCP", LoadBalancerArn=Ref(NetworkLB), DefaultActions=[ elb.Action(Type="forward", TargetGroupArn=Ref(StorReduceNLBTargetsPort80)) ])) t.add_resource( elb.Listener("StorReduceNLBPort443Listener", Port="443", Protocol="TCP", LoadBalancerArn=Ref(NetworkLB), DefaultActions=[ elb.Action( Type="forward", TargetGroupArn=Ref(StorReduceNLBTargetsPort443)) ])) t.add_resource( elb.Listener("StorReduceNLBPort8080Listener",
NATLBTargetGroup443Resource = t.add_resource(elb.TargetGroup( "NATLBTargetGroup443", Name=Join("", [Ref("AWS::StackName"), "-", Ref(LBNameParam), "-tgt443"]), HealthCheckIntervalSeconds=10, HealthyThresholdCount=6, UnhealthyThresholdCount=6, Protocol="TCP", Port=443, VpcId=Ref(VPCIDParam), )) NATLoadBalancerListener80Resource = t.add_resource(elb.Listener( "NATLoadBalancerListener80", DefaultActions=[ elb.Action( Type="forward", TargetGroupArn=Ref(NATLBTargetGroup80Resource) )], LoadBalancerArn=Ref(NATLoadBalancerResource), Port=elb.network_port(80), Protocol="TCP", )) NATLoadBalancerListener443Resource = t.add_resource(elb.Listener( "NATLoadBalancerListener443", DefaultActions=[ elb.Action( Type="forward", TargetGroupArn=Ref(NATLBTargetGroup443Resource) )], LoadBalancerArn=Ref(NATLoadBalancerResource), Port=elb.network_port(443),
def main(): template = Template() template.add_version("2010-09-09") template.set_description("AWS CloudFormation ECS Service") # Add the Parameters Application = template.add_parameter( Parameter( "Application", Type="String", )) DockerImage = template.add_parameter( Parameter( "DockerImage", Type="String", )) ClusterName = template.add_parameter( Parameter( "ClusterName", Type="String", )) ContainerPort = template.add_parameter( Parameter( "ContainerPort", Type="String", )) HostPort = template.add_parameter(Parameter( "HostPort", Type="String", )) HostedZoneName = template.add_parameter( Parameter( "HostedZoneName", Type="String", )) CertArn = template.add_parameter(Parameter( "CertArn", Type="String", )) ExecutionRoleArn = template.add_parameter( Parameter("ExecutionRoleArn", Type="String", Description="Execution Role to get creadentials from ssm")) HealthCheckPath = template.add_parameter( Parameter( "HealthCheckPath", Type="String", )) HealthCheckIntervalSeconds = template.add_parameter( Parameter( "HealthCheckIntervalSeconds", Type="String", )) HealthyThresholdCount = template.add_parameter( Parameter( "HealthyThresholdCount", Type="String", )) HealthCheckTimeoutSeconds = template.add_parameter( Parameter( "HealthCheckTimeoutSeconds", Type="String", )) UnhealthyThresholdCount = template.add_parameter( Parameter( "UnhealthyThresholdCount", Type="String", )) VpcId = template.add_parameter(Parameter( "VpcId", Type="String", )) Subnets = template.add_parameter( Parameter( "Subnets", Type="List<AWS::EC2::Subnet::Id>", )) PrivateSubnets = template.add_parameter( Parameter( "PrivateSubnets", Type="List<AWS::EC2::Subnet::Id>", )) # Add the application ELB NetworkLB = template.add_resource( elb.LoadBalancer("NetworkLB", Name=Join("", [Ref(Application), "-nlb"]), Scheme="internet-facing", Subnets=Ref(Subnets), Type='network')) NlbTargetGroup = template.add_resource( elb.TargetGroup( "NlbTargetGroup", Name='ecs-fargate-service-targetgroup', HealthCheckIntervalSeconds=Ref(HealthCheckIntervalSeconds), HealthCheckProtocol="TCP", HealthyThresholdCount=Ref(HealthyThresholdCount), Port=80, Protocol="TCP", TargetType="ip", UnhealthyThresholdCount=Ref(UnhealthyThresholdCount), VpcId=Ref(VpcId))) NlbListener = template.add_resource( elb.Listener( "Listener", DependsOn=["NlbTargetGroup", "NetworkLB"], Certificates=[elb.Certificate(CertificateArn=Ref(CertArn))], Port="443", Protocol="TLS", LoadBalancerArn=Ref(NetworkLB), DefaultActions=[ elb.Action(Type="forward", TargetGroupArn=Ref(NlbTargetGroup)) ])) Task_Definition = template.add_resource( TaskDefinition( 'TaskDefinition', Memory='512', Cpu='256', RequiresCompatibilities=['FARGATE'], NetworkMode='awsvpc', ExecutionRoleArn=Ref(ExecutionRoleArn), ContainerDefinitions=[ ContainerDefinition( Name=Join("", [Ref(Application)]), Image=Ref(DockerImage), Essential=True, Environment=[Environment(Name="MY_ENV_VAR", Value="true")], DockerLabels={ 'aws-account': Ref("AWS::AccountId"), 'region': Ref("AWS::Region"), 'stack': Ref("AWS::StackName") }, PortMappings=[ PortMapping(ContainerPort=Ref(ContainerPort)) ]) ])) AwsVpcSg = template.add_resource( ec2.SecurityGroup('SecurityGroup', GroupDescription='Security Group', SecurityGroupIngress=[ ec2.SecurityGroupRule(IpProtocol='-1', CidrIp='10.0.0.0/8') ], SecurityGroupEgress=[ ec2.SecurityGroupRule(IpProtocol="-1", CidrIp="0.0.0.0/0") ], VpcId=Ref(VpcId))) app_service = template.add_resource( Service("AppService", DependsOn=["Listener", "TaskDefinition"], Cluster=Ref(ClusterName), LaunchType='FARGATE', DesiredCount=1, TaskDefinition=Ref(Task_Definition), ServiceName=Join("", [Ref(Application), "-ecs-service"]), LoadBalancers=[ ecs.LoadBalancer(ContainerName=Join( "", [Ref(Application)]), ContainerPort=Ref(ContainerPort), TargetGroupArn=Ref(NlbTargetGroup)) ], NetworkConfiguration=NetworkConfiguration( AwsvpcConfiguration=AwsvpcConfiguration( Subnets=Ref(PrivateSubnets), SecurityGroups=[Ref(AwsVpcSg)])))) AppDNSRecord = template.add_resource( RecordSetType( "AppDNSRecord", DependsOn=["AppService"], HostedZoneName=Join("", [Ref(HostedZoneName), "."]), Name=Join("", [Ref(Application), ".", Ref(HostedZoneName), "."]), Type="CNAME", TTL="900", ResourceRecords=[GetAtt(NetworkLB, "DNSName")])) template.add_output( Output("URL", Description="DomainName", Value=Join("", ["https://", Ref(AppDNSRecord)]))) with open("ecs-fargate-service-cf.yaml", "w") as yamlout: yamlout.write(template.to_yaml())
def define_load_balancer(template, sg): alb_target_group_80 = elb.TargetGroup( stack_name_strict + "TG80", Tags=Tags(Name=stack_name, Custo=app_name), HealthCheckPath=Ref(alb_health_check_path), HealthCheckIntervalSeconds="30", HealthCheckProtocol="HTTP", HealthCheckTimeoutSeconds="10", HealthyThresholdCount="3", Matcher=elb.Matcher(HttpCode="301"), Port=80, Protocol="HTTP", UnhealthyThresholdCount="2", VpcId=Ref(vpc_id)) template.add_resource(alb_target_group_80) alb_target_group_9090 = elb.TargetGroup( stack_name_strict + "TG9090", Tags=Tags(Name=stack_name, Custo=app_name), HealthCheckPath=Ref(alb_health_check_path), HealthCheckIntervalSeconds="30", HealthCheckProtocol="HTTP", HealthCheckTimeoutSeconds="10", HealthyThresholdCount="3", Matcher=elb.Matcher(HttpCode="200"), Port=9090, Protocol="HTTP", UnhealthyThresholdCount="2", VpcId=Ref(vpc_id)) template.add_resource(alb_target_group_9090) alb = elb.LoadBalancer(stack_name_strict + "ALB", Tags=Tags(Name=stack_name, Custo=app_name), Scheme="internet-facing", Subnets=[Ref(subnet_id1), Ref(subnet_id2)], SecurityGroups=[Ref(sg)]) template.add_resource(alb) alb_listener_80 = elb.Listener( stack_name_strict + "ListenerALB80", Port=80, Protocol="HTTP", LoadBalancerArn=Ref(alb), DefaultActions=[ elb.Action(Type="forward", TargetGroupArn=Ref(alb_target_group_80)) ]) template.add_resource(alb_listener_80) alb_listener_443 = elb.Listener( stack_name_strict + "ListenerALB443", Port=443, Protocol="HTTPS", Certificates=[ elb.Certificate(CertificateArn=Ref(ssl_certificate_arn)) ], LoadBalancerArn=Ref(alb), DefaultActions=[ elb.Action(Type="forward", TargetGroupArn=Ref(alb_target_group_9090)) ]) template.add_resource(alb_listener_443) return { "loadbalancer": alb, "alb_target_group_80": alb_target_group_80, "alb_target_group_9090": alb_target_group_9090, "alb_listener_80": alb_listener_80, "alb_listener_9090": alb_listener_443 }
def main(): # Meta t.add_version("2010-09-09") t.add_description("Template for auto-scaling in an Application" "load balancer target group. " "The ALB will be used as an A Alias target " "for a specified Route53 hosted zone. " "This template also showcases " "Metadata Parameter Grouping, " "Special AWS Parameter Types, " "and Cloudformation Outputs with Exports" "which can be imported into other templates.") t.add_metadata({ "Author": "https://github.com/hmain/", "LastUpdated": "2017 01 31", "Version": "1", }) # Parameter grouping t.add_metadata({ "AWS::CloudFormation::Interface": { "ParameterGroups": [{ "Label": { "default": "Global parameters" }, "Parameters": ["environment"] }, { "Label": { "default": "Application Loadbalancer" }, "Parameters": [ "albSubnets", "loadbalancerPrefix", "loadBalancerArn", "albPaths", "albPort" ] }, { "Label": { "default": "VPC" }, "Parameters": ["ec2Subnets", "VPC", "securityGroup"] }, { "Label": { "default": "EC2" }, "Parameters": ["ec2Name", "ec2Type", "ec2Key"] }, { "Label": { "default": "Auto-scaling" }, "Parameters": [ "asgCapacity", "asgMinSize", "asgMaxSize", "asgCooldown", "asgHealthGrace" ] }, { "Label": { "default": "Route53" }, "Parameters": ["route53HostedZoneId", "route53HostedZoneName"] }] } }) AddAMI(t) environment = t.add_parameter( Parameter( "environment", Default="dev", Type="String", Description="Development or Production environment", AllowedValues=["dev", "prod"], ConstraintDescription="dev or prod", )) route53_hosted_zone_id = t.add_parameter( Parameter("route53HostedZoneId", Default="", Type="AWS::Route53::HostedZone::Id", Description="Route53 DNS zone ID")) route53_hosted_zone_name = t.add_parameter( Parameter("route53HostedZoneName", Default="my.aws.dns.com", Type="String", Description="Route53 hosted zone name")) security_group = t.add_parameter( Parameter("securityGroup", Default="", Type="List<AWS::EC2::SecurityGroup::Id>", Description="Which security groups to use")) alb_paths = t.add_parameter( Parameter( "albPaths", Default="/", Type="CommaDelimitedList", Description="Path-patterns you want the loadbalancer to point to in " "your application")) albPort = t.add_parameter( Parameter("albPort", Default="80", Type="Number", Description="Which loadbalancer port to use")) ec2_subnets = t.add_parameter( Parameter("ec2Subnets", Default="", Type="List<AWS::EC2::Subnet::Id>", Description="Private subnets for the instances.")) alb_subnets = t.add_parameter( Parameter("albSubnets", Default="", Type="List<AWS::EC2::Subnet::Id>", Description="Public subnets for the load balancer.")) loadbalancer_prefix = t.add_parameter( Parameter( "loadbalancerPrefix", Default="", Type="String", Description="Specify a prefix for your loadbalancer", )) vpc = t.add_parameter( Parameter("VPC", Default="", Type="AWS::EC2::VPC::Id", Description="Environment VPC")) # Auto scaling group parameters asg_capacity = t.add_parameter( Parameter("asgCapacity", Default="0", Type="Number", Description="Number of instances")) asg_min_size = t.add_parameter( Parameter("asgMinSize", Default="0", Type="Number", Description="Minimum size of AutoScalingGroup")) asg_max_size = t.add_parameter( Parameter("asgMaxSize", Default="1", Type="Number", Description="Maximum size of AutoScalingGroup")) asg_cooldown = t.add_parameter( Parameter( "asgCooldown", Default="300", Type="Number", Description="Cooldown before starting/stopping another instance")) asg_health_grace = t.add_parameter( Parameter( "asgHealthGrace", Default="300", Type="Number", Description="Wait before starting/stopping another instance")) # EC2 parameters ec2_name = t.add_parameter( Parameter("ec2Name", Default="myApplication", Type="String", Description="Name of the instances")) ec2_type = t.add_parameter( Parameter("ec2Type", Default="t2.large", Type="String", Description="Instance type.")) ec2_key = t.add_parameter( Parameter("ec2Key", Default="", Type="AWS::EC2::KeyPair::KeyName", Description="EC2 Key Pair")) # Launchconfiguration ec2_launchconfiguration = t.add_resource( autoscaling.LaunchConfiguration( "EC2LaunchConfiguration", ImageId=FindInMap("windowsAMI", Ref("AWS::Region"), "AMI"), KeyName=Ref(ec2_key), SecurityGroups=Ref(security_group), InstanceType=Ref(ec2_type), AssociatePublicIpAddress=False, )) # Application ELB alb_target_group = t.add_resource( elb.TargetGroup("albTargetGroup", HealthCheckPath=Select("0", Ref(alb_paths)), HealthCheckIntervalSeconds="30", HealthCheckProtocol="HTTP", HealthCheckTimeoutSeconds="10", HealthyThresholdCount="4", Matcher=elb.Matcher(HttpCode="200"), Name=Ref(ec2_name), Port=80, Protocol="HTTP", UnhealthyThresholdCount="3", VpcId=Ref(vpc))) # Auto scaling group t.add_resource( autoscaling.AutoScalingGroup( "autoScalingGroup", DesiredCapacity=Ref(asg_capacity), Tags=autoscaling.Tags(Environment=Ref(environment)), VPCZoneIdentifier=Ref(ec2_subnets), TargetGroupARNs=[Ref(alb_target_group)], MinSize=Ref(asg_min_size), MaxSize=Ref(asg_max_size), Cooldown=Ref(asg_cooldown), LaunchConfigurationName=Ref(ec2_launchconfiguration), HealthCheckGracePeriod=Ref(asg_health_grace), HealthCheckType="EC2", )) # Application Load Balancer application_load_balancer = t.add_resource( elb.LoadBalancer("applicationLoadBalancer", Name=Ref(loadbalancer_prefix), Scheme="internet-facing", Subnets=Ref(alb_subnets), SecurityGroups=Ref(security_group))) alb_listener = t.add_resource( elb.Listener("albListener", Port=Ref(albPort), Protocol="HTTP", LoadBalancerArn=Ref(application_load_balancer), DefaultActions=[ elb.Action(Type="forward", TargetGroupArn=Ref(alb_target_group)) ])) t.add_resource( elb.ListenerRule("albListenerRule", ListenerArn=Ref(alb_listener), Conditions=[ elb.Condition(Field="path-pattern", Values=Ref(alb_paths)) ], Actions=[ elb.Action(Type="forward", TargetGroupArn=Ref(alb_target_group)) ], Priority="1")) # Route53 t.add_resource( route53.RecordSetGroup( "route53RoundRobin", HostedZoneId=Ref(route53_hosted_zone_id), RecordSets=[ route53.RecordSet( Weight=1, SetIdentifier=Join(".", [ Ref(environment), Ref(route53_hosted_zone_name), "ELB" ]), Name=Join( ".", [Ref(environment), Ref(route53_hosted_zone_name)]), Type="A", AliasTarget=route53.AliasTarget( GetAtt(application_load_balancer, "CanonicalHostedZoneID"), GetAtt(application_load_balancer, "DNSName"))) ])) t.add_output( Output( "URL", Description="URL of the website", Value=Join("", [ "http://", GetAtt(application_load_balancer, "DNSName"), Select("0", Ref(alb_paths)) ]), Export=Export(Sub("${AWS::StackName}-URL")), )) print(t.to_json())
def main(): template = Template() subnetA = template.add_parameter(Parameter("subnetA", Type="String")) subnetB = template.add_parameter(Parameter("subnetB", Type="String")) alb = template.add_resource( elb.LoadBalancer( "ALB", Scheme="internet-facing", Subnets=[subnetA.ref(), subnetB.ref()], )) listener = template.add_resource( elb.Listener( "Listener", Port="80", Protocol="HTTP", LoadBalancerArn=alb.ref(), DefaultActions=[ elb.Action( Type="fixed-response", FixedResponseConfig=elb.FixedResponseConfig( StatusCode="200", MessageBody=( "This is a fixed response for the default " "ALB action"), ContentType="text/plain", ), ) ], )) template.add_resource([ elb.ListenerRule( "ListenerRuleApi", ListenerArn=listener.ref(), Conditions=[ elb.Condition(Field="host-header", Values=["api.example.com"]), elb.Condition( Field="http-header", HttpHeaderConfig=elb.HttpHeaderConfig( HttpHeaderName="X-Action", Values=["Create"]), ), elb.Condition( Field="path-pattern", PathPatternConfig=elb.PathPatternConfig(Values=["/api/*"]), ), elb.Condition( Field="http-request-method", HttpRequestMethodConfig=elb.HttpRequestMethodConfig( Values=["POST"]), ), ], Actions=[ elb.Action( Type="fixed-response", FixedResponseConfig=elb.FixedResponseConfig( StatusCode="200", MessageBody=( "This is a fixed response for any API POST " "request with header X-Action: Create"), ContentType="text/plain", ), ) ], Priority="10", ), elb.ListenerRule( "ListenerRuleWeb", ListenerArn=listener.ref(), Conditions=[ elb.Condition( Field="host-header", HostHeaderConfig=elb.HostHeaderConfig( Values=["www.example.com"]), ), elb.Condition( Field="path-pattern", PathPatternConfig=elb.PathPatternConfig(Values=["/web/*"]), ), ], Actions=[ elb.Action( Type="fixed-response", FixedResponseConfig=elb.FixedResponseConfig( StatusCode="200", MessageBody=("This is a fixed response for any WEB " "request"), ContentType="text/plain", ), ) ], Priority="20", ), elb.ListenerRule( "ListenerRuleMetrics", ListenerArn=listener.ref(), Conditions=[ elb.Condition(Field="path-pattern", Values=["/metrics/*"]) ], Actions=[ elb.Action( Type="redirect", RedirectConfig=elb.RedirectConfig(StatusCode="HTTP_301", Protocol="HTTPS", Port="443"), ) ], Priority="30", ), elb.ListenerRule( "ListenerRuleSourceIp", ListenerArn=listener.ref(), Conditions=[ elb.Condition( Field="source-ip", SourceIpConfig=elb.SourceIpConfig( Values=["52.30.12.16/28"]), ) ], Actions=[ elb.Action( Type="fixed-response", FixedResponseConfig=elb.FixedResponseConfig( StatusCode="200", MessageBody=("The request came from IP range " "52.30.12.16/28"), ContentType="text/plain", ), ) ], Priority="40", ), ]) print(template.to_json())