---
AWSTemplateFormatVersion: '2010-09-09'
Description: This stack deploys the core network infrastructure and IAM resources
             to be used for a service hosted in Amazon ECS using AWS Fargate.
#------------------------------------------------------
# Parameters
#------------------------------------------------------
Parameters:
  SkipBucket:
    Type: String
    Default: "false"
    AllowedValues:
      - "true"
      - "false"
  IdeInstanceType:
    Description: VSCode IDE EC2 instance type
    Type: String
    Default: t2.micro
    ConstraintDescription: must be a valid EC2 instance type.
  IdeAmiId:
    Description: latest image id for your OS
    Type: "AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>" 
    Default: "/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64" 
  IdeUser:
    Description: IDE EC2 username
    Type: String
    Default: ec2-user
    ConstraintDescription: must be a valid Linux user name.
  VSCodeServerVersion:
    Type: String
    Description: VSCodeServerVersion
    Default: 4.95.3
  IDEHashedPassword:
    Type: String
    Description: Hashed Password for VSCode Server
#------------------------------------------------------
# Conditions
#------------------------------------------------------
Conditions:
  MakeBucket:
    Fn::Equals: ["false", !Ref SkipBucket]

Mappings:
  # Hard values for the subnet masks. These masks define
  # the range of internal IP addresses that can be assigned.
  # The VPC can have all IP's from 10.0.0.0 to 10.0.255.255
  # There are four subnets which cover the ranges:
  #
  # 10.0.0.0 - 10.0.0.255
  # 10.0.1.0 - 10.0.1.255
  # 10.0.2.0 - 10.0.2.255
  # 10.0.3.0 - 10.0.3.255
  #
  # If you need more IP addresses (perhaps you have so many
  # instances that you run out) then you can customize these
  # ranges to add more
  SubnetConfig:
    VPC:
      CIDR: '10.0.0.0/16'
    PublicOne:
      CIDR: '10.0.0.0/24'
    PublicTwo:
      CIDR: '10.0.1.0/24'
    PrivateOne:
      CIDR: '10.0.2.0/24'
    PrivateTwo:
      CIDR: '10.0.3.0/24'
    PublicIDE:
      CIDR: '10.0.4.0/24'

Resources:
  MythicalBucket:
    Type: AWS::S3::Bucket
    Condition: MakeBucket
    Properties:
      # AccessControl: PublicRead
      PublicAccessBlockConfiguration:
        BlockPublicAcls: false
        BlockPublicPolicy: false
        IgnorePublicAcls: false
        RestrictPublicBuckets: false
      WebsiteConfiguration:
        IndexDocument: index.html
        ErrorDocument: error.html
      Tags:
        - Key: group
          Value: ecs-mythical

  Mono:
    Type: AWS::ECR::Repository
    Properties:
      Tags:
        - Key: group
          Value: ecs-mythical

  Like:
    Type: AWS::ECR::Repository
    Properties:
      Tags:
        - Key: group
          Value: ecs-mythical

  MythicalEcsCluster:
    Type: AWS::ECS::Cluster
    Properties:
      ClusterName: !Sub Cluster-${AWS::StackName}
      Tags:
        - Key: group
          Value: ecs-mythical

  MythicalMonolithLogGroup:
    Type: AWS::Logs::LogGroup
    Properties:
      Tags:
        - Key: group
          Value: ecs-mythical

  MythicalMonolithTaskDefinition:
    Type: AWS::ECS::TaskDefinition
    Properties:
      Tags:
        - Key: group
          Value: ecs-mythical
      Cpu: 256
      ExecutionRoleArn: !GetAtt EcsServiceRole.Arn
      Family: !Sub Monolith-Definition-${AWS::StackName}
      Memory: 512
      NetworkMode: awsvpc
      RequiresCompatibilities:
        - FARGATE
      TaskRoleArn: !GetAtt ECSTaskRole.Arn
      ContainerDefinitions:
        - Name: monolith-service
          Image: nginx:latest
          PortMappings:
            - ContainerPort: 80
              Protocol: http
          Environment:
            - Name: UPSTREAM_URL
              Value: !GetAtt MythicalLoadBalancer.DNSName
            - Name: DDB_TABLE_NAME
              Value: !Ref MythicalDynamoTable
          LogConfiguration:
            LogDriver: awslogs
            Options:
              awslogs-group: !Ref MythicalMonolithLogGroup
              awslogs-region: !Ref AWS::Region
              awslogs-stream-prefix: awslogs-mythicalmysfits-service
          Essential: true

  MythicalLoadBalancerSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: !Sub SecurityGroup-${AWS::StackName}
      GroupDescription: Access to the load balancer
      VpcId: !Ref 'VPC'
      SecurityGroupIngress:
          # Allow access to ALB from anywhere on the internet
          - IpProtocol: tcp
            FromPort: 80
            ToPort: 80
            CidrIp: 0.0.0.0/0
      Tags:
        - Key: group
          Value: ecs-mythical

  MythicalLoadBalancer:
    Type: AWS::ElasticLoadBalancingV2::LoadBalancer
    Properties:
      Name: !Sub alb-${AWS::StackName}
      Scheme: internet-facing
      Type: application
      SecurityGroups:
        - !Ref MythicalLoadBalancerSecurityGroup
      Subnets:
        - !Ref PublicSubnetOne
        - !Ref PublicSubnetTwo
      Tags:
        - Key: group
          Value: ecs-mythical

  MythicalListener:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      DefaultActions:
        - TargetGroupArn: !Ref MythicalMonolithTargetGroup
          Type: forward
      LoadBalancerArn: !Ref MythicalLoadBalancer
      Port: 80
      Protocol: HTTP
      Tags:
        - Key: group
          Value: ecs-mythical

  MythicalMonolithTargetGroup:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      HealthCheckIntervalSeconds: 10
      HealthCheckPath: /
      HealthCheckProtocol: HTTP
      HealthyThresholdCount: 3
      UnhealthyThresholdCount: 3
      Port: 80
      Protocol: HTTP
      VpcId: !Ref VPC
      TargetType: ip
      Tags:
        - Key: group
          Value: ecs-mythical

  MythicalMonolithService:
    Type: AWS::ECS::Service
    DependsOn: MythicalListener
    Properties:
      Cluster: !Ref MythicalEcsCluster
      DeploymentConfiguration:
        MinimumHealthyPercent: 0
        MaximumPercent: 200
      DesiredCount: 1
      LaunchType: FARGATE
      LoadBalancers:
        - ContainerName: monolith-service
          ContainerPort: 80
          TargetGroupArn: !Ref MythicalMonolithTargetGroup
      NetworkConfiguration:
        AwsvpcConfiguration:
          AssignPublicIp: DISABLED
          SecurityGroups:
            - !Ref FargateContainerSecurityGroup
          Subnets:
            - !Ref PrivateSubnetOne
            - !Ref PrivateSubnetTwo
      TaskDefinition: !Ref MythicalMonolithTaskDefinition
      Tags:
        - Key: group
          Value: ecs-mythical

  # VPC in which containers will be networked.
  # It has two public subnets, and two private subnets.
  # We distribute the subnets across the first two available subnets
  # for the region, for high availability.
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      EnableDnsSupport: true
      EnableDnsHostnames: true
      CidrBlock: !FindInMap ['SubnetConfig', 'VPC', 'CIDR']
      Tags:
        - Key: Name
          Value: !Sub Mysfits-VPC-${AWS::StackName}
        - Key: group
          Value: ecs-mythical

  # Two public subnets, where a public load balancer will later be created.
  PublicSubnetOne:
    Type: AWS::EC2::Subnet
    Properties:
      AvailabilityZone:
         Fn::Select:
         - 0
         - Fn::GetAZs: {Ref: 'AWS::Region'}
      VpcId: !Ref 'VPC'
      CidrBlock: !FindInMap ['SubnetConfig', 'PublicOne', 'CIDR']
      MapPublicIpOnLaunch: true
      Tags:
        - Key: Name
          Value: !Sub MysfitsPublicOne-${AWS::StackName}
        - Key: group
          Value: ecs-mythical
  PublicSubnetTwo:
    Type: AWS::EC2::Subnet
    Properties:
      AvailabilityZone:
         Fn::Select:
         - 1
         - Fn::GetAZs: {Ref: 'AWS::Region'}
      VpcId: !Ref 'VPC'
      CidrBlock: !FindInMap ['SubnetConfig', 'PublicTwo', 'CIDR']
      MapPublicIpOnLaunch: true
      Tags:
        - Key: Name
          Value: !Sub MysfitsPublicTwo-${AWS::StackName}
        - Key: group
          Value: ecs-mythical
  IdePublicSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      AvailabilityZone:
         Fn::Select:
         - 0
         - Fn::GetAZs: {Ref: 'AWS::Region'}
      VpcId: !Ref 'VPC'
      CidrBlock: !FindInMap ['SubnetConfig', 'PublicIDE', 'CIDR']
      MapPublicIpOnLaunch: true
      Tags:
        - Key: Name
          Value: !Sub MysfitsPublic4IDE-${AWS::StackName}
        - Key: group
          Value: ecs-mythical

  # Two private subnets where containers will only have private
  # IP addresses, and will only be reachable by other members of the
  # VPC
  PrivateSubnetOne:
    Type: AWS::EC2::Subnet
    Properties:
      AvailabilityZone:
         Fn::Select:
         - 0
         - Fn::GetAZs: {Ref: 'AWS::Region'}
      VpcId: !Ref 'VPC'
      CidrBlock: !FindInMap ['SubnetConfig', 'PrivateOne', 'CIDR']
      Tags:
        - Key: Name
          Value: !Sub MysfitsPrivateOne-${AWS::StackName}
        - Key: group
          Value: ecs-mythical
  PrivateSubnetTwo:
    Type: AWS::EC2::Subnet
    Properties:
      AvailabilityZone:
         Fn::Select:
         - 1
         - Fn::GetAZs: {Ref: 'AWS::Region'}
      VpcId: !Ref 'VPC'
      CidrBlock: !FindInMap ['SubnetConfig', 'PrivateTwo', 'CIDR']
      Tags:
        - Key: Name
          Value: !Sub MysfitsPrivateTwo-${AWS::StackName}
        - Key: group
          Value: ecs-mythical

  # Setup networking resources for the public subnets.
  InternetGateway:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags:
        - Key: group
          Value: ecs-mythical
  GatewayAttachement:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      VpcId: !Ref 'VPC'
      InternetGatewayId: !Ref 'InternetGateway'
  PublicRouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref 'VPC'
      Tags:
        - Key: group
          Value: ecs-mythical
  PublicRoute:
    Type: AWS::EC2::Route
    DependsOn: GatewayAttachement
    Properties:
      RouteTableId: !Ref 'PublicRouteTable'
      DestinationCidrBlock: '0.0.0.0/0'
      GatewayId: !Ref 'InternetGateway'
  PublicSubnetOneRouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PublicSubnetOne
      RouteTableId: !Ref PublicRouteTable
  PublicSubnetTwoRouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PublicSubnetTwo
      RouteTableId: !Ref PublicRouteTable
  IdePublicSubnetRouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref IdePublicSubnet
      RouteTableId: !Ref PublicRouteTable

  # Setup networking resources for the private subnets. Containers
  # in these subnets have only private IP addresses, and must use a NAT
  # gateway to talk to the internet. We launch two NAT gateways, one for
  # each private subnet.
  NatGatewayOneAttachment:
    Type: AWS::EC2::EIP
    DependsOn: GatewayAttachement
    Properties:
        Domain: vpc
  NatGatewayTwoAttachment:
    Type: AWS::EC2::EIP
    DependsOn: GatewayAttachement
    Properties:
        Domain: vpc
  NatGatewayOne:
    Type: AWS::EC2::NatGateway
    Properties:
      AllocationId: !GetAtt NatGatewayOneAttachment.AllocationId
      SubnetId: !Ref PublicSubnetOne
      Tags:
        - Key: group
          Value: ecs-mythical
  NatGatewayTwo:
    Type: AWS::EC2::NatGateway
    Properties:
      AllocationId: !GetAtt NatGatewayTwoAttachment.AllocationId
      SubnetId: !Ref PublicSubnetTwo
      Tags:
        - Key: group
          Value: ecs-mythical
  PrivateRouteTableOne:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref 'VPC'
      Tags:
        - Key: group
          Value: ecs-mythical
  PrivateRouteOne:
    Type: AWS::EC2::Route
    Properties:
      RouteTableId: !Ref PrivateRouteTableOne
      DestinationCidrBlock: 0.0.0.0/0
      NatGatewayId: !Ref NatGatewayOne
  PrivateRouteTableOneAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref PrivateRouteTableOne
      SubnetId: !Ref PrivateSubnetOne
  PrivateRouteTableTwo:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref 'VPC'
      Tags:
        - Key: group
          Value: ecs-mythical
  PrivateRouteTwo:
    Type: AWS::EC2::Route
    Properties:
      RouteTableId: !Ref PrivateRouteTableTwo
      DestinationCidrBlock: 0.0.0.0/0
      NatGatewayId: !Ref NatGatewayTwo
  PrivateRouteTableTwoAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref PrivateRouteTableTwo
      SubnetId: !Ref PrivateSubnetTwo

  # VPC Endpoint for DynamoDB
  # If a container needs to access DynamoDB (coming in module 3) this
  # allows a container in the private subnet to talk to DynamoDB directly
  # without needing to go via the NAT gateway.
  DynamoDBEndpoint:
    Type: AWS::EC2::VPCEndpoint
    Properties:
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Action: "*"
            Principal: "*"
            Resource: "*"
      RouteTableIds:
        - !Ref 'PrivateRouteTableOne'
        - !Ref 'PrivateRouteTableTwo'
      ServiceName: !Join [ "", [ "com.amazonaws.", { "Ref": "AWS::Region" }, ".dynamodb" ] ]
      VpcId: !Ref 'VPC'

  # The security group for our service containers to be hosted in Fargate.
  # Even though traffic from users will pass through a Network Load Balancer,
  # that traffic is purely TCP passthrough, without security group inspection.
  # Therefore, we will allow for traffic from the Internet to be accepted by our
  # containers.  But, because the containers will only have Private IP addresses,
  # the only traffic that will reach the containers is traffic that is routed
  # to them by the public load balancer on the specific ports that we configure.
  FargateContainerSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Access to the fargate containers from the Internet
      VpcId: !Ref 'VPC'
      SecurityGroupIngress:
          # Allow access to NLB from anywhere on the internet
          # - CidrIp: !FindInMap ['SubnetConfig', 'VPC', 'CIDR']
          - CidrIp: 0.0.0.0/0
            IpProtocol: -1
      Tags:
        - Key: group
          Value: ecs-mythical

  # This is an IAM role which authorizes ECS to manage resources on your
  # account on your behalf, such as updating your load balancer with the
  # details of where your containers are, so that traffic can reach your
  # containers.
  EcsServiceRole:
    Type: AWS::IAM::Role
    Properties:
      Tags:
        - Key: group
          Value: ecs-mythical
      AssumeRolePolicyDocument:
        Statement:
        - Effect: Allow
          Principal:
            Service:
            - ecs.amazonaws.com
            - ecs-tasks.amazonaws.com
          Action:
          - sts:AssumeRole
      Path: /
      Policies:
      - PolicyName: ecs-service
        PolicyDocument:
          Statement:
          - Effect: Allow
            Action:
              # Rules which allow ECS to attach network interfaces to instances
              # on your behalf in order for awsvpc networking mode to work right
              - 'ec2:AttachNetworkInterface'
              - 'ec2:CreateNetworkInterface'
              - 'ec2:CreateNetworkInterfacePermission'
              - 'ec2:DeleteNetworkInterface'
              - 'ec2:DeleteNetworkInterfacePermission'
              - 'ec2:Describe*'
              - 'ec2:DetachNetworkInterface'

              # Rules which allow ECS to update load balancers on your behalf
              # with the information sabout how to send traffic to your containers
              - 'elasticloadbalancing:DeregisterInstancesFromLoadBalancer'
              - 'elasticloadbalancing:DeregisterTargets'
              - 'elasticloadbalancing:Describe*'
              - 'elasticloadbalancing:RegisterInstancesWithLoadBalancer'
              - 'elasticloadbalancing:RegisterTargets'

              # Rules which allow ECS to run tasks that have IAM roles assigned to them.
              - 'iam:PassRole'

              # Rules that let ECS interact with container images.
              - 'ecr:GetAuthorizationToken'
              - 'ecr:BatchCheckLayerAvailability'
              - 'ecr:GetDownloadUrlForLayer'
              - 'ecr:BatchGetImage'

              # Rules that let ECS create and push logs to CloudWatch.
              - 'logs:DescribeLogStreams'
              - 'logs:CreateLogStream'
              - 'logs:CreateLogGroup'
              - 'logs:PutLogEvents'

            Resource: '*'

  # This is a role which is used by the ECS tasks. Tasks in Amazon ECS define
  # the containers that should be deployed togehter and the resources they
  # require from a compute/memory perspective. So, the policies below will define
  # the IAM permissions that our Mythical Mysfits docker containers will have.
  # If you attempted to write any code for the Mythical Mysfits service that
  # interacted with different AWS service APIs, these roles would need to include
  # those as allowed actions.
  ECSTaskRole:
    Type: AWS::IAM::Role
    Properties:
      Tags:
        - Key: group
          Value: ecs-mythical
      AssumeRolePolicyDocument:
        Statement:
        - Effect: Allow
          Principal:
            Service:
              - ecs-tasks.amazonaws.com
              # Also add EC2 for testing in VSCode
              - ec2.amazonaws.com
          Action: ['sts:AssumeRole']
      Path: /
      Policies:
        - PolicyName: AmazonECSTaskRolePolicy
          PolicyDocument:
            Statement:
            - Effect: Allow
              Action:
                # Allow the ECS Tasks to download images from ECR
                - 'ecr:GetAuthorizationToken'
                - 'ecr:BatchCheckLayerAvailability'
                - 'ecr:GetDownloadUrlForLayer'
                - 'ecr:BatchGetImage'

                # Allow the ECS tasks to upload logs to CloudWatch
                - 'logs:CreateLogStream'
                - 'logs:CreateLogGroup'
                - 'logs:PutLogEvents'
              Resource: '*'

            - Effect: Allow
              Action:
                # Allows the ECS tasks to interact with only the MysfitsTable
                # in DynamoDB
                - 'dynamodb:Scan'
                - 'dynamodb:Query'
                - 'dynamodb:UpdateItem'
                - 'dynamodb:GetItem'
              Resource: !GetAtt MythicalDynamoTable.Arn
  MythicalProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Roles:
        - !Ref ECSTaskRole

  MythicalDynamoTable:
    Type: AWS::DynamoDB::Table
    Properties:
      Tags:
        - Key: group
          Value: ecs-mythical
      TableName: !Sub Table-${AWS::StackName}
      AttributeDefinitions:
        - AttributeName: MysfitId
          AttributeType: S
        - AttributeName: GoodEvil
          AttributeType: S
        - AttributeName: LawChaos
          AttributeType: S
      GlobalSecondaryIndexes:
        - IndexName: LawChaosIndex
          KeySchema:
            - AttributeName: LawChaos
              KeyType: HASH
            - AttributeName: MysfitId
              KeyType: RANGE
          Projection:
            ProjectionType: ALL
          ProvisionedThroughput:
            ReadCapacityUnits: 5
            WriteCapacityUnits: 5
        - IndexName: GoodEvilIndex
          KeySchema:
            - AttributeName: GoodEvil
              KeyType: HASH
            - AttributeName: MysfitId
              KeyType: RANGE
          Projection:
            ProjectionType: ALL
          ProvisionedThroughput:
            ReadCapacityUnits: 5
            WriteCapacityUnits: 5
      KeySchema:
        - AttributeName: MysfitId
          KeyType: HASH
      ProvisionedThroughput:
        ReadCapacityUnits: 5
        WriteCapacityUnits: 5
#------------------------------------------------------
# IDE Server Security Group
#------------------------------------------------------
  VSCodeServerSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      Tags:
        - Key: group
          Value: ecs-mythical
      GroupDescription: allow ingress
      VpcId: !Ref VPC

  VSCodeServerSecurityGroupIngress:
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      Description: open port 8080 for the IDE instance
      GroupId: 
        Fn::GetAtt:
          - VSCodeServerSecurityGroup
          - GroupId
      IpProtocol: tcp
      FromPort: 8080
      ToPort: 8080
      CidrIp: 0.0.0.0/0

  VSCodeServerSecurityGroupEgress:
    Type: AWS::EC2::SecurityGroupEgress
    Properties:
      Description: egress for vscode security group
      GroupId:
        Fn::GetAtt:
          - VSCodeServerSecurityGroup
          - GroupId
      IpProtocol: -1
      CidrIp: 0.0.0.0/0
#------------------------------------------------------
# IDE Server Role and Instance Profile
#------------------------------------------------------
  VSCodeServerIAMRole:
    Type: AWS::IAM::Role
    Properties:
      Tags:
        - Key: group
          Value: ecs-mythical
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Action:
              - sts:AssumeRole
            Effect: Allow
            Principal:
              Service:
                - ec2.amazonaws.com
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AdministratorAccess
  IdeInstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Roles:
        - Ref: VSCodeServerIAMRole
#------------------------------------------------------
# EC2 Instance for VSCode Server
#------------------------------------------------------
  VSCodeServer:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: !Ref IdeAmiId
      InstanceType: !Ref IdeInstanceType
      IamInstanceProfile: !Ref IdeInstanceProfile
      Tags:
        - Key: Name
          Value: VSCodeServer
        - Key: group
          Value: ecs-mythical
      NetworkInterfaces:
        - DeviceIndex: "0"
          AssociatePublicIpAddress: "true"
          SubnetId: !Ref IdePublicSubnet 
          GroupSet:
            - Fn::GetAtt:
                - VSCodeServerSecurityGroup
                - GroupId
      Monitoring: true
      UserData:
        Fn::Base64:
          Fn::Sub:
            - |
              #!/bin/bash
              sudo dnf install git -y
              sudo dnf install wget  -y
              sudo yum install make -y
              sudo wget https://github.com/coder/code-server/releases/download/v${VERSION}/code-server-${VERSION}-amd64.rpm
              sudo rpm -i code-server-${VERSION}-amd64.rpm
              sudo systemctl enable --now code-server@${cUSER}
              sleep 30
              sed -i.bak 's/^password:.*/hashed-password:\ \"${HASHED_PW}\"/g' /home/${cUSER}/.config/code-server/config.yaml
              sed -i.bak 's/bind-addr: 127.0.0.1:8080/bind-addr: 0.0.0.0:8080/' /home/${cUSER}/.config/code-server/config.yaml
              sudo systemctl restart code-server@${cUSER}
              sudo -u ${cUSER} bash -c "code-server --install-extension AmazonWebServices.aws-toolkit-vscode"
              sudo dnf update
              sudo dnf install unzip -y
              curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
              unzip awscliv2.zip
              sudo ./aws/install
              curl "https://github.com/aws/aws-sam-cli/releases/latest/download/aws-sam-cli-linux-x86_64.zip" -o "awscliv2.zip"
              unzip aws-sam-cli-linux-x86_64.zip -d sam-installation
              sudo ./sam-installation/install
              sudo dnf install -y docker
              sudo service docker start
              sudo usermod -aG docker ${cUSER}
              sudo -u ${cUSER} bash -c "newgrp docker"
              sudo -u ${cUSER} bash -c "mkdir /home/${cUSER}/environment"
              sudo -u ${cUSER} bash -c "echo 'export REGION=${AWS_REGION}' >> /home/${cUSER}/.bashrc"
              sudo -u ${cUSER} bash -c "echo 'export STACK_NAME=${AWS_STACK_NAME}' >> /home/${cUSER}/.bashrc"
              sudo -u ec2-user bash -c "echo 'export PS1=\"\[\e[32m\][\[\e[m\]\[\e[31m\]\u\[\e[m\]\[\e[33m\]@\[\e[m\]\[\e[32m\]\h\[\e[m\]:\[\e[36m\]\w\[\e[m\]\[\e[32m\]]\[\e[m\]\[\e[32;47m\]\\$\[\e[m\] \"' >> /home/ec2-user/.bashrc"
              sudo reboot
            - VERSION: !Ref VSCodeServerVersion
              cUSER: !Ref IdeUser
              AWS_REGION: !Ref AWS::Region
              AWS_STACK_NAME: !Ref AWS::StackName
              HASHED_PW: !Ref IDEHashedPassword

Outputs:
  LoadBalancerDNS:
    Description: The DNS for the load balancer
    Value: !GetAtt MythicalLoadBalancer.DNSName
  DynamoTable:
    Value: !Ref MythicalDynamoTable
  SiteBucket:
    Value: !Ref MythicalBucket
    Condition: MakeBucket
  ProfileName:
    Value: !Ref MythicalProfile
  S3WebsiteURL:
    Description: This is the DNS name of your S3 site
    Value: !GetAtt MythicalBucket.WebsiteURL
  VSCodeServerDomainName:
    Value: 
      !Sub 
        - "http://${domain}:8080"
        - { domain: !GetAtt VSCodeServer.PublicDnsName }
    Export:
      Name: !Sub ${AWS::StackName}-public-domain-name
  VSCodeServerPrivateIP:
    Value: !GetAtt VSCodeServer.PrivateIp
    Export:
      Name: !Sub ${AWS::StackName}-code-server-private-ip
  VSCodeServerRoleARN:
    Value: !GetAtt VSCodeServerIAMRole.Arn
    Export:
      Name: !Sub ${AWS::StackName}-code-server-role-arn
  VSCodeServerInstanceId:
    Value: !Ref VSCodeServer
    Export:
      Name: !Sub ${AWS::StackName}-code-server-instance-id