AWSTemplateFormatVersion: '2010-09-09' Description: >- OpenCart 4 on AWS: CloudFront, ALB, Auto Scaling EC2 (Amazon Linux 2023, Graviton), RDS for MySQL, ElastiCache (Redis OSS) and EFS across two Availability Zones. From https://webocreation.com/scalable-ecommerce-architecture-peak-traffic/ Parameters: DomainName: Type: String Description: Store domain, for example shop.example.com HostedZoneId: Type: AWS::Route53::HostedZone::Id Description: Route 53 hosted zone that contains DomainName CloudFrontCertificateArn: Type: String Description: ACM certificate in us-east-1 covering DomainName AlbCertificateArn: Type: String Description: ACM certificate in this Region covering both DomainName and origin.DomainName (CloudFront forwards the Host header, so the ALB must present a certificate for DomainName) CloudFrontPrefixListId: Type: String Description: ID of the managed prefix list com.amazonaws.global.cloudfront.origin-facing in this Region (aws ec2 describe-managed-prefix-lists) OriginVerifySecret: Type: String NoEcho: true MinLength: 32 Description: Random string CloudFront sends to the ALB in X-Origin-Verify; requests without it get 403 CodeBucket: Type: String Description: S3 bucket with your OpenCart release tarballs CodeKey: Type: String Description: Object key of the release to run, for example releases/2026-11-26.tar.gz (change it to deploy) AdminDir: Type: String Default: admin Description: Name of your OpenCart admin folder InstanceType: Type: String Default: t4g.medium Description: Graviton (arm64) instance type for web nodes MinSize: Type: Number Default: 2 MaxSize: Type: Number Default: 6 DbInstanceClass: Type: String Default: db.t4g.medium DbEngineVersion: Type: String Default: '8.4' AllowedValues: ['8.0', '8.4'] Description: MySQL major version; RDS uses the current default minor version DbMultiAZ: Type: String Default: 'true' AllowedValues: ['true', 'false'] CacheNodeType: Type: String Default: cache.t4g.small AlarmEmail: Type: String Description: Email address for CloudWatch alarms LatestAmiId: Type: AWS::SSM::Parameter::Value Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-arm64 Conditions: IsMultiAZ: !Equals [!Ref DbMultiAZ, 'true'] Resources: # ---------- Network: 2 AZs, public, app and data subnets ---------- Vpc: Type: AWS::EC2::VPC Properties: CidrBlock: 10.20.0.0/16 EnableDnsHostnames: true EnableDnsSupport: true Tags: [{Key: Name, Value: !Ref AWS::StackName}] InternetGateway: Type: AWS::EC2::InternetGateway GatewayAttachment: Type: AWS::EC2::VPCGatewayAttachment Properties: VpcId: !Ref Vpc InternetGatewayId: !Ref InternetGateway PublicSubnetA: Type: AWS::EC2::Subnet Properties: VpcId: !Ref Vpc CidrBlock: 10.20.0.0/24 AvailabilityZone: !Select [0, !GetAZs ''] MapPublicIpOnLaunch: true PublicSubnetB: Type: AWS::EC2::Subnet Properties: VpcId: !Ref Vpc CidrBlock: 10.20.1.0/24 AvailabilityZone: !Select [1, !GetAZs ''] MapPublicIpOnLaunch: true AppSubnetA: Type: AWS::EC2::Subnet Properties: VpcId: !Ref Vpc CidrBlock: 10.20.10.0/24 AvailabilityZone: !Select [0, !GetAZs ''] AppSubnetB: Type: AWS::EC2::Subnet Properties: VpcId: !Ref Vpc CidrBlock: 10.20.11.0/24 AvailabilityZone: !Select [1, !GetAZs ''] DataSubnetA: Type: AWS::EC2::Subnet Properties: VpcId: !Ref Vpc CidrBlock: 10.20.20.0/24 AvailabilityZone: !Select [0, !GetAZs ''] DataSubnetB: Type: AWS::EC2::Subnet Properties: VpcId: !Ref Vpc CidrBlock: 10.20.21.0/24 AvailabilityZone: !Select [1, !GetAZs ''] PublicRouteTable: Type: AWS::EC2::RouteTable Properties: VpcId: !Ref Vpc PublicRoute: Type: AWS::EC2::Route DependsOn: GatewayAttachment Properties: RouteTableId: !Ref PublicRouteTable DestinationCidrBlock: 0.0.0.0/0 GatewayId: !Ref InternetGateway PublicSubnetARoutes: Type: AWS::EC2::SubnetRouteTableAssociation Properties: SubnetId: !Ref PublicSubnetA RouteTableId: !Ref PublicRouteTable PublicSubnetBRoutes: Type: AWS::EC2::SubnetRouteTableAssociation Properties: SubnetId: !Ref PublicSubnetB RouteTableId: !Ref PublicRouteTable NatEip: Type: AWS::EC2::EIP DependsOn: GatewayAttachment Properties: Domain: vpc NatGateway: Type: AWS::EC2::NatGateway Properties: AllocationId: !GetAtt NatEip.AllocationId SubnetId: !Ref PublicSubnetA PrivateRouteTable: Type: AWS::EC2::RouteTable Properties: VpcId: !Ref Vpc PrivateRoute: Type: AWS::EC2::Route Properties: RouteTableId: !Ref PrivateRouteTable DestinationCidrBlock: 0.0.0.0/0 NatGatewayId: !Ref NatGateway AppSubnetARoutes: Type: AWS::EC2::SubnetRouteTableAssociation Properties: SubnetId: !Ref AppSubnetA RouteTableId: !Ref PrivateRouteTable AppSubnetBRoutes: Type: AWS::EC2::SubnetRouteTableAssociation Properties: SubnetId: !Ref AppSubnetB RouteTableId: !Ref PrivateRouteTable S3Endpoint: Type: AWS::EC2::VPCEndpoint Properties: VpcId: !Ref Vpc ServiceName: !Sub com.amazonaws.${AWS::Region}.s3 VpcEndpointType: Gateway RouteTableIds: [!Ref PrivateRouteTable] # ---------- Security groups: each tier only accepts the tier in front ---------- AlbSecurityGroup: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: ALB, HTTPS from CloudFront only VpcId: !Ref Vpc SecurityGroupIngress: - IpProtocol: tcp FromPort: 443 ToPort: 443 SourcePrefixListId: !Ref CloudFrontPrefixListId AppSecurityGroup: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: Web nodes, HTTP from the ALB only VpcId: !Ref Vpc SecurityGroupIngress: - IpProtocol: tcp FromPort: 80 ToPort: 80 SourceSecurityGroupId: !Ref AlbSecurityGroup DbSecurityGroup: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: MySQL from web nodes VpcId: !Ref Vpc SecurityGroupIngress: - IpProtocol: tcp FromPort: 3306 ToPort: 3306 SourceSecurityGroupId: !Ref AppSecurityGroup CacheSecurityGroup: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: Redis from web nodes VpcId: !Ref Vpc SecurityGroupIngress: - IpProtocol: tcp FromPort: 6379 ToPort: 6379 SourceSecurityGroupId: !Ref AppSecurityGroup EfsSecurityGroup: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: NFS from web nodes VpcId: !Ref Vpc SecurityGroupIngress: - IpProtocol: tcp FromPort: 2049 ToPort: 2049 SourceSecurityGroupId: !Ref AppSecurityGroup # ---------- Data tier ---------- DbSecret: Type: AWS::SecretsManager::Secret Properties: Description: OpenCart database login GenerateSecretString: SecretStringTemplate: '{"username": "opencart"}' GenerateStringKey: password PasswordLength: 32 ExcludePunctuation: true DbSubnetGroup: Type: AWS::RDS::DBSubnetGroup Properties: DBSubnetGroupDescription: OpenCart data subnets SubnetIds: [!Ref DataSubnetA, !Ref DataSubnetB] DbParameterGroup: Type: AWS::RDS::DBParameterGroup Properties: Description: OpenCart MySQL settings Family: !Sub mysql${DbEngineVersion} Parameters: slow_query_log: '1' long_query_time: '1' Database: Type: AWS::RDS::DBInstance DeletionPolicy: Snapshot UpdateReplacePolicy: Snapshot Properties: Engine: mysql EngineVersion: !Ref DbEngineVersion DBInstanceClass: !Ref DbInstanceClass DBName: opencart MasterUsername: !Sub '{{resolve:secretsmanager:${DbSecret}:SecretString:username}}' MasterUserPassword: !Sub '{{resolve:secretsmanager:${DbSecret}:SecretString:password}}' AllocatedStorage: '50' MaxAllocatedStorage: 500 StorageType: gp3 StorageEncrypted: true MultiAZ: !If [IsMultiAZ, true, false] DBSubnetGroupName: !Ref DbSubnetGroup DBParameterGroupName: !Ref DbParameterGroup VPCSecurityGroups: [!Ref DbSecurityGroup] BackupRetentionPeriod: 7 DeletionProtection: true EnablePerformanceInsights: true EnableCloudwatchLogsExports: [error, slowquery] PubliclyAccessible: false CacheSubnetGroup: Type: AWS::ElastiCache::SubnetGroup Properties: Description: OpenCart cache subnets SubnetIds: [!Ref DataSubnetA, !Ref DataSubnetB] Cache: Type: AWS::ElastiCache::ReplicationGroup Properties: ReplicationGroupDescription: OpenCart data cache Engine: redis EngineVersion: '7.1' CacheNodeType: !Ref CacheNodeType NumCacheClusters: 2 AutomaticFailoverEnabled: true MultiAZEnabled: true TransitEncryptionEnabled: true AtRestEncryptionEnabled: true CacheSubnetGroupName: !Ref CacheSubnetGroup SecurityGroupIds: [!Ref CacheSecurityGroup] FileSystem: Type: AWS::EFS::FileSystem Properties: Encrypted: true ThroughputMode: elastic BackupPolicy: Status: ENABLED MountTargetA: Type: AWS::EFS::MountTarget Properties: FileSystemId: !Ref FileSystem SubnetId: !Ref AppSubnetA SecurityGroups: [!Ref EfsSecurityGroup] MountTargetB: Type: AWS::EFS::MountTarget Properties: FileSystemId: !Ref FileSystem SubnetId: !Ref AppSubnetB SecurityGroups: [!Ref EfsSecurityGroup] # ---------- Web tier ---------- WebRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: {Service: ec2.amazonaws.com} Action: sts:AssumeRole ManagedPolicyArns: - arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore - arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy Policies: - PolicyName: opencart-web PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: s3:GetObject Resource: !Sub arn:aws:s3:::${CodeBucket}/* - Effect: Allow Action: secretsmanager:GetSecretValue Resource: !Ref DbSecret WebInstanceProfile: Type: AWS::IAM::InstanceProfile Properties: Roles: [!Ref WebRole] LoadBalancer: Type: AWS::ElasticLoadBalancingV2::LoadBalancer Properties: Scheme: internet-facing Subnets: [!Ref PublicSubnetA, !Ref PublicSubnetB] SecurityGroups: [!Ref AlbSecurityGroup] LoadBalancerAttributes: - Key: routing.http.drop_invalid_header_fields.enabled Value: 'true' TargetGroup: Type: AWS::ElasticLoadBalancingV2::TargetGroup Properties: VpcId: !Ref Vpc Protocol: HTTP Port: 80 TargetType: instance HealthCheckPath: /healthz HealthCheckIntervalSeconds: 15 HealthyThresholdCount: 2 UnhealthyThresholdCount: 3 TargetGroupAttributes: - Key: deregistration_delay.timeout_seconds Value: '30' HttpsListener: Type: AWS::ElasticLoadBalancingV2::Listener Properties: LoadBalancerArn: !Ref LoadBalancer Protocol: HTTPS Port: 443 SslPolicy: ELBSecurityPolicy-TLS13-1-2-2021-06 Certificates: [{CertificateArn: !Ref AlbCertificateArn}] DefaultActions: - Type: fixed-response FixedResponseConfig: StatusCode: '403' ContentType: text/plain MessageBody: Forbidden FromCloudFrontRule: Type: AWS::ElasticLoadBalancingV2::ListenerRule Properties: ListenerArn: !Ref HttpsListener Priority: 1 Conditions: - Field: http-header HttpHeaderConfig: HttpHeaderName: X-Origin-Verify Values: [!Ref OriginVerifySecret] Actions: - Type: forward TargetGroupArn: !Ref TargetGroup LaunchTemplate: Type: AWS::EC2::LaunchTemplate Properties: LaunchTemplateData: ImageId: !Ref LatestAmiId InstanceType: !Ref InstanceType IamInstanceProfile: {Arn: !GetAtt WebInstanceProfile.Arn} SecurityGroupIds: [!Ref AppSecurityGroup] MetadataOptions: HttpTokens: required HttpPutResponseHopLimit: 1 BlockDeviceMappings: - DeviceName: /dev/xvda Ebs: {VolumeSize: 20, VolumeType: gp3, Encrypted: true} UserData: Fn::Base64: Fn::Join: - '' - - !Sub | #!/bin/bash export AWS_DEFAULT_REGION='${AWS::Region}' export SITE_URL='https://${DomainName}/' export ADMIN_DIR='${AdminDir}' export CODE_S3_URI='s3://${CodeBucket}/${CodeKey}' export DB_HOST='${Database.Endpoint.Address}' export DB_NAME='opencart' export DB_USER='opencart' export DB_SECRET_ARN='${DbSecret}' export CACHE_HOST='tls://${Cache.PrimaryEndPoint.Address}' export EFS_ID='${FileSystem}' - | # OpenCart 4 web node bootstrap for Amazon Linux 2023 (EC2 user data). # Expects these variables (set by the CloudFormation template above this script): # SITE_URL https://shop.example.com/ (with trailing slash) # ADMIN_DIR admin (your admin folder name) # CODE_S3_URI s3://bucket/opencart-release.tar.gz (html/ and storage/ folders) # DB_HOST DB_NAME DB_USER DB_SECRET_ARN (RDS endpoint and the Secrets Manager secret) # CACHE_HOST ElastiCache primary endpoint, or tls://endpoint with in-transit encryption # EFS_ID fs-0123456789abcdef0 # LOCAL_TEST=1 skips EFS, S3, Secrets Manager and systemd so the script can run in a container. set -euo pipefail PHP=php8.3 WEB=/var/www/html STORAGE=/var/www/storage EFS=/mnt/efs # 1. Packages. phpredis isn't packaged for Amazon Linux 2023, so build it with pecl. dnf -y -q install nginx $PHP $PHP-fpm $PHP-cli $PHP-mysqlnd $PHP-gd $PHP-zip $PHP-mbstring \ $PHP-opcache $PHP-intl $PHP-xml $PHP-devel php-pear gcc make amazon-efs-utils jq tar printf '\n\n\n\n\n\n' | pecl install -f redis > /var/log/pecl-redis.log echo 'extension=redis.so' > /etc/php.d/40-redis.ini # 2. PHP and PHP-FPM. Code is immutable per release, so OPcache never re-checks files. cat > /etc/php.d/99-opencart.ini <<'INI' memory_limit = 256M upload_max_filesize = 32M post_max_size = 32M max_execution_time = 60 expose_php = Off opcache.memory_consumption = 256 opcache.interned_strings_buffer = 32 opcache.max_accelerated_files = 20000 opcache.validate_timestamps = 0 realpath_cache_size = 4096K realpath_cache_ttl = 600 INI MEM_MB=$(awk '/MemTotal/ {print int($2/1024)}' /proc/meminfo) CHILDREN=$(( (MEM_MB - 512) / 80 )); [ "$CHILDREN" -lt 4 ] && CHILDREN=4 sed -i -e "s/^pm = .*/pm = dynamic/" -e "s/^pm.max_children = .*/pm.max_children = $CHILDREN/" \ -e "s/^pm.start_servers = .*/pm.start_servers = $(( CHILDREN / 4 + 1 ))/" \ -e "s/^pm.min_spare_servers = .*/pm.min_spare_servers = $(( CHILDREN / 4 + 1 ))/" \ -e "s/^pm.max_spare_servers = .*/pm.max_spare_servers = $(( CHILDREN / 2 + 1 ))/" \ -e "s/^;pm.max_requests = .*/pm.max_requests = 1000/" /etc/php-fpm.d/www.conf # 3. Shared files on EFS: product images and customer uploads/downloads. mkdir -p $EFS if [ "${LOCAL_TEST:-0}" != "1" ]; then echo "$EFS_ID:/ $EFS efs _netdev,tls 0 0" >> /etc/fstab mount -a -t efs fi mkdir -p $EFS/image $EFS/storage/upload $EFS/storage/download $EFS/storage/backup # 4. Code: one release tarball per deployment. if [ "${LOCAL_TEST:-0}" != "1" ]; then aws s3 cp "$CODE_S3_URI" /tmp/release.tar.gz --only-show-errors fi rm -rf /tmp/release && mkdir -p /tmp/release tar -xzf /tmp/release.tar.gz -C /tmp/release rm -rf $WEB $STORAGE && mkdir -p /var/www mv /tmp/release/html $WEB mv /tmp/release/storage $STORAGE # Seed EFS on the first boot only. OpenCart checks realpath() against DIR_IMAGE, so config.php # points DIR_IMAGE, DIR_UPLOAD and DIR_DOWNLOAD at the real EFS paths; the image symlink is only # there so nginx can serve /image/ URLs. cp -an $WEB/image/. $EFS/image/ rm -rf $WEB/image && ln -s $EFS/image $WEB/image for d in upload download backup; do cp -an $STORAGE/$d/. $EFS/storage/$d/ 2>/dev/null || true rm -rf $STORAGE/$d done ln -s $EFS/storage/backup $STORAGE/backup mkdir -p $STORAGE/cache $STORAGE/logs $STORAGE/session # 5. Database password from Secrets Manager (the secret the template created for RDS). if [ "${LOCAL_TEST:-0}" != "1" ]; then DB_PASSWORD=$(aws secretsmanager get-secret-value --secret-id "$DB_SECRET_ARN" --query SecretString --output text | jq -r .password) fi # 6. config.php for the storefront and the admin. write_config() { # $1 file, $2 application, $3 HTTP_SERVER, $4 application dir cat > "$1" < $WEB/healthz.php # Code stays owned by root (read-only for PHP); only storage and EFS are writable. chown -R root:apache $WEB && chmod -R g-w $WEB chown -R apache:apache $STORAGE $EFS/image $EFS/storage # 7. nginx: TLS ends at the load balancer; the visitor IP comes from CloudFront. rm -f /etc/nginx/conf.d/default.conf cat > /etc/nginx/conf.d/opencart.conf <<'NGINX' map $http_cloudfront_viewer_address $viewer_ip { "~^(?.+):\d+$" $ip; default $remote_addr; } server { listen 80 default_server; root /var/www/html; index index.php; client_max_body_size 32m; location = /healthz { access_log off; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root/healthz.php; fastcgi_pass unix:/run/php-fpm/www.sock; } location ~ /\.(?!well-known) { deny all; } location ~* ^/(system|storage)/ { deny all; } location ~* \.(twig|tpl|ini|log|sql)$ { deny all; } location ~ (^|/)config\.php$ { deny all; } location ~* ^/image/.*\.(jpe?g|png|gif|webp|avif|svg)$ { expires 30d; add_header Cache-Control "public"; try_files $uri =404; } location ~* \.(css|js|woff2?)$ { expires 7d; add_header Cache-Control "public"; try_files $uri =404; } location / { try_files $uri $uri/ @opencart; } location @opencart { rewrite ^/(.+)$ /index.php?_route_=$1 last; } location ~ \.php$ { try_files $uri =404; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param REMOTE_ADDR $viewer_ip; fastcgi_pass unix:/run/php-fpm/www.sock; fastcgi_read_timeout 60s; } } NGINX # 8. Hourly OpenCart cron, run by only one node at a time (lock in Redis). cat > /usr/local/bin/oc-cron <<'CRON' #!/bin/bash cd /var/www/html php -r 'require "config.php"; $r = new Redis(); $r->connect(CACHE_HOSTNAME, CACHE_PORT, 2.0); exit($r->set(CACHE_PREFIX . "cron_lock", gethostname(), ["nx", "ex" => 3300]) ? 0 : 1);' \ && runuser -u apache -- php -d auto_prepend_file=/var/www/storage/vendor/autoload.php cron.php CRON chmod 755 /usr/local/bin/oc-cron # 9. Start. if [ "${LOCAL_TEST:-0}" = "1" ]; then mkdir -p /run/php-fpm && php-fpm -D && nginx else cat > /etc/systemd/system/oc-cron.service <<'UNIT' [Unit] Description=OpenCart cron [Service] Type=oneshot ExecStart=/usr/local/bin/oc-cron UNIT cat > /etc/systemd/system/oc-cron.timer <<'UNIT' [Unit] Description=Run OpenCart cron hourly [Timer] OnCalendar=hourly RandomizedDelaySec=120 [Install] WantedBy=timers.target UNIT systemctl daemon-reload systemctl enable --now php-fpm nginx oc-cron.timer fi WebGroup: Type: AWS::AutoScaling::AutoScalingGroup DependsOn: [MountTargetA, MountTargetB, PrivateRoute] UpdatePolicy: AutoScalingRollingUpdate: MinInstancesInService: !Ref MinSize MaxBatchSize: 1 PauseTime: PT10M Properties: VPCZoneIdentifier: [!Ref AppSubnetA, !Ref AppSubnetB] LaunchTemplate: LaunchTemplateId: !Ref LaunchTemplate Version: !GetAtt LaunchTemplate.LatestVersionNumber MinSize: !Ref MinSize MaxSize: !Ref MaxSize DesiredCapacity: !Ref MinSize TargetGroupARNs: [!Ref TargetGroup] HealthCheckType: ELB HealthCheckGracePeriod: 600 Tags: - Key: Name Value: !Sub ${AWS::StackName}-web PropagateAtLaunch: true CpuScaling: Type: AWS::AutoScaling::ScalingPolicy Properties: AutoScalingGroupName: !Ref WebGroup PolicyType: TargetTrackingScaling EstimatedInstanceWarmup: 300 TargetTrackingConfiguration: PredefinedMetricSpecification: PredefinedMetricType: ASGAverageCPUUtilization TargetValue: 50 # ---------- Edge ---------- Distribution: Type: AWS::CloudFront::Distribution Properties: DistributionConfig: Enabled: true Aliases: [!Ref DomainName] HttpVersion: http2and3 PriceClass: PriceClass_All ViewerCertificate: AcmCertificateArn: !Ref CloudFrontCertificateArn SslSupportMethod: sni-only MinimumProtocolVersion: TLSv1.2_2021 Origins: - Id: alb DomainName: !Sub origin.${DomainName} CustomOriginConfig: OriginProtocolPolicy: https-only HTTPSPort: 443 OriginSSLProtocols: [TLSv1.2] OriginCustomHeaders: - HeaderName: X-Origin-Verify HeaderValue: !Ref OriginVerifySecret DefaultCacheBehavior: TargetOriginId: alb ViewerProtocolPolicy: redirect-to-https AllowedMethods: [GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE] CachedMethods: [GET, HEAD] Compress: true # CachingDisabled + AllViewerAndCloudFrontHeaders-2022-06 (forwards cookies, query strings, Host and CloudFront-Viewer-Address) CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad OriginRequestPolicyId: 33f36d7e-f396-46d9-90e0-52428a34d9dc CacheBehaviors: # CachingOptimized for files that never depend on the visitor - PathPattern: /image/* TargetOriginId: alb ViewerProtocolPolicy: redirect-to-https Compress: true CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6 - PathPattern: /catalog/view/* TargetOriginId: alb ViewerProtocolPolicy: redirect-to-https Compress: true CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6 - PathPattern: /extension/*/catalog/view/* TargetOriginId: alb ViewerProtocolPolicy: redirect-to-https Compress: true CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6 StoreRecord: Type: AWS::Route53::RecordSet Properties: HostedZoneId: !Ref HostedZoneId Name: !Ref DomainName Type: A AliasTarget: DNSName: !GetAtt Distribution.DomainName HostedZoneId: Z2FDTNDATAQYW2 OriginRecord: Type: AWS::Route53::RecordSet Properties: HostedZoneId: !Ref HostedZoneId Name: !Sub origin.${DomainName} Type: A AliasTarget: DNSName: !GetAtt LoadBalancer.DNSName HostedZoneId: !GetAtt LoadBalancer.CanonicalHostedZoneID # ---------- Alarms ---------- AlarmTopic: Type: AWS::SNS::Topic Properties: Subscription: [{Protocol: email, Endpoint: !Ref AlarmEmail}] Alb5xxAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmDescription: Web nodes return 5xx errors Namespace: AWS/ApplicationELB MetricName: HTTPCode_Target_5XX_Count Dimensions: [{Name: LoadBalancer, Value: !GetAtt LoadBalancer.LoadBalancerFullName}] Statistic: Sum Period: 60 EvaluationPeriods: 3 Threshold: 20 ComparisonOperator: GreaterThanThreshold TreatMissingData: notBreaching AlarmActions: [!Ref AlarmTopic] SlowResponseAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmDescription: p95 response time above 1.5 seconds Namespace: AWS/ApplicationELB MetricName: TargetResponseTime Dimensions: [{Name: LoadBalancer, Value: !GetAtt LoadBalancer.LoadBalancerFullName}] ExtendedStatistic: p95 Period: 60 EvaluationPeriods: 5 Threshold: 1.5 ComparisonOperator: GreaterThanThreshold TreatMissingData: notBreaching AlarmActions: [!Ref AlarmTopic] DbCpuAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmDescription: Database CPU above 80 percent Namespace: AWS/RDS MetricName: CPUUtilization Dimensions: [{Name: DBInstanceIdentifier, Value: !Ref Database}] Statistic: Average Period: 300 EvaluationPeriods: 2 Threshold: 80 ComparisonOperator: GreaterThanThreshold AlarmActions: [!Ref AlarmTopic] Outputs: StoreUrl: Value: !Sub https://${DomainName}/ CloudFrontDomain: Value: !GetAtt Distribution.DomainName DatabaseEndpoint: Value: !GetAtt Database.Endpoint.Address DatabaseSecretArn: Value: !Ref DbSecret CacheEndpoint: Value: !GetAtt Cache.PrimaryEndPoint.Address FileSystemId: Value: !Ref FileSystem