{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "This template will deploy Ubuntu 24.04 instance for Ubuntu.",
    "Parameters": {
        "CloudLabsDeploymentID": {
            "Description": "DeploymentID Value",
            "Type": "String"
        },
        "VPCCIDR": {
            "Type": "String",
            "Default": "10.0.0.0/16"
        },
        "clgclusterSubnetCidr": {
            "Type": "String",
            "Default": "10.0.2.0/24"
        },
        "EC2InstancesSubnetCIDR": {
            "Type": "String",
            "Default": "10.0.1.0/24"
        },
        "cgWhitelist": {
            "Type": "String",
            "Default": "0.0.0.0/0"
        },
        "CheckAcknowledgement": {
            "Type": "String",
            "Default": "TRUE"
        },
        "UbuntuVMUserName": {
            "Type": "String",
            "Default": "ubuntu"
        },
        "UbuntuVMPassword": {
            "Type": "String",
            "Default": "Password!1234"
        },
        "AmazonECSTaskExecutionRolePolicy": {
            "Type": "String",
            "Default": "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
        },
        "AppEnabled": {
            "Type": "String",
            "Default": "True"
        },
        "ShutdownOnIdle": {
            "Type": "String",
            "Default": "True"
        },
        "ShutdownOnIdleTimeout": {
            "Type": "Number",
            "Default": 15
        },
        "WarningWaitTimeout": {
            "Type": "Number",
            "Default": 15
        },
        "TrackingMode": {
            "Type": "Number",
            "Default": 1
        },
        "ShutdownOnDisconnect": {
            "Type": "String",
            "Default": "True"
        },
        "ShutdownOnDisconnectTimeout": {
            "Type": "Number",
            "Default": 15
        },
        "ShutdownWhenNoUsersConnected": {
            "Type": "String",
            "Default": "True"
        },
        "ShutdownWhenNoUsersConnectedTimeout": {
            "Type": "Number",
            "Default": 15
        },
        "OdlTrackingSource": {
            "Type": "Number",
            "Default": 3
        },
        "AppPopupWaitTimeout": {
            "Type": "Number",
            "Default": 10
        },
        "Version": {
            "Type": "String",
            "Default": "Version"
        },
        "AppCheckFrequency": {
            "Type": "Number",
            "Default": 2
        },
        "CloudLabsDeploymentIDEncrypt": {
            "Type": "String",
            "Default": "CloudLabsDeploymentIDEncrypt"
        },
        "IdleTrackingInstallationScriptUrl": {
            "Type": "String",
            "Default": "IdleTrackingInstallationScriptUrl"
        },
        "X64LinuxIdleCheckDownloadUrl": {
            "Type": "String",
            "Default": "X64LinuxIdleCheckDownloadUrl"
        },
        "Arm64LinuxIdleCheckDownloadUrl": {
            "Type": "String",
            "Default": "Arm64LinuxIdleCheckDownloadUrl"
        },
        "X64xprintIdleDownloadUrl": {
            "Type": "String",
            "Default": "X64xprintIdleDownloadUrl"
        },
        "Arm64xprintIdleDownloadUrl": {
            "Type": "String",
            "Default": "Arm64xprintIdleDownloadUrl"
        },
        "AddToBashrcScriptUrl": {
            "Type": "String",
            "Default": "AddToBashrcScriptUrl"
        }
    },
    "Mappings": {
    "RegionMap": {
      "us-east-1": {
        "AMI": "ami-05e4e4269622953b4",
        "AZ": "us-east-1a"
      },
      "us-west-2": {
        "AMI": "ami-0550326b23b293bee",
        "AZ": "us-west-2a"
      },
      "us-east-2": {
        "AMI": "ami-0ed30ba669a4c5f32",
        "AZ": "us-east-2a"
      },
      "us-west-1": {
        "AMI": "ami-077dbd4f5f0c50e52",
        "AZ": "us-west-1a"
      }
    }
  },

    "Resources": {
        "TaskExecutionRole": {
            "Type": "AWS::IAM::Role",
            "Properties": {
                "AssumeRolePolicyDocument": {
                    "Version": "2012-10-17",
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Principal": {
                                "Service": [
                                    "ecs-tasks.amazonaws.com"
                                ]
                            },
                            "Action": [
                                "sts:AssumeRole"
                            ]
                        }
                    ]
                },
                "Path": "/",
                "ManagedPolicyArns": [
                    {
                        "Ref": "AmazonECSTaskExecutionRolePolicy"
                    }
                ],
                "Tags": [
                    {
                        "Key": "Name",
                        "Value": {
                            "Fn::Join": [
                                "",
                                [
                                    "TaskExecutionRole-",
                                    {
                                        "Ref": "CloudLabsDeploymentID"
                                    }
                                ]
                            ]
                        }
                    }
                ]
            }
        },
        "ElasticIP": {
        "Type": "AWS::EC2::EIP",
        "Properties": {
            "Domain": "vpc",
            "Tags": [
            {
                "Key": "Name",
                "Value": {
                "Fn::Join": [
                    "",
                    [
                    "ElasticIP-",
                    { "Ref": "CloudLabsDeploymentID" }
                    ]
                ]
                }
            },
            {
              "Key": "aws-apn-id",
              "Value": "pc:7finjv2fdluw3t9gvedjkgubj"
            }
            ]
        }
        },
        "EIPAssociation": {
        "Type": "AWS::EC2::EIPAssociation",
        "DependsOn": "UbuntuVM",
        "Properties": {
            "InstanceId": {
            "Ref": "UbuntuVM"
            },
            "AllocationId": {
            "Fn::GetAtt": ["ElasticIP", "AllocationId"]
            }
        }
        },    
        "EC2InstancesVPC": {
            "Type": "AWS::EC2::VPC",
            "Properties": {
                "CidrBlock": {
                    "Ref": "VPCCIDR"
                },
                "EnableDnsSupport": true,
                "EnableDnsHostnames": true,
                "Tags": [
                    {
                        "Key": "Name",
                        "Value": {
                            "Fn::Join": [
                                "",
                                [
                                    "EC2InstancesVPC-",
                                    {
                                        "Ref": "CloudLabsDeploymentID"
                                    }
                                ]
                            ]
                        }
                    },
                    {
                        "Key": "aws-apn-id",
                        "Value": "pc:7finjv2fdluw3t9gvedjkgubj"
                    }
                ]
            }
        },
        "clgClusterSubnet": {
            "Type": "AWS::EC2::Subnet",
            "Properties": {
                "MapPublicIpOnLaunch": true,
                "VpcId": {
                    "Ref": "EC2InstancesVPC"
                },
                "CidrBlock": {
                    "Ref": "clgclusterSubnetCidr"
                },
                "Tags": [
                    {
                        "Key": "Name",
                        "Value": {
                            "Fn::Join": [
                                "",
                                [
                                    "clgClusterSubnet-",
                                    {
                                        "Ref": "CloudLabsDeploymentID"
                                    }
                                ]
                            ]
                        }
                    },
                    {
                        "Key": "aws-apn-id",
                        "Value": "pc:7finjv2fdluw3t9gvedjkgubj"
                    }
                ]
            }
        },
        "EC2InstanceSubnet": {
            "Type": "AWS::EC2::Subnet",
            "Properties": {
                "MapPublicIpOnLaunch": false,
                "AvailabilityZone": {
                  "Fn::FindInMap": [
                    "RegionMap",
                    { "Ref": "AWS::Region" },
                    "AZ"
                  ]
                },
                "VpcId": {
                    "Ref": "EC2InstancesVPC"
                },
                "CidrBlock": {
                    "Ref": "EC2InstancesSubnetCIDR"
                },
                "Tags": [
                    {
                        "Key": "Name",
                        "Value": {
                            "Fn::Join": [
                                "",
                                [
                                    "EC2InstanceSubnet-",
                                    {
                                        "Ref": "CloudLabsDeploymentID"
                                    }
                                ]
                            ]
                        }
                    },
                    {
                        "Key": "aws-apn-id",
                        "Value": "pc:7finjv2fdluw3t9gvedjkgubj"
                    }
                ]
            }
        },
        "InternetGateway": {
            "Type": "AWS::EC2::InternetGateway",
            "Properties": {
                "Tags": [
                    {
                        "Key": "Name",
                        "Value": {
                            "Fn::Join": [
                                "",
                                [
                                    "InternetGateway-",
                                    {
                                        "Ref": "CloudLabsDeploymentID"
                                    }
                                ]
                            ]
                        }
                    },
                    {
                        "Key": "aws-apn-id",
                        "Value": "pc:7finjv2fdluw3t9gvedjkgubj"
                    }
                ]
            }
        },
        "AttachInternetGateway": {
            "Type": "AWS::EC2::VPCGatewayAttachment",
            "Properties": {
                "InternetGatewayId": {
                    "Ref": "InternetGateway"
                },
                "VpcId": {
                    "Ref": "EC2InstancesVPC"
                }
            }
        },
        "EC2InstancesVPCpublicRT": {
            "Type": "AWS::EC2::RouteTable",
            "Properties": {
                "VpcId": {
                    "Ref": "EC2InstancesVPC"
                },
                "Tags": [
                    {
                        "Key": "Name",
                        "Value": {
                            "Fn::Join": [
                                "",
                                [
                                    "EC2InstancesVPCpublicRT",
                                    {
                                        "Ref": "CloudLabsDeploymentID"
                                    }
                                ]
                            ]
                        }
                    },
                    {
                        "Key": "aws-apn-id",
                        "Value": "pc:7finjv2fdluw3t9gvedjkgubj"
                    }
                ]
            }
        },
        "EC2InstancesVPCRoute": {
            "Type": "AWS::EC2::Route",
            "DependsOn": "AttachInternetGateway",
            "Properties": {
                "RouteTableId": {
                    "Ref": "EC2InstancesVPCpublicRT"
                },
                "DestinationCidrBlock": "0.0.0.0/0",
                "GatewayId": {
                    "Ref": "InternetGateway"
                }
            }
        },
        "EC2InstancesVPCRouteattach": {
            "Type": "AWS::EC2::SubnetRouteTableAssociation",
            "Properties": {
                "SubnetId": {
                    "Ref": "EC2InstanceSubnet"
                },
                "RouteTableId": {
                    "Ref": "EC2InstancesVPCpublicRT"
                }
            }
        },
        "clusterSubnetRouteTableAssociation": {
            "Type": "AWS::EC2::SubnetRouteTableAssociation",
            "Properties": {
                "SubnetId": {
                    "Ref": "clgClusterSubnet"
                },
                "RouteTableId": {
                    "Ref": "EC2InstancesVPCpublicRT"
                }
            }
        },
        "clgSg": {
            "Type": "AWS::EC2::SecurityGroup",
            "Properties": {
                "GroupDescription": "this is for container",
                "GroupName": "clgSg",
                "VpcId": {
                    "Ref": "EC2InstancesVPC"
                },
                "SecurityGroupIngress": [
                    {
                        "IpProtocol": "-1",
                        "FromPort": "0",
                        "ToPort": "65535",
                        "CidrIp": {
                            "Ref": "cgWhitelist"
                        }
                    },
                    {
                        "FromPort": 443,
                        "ToPort": 443,
                        "IpProtocol": "tcp",
                        "CidrIpv6": "::/0"
                    }
                ],
                "Tags": [
                    {
                        "Key": "Name",
                        "Value": {
                            "Fn::Join": [
                                "",
                                [
                                    "clgSg-",
                                    {
                                        "Ref": "CloudLabsDeploymentID"
                                    }
                                ]
                            ]
                        }
                    },
                    {
                        "Key": "aws-apn-id",
                        "Value": "pc:7finjv2fdluw3t9gvedjkgubj"
                    }
                ]
            }
        },
        "EC2InstancesVPCSSH": {
          "Type": "AWS::EC2::SecurityGroup",
          "Properties": {
            "GroupDescription": "Allow all traffic",
            "VpcId": {
              "Ref": "EC2InstancesVPC"
            },
            "SecurityGroupIngress": [
              {
                "IpProtocol": "-1",
                "CidrIp": "0.0.0.0/0"
              }
            ],
            "SecurityGroupEgress": [
              {
                "IpProtocol": "-1",
                "CidrIp": "0.0.0.0/0"
              }
            ],
            "Tags": [
              {
                "Key": "Name",
                "Value": {
                  "Fn::Join": [
                    "",
                    [
                      "EC2InstancesVPCSSH-",
                      { "Ref": "CloudLabsDeploymentID" }
                    ]
                  ]
                }
              },
              {
                "Key": "aws-apn-id",
                "Value": "pc:7finjv2fdluw3t9gvedjkgubj"
              }
            ]
          }
        },
        "EC2InstancesVPCRDP": {
          "Type": "AWS::EC2::SecurityGroup",
          "Properties": {
            "GroupDescription": "Allow all traffic",
            "VpcId": {
              "Ref": "EC2InstancesVPC"
            },
            "SecurityGroupIngress": [
              {
                "IpProtocol": "-1",
                "CidrIp": "0.0.0.0/0"
              }
            ],
            "SecurityGroupEgress": [
              {
                "IpProtocol": "-1",
                "CidrIp": "0.0.0.0/0"
              }
            ],
            "Tags": [
              {
                "Key": "aws-apn-id",
                "Value": "pc:7finjv2fdluw3t9gvedjkgubj"
              }
            ]
          }
        },
        "UbuntuVM": {
            "Type": "AWS::EC2::Instance",
            "Properties": {
                "ImageId": {
                  "Fn::FindInMap": [
                    "RegionMap",
                    { "Ref": "AWS::Region" },
                    "AMI"
                  ]
                },
                "InstanceType": "t3.2xlarge",
                "NetworkInterfaces": [
                    {
                        "DeleteOnTermination": "true",
                        "GroupSet": [
                            {
                                "Ref": "EC2InstancesVPCSSH"
                            }
                        ],
                        "DeviceIndex": 0,
                        "SubnetId": {
                            "Ref": "EC2InstanceSubnet"
                        }
                    }
                ],
                "BlockDeviceMappings": [
                    {
                        "DeviceName": "/dev/sda1",
                        "Ebs": {
                            "VolumeType": "gp3",
                            "VolumeSize": 128
                        }
                    }
                ],
        "UserData": {
          "Fn::Base64": {
            "Fn::Join": [
              "\n",
              [
                {
                  "Fn::Sub": "#!/bin/bash -ex\nexec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1\necho BEGIN\n\n# -------------------------------\n# PRE-REQ INSTALLATION\n# -------------------------------\napt-get update -y\nDEBIAN_FRONTEND=noninteractive apt-get install -y openssh-server sudo curl wget dos2unix\n\n# -------------------------------\n# ENABLE PASSWORD AUTH (ROBUST)\n# -------------------------------\nsed -i 's/^#PasswordAuthentication yes/PasswordAuthentication yes/' /etc/ssh/sshd_config\nsed -i 's/^PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config\nsed -i 's/^#PermitRootLogin.*/PermitRootLogin yes/' /etc/ssh/sshd_config\n\n# handle override configs\nsed -i 's/^PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config.d/* 2>/dev/null || true\n\n# -------------------------------\n# RESTART SSH AFTER CONFIG\n# -------------------------------\nsystemctl restart ssh || systemctl restart sshd\n\n# -------------------------------\n# SET PASSWORD FOR UBUNTU USER\n# -------------------------------\nUSERNAME=\"ubuntu\"\nPASSWORD=\"${UbuntuVMPassword}\"\n\necho \"$USERNAME:$PASSWORD\" | chpasswd\n\n# ensure ubuntu has sudo\nusermod -aG sudo $USERNAME || true\n\n# unlock user if locked\npasswd -u $USERNAME || true\n"
                },
                {
                  "Fn::If": [
                    "AppEnabledAndOdlTrackingCondition",
                    {
                      "Fn::Join": [
                        "\n",
                        [
                          {
                            "Fn::Sub": "wget ${AddToBashrcScriptUrl} -O /opt/main.sh\nchmod 0777 /opt/main.sh\ndos2unix /opt/main.sh\n/opt/main.sh"
                          },
                          {
                            "Fn::Sub": "wget ${IdleTrackingInstallationScriptUrl} -O /opt/LinuxIdleTrackingInstallationScript.sh\nchmod 0777 /opt/LinuxIdleTrackingInstallationScript.sh\ndos2unix /opt/LinuxIdleTrackingInstallationScript.sh"
                          },
                          {
                            "Fn::Sub": "echo 'sysadmin ALL=(ALL:ALL) ALL' >> /etc/sudoers\nTOKEN=$(curl -X PUT 'http://169.254.169.254/latest/api/token' -H 'X-aws-ec2-metadata-token-ttl-seconds: 21600')\ninstanceId=$(curl -H \"X-aws-ec2-metadata-token: $TOKEN\" -v http://169.254.169.254/latest/meta-data/instance-id)"
                          },
                          {
                            "Fn::Sub": "/opt/LinuxIdleTrackingInstallationScript.sh ${X64LinuxIdleCheckDownloadUrl} ${Arm64LinuxIdleCheckDownloadUrl} ${X64xprintIdleDownloadUrl} ${Arm64xprintIdleDownloadUrl} ${Version} ${AppEnabled} ${ShutdownOnIdle} ${ShutdownOnIdleTimeout} ${WarningWaitTimeout} ${TrackingMode} ${ShutdownOnDisconnect} ${ShutdownOnDisconnectTimeout} ${ShutdownWhenNoUsersConnected} ${ShutdownWhenNoUsersConnectedTimeout} ${AppCheckFrequency} $instanceId ${CloudLabsDeploymentIDEncrypt}"
                          },
                          {
                            "Fn::Sub": "rm /opt/LinuxIdleTrackingInstallationScript.sh\nrm /opt/main.sh"
                          }
                        ]
                      ]
                    },
                    {
                      "Fn::Sub": "echo 'App Enabled is False'"
                    }
                  ]
                },
                {
                  "Fn::Sub": "echo END"
                }
              ]
            ]
          }
        },
                "Tags": [
                    {
                        "Key": "Name",
                        "Value": {
                            "Fn::Join": [
                                "",
                                [
                                    "UbuntuVM-",
                                    {
                                        "Ref": "CloudLabsDeploymentID"
                                    }
                                ]
                            ]
                        }
                    },
                    {
                        "Key": "aws-apn-id",
                        "Value": "pc:7finjv2fdluw3t9gvedjkgubj"
                    }
                ]
            }
        }
    },
    "Conditions": {
        "AppEnabledAndOdlTrackingCondition": {
            "Fn::And": [
                {
                    "Fn::Equals": [
                        {
                            "Ref": "AppEnabled"
                        },
                        "True"
                    ]
                },
                {
                    "Fn::Or": [
                        {
                            "Fn::Equals": [
                                {
                                    "Ref": "OdlTrackingSource"
                                },
                                1
                            ]
                        },
                        {
                            "Fn::Equals": [
                                {
                                    "Ref": "OdlTrackingSource"
                                },
                                2
                            ]
                        }
                    ]
                }
            ]
        }
    },
    "Outputs": {
        "VpcId": {
            "Description": "The ID of the VPC",
            "Value": {
                "Ref": "EC2InstancesVPC"
            }
        },
        "UbuntuVMDNSName": {
            "Description": "Ubuntu vm dns name",
            "Value": {
                "Fn::GetAtt": [
                    "UbuntuVM",
                    "PublicDnsName"
                ]
            }
        },
        "UbuntuVMUserName": {
            "Description": "UbuntuVMUserName",
            "Value": {
                "Ref": "UbuntuVMUserName"
            }
        },
        "UbuntuVMPassword": {
            "Description": "UbuntuVMPassword",
            "Value": {
                "Ref": "UbuntuVMPassword"
            }
        },
        "UbuntuVMPublicIp": {
        "Description": "Public IP of the Ubuntu VM",
        "Value": {
            "Ref": "ElasticIP"
            }
        },
        "UbuntuVMPrivateIp": {
            "Description": "Private Ip of the Ubuntu VM",
            "Value": {
                "Fn::GetAtt": [
                    "UbuntuVM",
                    "PrivateIp"
                ]
            }
        },
        "clusterSubnetId": {
            "Description": "The ID of the ClusterSubnet",
            "Value": {
                "Ref": "clgClusterSubnet"
            }
        },
        "clusterSecurityGroupId": {
            "Description": "The SG ID of the Cluster",
            "Value": {
                "Ref": "clgSg"
            }
        },
        "TaskExecutionRole": {
            "Description": "The Arn of Role that is utilised by ECS Task Definition",
            "Value": {
                "Fn::GetAtt": [
                    "TaskExecutionRole",
                    "Arn"
                ]
            }
        }
    }
}