AWSTemplateFormatVersion: '2010-09-09'
Description: >-
  AWS Elastic Disaster Recovery (DRS) workshop infrastructure for the Region you
  deploy in (the workshop uses us-west-2).
  Creates a simulated on-premises data center (source VPC with an Amazon Linux 2023
  WordPress web server and MariaDB database server, reachable only through
  AWS Systems Manager Session Manager) and an isolated recovery VPC with the
  "DRS Staging" and "Target Private" subnets used by DRS. Single stack, no nested
  stacks, no key pairs, no inbound management ports. Requires CAPABILITY_NAMED_IAM.

# ---------------------------------------------------------------------------
# Parameters
# ---------------------------------------------------------------------------
Parameters:
  LatestAmiId:
    Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
    Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64
    Description: >-
      Amazon Linux 2023 AMI with kernel 6.1. The kernel-default alias now boots
      kernel 6.18, but DRS supports Amazon Linux 2023 only up to kernel 6.12, so the
      6.1 kernel line is pinned here (its devel package is kernel-devel-$(uname -r)).
  InstanceType:
    Type: String
    Default: t3.small
    AllowedValues:
      - t3.small
      - t3.medium
    Description: Instance type for the two source servers.
  RootVolumeSize:
    Type: Number
    Default: 10
    MinValue: 10
    MaxValue: 30
    Description: Root EBS volume size (GiB) of each source server.

Resources:
  # ---------------------------------------------------------------------------
  # Source ("on-premises") VPC: simulated data center
  # Public subnet holds only the NAT gateway; the servers live in the private
  # subnet and reach the internet (SSM, dnf, DRS replication) through the NAT.
  # ---------------------------------------------------------------------------
  SourceVpc:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags:
        - Key: Name
          Value: onpremsim-source-vpc

  SourceInternetGateway:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags:
        - Key: Name
          Value: onpremsim-source-igw

  SourceInternetGatewayAttachment:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      VpcId: !Ref SourceVpc
      InternetGatewayId: !Ref SourceInternetGateway

  SourcePublicSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref SourceVpc
      CidrBlock: 10.0.0.0/24
      AvailabilityZone: !Select [0, !GetAZs '']
      Tags:
        - Key: Name
          Value: Source Public

  SourcePrivateSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref SourceVpc
      CidrBlock: 10.0.1.0/24
      AvailabilityZone: !Select [0, !GetAZs '']
      Tags:
        - Key: Name
          Value: Source Private

  SourceNatEip:
    Type: AWS::EC2::EIP
    DependsOn: SourceInternetGatewayAttachment
    Properties:
      Domain: vpc
      Tags:
        - Key: Name
          Value: onpremsim-source-nat-eip

  SourceNatGateway:
    Type: AWS::EC2::NatGateway
    Properties:
      AllocationId: !GetAtt SourceNatEip.AllocationId
      SubnetId: !Ref SourcePublicSubnet
      Tags:
        - Key: Name
          Value: onpremsim-source-nat

  SourcePublicRouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref SourceVpc
      Tags:
        - Key: Name
          Value: Source Public

  SourcePublicDefaultRoute:
    Type: AWS::EC2::Route
    DependsOn: SourceInternetGatewayAttachment
    Properties:
      RouteTableId: !Ref SourcePublicRouteTable
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref SourceInternetGateway

  SourcePublicSubnetRouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref SourcePublicSubnet
      RouteTableId: !Ref SourcePublicRouteTable

  SourcePrivateRouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref SourceVpc
      Tags:
        - Key: Name
          Value: Source Private

  SourcePrivateDefaultRoute:
    Type: AWS::EC2::Route
    Properties:
      RouteTableId: !Ref SourcePrivateRouteTable
      DestinationCidrBlock: 0.0.0.0/0
      NatGatewayId: !Ref SourceNatGateway

  SourcePrivateSubnetRouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref SourcePrivateSubnet
      RouteTableId: !Ref SourcePrivateRouteTable

  # ---------------------------------------------------------------------------
  # Source security groups: application traffic only. There are no SSH or
  # remote-desktop rules; shell access goes through Session Manager.
  # ---------------------------------------------------------------------------
  WebSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: WordPress web server - HTTP from inside the source VPC
      VpcId: !Ref SourceVpc
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 10.0.0.0/16
          Description: HTTP from the source VPC
      Tags:
        - Key: Name
          Value: onpremsim-web-sg

  DbSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: MariaDB database server - MySQL from the web server only
      VpcId: !Ref SourceVpc
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 3306
          ToPort: 3306
          SourceSecurityGroupId: !Ref WebSecurityGroup
          Description: MySQL from the WordPress web server
      Tags:
        - Key: Name
          Value: onpremsim-db-sg

  # ---------------------------------------------------------------------------
  # Source server IAM: Session Manager access only. The DRS agent gets its own
  # credentials in the workshop (section 5), like a real on-premises server.
  # ---------------------------------------------------------------------------
  SourceServerRole:
    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

  SourceServerInstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Roles:
        - !Ref SourceServerRole

  # ---------------------------------------------------------------------------
  # WordPress database password, generated by Secrets Manager (no fixed or
  # parameter passwords). Alphanumeric only so it is safe inside SQL and sed.
  # ---------------------------------------------------------------------------
  WordPressDbSecret:
    Type: AWS::SecretsManager::Secret
    Properties:
      Name: !Sub ${AWS::StackName}-wordpress-db
      Description: Password of the wordpress MariaDB user used by the DRS workshop
      GenerateSecretString:
        SecretStringTemplate: '{"username":"wordpress"}'
        GenerateStringKey: password
        PasswordLength: 20
        ExcludePunctuation: true

  # ---------------------------------------------------------------------------
  # Source servers (Amazon Linux 2023, private subnet, fixed private IPs).
  # CreationPolicy + cfn-signal: the stack reaches CREATE_COMPLETE only after the
  # software is installed; any failing UserData command signals failure.
  # No "dnf upgrade" on purpose: it would move the kernel away from the AMI's.
  #
  # LAB TRADEOFF: the {{resolve:secretsmanager:...}} dynamic reference is resolved
  # by CloudFormation, so the plain password ends up in the instance user data
  # and is readable by principals with ec2:DescribeInstanceAttribute. This keeps
  # the source role free of Secrets Manager permissions; acceptable for a lab,
  # not for production.
  # ---------------------------------------------------------------------------
  DbServer:
    Type: AWS::EC2::Instance
    DependsOn:
      - SourcePrivateDefaultRoute
      - SourcePrivateSubnetRouteTableAssociation
    CreationPolicy:
      ResourceSignal:
        Count: 1
        Timeout: PT20M
    Properties:
      ImageId: !Ref LatestAmiId
      InstanceType: !Ref InstanceType
      SubnetId: !Ref SourcePrivateSubnet
      PrivateIpAddress: 10.0.1.20
      SecurityGroupIds:
        - !Ref DbSecurityGroup
      IamInstanceProfile: !Ref SourceServerInstanceProfile
      BlockDeviceMappings:
        - DeviceName: /dev/xvda
          Ebs:
            VolumeSize: !Ref RootVolumeSize
            VolumeType: gp3
            Encrypted: true
            DeleteOnTermination: true
      Tags:
        - Key: Name
          Value: wordpress-db.onpremsim.env
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash
          set -Eeuo pipefail

          # Retry helper for network-dependent commands (10 tries, 15 s apart)
          retry() {
            local n=1
            until "$@"; do
              if [ "$n" -ge 10 ]; then return 1; fi
              n=$((n + 1))
              sleep 15
            done
          }

          # Any failing command reports failure to CloudFormation
          trap '/opt/aws/bin/cfn-signal -e 1 --stack ${AWS::StackName} --resource DbServer --region ${AWS::Region} || true' ERR

          retry dnf install -y aws-cfn-bootstrap

          # Hostname that matches the private DNS record, kept across reboots
          hostnamectl set-hostname wordpress-db.onpremsim.env
          echo 'preserve_hostname: true' > /etc/cloud/cloud.cfg.d/99-preserve-hostname.cfg

          # MariaDB listening on all interfaces (protected by DbSecurityGroup)
          retry dnf install -y mariadb105-server wget
          printf '[mysqld]\nbind-address=0.0.0.0\n' > /etc/my.cnf.d/99-bind.cnf
          systemctl enable --now mariadb

          # WordPress database and user (root connects through the unix socket)
          mysql -u root <<'SQL'
          CREATE DATABASE IF NOT EXISTS wordpress;
          CREATE USER IF NOT EXISTS 'wordpress'@'%' IDENTIFIED BY '{{resolve:secretsmanager:${WordPressDbSecret}:SecretString:password}}';
          GRANT ALL PRIVILEGES ON wordpress.* TO 'wordpress'@'%';
          FLUSH PRIVILEGES;
          SQL

          /opt/aws/bin/cfn-signal -e 0 --stack ${AWS::StackName} --resource DbServer --region ${AWS::Region}

  WebServer:
    Type: AWS::EC2::Instance
    DependsOn:
      - SourcePrivateDefaultRoute
      - SourcePrivateSubnetRouteTableAssociation
    CreationPolicy:
      ResourceSignal:
        Count: 1
        Timeout: PT20M
    Properties:
      ImageId: !Ref LatestAmiId
      InstanceType: !Ref InstanceType
      SubnetId: !Ref SourcePrivateSubnet
      PrivateIpAddress: 10.0.1.10
      SecurityGroupIds:
        - !Ref WebSecurityGroup
      IamInstanceProfile: !Ref SourceServerInstanceProfile
      BlockDeviceMappings:
        - DeviceName: /dev/xvda
          Ebs:
            VolumeSize: !Ref RootVolumeSize
            VolumeType: gp3
            Encrypted: true
            DeleteOnTermination: true
      Tags:
        - Key: Name
          Value: wordpress-web.onpremsim.env
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash
          set -Eeuo pipefail

          # Retry helper for network-dependent commands (10 tries, 15 s apart)
          retry() {
            local n=1
            until "$@"; do
              if [ "$n" -ge 10 ]; then return 1; fi
              n=$((n + 1))
              sleep 15
            done
          }

          # Any failing command reports failure to CloudFormation
          trap '/opt/aws/bin/cfn-signal -e 1 --stack ${AWS::StackName} --resource WebServer --region ${AWS::Region} || true' ERR

          retry dnf install -y aws-cfn-bootstrap

          # Hostname that matches the private DNS record, kept across reboots
          hostnamectl set-hostname wordpress-web.onpremsim.env
          echo 'preserve_hostname: true' > /etc/cloud/cloud.cfg.d/99-preserve-hostname.cfg

          # Apache + PHP (php-fpm) for WordPress; wget is used later by the workshop
          retry dnf install -y httpd php php-fpm php-mysqlnd php-gd php-mbstring php-xml wget openssl
          systemctl enable --now php-fpm httpd

          # WordPress files
          cd /tmp
          retry wget -q -O /tmp/latest.tar.gz https://wordpress.org/latest.tar.gz
          tar -xzf /tmp/latest.tar.gz -C /tmp
          cp -r /tmp/wordpress/. /var/www/html/
          rm -rf /tmp/wordpress /tmp/latest.tar.gz

          # wp-config.php pointing at the database server's private DNS name.
          sed -e "s|database_name_here|wordpress|" \
              -e "s|username_here|wordpress|" \
              -e "s|password_here|{{resolve:secretsmanager:${WordPressDbSecret}:SecretString:password}}|" \
              -e "s|localhost|wordpress-db.onpremsim.env|" \
              /var/www/html/wp-config-sample.php > /var/www/html/wp-config.php

          # Unique WordPress keys and salts generated on the instance (base64 has no | or &)
          for k in AUTH_KEY SECURE_AUTH_KEY LOGGED_IN_KEY NONCE_KEY AUTH_SALT SECURE_AUTH_SALT LOGGED_IN_SALT NONCE_SALT; do
            v=$(openssl rand -base64 48 | tr -d '\n')
            sed -i "s|define( *'$k', *'put your unique phrase here' );|define( '$k', '$v' );|" /var/www/html/wp-config.php
          done

          chown -R apache:apache /var/www/html
          systemctl restart httpd

          /opt/aws/bin/cfn-signal -e 0 --stack ${AWS::StackName} --resource WebServer --region ${AWS::Region}

  # ---------------------------------------------------------------------------
  # Private DNS zone shared by both VPCs. Because the drill instances keep the
  # same private IPs (DRS "Copy private IP"), these records also work after
  # failover in the recovery VPC.
  # ---------------------------------------------------------------------------
  PrivateHostedZone:
    Type: AWS::Route53::HostedZone
    Properties:
      Name: onpremsim.env
      HostedZoneConfig:
        Comment: Private DNS for the DRS workshop simulated data center
      VPCs:
        - VPCId: !Ref SourceVpc
          VPCRegion: !Ref AWS::Region
        - VPCId: !Ref DrVpc
          VPCRegion: !Ref AWS::Region

  WebDnsRecord:
    Type: AWS::Route53::RecordSet
    Properties:
      HostedZoneId: !Ref PrivateHostedZone
      Name: wordpress-web.onpremsim.env
      Type: A
      TTL: '60'
      ResourceRecords:
        - !GetAtt WebServer.PrivateIp

  DbDnsRecord:
    Type: AWS::Route53::RecordSet
    Properties:
      HostedZoneId: !Ref PrivateHostedZone
      Name: wordpress-db.onpremsim.env
      Type: A
      TTL: '60'
      ResourceRecords:
        - !GetAtt DbServer.PrivateIp

  # ---------------------------------------------------------------------------
  # Recovery (DR) VPC. Its CIDR intentionally overlaps the source VPC
  # (10.0.0.0/16): the VPCs are never peered, and "Target Private" reuses
  # 10.0.1.0/24 so DRS "Copy private IP" gives drill instances the same IPs as
  # the source servers. Replication reaches "DRS Staging" over the internet,
  # like an on-premises site without VPN or Direct Connect.
  # ---------------------------------------------------------------------------
  DrVpc:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags:
        - Key: Name
          Value: drs-recovery-vpc

  DrInternetGateway:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags:
        - Key: Name
          Value: drs-recovery-igw

  DrInternetGatewayAttachment:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      VpcId: !Ref DrVpc
      InternetGatewayId: !Ref DrInternetGateway

  # Public subnet for the DRS replication servers (DRS gives them a public IP)
  DrsStagingSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref DrVpc
      CidrBlock: 10.0.100.0/24
      AvailabilityZone: !Select [0, !GetAZs '']
      Tags:
        - Key: Name
          Value: DRS Staging

  # Public subnet that only hosts the NAT gateway for "Target Private"
  DrPublicSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref DrVpc
      CidrBlock: 10.0.200.0/24
      AvailabilityZone: !Select [0, !GetAZs '']
      Tags:
        - Key: Name
          Value: DR Public

  DrPublicRouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref DrVpc
      Tags:
        - Key: Name
          Value: DR Public

  DrPublicDefaultRoute:
    Type: AWS::EC2::Route
    DependsOn: DrInternetGatewayAttachment
    Properties:
      RouteTableId: !Ref DrPublicRouteTable
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref DrInternetGateway

  DrsStagingSubnetRouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref DrsStagingSubnet
      RouteTableId: !Ref DrPublicRouteTable

  DrPublicSubnetRouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref DrPublicSubnet
      RouteTableId: !Ref DrPublicRouteTable

  DrNatEip:
    Type: AWS::EC2::EIP
    DependsOn: DrInternetGatewayAttachment
    Properties:
      Domain: vpc
      Tags:
        - Key: Name
          Value: drs-recovery-nat-eip

  DrNatGateway:
    Type: AWS::EC2::NatGateway
    Properties:
      AllocationId: !GetAtt DrNatEip.AllocationId
      SubnetId: !Ref DrPublicSubnet
      Tags:
        - Key: Name
          Value: drs-recovery-nat

  # Private subnet for drill/recovery instances (same CIDR as "Source Private")
  TargetPrivateSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref DrVpc
      CidrBlock: 10.0.1.0/24
      AvailabilityZone: !Select [0, !GetAZs '']
      Tags:
        - Key: Name
          Value: Target Private

  TargetPrivateRouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref DrVpc
      Tags:
        - Key: Name
          Value: Target Private

  TargetPrivateDefaultRoute:
    Type: AWS::EC2::Route
    Properties:
      RouteTableId: !Ref TargetPrivateRouteTable
      DestinationCidrBlock: 0.0.0.0/0
      NatGatewayId: !Ref DrNatGateway

  TargetPrivateSubnetRouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref TargetPrivateSubnet
      RouteTableId: !Ref TargetPrivateRouteTable

  # Security group selected for drill instances in the DRS launch settings
  TargetSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: TargetSecurityGroup
      GroupDescription: DRS drill and recovery instances - HTTP and MySQL inside the recovery VPC
      VpcId: !Ref DrVpc
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 10.0.0.0/16
          Description: HTTP from the recovery VPC
        - IpProtocol: tcp
          FromPort: 3306
          ToPort: 3306
          CidrIp: 10.0.1.0/24
          Description: MySQL from the Target Private subnet
      Tags:
        - Key: Name
          Value: TargetSecurityGroup

  # ---------------------------------------------------------------------------
  # Recovery instance profile: selected in the DRS EC2 launch settings so that
  # drill instances can be reached with Session Manager. DRS requires
  # AWSElasticDisasterRecoveryRecoveryInstancePolicy on custom recovery profiles.
  # ---------------------------------------------------------------------------
  RecoveryInstanceRole:
    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
        - !Sub arn:${AWS::Partition}:iam::aws:policy/service-role/AWSElasticDisasterRecoveryRecoveryInstancePolicy

  RecoveryInstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      InstanceProfileName: drs-workshop-recovery-instance-profile
      Roles:
        - !Ref RecoveryInstanceRole

# ---------------------------------------------------------------------------
# Outputs used by the workshop steps
# ---------------------------------------------------------------------------
Outputs:
  WebServerInstanceId:
    Description: Instance ID of the WordPress web server (wordpress-web.onpremsim.env)
    Value: !Ref WebServer
  DbServerInstanceId:
    Description: Instance ID of the MariaDB database server (wordpress-db.onpremsim.env)
    Value: !Ref DbServer
  SourcePrivateSubnetId:
    Description: Subnet ID of "Source Private" (10.0.1.0/24) in the source VPC
    Value: !Ref SourcePrivateSubnet
  DrsStagingSubnetId:
    Description: Subnet ID of "DRS Staging" (10.0.100.0/24) for the DRS replication servers
    Value: !Ref DrsStagingSubnet
  TargetPrivateSubnetId:
    Description: Subnet ID of "Target Private" (10.0.1.0/24) for drill and recovery instances
    Value: !Ref TargetPrivateSubnet
  TargetSecurityGroupId:
    Description: Security group ID of TargetSecurityGroup for drill and recovery instances
    Value: !Ref TargetSecurityGroup
  RecoveryInstanceProfileName:
    Description: IAM instance profile to select in the DRS EC2 launch settings
    Value: !Ref RecoveryInstanceProfile
  WordPressPrivateUrl:
    Description: Private URL of WordPress (resolvable inside both VPCs)
    Value: http://wordpress-web.onpremsim.env/
  WordPressDbSecretArn:
    Description: ARN of the Secrets Manager secret holding the WordPress database password
    Value: !Ref WordPressDbSecret
  WebSessionCommand:
    Description: Session Manager command (CloudShell) for the web server
    Value: !Sub aws ssm start-session --target ${WebServer} --region ${AWS::Region}
  DbSessionCommand:
    Description: Session Manager command (CloudShell) for the database server
    Value: !Sub aws ssm start-session --target ${DbServer} --region ${AWS::Region}
