EC2 cloudFormationTemplate Example

Материал из noname.com.ua
Перейти к навигацииПерейти к поиску
{
  "AWSTemplateFormatVersion" : "2010-09-09",
  
  "Description" : "Mirantis Test Stack",
  "Parameters" : {
    "HostName": {
      "Description" : "Local Host Name (for puppet auth)",
      "Type": "String",
      "Default": "testtomcatnode.test.com"
    },

    "PuppetMasterDNSName": {
      "Description" : "The PuppetMaster DNS name",
      "Type": "String",
      "Default": "ip-10-117-81-201.ec2.internal"
    },

    "PuppetMasterIPAddress": {
      "Description" : "The PuppetMaster IP address",
      "Type": "String",
      "Default": "10.62.67.238"
    },

    "KeyName" : {
      "Description" : "Name of an existing EC2 KeyPair to enable SSH access to the instances",
      "Type" : "String",
      "Default" :  "hp"
    },
      
    "DBRootPassword": {
      "NoEcho": "true",
      "Description" : "Root password for MySQL",
      "Default" : "admin",
      "Type": "String",
      "MinLength": "1",
      "MaxLength": "41",
      "AllowedPattern" : "[a-zA-Z0-9]*",
      "ConstraintDescription" : "must contain only alphanumeric characters."
    },

    "InstanceType" : {
      "Description" : "WebServer EC2 instance type",
      "Type" : "String",
      "Default" : "t1.micro",
      "AllowedValues" : [ "t1.micro","m1.small","m1.medium","m1.large","m1.xlarge","m2.xlarge","m2.2xlarge","m2.4xlarge","c1.medium","c1.xlarge","cc1.4xlarge","cc2.8xlarge","cg1.4xlarge"],
      "ConstraintDescription" : "must be a valid EC2 instance type."
    }
  },
  
  "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" },
      "c1.medium"   : { "Arch" : "64" },
      "c1.xlarge"   : { "Arch" : "64" },
      "cc1.4xlarge" : { "Arch" : "64HVM" },
      "cc2.8xlarge" : { "Arch" : "64HVM" },
      "cg1.4xlarge" : { "Arch" : "64HVM" }
    },

    "AWSRegionArch2AMI" : {
      "us-east-1"      : { "32" : "ami-31814f58", "64" : "ami-1b814f72", "64HVM" : "ami-0da96764" },
      "us-west-2"      : { "32" : "ami-38fe7308", "64" : "ami-30fe7300", "64HVM" : "NOT_YET_SUPPORTED" },
      "us-west-1"      : { "32" : "ami-11d68a54", "64" : "ami-1bd68a5e", "64HVM" : "NOT_YET_SUPPORTED" },
      "eu-west-1"      : { "32" : "ami-973b06e3", "64" : "ami-953b06e1", "64HVM" : "NOT_YET_SUPPORTED" },
      "ap-southeast-1" : { "32" : "ami-b4b0cae6", "64" : "ami-beb0caec", "64HVM" : "NOT_YET_SUPPORTED" },
      "ap-northeast-1" : { "32" : "ami-0644f007", "64" : "ami-0a44f00b", "64HVM" : "NOT_YET_SUPPORTED" },
      "sa-east-1"      : { "32" : "ami-3e3be423", "64" : "ami-3c3be421", "64HVM" : "NOT_YET_SUPPORTED" }
    }
  },
    
  "Resources" : {     
      
    "CfnUser" : {
      "Type" : "AWS::IAM::User",
      "Properties" : {
        "Path": "/",
        "Policies": [{
          "PolicyName": "root",
          "PolicyDocument": { "Statement":[{
            "Effect":"Allow",
            "Action":"cloudformation:DescribeStackResource",
            "Resource":"*"
          }]}
        }]
      }
    },



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


    "ElasticLoadBalancer" : {
      "Type" : "AWS::ElasticLoadBalancing::LoadBalancer",
      "Properties" : {
        "AvailabilityZones" : { "Fn::GetAZs" : "" },
        "Listeners" : [ {
          "LoadBalancerPort" : "80",
          "InstancePort" : "8080",
          "Protocol" : "HTTP"
        } ],
        "HealthCheck" : {
          "Target" : "HTTP:80/",
          "HealthyThreshold" : "3",
          "UnhealthyThreshold" : "5",
          "Interval" : "30",
          "Timeout" : "5"
        }
      }
    },


    "WebServerAutoScailingGroup" : {
      "Type" : "AWS::AutoScaling::AutoScalingGroup",
      "Properties" : {
        "AvailabilityZones" : { "Fn::GetAZs" : ""},
        "LaunchConfigurationName" : { "Ref" : "WebServerLaunchConfig" },
        "MinSize" : "1",
        "MaxSize" : "3",
        "LoadBalancerNames" : [ { "Ref" : "ElasticLoadBalancer" } ]
      }
    },



    "WebServerScaleUpPolicy" : {
      "Type" : "AWS::AutoScaling::ScalingPolicy",
      "Properties" : {
        "AdjustmentType" : "ChangeInCapacity",
        "AutoScalingGroupName" : { "Ref" : "WebServerAutoScailingGroup" },
        "Cooldown" : "60",
        "ScalingAdjustment" : "1"
      }
    },
    "WebServerScaleDownPolicy" : {
      "Type" : "AWS::AutoScaling::ScalingPolicy",
      "Properties" : {
        "AdjustmentType" : "ChangeInCapacity",
        "AutoScalingGroupName" : { "Ref" : "WebServerAutoScailingGroup" },
        "Cooldown" : "60",
        "ScalingAdjustment" : "-1"
      }
    },

    "CPUAlarmHigh": {
     "Type": "AWS::CloudWatch::Alarm",
     "Properties": {
        "AlarmDescription": "Scale-up if CPU > 90% for 60 sec",
        "MetricName": "CPUUtilization",
        "Namespace": "AWS/EC2",
        "Statistic": "Average",
        "Period": "60",
        "EvaluationPeriods": "2",
        "Threshold": "90",
        "AlarmActions": [ { "Ref": "WebServerScaleUpPolicy" } ],
        "Dimensions": [
          {
            "Name": "AutoScalingGroupName",
            "Value": { "Ref": "WebServerAutoScailingGroup" }
          }
        ],
        "ComparisonOperator": "GreaterThanThreshold"
      }
    },
    "CPUAlarmLow": {
     "Type": "AWS::CloudWatch::Alarm",
     "Properties": {
        "AlarmDescription": "Scale-down if CPU < 70% for 1 minutes",
        "MetricName": "CPUUtilization",
        "Namespace": "AWS/EC2",
        "Statistic": "Average",
        "Period": "60",
        "EvaluationPeriods": "2",
        "Threshold": "70",
        "AlarmActions": [ { "Ref": "WebServerScaleDownPolicy" } ],
        "Dimensions": [
          {
            "Name": "AutoScalingGroupName",
            "Value": { "Ref": "WebServerAutoScailingGroup" }
          }
        ],
        "ComparisonOperator": "LessThanThreshold"
      }
    },


    "WebServerLaunchConfig": {  
      "Type" : "AWS::AutoScaling::LaunchConfiguration",
      "Metadata" : {
        "Comment1" : "this is test config",

        "AWS::CloudFormation::Init" : {
          "config" : {
            "packages" : {
             "rubygems" : {
                "chef" : [ "0.10.2" ]
	      },
              "yum" : {
                "puppet"       : [],
                "mc"           : [],
                "tomcat7"      : [],
                "nginx"        : [],
                "mysql"        : [],
                "mysql-server" : [],
                "mysql-libs"   : [],
                "httpd"        : [],
                "php"          : [],
                "php-mysql"    : [],
                "gcc-c++"      : [],
                "ruby-devel"   : [],
                "make"         : [],
                "autoconf"     : [],
                "automake"     : [],
                "rubygems"     : []

              }
            },

            "sources" : {
              "/var/www/html" : "https://s3.amazonaws.com/cloudformation-examples/CloudFormationPHPSample.zip"
            },

            "files" : {
              "/etc/chef/solo.rb" : {
                "content" : { "Fn::Join" : ["", [
                  "log_level :info\n",
                  "log_location STDOUT\n",
                  "file_cache_path \"/var/chef-solo\"\n",
                  "cookbook_path \"/var/chef-solo/cookbooks\"\n",
                  "json_attribs \"/etc/chef/node.json\"\n"
                ]] },
                "mode"  : "000644",
                "owner" : "root",
                "group" : "root"
              },
              "/tmp/setup.mysql" : {
                "content" : "CREATE DATABASE lampdb;\n",
                "mode"    : "000644",
                "owner"   : "root",
                "group"   : "root"
              },
	      "/etc/yum.repos.d/epel.repo" : {
                "source" : "https://s3.amazonaws.com/cloudformation-examples/enable-epel-on-amazon-linux-ami",
                "mode"   : "000644",
                "owner"  : "root",
                "group"  : "root"
              },
              "/etc/puppet/puppet.conf" : {
                "content" : { "Fn::Join" : ["", [
                  "[main]\n",
                  "   logdir=/var/log/puppet\n",
                  "   rundir=/var/run/puppet\n",
                  "   ssldir=$vardir/ssl\n",
                  "   pluginsync=true\n",
                  "[agent]\n",
                  "   classfile=$vardir/classes.txt\n",
                  "   localconfig=$vardir/localconfig\n",
                  "   server=",{ "Ref" : "PuppetMasterDNSName" },"\n"
                ]] },
                "mode" : "000644",
                "owner" : "root",
                "group" : "root"
              }
	    },
            "services" : {
              "sysvinit" : {  
                "mysqld" : {
                  "enabled"       : "true",
                  "ensureRunning" : "true"                
                },
                "httpd" : {
                  "enabled"       : "true",
                  "ensureRunning" : "true"                
                }
              }
            }
          }
        }
      },
      "Properties": {
        "ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" },
                          { "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : "InstanceType" }, "Arch" ] } ] },
        "InstanceType"   : { "Ref" : "InstanceType" },
	"KeyName" : { "Ref" : "KeyName" },
        "SecurityGroups" : [ {"Ref" : "WebServerSecurityGroup"} ],
        "UserData"       : { "Fn::Base64" : { "Fn::Join" : ["", [
          "#!/bin/bash -v\n",
          "yum update -y aws-cfn-bootstrap\n",

          "# Helper function\n",
          "function error_exit\n",
          "{\n",
          "  /opt/aws/bin/cfn-signal -e 1 -r \"$1\" '", { "Ref" : "WaitHandle" }, "'\n",
          "  exit 1\n",
          "}\n",

          "# Install LAMP packages\n",
          "#/opt/aws/bin/cfn-init -s ", { "Ref" : "AWS::StackName" }, " -r WebServer             ",  "--access-key ", { "Ref" : "HostKeys" }, " --secret-key ", {"Fn::GetAtt": ["HostKeys", "SecretAccessKey"]}, " --region ", { "Ref" : "AWS::Region" }, " || error_exit 'Failed to run cfn-init'\n",
          " /opt/aws/bin/cfn-init -s ", { "Ref" : "AWS::StackName" }, " -r WebServerLaunchConfig ",  "--access-key ", { "Ref" : "HostKeys" }, " --secret-key ", {"Fn::GetAtt": ["HostKeys", "SecretAccessKey"]}, " --region ", { "Ref" : "AWS::Region" }, " || error_exit 'Failed to run cfn-init'\n",


          "# Setup MySQL, create a user and a database\n",
          "mysqladmin -u root password '", { "Ref" : "DBRootPassword" }, "' || error_exit 'Failed to initialize root password'\n",
          "mysql -u root --password='", { "Ref" : "DBRootPassword" }, "' < /tmp/setup.mysql || error_exit 'Failed to initialize database'\n",

          "# Configure the PHP application - in this case, fixup the page with the right references to the database\n",
          "sed -i \"s/REPLACE_WITH_DATABASE/localhost/g\" /var/www/html/index.php\n",
          "sed -i \"s/REPLACE_WITH_DBUSER/root/g\" /var/www/html/index.php\n",
          "sed -i \"s/REPLACE_WITH_DBPASSWORD/", { "Ref" : "DBRootPassword" }, "/g\" /var/www/html/index.php\n",

	  "echo interface \"eth0\" > /etc/dhcp/dhclient-eth0.conf \n",
          "sed -i \"s/localhost.localdomain/", { "Ref" : "HostName" }, "/g\" /etc/sysconfig/network\n",
	  "/bin/hostname  ",  { "Ref" : "HostName" }, "\n",
	  "echo " , { "Ref" : "PuppetMasterIPAddress" }," ", { "Ref" : "PuppetMasterDNSName" }, ">> /etc/hosts\n",
	  "rm -rf /var/lib/puppet/ \n",
	  "/usr/bin/wget http://", { "Ref" : "PuppetMasterDNSName" },"/puppet/puppet_cert/puppet.tar.gz -O /puppet.tar.gz \n",
          "tar -xvf puppet.tar.gz  \n",
          "chown puppet:puppet /var/lib/puppet/ -Rc \n",
          "/usr/sbin/puppetd --server ", { "Ref" : "PuppetMasterDNSName" }, " --verbose --test --no-daemonize  --debug \n",
	  " sleep 60 \n",
	  "/usr/bin/chef-solo -l debug -c /etc/chef/solo.rb -j /etc/chef/run_list.syslog-ng.json  \n",
	  " sleep 10 \n",
	  "/usr/bin/chef-solo -l debug -c /etc/chef/solo.rb -j /etc/chef/run_list.tomcat.json \n",

          "# All is well so signal success\n",
          "/opt/aws/bin/cfn-signal -e 0 -r \"LAMP Stack setup complete\" '", { "Ref" : "WaitHandle" }, "'\n"
        ]]}}
      }
    },

    "WaitHandle" : {
      "Type" : "AWS::CloudFormation::WaitConditionHandle"
    },
      
    "WebServerSecurityGroup" : {
      "Type" : "AWS::EC2::SecurityGroup",
      "Properties" : {
        "GroupDescription" : "Enable HTTP access via port 80, ssh via 22",
        "SecurityGroupIngress" : [
          {"IpProtocol" : "tcp", "FromPort" : "80", "ToPort" : "80", "CidrIp" : "0.0.0.0/0"},
          {"IpProtocol" : "tcp", "FromPort" : "8080", "ToPort" : "8080", "CidrIp" : "0.0.0.0/0"},
          {"IpProtocol" : "tcp", "FromPort" : "22", "ToPort" : "22", "CidrIp" : "0.0.0.0/0"}
        ]
      }      
    }
  },    

  "Outputs" : {
    "WebsiteURL" : {
      "Value" :  { "Fn::Join" : [ "", [ "http://", { "Fn::GetAtt" : [ "ElasticLoadBalancer", "DNSName" ]}]]},
      "Description" : "Application URL"
    }
  }

}