def test_allow_placement_strategy_constraint(self): task_definition = ecs.TaskDefinition( "mytaskdef", ContainerDefinitions=[ ecs.ContainerDefinition( Image="myimage", Memory="300", Name="mycontainer", ) ], Volumes=[ ecs.Volume(Name="my-vol"), ], ) ecs_service = ecs.Service( 'Service', Cluster='cluster', DesiredCount=2, PlacementStrategies=[ ecs.PlacementStrategy( Type="random", ) ], PlacementConstraints=[ ecs.PlacementConstraint( Type="distinctInstance", ) ], TaskDefinition=Ref(task_definition), ) ecs_service.to_dict()
def test_fargate_task_definition(stack: Stack) -> None: """Test fargate task definition creation.""" docker_container_def = ecs.ContainerDefinition( Image="image-uri", Name="container-def-name", LogConfiguration=ecs.LogConfiguration( LogDriver="awslogs", Options={ "awslogs-group": "test-log-group", "awslogs-create-group": "true", "awslogs-region": "eu-west-1", "awslogs-stream-prefix": "test-prefix", }, ), ) stack.add( FargateTaskDefinition( name="test-fargate-task-definition", container_definitions=[docker_container_def], task_role_arn="task-role-name", cpu="1024", memory="4096", )) assert stack.export()["Resources"] == EXPECTED_FARGATE_TASK_DEFINITION
def gen_task_definition(self): log_configuration = ecs.LogConfiguration( LogDriver="awslogs", Options={ "awslogs-group": self.log_group_name, "awslogs-region": Ref("AWS::Region"), "awslogs-stream-prefix": self.service_name, }, ) container_definition = ecs.ContainerDefinition( Name=self.service_name, Image=self.get_service_image(), PortMappings=[ecs.PortMapping(ContainerPort=80, Protocol="tcp")], LogConfiguration=log_configuration, Essential=True, ) self.task_definition = ecs.TaskDefinition( "TasDefinition", Family="conducto-demo-family", ExecutionRoleArn=Ref(self.execution_role), TaskRoleArn=Ref(self.task_role), NetworkMode="awsvpc", RequiresCompatibilities=["FARGATE"], Cpu=f"0.25 vCPU", Memory="0.5 GB", ContainerDefinitions=[container_definition], ) self.template.add_resource(self.task_definition)
def test_allow_host_network_mode(self): container_definition = ecs.ContainerDefinition(Image="myimage", Memory="300", Name="mycontainer", NetworkMode="host") container_definition.JSONrepr()
def test_fargate_launch_type(self): task_definition = ecs.TaskDefinition( "mytaskdef", ContainerDefinitions=[ ecs.ContainerDefinition( Image="myimage", Memory="300", Name="mycontainer", ) ], Volumes=[ ecs.Volume(Name="my-vol"), ], ) ecs_service = ecs.Service( 'Service', Cluster='cluster', DesiredCount=2, PlacementStrategies=[ecs.PlacementStrategy(Type="random", )], LaunchType='FARGATE', NetworkConfiguration=ecs.NetworkConfiguration( AwsVpcConfiguration=ecs.AwsVpcConfiguration( AssignPublicIp='DISABLED', SecurityGroups=['sg-1234'], Subnets=['subnet-1234'])), PlacementConstraints=[ ecs.PlacementConstraint(Type="distinctInstance", ) ], TaskDefinition=Ref(task_definition), ) ecs_service.to_dict()
def generate_container_definition(self): return ecs.ContainerDefinition( Command=self.command, Cpu=self.cpu, Environment=self.environment, Essential=True, Image=self.image, LogConfiguration=self.log_configuration, Memory=self.memory, Name=self.service_name, )
def test_allow_port_mapping_protocol(self): container_definition = ecs.ContainerDefinition( Image="myimage", Memory="300", Name="mycontainer", PortMappings=[ ecs.PortMapping(ContainerPort=8125, HostPort=8125, Protocol="udp") ], ) container_definition.to_dict()
def test_allow_string_task_role_arn(self): task_definition = ecs.TaskDefinition("mytaskdef", ContainerDefinitions=[ ecs.ContainerDefinition( Image="myimage", Memory="300", Name="mycontainer", ) ], TaskRoleArn="myiamrole") task_definition.JSONrepr()
def test_task_role_arn_is_optional(self): task_definition = ecs.TaskDefinition( "mytaskdef", ContainerDefinitions=[ ecs.ContainerDefinition( Image="myimage", Memory="300", Name="mycontainer", ) ], ) task_definition.JSONrepr()
def test_port_mapping_does_not_require_protocol(self): container_definition = ecs.ContainerDefinition( Image="myimage", Memory="300", Name="mycontainer", PortMappings=[ ecs.PortMapping( ContainerPort=8125, HostPort=8125, ) ]) container_definition.JSONrepr()
def test_allow_ref_task_role_arn(self): task_definition = ecs.TaskDefinition("mytaskdef", ContainerDefinitions=[ ecs.ContainerDefinition( Image="myimage", Memory="300", Name="mycontainer", ) ], TaskRoleArn=Ref( iam.Role("myRole"))) task_definition.to_dict()
def create_queue_worker_task_definition_resource(template, queue_worker_task_definition_family_variable, docker_repository_resource, queue_worker_log_group_resource, default_queue_name_variable, notifications_queue_name_variable, search_queue_name_variable): return template.add_resource( ecs.TaskDefinition( 'QueueWorkerTaskDefinition', Family=queue_worker_task_definition_family_variable, NetworkMode='bridge', RequiresCompatibilities=['EC2'], ContainerDefinitions=[ecs.ContainerDefinition( Name='api', Image=Join('.', [ Ref('AWS::AccountId'), 'dkr.ecr', Ref('AWS::Region'), Join('/', [ 'amazonaws.com', Ref(docker_repository_resource) ]) ]), MemoryReservation='256', Essential=True, LogConfiguration=ecs.LogConfiguration( LogDriver='awslogs', Options={ 'awslogs-group': Ref(queue_worker_log_group_resource), 'awslogs-region': Ref('AWS::Region'), 'awslogs-stream-prefix': 'ecs' } ), Command=[ 'php', 'artisan', 'queue:work', '--tries=1', '--queue=default,notifications,search' ], WorkingDirectory='/var/www/html', HealthCheck=ecs.HealthCheck( Command=[ 'CMD-SHELL', 'php -v || exit 1' ], Interval=30, Retries=3, Timeout=5 ) )] ) )
def create_task_definition(self, t): return t.add_resource(ecs.TaskDefinition( self.resource_name_format % ('TaskDefinition'), Family=Sub('${AWS::StackName}-app'), ContainerDefinitions=[ecs.ContainerDefinition( Name=self.container_name, Image=self.docker_image, Memory=self.memory, PortMappings=[ecs.PortMapping(ContainerPort=self.port)], Environment=[ ecs.Environment(Name=key, Value=value) for (key, value) in sorted(self.get_envs(t).items()) ] )] ))
def test_allow_container_healthcheck(self): health_check_def = ecs.HealthCheck( Command=["CMD-SHELL", "curl -f http://localhost/ || exit 1"], Interval=5, Timeout=30, Retries=5, ) container_definition = ecs.ContainerDefinition( Image="myimage", Memory="300", Name="mycontainer", HealthCheck=health_check_def, ) container_definition.to_dict()
def add_ecs(self, name, image, cpu, memory, container_port, alb_port, envvars, cidr, hosted_zone): """ Helper method creates ingress given a source cidr range and a set of ports @param name [string] Name of the service @param image [string] Docker image name @param memory [int] Sets the memory size of the service @param envvars [list] List of envvars @param cidr [string] Range of addresses for this vpc @param hosted_zone [string] Name of the hosted zone the elb will be mapped to """ print "Creating ECS" self.internal_security_group = self.add_sg_with_cidr_port_list( "ASGSG", "Security Group for ECS", 'vpcId', cidr, [{ "80": "80" }]) self.public_lb_security_group = self.add_sg_with_cidr_port_list( "ELBSG", "Security Group for accessing ECS publicly", 'vpcId', '0.0.0.0/0', [{ "443": "443" }]) container_def = ecs.ContainerDefinition( name + 'containerdef', Name=name, Image=image, Cpu=cpu, Memory=memory, PortMappings=[ecs.PortMapping(ContainerPort=container_port)]) task_def = self.add_resource( ecs.TaskDefinition(name + 'taskdef', Cpu=cpu, Memory=memory, RequiresCompatibilities=['FARGATE'], NetworkMode='awsvpc', ContainerDefinitions=[container_def])) self.add_resource( ecs.Service(name + 'service', Cluster=Ref(cluster), LaunchType='FARGATE', TaskDefinition=Ref(task_def), DesiredCount=1))
def test_docker_volume_configuration(self): docker_volume_configuration = ecs.DockerVolumeConfiguration( Autoprovision=True, Scope="task", Labels=dict(label="ok"), DriverOpts=dict(option="ok")) task_definition = ecs.TaskDefinition( "mytaskdef", ContainerDefinitions=[ ecs.ContainerDefinition( Image="myimage", Memory="300", Name="mycontainer", ) ], Volumes=[ ecs.Volume( Name="my-vol", DockerVolumeConfiguration=docker_volume_configuration), ], ) task_definition.to_dict()
def test_allow_scheduling_strategy(self): task_definition = ecs.TaskDefinition( "mytaskdef", ContainerDefinitions=[ ecs.ContainerDefinition( Image="myimage", Memory="300", Name="mycontainer", ) ], Volumes=[ ecs.Volume(Name="my-vol"), ], ) ecs_service = ecs.Service( 'Service', Cluster='cluster', DesiredCount=2, TaskDefinition=Ref(task_definition), SchedulingStrategy=ecs.SCHEDULING_STRATEGY_DAEMON) ecs_service.to_dict()
def build(self, t): env = [] logConf = None data = deepcopy(self.data) if data.get('Environment'): for v in data.get('Environment'): e = ecs.Environment(Name=self.jinja_txt(v['name']), Value=self.jinja_txt(v['value'])) env.append(e) del data['Environment'] if data.get('Image'): data['Image'] = self.jinja_txt(data['Image']) if data.get('LogConfiguration'): logConf = ecs.LogConfiguration( LogDriver=data.get('LogConfiguration').get('LogDriver'), Options={}) if data.get('LogConfiguration').get('Options').get( 'awslogs-group'): logConf.Options['awslogs-group'] = self.jinja_txt( data['LogConfiguration']['Options']['awslogs-group']) if data.get('LogConfiguration').get('Options').get( 'awslogs-region'): logConf.Options['awslogs-region'] = data['LogConfiguration'][ 'Options']['awslogs-region'] if data.get('LogConfiguration').get('Options').get( 'awslogs-stream-prefix'): logConf.Options['awslogs-stream-prefix'] = data[ 'LogConfiguration']['Options']['awslogs-stream-prefix'] del data['LogConfiguration'] ctr = ecs.ContainerDefinition(**data) ctr.Environment = env if logConf is not None: ctr.LogConfiguration = logConf return ctr
def test_allow_string_cluster(self): task_definition = ecs.TaskDefinition( "mytaskdef", ContainerDefinitions=[ ecs.ContainerDefinition( Image="myimage", Memory="300", Name="mycontainer", ) ], Volumes=[ ecs.Volume(Name="my-vol"), ], ) ecs_service = ecs.Service( 'Service', Cluster='cluster', DesiredCount=2, TaskDefinition=Ref(task_definition), ) ecs_service.JSONrepr()
def create_ecs_task(self): t = self.template if not self.vars['TaskRoleArn']: self.vars['TaskRoleArn'] = NoValue task_definition = t.add_resource( ecs.TaskDefinition( 'TaskDefinition', RequiresCompatibilities=['FARGATE'], Family=self.vars['Family'], Cpu=str(self.vars['Cpu']), Memory=str(self.vars['Memory']), NetworkMode='awsvpc', ExecutionRoleArn=Join( '', ['arn:aws:iam::', AccountId, ':role/ecsTaskExecutionRole' ]), TaskRoleArn=self.vars['TaskRoleArn'], ContainerDefinitions=[ ecs.ContainerDefinition( **self.munge_container_attributes()) ], )) return task_definition
def test_allow_ref_cluster(self): task_definition = ecs.TaskDefinition( "mytaskdef", ContainerDefinitions=[ ecs.ContainerDefinition( Image="myimage", Memory="300", Name="mycontainer", ) ], Volumes=[ ecs.Volume(Name="my-vol"), ], ) cluster = ecs.Cluster("mycluster") ecs_service = ecs.Service( 'Service', Cluster=Ref(cluster), DesiredCount=2, TaskDefinition=Ref(task_definition), ) ecs_service.to_dict()
def create_api_task_definition_resource(template, api_task_definition_family_variable, docker_repository_resource, api_log_group_resource): return template.add_resource( ecs.TaskDefinition( 'ApiTaskDefinition', Family=api_task_definition_family_variable, NetworkMode='bridge', RequiresCompatibilities=['EC2'], ContainerDefinitions=[ecs.ContainerDefinition( Name='api', Image=Join('.', [ Ref('AWS::AccountId'), 'dkr.ecr', Ref('AWS::Region'), Join('/', [ 'amazonaws.com', Ref(docker_repository_resource) ]) ]), MemoryReservation='256', PortMappings=[ecs.PortMapping( HostPort='0', ContainerPort='80', Protocol='tcp' )], Essential=True, LogConfiguration=ecs.LogConfiguration( LogDriver='awslogs', Options={ 'awslogs-group': Ref(api_log_group_resource), 'awslogs-region': Ref('AWS::Region'), 'awslogs-stream-prefix': 'ecs' } ) )] ) )
def create_ecs_resources(self): t = self.template # Give the instances access that the Empire daemon needs. t.add_resource( PolicyType( "AccessPolicy", PolicyName="empire", PolicyDocument=empire_policy({ "Environment": Ref("Environment"), "CustomResourcesTopic": Ref("CustomResourcesTopic"), "CustomResourcesQueue": (GetAtt("CustomResourcesQueue", "Arn")), "TemplateBucket": (Join("", ["arn:aws:s3:::", Ref("TemplateBucket"), "/*"])) }), Roles=[Ref("InstanceRole")])) t.add_resource( sns.Topic( EVENTS_TOPIC, DisplayName="Empire events", Condition="CreateSNSTopic", )) t.add_output( Output("EventsSNSTopic", Value=Ref(EVENTS_TOPIC), Condition="CreateSNSTopic")) # Add SNS Events policy if Events are enabled t.add_resource( PolicyType("SNSEventsPolicy", PolicyName="EmpireSNSEventsPolicy", Condition="EnableSNSEvents", PolicyDocument=sns_events_policy( If("CreateSNSTopic", Ref(EVENTS_TOPIC), Ref("EventsSNSTopicName"))), Roles=[Ref("InstanceRole")])) # Add run logs policy if run logs are enabled t.add_resource( PolicyType("RunLogsPolicy", PolicyName="EmpireRunLogsPolicy", Condition="EnableCloudwatchLogs", PolicyDocument=runlogs_policy( If("CreateRunLogsGroup", Ref(RUN_LOGS), Ref("RunLogsCloudwatchGroup"))), Roles=[Ref("InstanceRole")])) # Allow the controller to write empire events to kinesis if kinesis is # enabled. t.add_resource( PolicyType("AppEventStreamPolicy", PolicyName="EmpireAppEventStreamPolicy", Condition="EnableAppEventStream", PolicyDocument=logstream_policy(), Roles=[Ref("InstanceRole")])) t.add_resource( ecs.TaskDefinition( "TaskDefinition", Volumes=[ ecs.Volume( Name="dockerSocket", Host=ecs.Host(SourcePath="/var/run/docker.sock")), ecs.Volume(Name="dockerCfg", Host=ecs.Host(SourcePath="/root/.dockercfg")) ], ContainerDefinitions=[ ecs.ContainerDefinition( Command=["server", "-automigrate=true"], Name="empire", Environment=self.get_empire_environment(), Essential=True, Image=Ref("DockerImage"), MountPoints=[ ecs.MountPoint( SourceVolume="dockerSocket", ContainerPath="/var/run/docker.sock", ReadOnly=False), ecs.MountPoint(SourceVolume="dockerCfg", ContainerPath="/root/.dockercfg", ReadOnly=False) ], PortMappings=[ ecs.PortMapping(HostPort=8081, ContainerPort=8081) ], Cpu=Ref("TaskCPU"), Memory=Ref("TaskMemory")) ])) t.add_resource( Role("ServiceRole", AssumeRolePolicyDocument=get_ecs_assumerole_policy(), Path="/", Policies=[ Policy(PolicyName="ecs-service-role", PolicyDocument=service_role_policy()) ])) t.add_resource( ecs.Service( "Service", Cluster=Ref("ControllerCluster"), DeploymentConfiguration=ecs.DeploymentConfiguration( MaximumPercent=Ref("ServiceMaximumPercent"), MinimumHealthyPercent=Ref("ServiceMinimumHealthyPercent"), ), DesiredCount=Ref("DesiredCount"), LoadBalancers=[ ecs.LoadBalancer(ContainerName="empire", ContainerPort=8081, LoadBalancerName=Ref("LoadBalancer")) ], Role=Ref("ServiceRole"), TaskDefinition=Ref("TaskDefinition")))
TaskDefinition = t.add_resource(ecs.TaskDefinition( "TaskDefinition", DependsOn=TaskExecutionPolicy, RequiresCompatibilities=["FARGATE"], Cpu="512", Memory="1GB", NetworkMode="awsvpc", ExecutionRoleArn=GetAtt(TaskExecutionRole, "Arn"), ContainerDefinitions=[ ecs.ContainerDefinition( Name="nginx-container", Image=Ref(NginxImage), Essential=True, PortMappings=[ecs.PortMapping(ContainerPort=80)], LogConfiguration=ecs.LogConfiguration( LogDriver="awslogs", Options={"awslogs-group": Ref(CWLogGroup), "awslogs-region": Ref("AWS::Region"), "awslogs-stream-prefix": "nginx-container"} ) ) ] )) Service = t.add_resource(ecs.Service( "Service", DependsOn=ALBListener, Cluster=Ref(ECSCluster), DesiredCount=1, TaskDefinition=Ref(TaskDefinition), LaunchType="FARGATE",
def generate_container_definition(self): return ecs.ContainerDefinition( **self.generate_container_definition_kwargs())
def ECS_ContainerDefinition(): Containers = [] for n, v in cfg.ContainerDefinitions.items(): name = f"ContainerDefinitions{n}" # Ex. ContainerDefinitions1 EnvValue_Out_String = [] EnvValue_Out_Map = {} for m, w in v["Environment"].items(): if m.startswith("Env"): continue envname = f"{name}Environment{m}" envkeyname = w["Name"] # parameters p_EnvValue = Parameter( f"{envname}Value", Description= f"{envkeyname} - empty for default based on env/role", ) # If key NoParam is present skip adding Parameters # (usefull as they have a limited max number) if "NoParam" not in w: add_obj(p_EnvValue) EnvValue_Out_String.append("%s=${%s}" % (envkeyname, envkeyname)) EnvValue_Out_Map.update( {envkeyname: get_endvalue(f"{envname}Value")}) # resources Container = ecs.ContainerDefinition(name) auto_get_props(Container, indexname=n) if len(cfg.ContainerDefinitions) == 1: # parameters p_UseTaskCpu = Parameter( f"{name}UseTaskCpu", Description= "Empty for mapped value - Use Task Cpu Value, if present, for Container Cpu", AllowedValues=["", "true", "false"], ) add_obj(p_UseTaskCpu) # conditions c_UseTaskCpu = { f"{name}UseTaskCpu": And( Condition("CpuTask"), get_condition("", "equals", "true", f"{name}UseTaskCpu"), ) } add_obj(c_UseTaskCpu) Container.Cpu = If(f"{name}UseTaskCpu", get_endvalue("Cpu"), get_endvalue(f"{name}Cpu")) Container.Memory = If( "LaunchTypeFarGate", get_endvalue("Memory"), get_endvalue(f"{name}Memory"), ) Containers.append(Container) # outputs o_EnvValueOut = Output( f"{name}Environment", Value=Sub(",".join(EnvValue_Out_String), **EnvValue_Out_Map), ) add_obj(o_EnvValueOut) return Containers
def add_container_def(self, container): return ecs.ContainerDefinition(Image=container['Image'], Memory=container['Memory'], Name=container['Name'], Privileged=container['Priviledge'])
jicketthreadtemplate = "/etc/jicket/threadtemplate.html" t = Template("Jicket ECS Deployment") # ECS Cluster # ============= cluster = ecs.Cluster("JicketCluster") cluster.ClusterName = "Jicket" t.add_resource(cluster) # ECS Task Definition # ===================== taskdef = ecs.TaskDefinition("JicketTask") contdef = ecs.ContainerDefinition() contdef.Cpu = 0 contdef.Environment = [ ecs.Environment(Name="JICKET_IMAP_HOST", Value=jicketimaphost), ecs.Environment(Name="JICKET_JIRA_USER", Value=jicketjirauser), ecs.Environment(Name="JICKET_TICKET_ADDRESS", Value=jicketticketaddress), ecs.Environment(Name="JICKET_SMTP_HOST", Value=jicketsmtphost), ecs.Environment(Name="JICKET_JIRA_PASS", Value=jicketjirapass), ecs.Environment(Name="JICKET_JIRA_PROJECT", Value=jicketjiraproject), ecs.Environment(Name="JICKET_JIRA_URL", Value=jicketjiraurl), ecs.Environment(Name="JICKET_THREAD_TEMPLATE", Value=jicketthreadtemplate), ecs.Environment(Name="JICKET_IMAP_PASS", Value=jicketimappass), ecs.Environment(Name="JICKET_IMAP_USER", Value=jicketimapuser), ] contdef.Image = "kwpcommunications/jicket:latest" contdef.MemoryReservation = 512
NetworkMode='bridge', RequiresCompatibilities=['EC2'], ContainerDefinitions=[ecs.ContainerDefinition( Name='api', Image=Join('.', [ Ref('AWS::AccountId'), 'dkr.ecr', Ref('AWS::Region'), Join('/', [ 'amazonaws.com', Ref(docker_repository) ]) ]), MemoryReservation='256', PortMappings=[ecs.PortMapping( HostPort='0', ContainerPort='80', Protocol='tcp' )], Essential=True, LogConfiguration=ecs.LogConfiguration( LogDriver='awslogs', Options={ 'awslogs-group': Ref(api_log_group), 'awslogs-region': Ref('AWS::Region'), 'awslogs-stream-prefix': 'ecs' } ) )] ) )
def main(): template = Template() template.add_resource( ecs.Cluster("ECSCluster", ClusterName="WorldCheckCluster")) template.add_resource( iam.Role("ECSTaskRole", AssumeRolePolicyDocument={ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": { "Service": ["ecs-tasks.amazonaws.com"] }, "Action": ["sts:AssumeRole"] }] })) template.add_resource( iam.Role( "ECSServiceSchedulerRole", AssumeRolePolicyDocument={ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": { "Service": ["ecs.amazonaws.com"] }, "Action": ["sts:AssumeRole"] }] }, Policies=[ iam.Policy(PolicyDocument={ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": [ "ec2:Describe*", "elasticloadbalancing:DeregisterInstancesFromLoadBalancer", "elasticloadbalancing:DeregisterTargets", "elasticloadbalancing:Describe*", "elasticloadbalancing:RegisterInstancesWithLoadBalancer", "elasticloadbalancing:RegisterTargets" ], "Resource": "*" }] }, PolicyName="ecs-service") ])) template.add_resource( iam.Role("EC2InstanceRole", AssumeRolePolicyDocument={ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": { "Service": ["ec2.amazonaws.com"] }, "Action": ["sts:AssumeRole"] }] }, Policies=[ iam.Policy(PolicyDocument={ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": [ "ecs:CreateCluster", "ecs:DeregisterContainerInstance", "ecs:DiscoverPollEndpoint", "ecs:Poll", "ecs:RegisterContainerInstance", "ecs:StartTelemetrySession", "ecr:GetAuthorizationToken", "ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer", "ecs:Submit*", "logs:CreateLogStream", "logs:PutLogEvents", "ec2:DescribeTags", "cloudwatch:PutMetricData" ], "Resource": "*" }] }, PolicyName="ecs-service") ])) template.add_resource( iam.InstanceProfile("EC2InstanceProfile", Roles=[Ref("EC2InstanceRole")])) with open("user-data.sh", "r") as f: user_data_content = f.readlines() template.add_resource( ec2.Instance( "EC2Instance", ImageId="ami-13f7226a", InstanceType="t2.micro", SecurityGroups=["default"], UserData=Base64(Join('', [Sub(x) for x in user_data_content])), IamInstanceProfile=Ref("EC2InstanceProfile"), )) template.add_resource( ecs.TaskDefinition( "ECSTaskDefinition", TaskRoleArn=Ref("ECSTaskRole"), ContainerDefinitions=[ ecs.ContainerDefinition( Name="SimpleServer", Memory="128", Image="abbas123456/simple-server:latest", PortMappings=[ecs.PortMapping(ContainerPort=8000)], ) ])) template.add_resource( elb.TargetGroup( "ECSTargetGroup", VpcId="vpc-925497f6", Port=8000, Protocol="HTTP", )) template.add_resource( elb.LoadBalancer( "LoadBalancer", Subnets=["subnet-a321c8fb", "subnet-68fa271e", "subnet-689d350c"], SecurityGroups=["sg-0202bd65"])) template.add_resource( elb.Listener( "LoadBalancerListener", DefaultActions=[ elb.Action(Type="forward", TargetGroupArn=Ref("ECSTargetGroup")) ], LoadBalancerArn=Ref("LoadBalancer"), Port=80, Protocol="HTTP", )) template.add_resource( ecs.Service("ECSService", Cluster=Ref("ECSCluster"), DesiredCount=1, LoadBalancers=[ ecs.LoadBalancer(ContainerPort=8000, ContainerName="SimpleServer", TargetGroupArn=Ref("ECSTargetGroup")) ], Role=Ref("ECSServiceSchedulerRole"), TaskDefinition=Ref("ECSTaskDefinition"), DependsOn="LoadBalancerListener")) return template.to_json()