{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Description": "AWS CloudFormation Template WordPress_Custom_Instance_With_RDS",
  "Parameters": {
    "EnvironmentType": {
      "Type": "String",
      "Default": "DEV",
      "AllowedValues": [
        "DEV",
        "PROD"
      ],
      "Description": "Enter environment type. Default is DEV"
    },
    "KeyName": {
      "Description": "Name of an existing EC2 KeyPair to enable SSH access to the instances",
      "Type": "String",
      "MinLength": "1",
      "MaxLength": "255",
      "AllowedPattern": "[\\x20-\\x7E]*",
      "ConstraintDescription": "can contain only ASCII characters."
    },
    "DBUsername": {
      "Default": "admin",
      "NoEcho": "false",
      "Description": "The WordPress database admin account username",
      "Type": "String",
      "MinLength": "1",
      "MaxLength": "16",
      "AllowedPattern": "[a-zA-Z][a-zA-Z0-9]*",
      "ConstraintDescription": "must begin with a letter and contain only alphanumeric characters."
    },
    "DBPassword": {
      "Default": "password",
      "NoEcho": "true",
      "Description": "The WordPress database admin account password",
      "Type": "String",
      "MinLength": "8",
      "MaxLength": "41",
      "AllowedPattern": "[a-zA-Z0-9]*",
      "ConstraintDescription": "must contain only alphanumeric characters."
    }
  },
  "Mappings": {
    "RegionMap": {
      "eu-west-1": {
        "AMI": "ami-a609b6d5"
      }
    },
    "InstanceTypeMap": {
      "DEV": {
        "instancetype": "t2.nano"
      },
      "PROD": {
        "instancetype": "t2.micro"
      }
    },
    "DBInstanceTypeMap": {
      "DEV": {
        "dbinstancetype": "db.t1.micro"
      },
      "PROD": {
        "dbinstancetype": "db.m1.small"
      }
    },
    "DBAllocatedStorageMap": {
      "DEV": {
        "dbstorage": "5"
      },
      "PROD": {
        "dbstorage": "10"
      }
    },
    "DBNameMap": {
      "DEV": {
        "dbname": "wordpress_dev"
      },
      "PROD": {
        "dbname": "wordpress_prod"
      }
    }
  },
  "Resources": {

    "WebNodeSecurityGroup" : {
      "Type" : "AWS::EC2::SecurityGroup",
      "Properties" : {
        "GroupDescription" : "Enable SSH, HTTP from anywhere",
        "SecurityGroupIngress" : [
          {
            "IpProtocol" : "tcp",
            "FromPort"   : "22",
            "ToPort"     : "22",
            "CidrIp"     : "0.0.0.0/0"
          },
          {
            "IpProtocol" : "tcp",
            "FromPort"   : "80",
            "ToPort"     : "80",
            "CidrIp"     : "0.0.0.0/0"
          }
        ]
      }
    },
    "DBSecurityGroup": {
      "Type": "AWS::RDS::DBSecurityGroup",
      "Properties": {
        "DBSecurityGroupIngress": { "EC2SecurityGroupName": { "Ref": "WebNodeSecurityGroup"} },
        "GroupDescription"      : "Frontend Access"
      }
    },
    "WebNodeWaitHandle" : {
      "Type" : "AWS::CloudFormation::WaitConditionHandle"
    },
    "WebNodeWaitCondition" : {
      "Type" : "AWS::CloudFormation::WaitCondition",
      "DependsOn" : "WebNode",
      "Properties" : {
        "Handle" : {
          "Ref" : "WebNodeWaitHandle"
        },
        "Timeout" : "1600"
      }
    },
    "WebNode": {
      "Type": "AWS::EC2::Instance",
      "Metadata": {
        "AWS::CloudFormation::Init": {
          "config": {
            "packages": {
              "apt": {
                "apache2": [],
                "php5": [],
                "php5-mysql": []
              }
            },
            "sources": {
              "/var/www/html": "http://wordpress.org/latest.tar.gz"
            },
            "files": {
              "/var/www/html/wordpress/wp-config.php": {
                "content": {
                  "Fn::Join": [
                    "",
                    [
                      "<?php\n",
                      "define('DB_NAME',          '",
                      {
                        "Fn::FindInMap": [
                          "DBNameMap",
                          {
                            "Ref": "EnvironmentType"
                          },
                          "dbname"
                        ]
                      },
                      "');\n",
                      "define('DB_USER',          '",
                      {
                        "Ref": "DBUsername"
                      },
                      "');\n",
                      "define('DB_PASSWORD',      '",
                      {
                        "Ref": "DBPassword"
                      },
                      "');\n",
                      "define('DB_HOST',          '",
                      {
                        "Fn::GetAtt": [
                          "DBInstance",
                          "Endpoint.Address"
                        ]
                      },
                      "');\n",
                      "define('DB_CHARSET',       'utf8');\n",
                      "define('DB_COLLATE',       '');\n"
                    ]
                  ]
                },
                "mode": "000644",
                "owner": "root",
                "group": "root"
              }
            },
            "services": {
              "sysvinit": {
                "apache2": {
                  "enabled": "true",
                  "ensureRunning": "true"
                }
              }
            }
          }
        }
      },
      "Properties": {
        "ImageId": {
          "Fn::FindInMap": [
            "RegionMap", { "Ref" : "AWS::Region" }, "AMI"
          ]
        },
        "InstanceType" : {
          "Fn::FindInMap" : [ "InstanceTypeMap", { "Ref" : "EnvironmentType" }, "instancetype" ]
        },
        "SecurityGroups": [
          {
            "Ref": "WebNodeSecurityGroup"
          }
        ],
        "KeyName": {
          "Ref": "KeyName"
        },
        "UserData": {
          "Fn::Base64": {
            "Fn::Join": [
              "",
              [
                "#!/bin/bash\n",
                "apt-get update\n",
                "apt-get -y install python-setuptools\n",
                "easy_install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz\n",
                "cfn-init -s ",
                {
                  "Ref": "AWS::StackId"
                },
                " -r WebNode ",
                "         --region ",
                {
                  "Ref": "AWS::Region"
                },
                "\n",
                "cfn-signal -e $? '",
                {
                  "Ref": "WebNodeWaitHandle"
                },
                "'\n",
                "# Setup correct file ownership\n",
                "chown -R www-data:www-data /var/www/html/wordpress\n",
                "# Add keys and salts to the config file\n",
                "wp_config=/var/www/html/wordpress/wp-config.php\n",
                "GET https://api.wordpress.org/secret-key/1.1/salt/ >> $wp_config\n",
                "echo \"define('WPLANG'            , '');\" >> $wp_config\n",
                "echo \"define('WP_DEBUG'          , false);\" >> $wp_config\n",
                "echo \"\\$table_prefix  = 'wp_';\" >> $wp_config\n",
                "echo \"if ( !defined('ABSPATH') )\" >> $wp_config\n",
                "echo \"    define('ABSPATH', dirname(__FILE__) . '/');\" >> $wp_config\n",
                "echo \"require_once(ABSPATH . 'wp-settings.php');\" >> $wp_config\n"
              ]
            ]
          }
        }
      }
    },
    "DBInstance" : {
      "Type": "AWS::RDS::DBInstance",
      "Properties": {
        "DBName"            : { "Fn::FindInMap" : [ "DBNameMap", { "Ref" : "EnvironmentType" }, "dbname" ] },
        "Engine"            : "MySQL",
        "MasterUsername"    : { "Ref" : "DBUsername" },
        "DBInstanceClass"   : { "Fn::FindInMap" : [ "DBInstanceTypeMap", { "Ref" : "EnvironmentType" }, "dbinstancetype" ] },
        "DBSecurityGroups"  : [{ "Ref" : "DBSecurityGroup" }],
        "AllocatedStorage"  : { "Fn::FindInMap" : [ "DBAllocatedStorageMap", { "Ref" : "EnvironmentType" }, "dbstorage" ] },
        "MasterUserPassword": { "Ref" : "DBPassword" }
      }
    }
  }
}