AWSTemplateFormatVersion: '2010-09-09'
Description: Private EKS and ECS Fargate lab with an EC2 echo backend and SSM management.
Parameters:
  Vpc: {Type: 'AWS::EC2::VPC::Id'}
  PrivateA: {Type: 'AWS::EC2::Subnet::Id'}
  PrivateB: {Type: 'AWS::EC2::Subnet::Id'}
  PrivateRoutes: {Type: String}
  Ami:
    Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
    Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-arm64
Resources:
  Repo:
    Type: AWS::ECR::Repository
    Properties:
      ImageTagMutability: IMMUTABLE
      EmptyOnDelete: true
  ProxySG:
    Type: AWS::EC2::SecurityGroup
    Properties: {VpcId: !Ref Vpc, GroupDescription: Managed Envoy}
  BackendSG:
    Type: AWS::EC2::SecurityGroup
    Properties:
      VpcId: !Ref Vpc
      GroupDescription: Accept echo requests from Envoy
      SecurityGroupIngress:
        - {IpProtocol: tcp, FromPort: 8080, ToPort: 8080, SourceSecurityGroupId: !Ref ProxySG}
  EndpointSG:
    Type: AWS::EC2::SecurityGroup
    Properties:
      VpcId: !Ref Vpc
      GroupDescription: Private AWS API endpoints for the lab
      SecurityGroupIngress: [{IpProtocol: tcp, FromPort: 443, ToPort: 443, CidrIp: 10.86.0.0/16}]
  EcrApi:
    Type: AWS::EC2::VPCEndpoint
    Properties:
      VpcId: !Ref Vpc
      VpcEndpointType: Interface
      PrivateDnsEnabled: true
      SecurityGroupIds: [!Ref EndpointSG]
      SubnetIds: [!Ref PrivateA, !Ref PrivateB]
      ServiceName: !Sub 'com.amazonaws.${AWS::Region}.ecr.api'
  EcrDocker:
    Type: AWS::EC2::VPCEndpoint
    Properties:
      VpcId: !Ref Vpc
      VpcEndpointType: Interface
      PrivateDnsEnabled: true
      SecurityGroupIds: [!Ref EndpointSG]
      SubnetIds: [!Ref PrivateA, !Ref PrivateB]
      ServiceName: !Sub 'com.amazonaws.${AWS::Region}.ecr.dkr'
  S3:
    Type: AWS::EC2::VPCEndpoint
    Properties:
      VpcId: !Ref Vpc
      RouteTableIds: [!Ref PrivateRoutes]
      ServiceName: !Sub 'com.amazonaws.${AWS::Region}.s3'
  Ssm:
    Type: AWS::EC2::VPCEndpoint
    Properties:
      VpcId: !Ref Vpc
      VpcEndpointType: Interface
      PrivateDnsEnabled: true
      SecurityGroupIds: [!Ref EndpointSG]
      SubnetIds: [!Ref PrivateA]
      ServiceName: !Sub 'com.amazonaws.${AWS::Region}.ssm'
  SsmMessages:
    Type: AWS::EC2::VPCEndpoint
    Properties:
      VpcId: !Ref Vpc
      VpcEndpointType: Interface
      PrivateDnsEnabled: true
      SecurityGroupIds: [!Ref EndpointSG]
      SubnetIds: [!Ref PrivateA]
      ServiceName: !Sub 'com.amazonaws.${AWS::Region}.ssmmessages'
  EksRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement: [{Effect: Allow, Principal: {Service: eks.amazonaws.com}, Action: 'sts:AssumeRole'}]
      ManagedPolicyArns: [!Sub 'arn:${AWS::Partition}:iam::aws:policy/AmazonEKSClusterPolicy']
  Eks:
    Type: AWS::EKS::Cluster
    Properties:
      Name: !Ref 'AWS::StackName'
      RoleArn: !GetAtt EksRole.Arn
      AccessConfig: {AuthenticationMode: API}
      ResourcesVpcConfig: {SubnetIds: [!Ref PrivateA, !Ref PrivateB], EndpointPrivateAccess: true, EndpointPublicAccess: false}
  KubeletRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal: {Service: eks-fargate-pods.amazonaws.com}
            Action: 'sts:AssumeRole'
            Condition:
              ArnLike: {'aws:SourceArn': !Sub 'arn:${AWS::Partition}:eks:${AWS::Region}:${AWS::AccountId}:fargateprofile/${AWS::StackName}/*'}
      ManagedPolicyArns: [!Sub 'arn:${AWS::Partition}:iam::aws:policy/AmazonEKSFargatePodExecutionRolePolicy']
  FargateProfile:
    Type: AWS::EKS::FargateProfile
    Properties:
      ClusterName: !Ref Eks
      PodExecutionRoleArn: !GetAtt KubeletRole.Arn
      Selectors: [{Namespace: default, Labels: [{Key: app, Value: envoy-lab-echo}]}]
      Subnets: [!Ref PrivateA, !Ref PrivateB]
  EksEchoIn:
    Type: AWS::EC2::SecurityGroupIngress
    Properties: {GroupId: !GetAtt Eks.ClusterSecurityGroupId, SourceSecurityGroupId: !Ref ProxySG, IpProtocol: tcp, FromPort: 8080, ToPort: 8080}
  EksAdminIn:
    Type: AWS::EC2::SecurityGroupIngress
    Properties: {GroupId: !GetAtt Eks.ClusterSecurityGroupId, SourceSecurityGroupId: !Ref BackendSG, IpProtocol: tcp, FromPort: 443, ToPort: 443}
  Admin:
    Type: AWS::EKS::AccessEntry
    Properties:
      ClusterName: !Ref Eks
      PrincipalArn: !GetAtt HostRole.Arn
      AccessPolicies:
        - PolicyArn: !Sub 'arn:${AWS::Partition}:eks::aws:cluster-access-policy/AmazonEKSEditPolicy'
          AccessScope: {Type: namespace, Namespaces: [default]}
  ECS:
    Type: AWS::ECS::Cluster
  TaskRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement: [{Effect: Allow, Principal: {Service: ecs-tasks.amazonaws.com}, Action: 'sts:AssumeRole'}]
      ManagedPolicyArns: [!Sub 'arn:${AWS::Partition}:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy']
  HostRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement: [{Effect: Allow, Principal: {Service: ec2.amazonaws.com}, Action: 'sts:AssumeRole'}]
      ManagedPolicyArns: [!Sub 'arn:${AWS::Partition}:iam::aws:policy/AmazonSSMManagedInstanceCore']
  Profile:
    Type: AWS::IAM::InstanceProfile
    Properties: {Roles: [!Ref HostRole]}
  HostTemplate:
    Type: AWS::EC2::LaunchTemplate
    Properties:
      LaunchTemplateData:
        InstanceType: t4g.micro
        ImageId: !Ref Ami
        MetadataOptions: {HttpTokens: required, HttpEndpoint: enabled}
        BlockDeviceMappings: [{DeviceName: /dev/xvda, Ebs: {VolumeType: gp3, Encrypted: true, DeleteOnTermination: true}}]
        IamInstanceProfile: {Name: !Ref Profile}
        SecurityGroupIds: [!Ref BackendSG]
        UserData:
          Fn::Base64: |
            #!/bin/bash
            set -eu
            cat > /opt/echo.py <<'PY'
            import json
            from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
            class Echo(BaseHTTPRequestHandler):
                def do_GET(self):
                    data = json.dumps({"backend": "ec2", "path": self.path}).encode()
                    self.send_response(200)
                    self.send_header("Content-Type", "application/json")
                    self.send_header("Content-Length", str(len(data)))
                    self.end_headers()
                    self.wfile.write(data)
            ThreadingHTTPServer(("0.0.0.0", 8080), Echo).serve_forever()
            PY
            cat > /etc/systemd/system/echo.service <<'UNIT'
            [Unit]
            Description=Lab echo backend
            [Service]
            DynamicUser=yes
            ExecStart=/usr/bin/python3 /opt/echo.py
            Restart=on-failure
            [Install]
            WantedBy=multi-user.target
            UNIT
            systemctl daemon-reload
            systemctl enable --now echo.service
  Host:
    Type: AWS::EC2::Instance
    Properties:
      SubnetId: !Ref PrivateA
      LaunchTemplate: {LaunchTemplateId: !Ref HostTemplate, Version: !GetAtt HostTemplate.LatestVersionNumber}
Outputs:
  Repo: {Value: !GetAtt Repo.RepositoryUri}
  Host: {Value: !Ref Host}
  Ec2IP: {Value: !GetAtt Host.PrivateIp}
  ProxySG: {Value: !Ref ProxySG}
  BackendSG: {Value: !Ref BackendSG}
  Eks: {Value: !Ref Eks}
  Endpoint: {Value: !GetAtt Eks.Endpoint}
  CA: {Value: !GetAtt Eks.CertificateAuthorityData}
  ECS: {Value: !Ref ECS}
  TaskRole: {Value: !GetAtt TaskRole.Arn}
