{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Description": "Disposable private Fargate job lab with explicit ECR, S3 and Logs paths; no public internet gateway, NAT or application task role.",
  "Metadata": {
    "AWSToolsMetrics": {
      "AWSAgentToolkit": "aws-cloudformation@3"
    },
    "com.aws.cloudformation.Context": {
      "arch": "One private subnet, one task per run, image pinned to digest. No ECS service.",
      "must": [
        "Use synthetic input only. Never attach existing networks.",
        "Stop tasks and delete the stack after the exercise; interface endpoints accrue hourly charges."
      ],
      "ref": [
        {
          "at": "https://heap.page/aws-playbooks/issues/fargate-private-job"
        }
      ]
    }
  },
  "Parameters": {
    "RepositoryName": {
      "Type": "String",
      "AllowedPattern": "[a-z0-9]+(?:[._/-][a-z0-9]+)*",
      "Description": "Existing lab ECR repository in this account and Region"
    },
    "ImageDigest": {
      "Type": "String",
      "AllowedPattern": "sha256:[a-f0-9]{64}",
      "Description": "Published image digest, not a mutable tag"
    },
    "S3PrefixListId": {
      "Type": "String",
      "AllowedPattern": "pl-[a-f0-9]+",
      "Description": "Managed prefix list ID for this Region S3 service"
    }
  },
  "Resources": {
    "Vpc": {
      "Type": "AWS::EC2::VPC",
      "Metadata": {
        "com.aws.cloudformation.Context": {
          "why": "Disposable IPv4 teaching lab; no gateway or connectivity to existing networks."
        }
      },
      "Properties": {
        "CidrBlock": "10.42.0.0/24",
        "EnableDnsSupport": true,
        "EnableDnsHostnames": true
      }
    },
    "Subnet": {
      "Type": "AWS::EC2::Subnet",
      "Metadata": {
        "com.aws.cloudformation.Context": {
          "why": "Single private AZ keeps this one-task lab small; production availability is a separate design."
        }
      },
      "Properties": {
        "VpcId": {
          "Ref": "Vpc"
        },
        "CidrBlock": "10.42.0.0/26",
        "MapPublicIpOnLaunch": false,
        "AvailabilityZone": {
          "Fn::Select": [
            0,
            {
              "Fn::GetAZs": ""
            }
          ]
        }
      }
    },
    "Routes": {
      "Type": "AWS::EC2::RouteTable",
      "Metadata": {
        "com.aws.cloudformation.Context": {
          "why": "Only local and S3 gateway routes; never attach NAT or an internet gateway."
        }
      },
      "Properties": {
        "VpcId": {
          "Ref": "Vpc"
        }
      }
    },
    "RouteAssociation": {
      "Type": "AWS::EC2::SubnetRouteTableAssociation",
      "Metadata": {
        "com.aws.cloudformation.Context": {
          "why": "Explicit association makes the task route table auditable."
        }
      },
      "Properties": {
        "SubnetId": {
          "Ref": "Subnet"
        },
        "RouteTableId": {
          "Ref": "Routes"
        }
      }
    },
    "EndpointSg": {
      "Type": "AWS::EC2::SecurityGroup",
      "Metadata": {
        "com.aws.cloudformation.Context": {
          "why": "A non-routable explicit rule suppresses default unrestricted egress; no endpoint-initiated outbound traffic is required."
        }
      },
      "Properties": {
        "GroupDescription": "TLS endpoints only; response traffic is stateful",
        "VpcId": {
          "Ref": "Vpc"
        },
        "SecurityGroupEgress": [
          {
            "IpProtocol": "tcp",
            "FromPort": 443,
            "ToPort": 443,
            "CidrIp": "127.0.0.1/32",
            "Description": "Suppress default allow-all outbound rule"
          }
        ]
      }
    },
    "TaskSg": {
      "Type": "AWS::EC2::SecurityGroup",
      "Metadata": {
        "com.aws.cloudformation.Context": {
          "why": "Permit only endpoint TLS and regional S3; no general public egress. Security groups do not block AmazonProvidedDNS."
        }
      },
      "Properties": {
        "GroupDescription": "No ingress; explicit image and log paths",
        "VpcId": {
          "Ref": "Vpc"
        },
        "SecurityGroupEgress": [
          {
            "IpProtocol": "tcp",
            "FromPort": 443,
            "ToPort": 443,
            "DestinationSecurityGroupId": {
              "Ref": "EndpointSg"
            }
          },
          {
            "IpProtocol": "tcp",
            "FromPort": 443,
            "ToPort": 443,
            "DestinationPrefixListId": {
              "Ref": "S3PrefixListId"
            }
          }
        ]
      }
    },
    "EndpointIngress": {
      "Type": "AWS::EC2::SecurityGroupIngress",
      "Metadata": {
        "com.aws.cloudformation.Context": {
          "why": "Separate ingress resource avoids a circular security-group reference."
        }
      },
      "Properties": {
        "GroupId": {
          "Ref": "EndpointSg"
        },
        "IpProtocol": "tcp",
        "FromPort": 443,
        "ToPort": 443,
        "SourceSecurityGroupId": {
          "Ref": "TaskSg"
        }
      }
    },
    "EcrApi": {
      "Type": "AWS::EC2::VPCEndpoint",
      "Metadata": {
        "com.aws.cloudformation.Context": {
          "why": "Private TLS path for Fargate startup without NAT; hourly endpoint charges continue until stack deletion."
        }
      },
      "Properties": {
        "VpcEndpointType": "Interface",
        "VpcId": {
          "Ref": "Vpc"
        },
        "SubnetIds": [
          {
            "Ref": "Subnet"
          }
        ],
        "SecurityGroupIds": [
          {
            "Ref": "EndpointSg"
          }
        ],
        "PrivateDnsEnabled": true,
        "ServiceName": {
          "Fn::Sub": "com.amazonaws.${AWS::Region}.ecr.api"
        }
      }
    },
    "EcrDkr": {
      "Type": "AWS::EC2::VPCEndpoint",
      "Metadata": {
        "com.aws.cloudformation.Context": {
          "why": "Private TLS path for Fargate startup without NAT; hourly endpoint charges continue until stack deletion."
        }
      },
      "Properties": {
        "VpcEndpointType": "Interface",
        "VpcId": {
          "Ref": "Vpc"
        },
        "SubnetIds": [
          {
            "Ref": "Subnet"
          }
        ],
        "SecurityGroupIds": [
          {
            "Ref": "EndpointSg"
          }
        ],
        "PrivateDnsEnabled": true,
        "ServiceName": {
          "Fn::Sub": "com.amazonaws.${AWS::Region}.ecr.dkr"
        }
      }
    },
    "LogsEndpoint": {
      "Type": "AWS::EC2::VPCEndpoint",
      "Metadata": {
        "com.aws.cloudformation.Context": {
          "why": "Private TLS path for Fargate startup without NAT; hourly endpoint charges continue until stack deletion."
        }
      },
      "Properties": {
        "VpcEndpointType": "Interface",
        "VpcId": {
          "Ref": "Vpc"
        },
        "SubnetIds": [
          {
            "Ref": "Subnet"
          }
        ],
        "SecurityGroupIds": [
          {
            "Ref": "EndpointSg"
          }
        ],
        "PrivateDnsEnabled": true,
        "ServiceName": {
          "Fn::Sub": "com.amazonaws.${AWS::Region}.logs"
        }
      }
    },
    "S3Endpoint": {
      "Type": "AWS::EC2::VPCEndpoint",
      "Metadata": {
        "com.aws.cloudformation.Context": {
          "why": "ECR image layers use regional S3; endpoint policy limits this route to the ECR layer bucket, not arbitrary S3 objects."
        }
      },
      "Properties": {
        "VpcEndpointType": "Gateway",
        "VpcId": {
          "Ref": "Vpc"
        },
        "RouteTableIds": [
          {
            "Ref": "Routes"
          }
        ],
        "ServiceName": {
          "Fn::Sub": "com.amazonaws.${AWS::Region}.s3"
        },
        "PolicyDocument": {
          "Version": "2012-10-17",
          "Statement": [
            {
              "Effect": "Allow",
              "Principal": "*",
              "Action": [
                "s3:GetObject"
              ],
              "Resource": {
                "Fn::Sub": "arn:${AWS::Partition}:s3:::prod-${AWS::Region}-starport-layer-bucket/*"
              }
            }
          ]
        }
      }
    },
    "LogGroup": {
      "Type": "AWS::Logs::LogGroup",
      "Metadata": {
        "com.aws.cloudformation.Context": {
          "why": "Precreated disposable non-sensitive lab logs; runtime cannot create arbitrary log groups."
        }
      },
      "Properties": {
        "RetentionInDays": 7
      }
    },
    "ExecutionRole": {
      "Type": "AWS::IAM::Role",
      "Metadata": {
        "com.aws.cloudformation.Context": {
          "why": "Execution-only role for an existing same-account ECR repository and this log group. GetAuthorizationToken requires Resource *. No application task role."
        }
      },
      "Properties": {
        "AssumeRolePolicyDocument": {
          "Version": "2012-10-17",
          "Statement": [
            {
              "Effect": "Allow",
              "Principal": {
                "Service": "ecs-tasks.amazonaws.com"
              },
              "Action": "sts:AssumeRole",
              "Condition": {
                "StringEquals": {
                  "aws:SourceAccount": {
                    "Ref": "AWS::AccountId"
                  }
                },
                "ArnLike": {
                  "aws:SourceArn": {
                    "Fn::Sub": "arn:${AWS::Partition}:ecs:${AWS::Region}:${AWS::AccountId}:*"
                  }
                }
              }
            }
          ]
        },
        "Policies": [
          {
            "PolicyName": "ImageAndLogs",
            "PolicyDocument": {
              "Version": "2012-10-17",
              "Statement": [
                {
                  "Effect": "Allow",
                  "Action": "ecr:GetAuthorizationToken",
                  "Resource": "*"
                },
                {
                  "Effect": "Allow",
                  "Action": [
                    "ecr:BatchCheckLayerAvailability",
                    "ecr:GetDownloadUrlForLayer",
                    "ecr:BatchGetImage"
                  ],
                  "Resource": {
                    "Fn::Sub": "arn:${AWS::Partition}:ecr:${AWS::Region}:${AWS::AccountId}:repository/${RepositoryName}"
                  }
                },
                {
                  "Effect": "Allow",
                  "Action": [
                    "logs:CreateLogStream",
                    "logs:PutLogEvents"
                  ],
                  "Resource": {
                    "Fn::Sub": "${LogGroup.Arn}"
                  }
                }
              ]
            }
          }
        ]
      }
    },
    "Cluster": {
      "Type": "AWS::ECS::Cluster",
      "Metadata": {
        "com.aws.cloudformation.Context": {
          "why": "A separate lab cluster makes single-task cleanup and orphan inspection unambiguous."
        }
      },
      "Properties": {}
    },
    "Task": {
      "Type": "AWS::ECS::TaskDefinition",
      "Metadata": {
        "com.aws.cloudformation.Context": {
          "why": "One non-root, read-only task per job; image owns the scratch mount path. Blocking logs trade progress for delivery, so enforce an external deadline."
        }
      },
      "Properties": {
        "RequiresCompatibilities": [
          "FARGATE"
        ],
        "NetworkMode": "awsvpc",
        "Cpu": "256",
        "Memory": "512",
        "RuntimePlatform": {
          "OperatingSystemFamily": "LINUX",
          "CpuArchitecture": "X86_64"
        },
        "ExecutionRoleArn": {
          "Fn::GetAtt": [
            "ExecutionRole",
            "Arn"
          ]
        },
        "Volumes": [
          {
            "Name": "scratch"
          }
        ],
        "ContainerDefinitions": [
          {
            "Name": "job",
            "Image": {
              "Fn::Sub": "${AWS::AccountId}.dkr.ecr.${AWS::Region}.${AWS::URLSuffix}/${RepositoryName}@${ImageDigest}"
            },
            "Essential": true,
            "User": "10001:10001",
            "ReadonlyRootFilesystem": true,
            "LinuxParameters": {
              "Capabilities": {
                "Drop": [
                  "ALL"
                ]
              },
              "InitProcessEnabled": true
            },
            "MountPoints": [
              {
                "SourceVolume": "scratch",
                "ContainerPath": "/scratch",
                "ReadOnly": false
              }
            ],
            "Environment": [
              {
                "Name": "HOME",
                "Value": "/scratch"
              },
              {
                "Name": "TMPDIR",
                "Value": "/scratch"
              },
              {
                "Name": "PYTHONDONTWRITEBYTECODE",
                "Value": "1"
              },
              {
                "Name": "PYTHONUNBUFFERED",
                "Value": "1"
              }
            ],
            "StopTimeout": 30,
            "LogConfiguration": {
              "LogDriver": "awslogs",
              "Options": {
                "awslogs-group": {
                  "Ref": "LogGroup"
                },
                "awslogs-region": {
                  "Ref": "AWS::Region"
                },
                "awslogs-stream-prefix": "job",
                "mode": "blocking"
              }
            }
          }
        ]
      }
    }
  },
  "Outputs": {
    "ClusterArn": {
      "Value": {
        "Fn::GetAtt": [
          "Cluster",
          "Arn"
        ]
      }
    },
    "TaskDefinitionArn": {
      "Value": {
        "Ref": "Task"
      }
    },
    "SubnetId": {
      "Value": {
        "Ref": "Subnet"
      }
    },
    "TaskSecurityGroup": {
      "Value": {
        "Ref": "TaskSg"
      }
    },
    "LogGroupName": {
      "Value": {
        "Ref": "LogGroup"
      }
    }
  }
}
