{
  "AWSTemplateFormatVersion": "2010-09-09",

  "Description": "Sample template to bring up an Edx Server.  A WaitCondition is used to hold up the stack creation until the application is deployed. **WARNING** This template creates one or more Amazon EC2 instances. You will be billed for the AWS resources used if you create a stack from this template.",

  "Parameters": {

    "NameTag": {
      "Type": "String",
      "Description": "Name Tag"
    },
    "GroupTag": {
      "Type": "String",
      "Description": "Group Tag"
    },
    "KeyName": {
      "Type": "String",
      "Description" : "Name of an existing EC2 KeyPair to enable SSH access to the web server"
    },
    "InstanceType" : {
      "Description" : "WebServer EC2 instance type",
      "Type" : "String",
      "Default" : "m1.small",
      "AllowedValues" : [ "t1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m2.xlarge","m2.2xlarge","m2.4xlarge","m3.xlarge","m3.2xlarge","c1.medium","c1.xlarge","cc1.4xlarge","cc2.8xlarge","cg1.4xlarge"],
      "ConstraintDescription" : "must be a valid EC2 instance type."
    },
    "SSHLocation" : {
      "Description" : "The IP address range that can be used to SSH to the EC2 instances",
      "Type": "String",
      "MinLength": "9",
      "MaxLength": "18",
      "Default": "0.0.0.0/0",
      "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
      "ConstraintDescription": "must be a valid IP CIDR range of the form x.x.x.x/x."
   }
  },

  "Mappings" : {

    "AWSInstanceType2Arch" : {
      "t1.micro"    : { "Arch" : "64" },
      "m1.small"    : { "Arch" : "64" },
      "m1.medium"   : { "Arch" : "64" },
      "m1.large"    : { "Arch" : "64" },
      "m1.xlarge"   : { "Arch" : "64" },
      "m2.xlarge"   : { "Arch" : "64" },
      "m2.2xlarge"  : { "Arch" : "64" },
      "m2.4xlarge"  : { "Arch" : "64" },
      "m3.xlarge"   : { "Arch" : "64" },
      "m3.2xlarge"  : { "Arch" : "64" },
      "c1.medium"   : { "Arch" : "64" },
      "c1.xlarge"   : { "Arch" : "64" }
    },

    "AWSRegionArch2AMI" : {
      "us-east-1" :      { "32" : "ami-def89fb7", "64" : "ami-d0f89fb9" },
      "us-west-1" :      { "32" : "ami-fc002cb9", "64" : "ami-fe002cbb" },
      "us-west-2" :      { "32" : "ami-0ef96e3e", "64" : "ami-70f96e40" },
      "eu-west-1" :      { "32" : "ami-c27b6fb6", "64" : "ami-ce7b6fba" },
      "sa-east-1"      : { "32" : "ami-a1da00bc", "64" : "ami-a3da00be" },
      "ap-southeast-1" : { "32" : "ami-66084734", "64" : "ami-64084736" },
      "ap-southeast-2" : { "32" : "ami-06ea7a3c", "64" : "ami-04ea7a3e" },
      "ap-northeast-1" : { "32" : "ami-fc6ceefd", "64" : "ami-fe6ceeff" }
    }
  },

  "Resources" : {

    "EdxServerUser" : {
      "Type" : "AWS::IAM::User",
      "Properties" : {
        "Path": "/",
        "Policies": [{
          "PolicyName": "root",
          "PolicyDocument": { "Statement":[{
            "Effect":"Allow",
            "Action": [
              "cloudformation:DescribeStackResource",
              "s3:Put"
            ],
            "Resource":"*"
          }]}
        }]
      }
    },

    "HostKeys" : {
      "Type" : "AWS::IAM::AccessKey",
      "Properties" : {
        "UserName" : {"Ref": "EdxServerUser"}
      }
    },

    "EdxServer": {
      "Type": "AWS::EC2::Instance",
      "Metadata" : {
        "AWS::CloudFormation::Init" : {
          "config" : {
            "packages" : {
              "apt" : {
                "ruby"            : [],
                "ruby-dev"        : [],
                "libopenssl-ruby" : [],
                "rdoc"            : [],
                "ri"              : [],
                "irb"             : [],
                "build-essential" : [],
                "wget"            : [],
                "ssl-cert"        : [],
                "rubygems"        : [],
                "git"             : [],
                "s3cmd"           : []
              }
            },
            "files" : {
              "/home/ubuntu/.s3cfg" : {
                "content" : { "Fn::Join" : ["", [
                  "[default]\n",
                  "access_key = ", { "Ref" : "HostKeys" }, "\n",
                  "secret_key = ", {"Fn::GetAtt": ["HostKeys", "SecretAccessKey"]}, "\n",
                  "use_https = True\n"
                  ]]},
                "mode"   : "000644",
                "owner"  : "ubuntu",
                "group"  : "ubuntu"
              }
            }
          }
        }
      },
      "Properties": {
        "Tags" : [ {
            "Key" : "Name",
            "Value" :{ "Ref": "NameTag" }
          },
          {
            "Key" : "Group",
            "Value" : { "Ref": "GroupTag" }
          }
        ],
        "SecurityGroups": [ { "Ref": "EdxServerSecurityGroup" } ],
        "ImageId": { "Fn::FindInMap": [ "AWSRegionArch2AMI", { "Ref": "AWS::Region" }, { "Fn::FindInMap": [ "AWSInstanceType2Arch", { "Ref": "InstanceType" }, "Arch" ] } ]
        },
        "UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [
            "#!/bin/bash\n",
            "function error_exit\n",
            "{\n",
            "  cfn-signal -e 1 -r \"$1\" '", { "Ref" : "EdxServerWaitHandle" }, "'\n",
            "  exit 1\n",
            "}\n",

            "apt-get update\n",
            "apt-get -y install python-setuptools\n",
            "echo \"Python Tools installed\" - `date` >> /home/ubuntu/cflog.txt\n",
            "easy_install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz\n",
            "echo \"Cloudformation Boostrap installed \" - `date` >> /home/ubuntu/cflog.txt\n",
            "cfn-init --region ", { "Ref" : "AWS::Region" },
            "    -s ", { "Ref" : "AWS::StackId" }, " -r EdxServer ",
            "         --access-key ", { "Ref" : "HostKeys" },
            "         --secret-key ", {"Fn::GetAtt": ["HostKeys", "SecretAccessKey"]}, " || error_exit 'Failed to run cfn-init'\n",
            "echo \"cfn-init run \" - `date` >> /home/ubuntu/cflog.txt\n",
            "# If all went well, signal success\n",
            "cfn-signal -e $? -r 'Edx Server configuration' '", { "Ref" : "EdxServerWaitHandle" }, "'\n"
        ]]}},
        "KeyName": { "Ref": "KeyName" },
        "InstanceType": { "Ref": "InstanceType" }
      }
    },

    "EdxServerSecurityGroup" : {
      "Type" : "AWS::EC2::SecurityGroup",
      "Properties" : {
        "GroupDescription" : "Open up SSH access plus Edx Server required ports",
        "SecurityGroupIngress" : [
          { "IpProtocol": "tcp", "FromPort": "22",   "ToPort": "22",   "CidrIp": { "Ref" : "SSHLocation"} },
          { "IpProtocol": "tcp", "FromPort": "4000", "ToPort": "4000", "SourceSecurityGroupName": { "Ref" :"EdxClientSecurityGroup" }},
          { "IpProtocol": "tcp", "FromPort": "4040", "ToPort": "4040", "CidrIp": "0.0.0.0/0"}
        ]
      }
    },

    "EdxClientSecurityGroup" : {
      "Type" : "AWS::EC2::SecurityGroup",
      "Properties" : {
        "GroupDescription" : "Group with access to Edx Server"
      }
    },

    "EdxServerWaitHandle" : {
      "Type" : "AWS::CloudFormation::WaitConditionHandle"
    },

    "EdxServerWaitCondition" : {
      "Type" : "AWS::CloudFormation::WaitCondition",
      "DependsOn" : "EdxServer",
      "Properties" : {
        "Handle"  : { "Ref" : "EdxServerWaitHandle" },
        "Timeout" : "1200"
      }
    }
  },

  "Outputs" : {
    "EdxSecurityGroup" : {
       "Description" : "EC2 Security Group with access to the Edx server",
       "Value" : { "Ref" :"EdxClientSecurityGroup" }
    }
  }
}