AWSTemplateFormatVersion: '2010-09-09' Description: Private xyOps EC2 hosts, instance permissions, cluster credentials, host installation, and browser sign-out. Metadata: AWS::CloudFormation::Interface: ParameterGroups: - Label: {default: Private network} Parameters: [Network, PrivateA, PrivateB, ConductorSG, WorkerSG] - Label: {default: Application and sign-in} Parameters: [Files, BrowserName, Listener, Pool, Client, Domain] Parameters: Network: Type: AWS::EC2::VPC::Id Description: The VPC created in the guide. PrivateA: Type: AWS::EC2::Subnet::Id Description: First private subnet. PrivateB: Type: AWS::EC2::Subnet::Id Description: Second private subnet, in a different Availability Zone. ConductorSG: Type: AWS::EC2::SecurityGroup::Id Description: Security group for the two conductors. WorkerSG: Type: AWS::EC2::SecurityGroup::Id Description: Security group for the two workers. Files: Type: String Description: Name of the dedicated private S3 bucket. AllowedPattern: '[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]' BrowserName: Type: String Description: Lowercase public hostname, without https or a path. AllowedPattern: '[a-z0-9][a-z0-9.-]*[a-z0-9]' Listener: Type: String Description: ARN of the public HTTPS listener on port 443. AllowedPattern: 'arn:aws:elasticloadbalancing:[a-z0-9-]+:[0-9]{12}:listener/app/.+' Pool: Type: String Description: Cognito user pool ID. AllowedPattern: '[a-z0-9-]+_[a-zA-Z0-9]+' Client: Type: String Description: Cognito app client ID. AllowedPattern: '[a-zA-Z0-9]+' Domain: Type: String Description: Cognito prefix domain. Enter the part before .auth. AllowedPattern: '[a-z0-9-]+' Resources: ClusterKey: Type: AWS::SecretsManager::Secret Properties: {GenerateSecretString: {PasswordLength: 64, ExcludePunctuation: true}} AppPassword: Type: AWS::SecretsManager::Secret Properties: {GenerateSecretString: {PasswordLength: 48, ExcludePunctuation: true}} SignedOut: Type: AWS::ElasticLoadBalancingV2::ListenerRule Properties: ListenerArn: !Ref Listener Priority: 1 Conditions: [{Field: host-header, Values: [!Ref BrowserName]}, {Field: path-pattern, Values: [/signed-out]}] Actions: [{Type: fixed-response, FixedResponseConfig: {StatusCode: '200', ContentType: text/plain, MessageBody: Signed out of xyOps.}}] PrivateZone: Type: AWS::Route53::HostedZone Properties: {Name: xyops.internal., VPCs: [{VPCId: !Ref Network, VPCRegion: !Ref 'AWS::Region'}]} NameA: Type: AWS::Route53::RecordSet Properties: {HostedZoneId: !Ref PrivateZone, Name: c1.xyops.internal., Type: A, TTL: '30', ResourceRecords: [!GetAtt C1.PrivateIp]} NameB: Type: AWS::Route53::RecordSet Properties: {HostedZoneId: !Ref PrivateZone, Name: c2.xyops.internal., Type: A, TTL: '30', ResourceRecords: [!GetAtt C2.PrivateIp]} LogoutRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: {Version: '2012-10-17', Statement: [{Effect: Allow, Principal: {Service: lambda.amazonaws.com}, Action: 'sts:AssumeRole'}]} ManagedPolicyArns: [!Sub 'arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'] LogoutLogs: Type: AWS::Logs::LogGroup Properties: {LogGroupName: !Sub '/aws/lambda/${AWS::StackName}-logout', RetentionInDays: 3} Logout: Type: AWS::Lambda::Function DependsOn: LogoutLogs Properties: FunctionName: !Sub '${AWS::StackName}-logout' Runtime: nodejs22.x Handler: index.handler Role: !GetAtt LogoutRole.Arn Environment: Variables: {DOMAIN: !Ref Domain, REGION_NAME: !Ref 'AWS::Region', CLIENT: !Ref Client, SITE: !Ref BrowserName} Code: ZipFile: | exports.handler = async (event) => { // The ALB can split its HttpOnly session cookie into several pieces. const names = new Set(['XYOpsAuth', 'XYOpsAuth-0', 'XYOpsAuth-1', 'XYOpsAuth-2', 'XYOpsAuth-3']); for (const line of (event.multiValueHeaders || {}).cookie || []) { for (const match of line.matchAll(/(?:^|;\s*)(XYOpsAuth(?:-\d+)?)=/g)) names.add(match[1]); } const env = process.env; const dest = new URL('https://' + env.DOMAIN + '.auth.' + env.REGION_NAME + '.amazoncognito.com/logout'); dest.searchParams.set('client_id', env.CLIENT); dest.searchParams.set('logout_uri', 'https://' + env.SITE + '/signed-out'); return {statusCode: 302, isBase64Encoded: false, body: '', multiValueHeaders: { location: [dest.href], 'cache-control': ['no-store'], 'set-cookie': Array.from(names, name => name + '=; Path=/; Max-Age=0; Secure; HttpOnly; SameSite=None') }}; }; AllowLogout: Type: AWS::Lambda::Permission Properties: {FunctionName: !Ref Logout, Action: 'lambda:InvokeFunction', Principal: elasticloadbalancing.amazonaws.com, SourceAccount: !Ref 'AWS::AccountId', SourceArn: !Sub 'arn:${AWS::Partition}:elasticloadbalancing:${AWS::Region}:${AWS::AccountId}:targetgroup/${AWS::StackName}-exit/*'} ExitTargets: Type: AWS::ElasticLoadBalancingV2::TargetGroup DependsOn: AllowLogout Properties: Name: !Sub '${AWS::StackName}-exit' TargetType: lambda Targets: [{Id: !GetAtt Logout.Arn}] TargetGroupAttributes: [{Key: lambda.multi_value_headers.enabled, Value: 'true'}] ExitRule: Type: AWS::ElasticLoadBalancingV2::ListenerRule Properties: ListenerArn: !Ref Listener Priority: 2 Conditions: [{Field: host-header, Values: [!Ref BrowserName]}, {Field: path-pattern, Values: [/alb-logout]}] Actions: [{Type: forward, TargetGroupArn: !Ref ExitTargets}] ConductorRole: 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'] Policies: - PolicyName: xyops-storage PolicyDocument: Version: '2012-10-17' Statement: - {Effect: Allow, Action: ['secretsmanager:GetSecretValue'], Resource: [!Ref ClusterKey, !Ref AppPassword]} - {Effect: Allow, Action: ['s3:ListBucket'], Resource: !Sub 'arn:${AWS::Partition}:s3:::${Files}', Condition: {StringLike: {'s3:prefix': ['xyops/*']}}} - {Effect: Allow, Action: ['s3:GetObject', 's3:PutObject', 's3:DeleteObject', 's3:AbortMultipartUpload', 's3:ListMultipartUploadParts'], Resource: !Sub 'arn:${AWS::Partition}:s3:::${Files}/xyops/*'} - {Effect: Allow, Action: ['s3:GetObject'], Resource: !Sub 'arn:${AWS::Partition}:s3:::${Files}/bootstrap/*'} WorkerRole: 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'] Policies: - PolicyName: xyops-private-ca PolicyDocument: Version: '2012-10-17' Statement: - {Effect: Allow, Action: ['s3:GetObject'], Resource: !Sub 'arn:${AWS::Partition}:s3:::${Files}/bootstrap/ca.crt'} ConductorProfile: Type: AWS::IAM::InstanceProfile Properties: {Roles: [!Ref ConductorRole]} WorkerProfile: Type: AWS::IAM::InstanceProfile Properties: {Roles: [!Ref WorkerRole]} HostDefaults: Type: AWS::EC2::LaunchTemplate Properties: LaunchTemplateData: MetadataOptions: {HttpTokens: required, HttpPutResponseHopLimit: 2} BlockDeviceMappings: [{DeviceName: /dev/xvda, Ebs: {VolumeSize: 20, VolumeType: gp3, Encrypted: true, DeleteOnTermination: true}}] C1: Type: AWS::EC2::Instance Properties: ImageId: '{{resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64}}' InstanceType: t3.medium IamInstanceProfile: !Ref ConductorProfile SubnetId: !Ref PrivateA SecurityGroupIds: [!Ref ConductorSG] LaunchTemplate: {LaunchTemplateId: !Ref HostDefaults, Version: !GetAtt HostDefaults.LatestVersionNumber} Tags: [{Key: Name, Value: !Sub '${AWS::StackName}-C1'}] C2: Type: AWS::EC2::Instance Properties: ImageId: '{{resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64}}' InstanceType: t3.medium IamInstanceProfile: !Ref ConductorProfile SubnetId: !Ref PrivateB SecurityGroupIds: [!Ref ConductorSG] LaunchTemplate: {LaunchTemplateId: !Ref HostDefaults, Version: !GetAtt HostDefaults.LatestVersionNumber} Tags: [{Key: Name, Value: !Sub '${AWS::StackName}-C2'}] W1: Type: AWS::EC2::Instance Properties: ImageId: '{{resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64}}' InstanceType: t3.small IamInstanceProfile: !Ref WorkerProfile SubnetId: !Ref PrivateA SecurityGroupIds: [!Ref WorkerSG] LaunchTemplate: {LaunchTemplateId: !Ref HostDefaults, Version: !GetAtt HostDefaults.LatestVersionNumber} Tags: [{Key: Name, Value: !Sub '${AWS::StackName}-W1'}] W2: Type: AWS::EC2::Instance Properties: ImageId: '{{resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64}}' InstanceType: t3.small IamInstanceProfile: !Ref WorkerProfile SubnetId: !Ref PrivateB SecurityGroupIds: [!Ref WorkerSG] LaunchTemplate: {LaunchTemplateId: !Ref HostDefaults, Version: !GetAtt HostDefaults.LatestVersionNumber} Tags: [{Key: Name, Value: !Sub '${AWS::StackName}-W2'}] ConfigureHosts: Type: AWS::SSM::Document Properties: DocumentType: Command Content: schemaVersion: '2.2' description: Install the conductor container or the worker TLS trust, according to the selected instance. parameters: OperatorRoleID: type: String default: '' allowedPattern: '^[a-zA-Z0-9_]*$' description: Leave empty to install. To map the Job Operator role on an installed conductor, enter its xyOps Role ID. mainSteps: - name: ConfigureHost action: aws:runShellScript inputs: timeoutSeconds: '1200' runCommand: - !Sub | set -eu umask 077 # Identify this host from cloud-init. Refuse to run on unrelated instances. case "$(cat /var/lib/cloud/data/instance-id)" in '${C1}') slot=c1 ;; '${C2}') slot=c2 ;; '${W1}'|'${W2}') slot=worker ;; *) echo 'Select a host from this xyOps stack.' >&2; exit 1 ;; esac # The role ID is generated by the xyOps UI after the first login. role='{{ OperatorRoleID }}' if [ -n "$role" ]; then [ "$slot" != worker ] || { echo 'Select only the two conductors.' >&2; exit 1; } config=/srv/xyops/conf/sso.json pending=$(mktemp /srv/xyops/conf/sso.XXXXXX) trap 'rm -f "$pending"' EXIT jq -e --arg role "$role" '.group_role_map.operator = [$role]' "$config" > "$pending" mv "$pending" "$config" echo "Mapped operator to $role." exit 0 fi if [ "$slot" = worker ]; then # Both curl and the Node.js service must trust the private conductors. ca=/etc/pki/ca-trust/source/anchors/xyops-aws.crt aws s3 cp 's3://${Files}/bootstrap/ca.crt' "$ca" --only-show-errors chmod 644 "$ca" update-ca-trust mkdir -p /etc/systemd/system/xysat.service.d printf '[Service]\nEnvironment=NODE_EXTRA_CA_CERTS=%s\n' "$ca" > /etc/systemd/system/xysat.service.d/trust.conf systemctl daemon-reload echo 'Private CA installed. Enroll this worker from xyOps.' exit 0 fi # Preserve the running configuration (including the operator role) on a retry. if command -v docker >/dev/null && docker container inspect xyops >/dev/null 2>&1; then if [ -n "$(docker ps -q --filter 'name=^/xyops$')" ]; then echo 'xyOps is already running.' exit 0 fi echo 'Existing xyOps container is stopped. Check docker logs xyops on this host.' >&2 exit 1 fi dnf -qy install jq aws s3 cp 's3://${Files}/bootstrap/conductor.sh' /root/conductor.sh --only-show-errors bash /root/conductor.sh "$slot" '${Files}' '${AWS::Region}' echo "Installed xyOps on $slot." Outputs: Bucket: {Value: !Ref Files} VPC: {Value: !Ref Network} AppSecret: {Value: !Ref AppPassword} KeySecret: {Value: !Ref ClusterKey} BrowserName: {Value: !Ref BrowserName} Pool: {Value: !Ref Pool} Client: {Value: !Ref Client} Listener: {Value: !Ref Listener} InstallDocument: {Value: !Ref ConfigureHosts} C1: {Value: !Ref C1} C2: {Value: !Ref C2} W1: {Value: !Ref W1} W2: {Value: !Ref W2}