AWSTemplateFormatVersion: "2010-09-09" Description: AWS CloudFormation workshop - User data (uksb-1q9p31idr) (tag:user-data). Metadata: AWS::CloudFormation::Interface: ParameterGroups: - Label: default: Amazon EC2 Configuration Parameters: - AmiID ParameterLabels: AmiID: default: Amazon Machine Image ID Parameters: EnvironmentType: Description: Specify the Environment type of the stack. Type: String AllowedValues: - Dev - Test - Prod Default: Test ConstraintDescription: Specify either Dev, Test or Prod. AmiID: Description: The ID of the AMI. Type: AWS::SSM::Parameter::Value Default: /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2 Mappings: EnvironmentToInstanceType: Dev: InstanceType: t2.nano Test: InstanceType: t2.micro Prod: InstanceType: t2.small Resources: SSMIAMRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Statement: - Effect: Allow Principal: Service: - ec2.amazonaws.com Action: - sts:AssumeRole ManagedPolicyArns: - arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore WebServerInstanceProfile: Type: AWS::IAM::InstanceProfile Properties: Path: / Roles: - !Ref SSMIAMRole WebServerInstance: Type: AWS::EC2::Instance Properties: IamInstanceProfile: !Ref WebServerInstanceProfile ImageId: !Ref AmiID InstanceType: !FindInMap [EnvironmentToInstanceType, !Ref EnvironmentType, InstanceType] SecurityGroupIds: - !Ref WebServerSecurityGroup Tags: - Key: Name Value: !Join ['-', [!Ref EnvironmentType, webserver]] UserData: !Base64 | #!/bin/bash yum update -y yum install -y httpd php systemctl start httpd systemctl enable httpd usermod -a -G apache ec2-user chown -R ec2-user:apache /var/www chmod 2775 /var/www find /var/www -type d -exec chmod 2775 {} \; find /var/www -type f -exec chmod 0664 {} \; # PHP script to display Instance ID and Availability Zone cat << 'EOF' > /var/www/html/index.php

EC2 Instance ID:

Availability Zone:

EOF WebServerSecurityGroup: Type: AWS::EC2::SecurityGroup Metadata: cfn_nag: rules_to_suppress: - id: F1000 reason: This is using default VPC where we dont know VpcId to support egress. Missing egress rule means all traffic is allowed outbound. Properties: GroupDescription: Enable HTTP access via port 80 SecurityGroupIngress: - IpProtocol: tcp FromPort: 80 ToPort: 80 CidrIp: 0.0.0.0/0 WebServerEIP: Type: AWS::EC2::EIP Properties: Domain: vpc InstanceId: !Ref WebServerInstance Outputs: WebServerPublicDNS: Description: Public DNS of EC2 instance Value: !GetAtt WebServerInstance.PublicDnsName WebServerElasticIP: Description: Elastic IP assigned to EC2 Value: !Ref WebServerEIP WebsiteURL: Description: Application URL Value: !Sub http://${WebServerEIP}