AWSTemplateFormatVersion: '2010-09-09'

Description: >
  EKS CI/CD Workshop
  
  Template to setup the EC2 environment for VS Code Remote SSH.

Parameters:
  KeyName:
    Description: Name of an existing EC2 KeyPair to enable SSH access to the instance
    Type: AWS::EC2::KeyPair::KeyName

Resources:
  InstanceSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Allow SSH access
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: 0.0.0.0/0

  WorkspaceInstance:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: t3.small
      ImageId: resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64
      KeyName: !Ref KeyName
      SecurityGroupIds:
        - !Ref InstanceSecurityGroup
      BlockDeviceMappings:
        - DeviceName: /dev/xvda
          Ebs:
            VolumeSize: 30
            VolumeType: gp3
      Tags:
        - Key: Name
          Value: !Sub "EKSCICD-Workspace-${AWS::StackName}"
      UserData: 
        Fn::Base64: !Sub |
          #!/bin/bash
          # Update and install dependencies
          dnf update -y
          dnf install -y git docker python3 python3-pip util-linux
          
          # Start docker
          systemctl enable docker
          systemctl start docker
          usermod -aG docker ec2-user

Outputs:
  SSHCommand:
    Description: Command to SSH into the EC2 Instance
    Value: !Sub "ssh -i <YOUR_KEY.pem> ec2-user@${WorkspaceInstance.PublicIp}"
  VSCodeRemoteSSH:
    Description: Hostname for VS Code Remote SSH
    Value: !GetAtt WorkspaceInstance.PublicIp
