CloudFormation編~CloudFormationでVPCパート③~

こんにちは! JQです。

前回は『 CloudFormation編~CloudFormationでVPCパート②~ 』 ということで、CloudFormationのStackでVPCを構築してみました。

今回は『CloudFormation編~CloudFormationでVPCパート③~』と題して、CloudFormationのStackでVPCにWEBインスタンスを構築してみたいと思います。

Templateの作成

4 インスタンス構築Templateの作成

インスタンス構築のTemplateを作成します。

下記テンプレートではhttpとphpをインストールしてphpinfoのファイルを設置するWEBサーバを起動します。

「Parameters」で指定する項目は以下になります。

InstanceType インスタンスタイプ
WebKeyName SSHキー
SSHLocation SSHの許可IP(デフォルトは0.0.0.0/0)
VpcId VPCのID
SubnetId SubnetのID

「Mappings」はAmazonLinuxのAMIになります。

CloudFormationの「Metadata」を利用してパッケージのインストールと起動にphpinfoファイルの作成を行っております。

※「UserData」で上記のトリガーが行われます。

成功した場合には「Outputs」で次の項目が出力されます。

WebInstanceID 作成されたインスタンスのInstanceID
AZ 作成されたインスタンスのゾーン
URL 作成されたインスタンスにアクセスする為のURL
1{2{3  "AWSTemplateFormatVersion" : "2010-09-09",45  "Description" : "AWS CloudFormation Template : Build to instance. AmazonLinux. ",67  "Parameters" : {8    "InstanceType" : {9      "Description" : "WebServer EC2 instance type",10      "Type" : "String",11      "Default" : "t1.micro",1213      "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"],14      "ConstraintDescription" : "must be a valid EC2 instance type."15    },    16    "WebKeyName" : {17      "Description" : "Name of an existing EC2 KeyPair to enable SSH access to the instances",18      "Type" : "String",19      "MinLength": "1",20      "MaxLength": "64",21      "AllowedPattern" : "[-_ a-zA-Z0-9]*",2223      "ConstraintDescription" : "can contain only alphanumeric characters, spaces, dashes and underscores."24    },2526    "SSHLocation" : {27      "Description" : "The IP address range that can be used to SSH to the EC2 instances",28      "Type": "String",29      "MinLength": "9",30      "MaxLength": "18",31      "Default": "0.0.0.0/0",32      "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",33      "ConstraintDescription": "must be a valid IP CIDR range of the form x.x.x.x/x."34    },35   36    "VpcId" : {37      "Type" : "String",38      "Description" : "VpcId of your existing Virtual Private Cloud (VPC)"39    },4041    "SubnetId" : {42      "Type" : "String",43      "Description" : "SubnetId of an existing Public facing subnet in your Virtual Private Cloud (VPC)"44    }45  },4647  "Mappings" : {48    "AWSInstanceType2Arch" : {49      "t1.micro"    : { "Arch" : "64" },50      "m1.small"    : { "Arch" : "64" },51      "m1.medium"   : { "Arch" : "64" },52      "m1.large"    : { "Arch" : "64" },53      "m1.xlarge"   : { "Arch" : "64" },54      "m2.xlarge"   : { "Arch" : "64" },55      "m2.2xlarge"  : { "Arch" : "64" },56      "m2.4xlarge"  : { "Arch" : "64" },57      "m3.xlarge"   : { "Arch" : "64" },58      "m3.2xlarge"  : { "Arch" : "64" },59      "c1.medium"   : { "Arch" : "64" },60      "c1.xlarge"   : { "Arch" : "64" },61      "cc1.4xlarge" : { "Arch" : "64HVM" },62      "cc2.8xlarge" : { "Arch" : "64HVM" },63      "cg1.4xlarge" : { "Arch" : "64HVM" }64    },    6566    "AWSRegionArch2AMI" : {67      "us-east-1"      : { "64" : "ami-35792c5c" },68      "us-west-1"      : { "64" : "ami-687b4f2d" },69      "us-west-2"      : { "64" : "ami-d03ea1e0" },70      "eu-west-1"      : { "64" : "ami-149f7863" },71      "sa-east-1"      : { "64" : "ami-9f6ec982" },72      "ap-southeast-1" : { "64" : "ami-14f2b946" },73      "ap-southeast-2" : { "64" : "ami-a148d59b" },74      "ap-northeast-1" : { "64" : "ami-3561fe34" }75    }76  },7778  "Resources" : {79                   80    "WebSecurityGroup" : {81      "Type" : "AWS::EC2::SecurityGroup",82      "Properties" : {83        "VpcId" : { "Ref" : "VpcId" },84        "GroupDescription" : "Enable SSH access via port 22",85        "SecurityGroupIngress" : [86           { "IpProtocol" : "tcp", "FromPort" : "22", "ToPort" : "22", "CidrIp" : "219.111.8.217/32" }, 87           { "IpProtocol" : "tcp", "FromPort" : "80", "ToPort" : "80", "CidrIp" : "0.0.0.0/0" }88           ]89      }90    },91   92    "WebHost" : {93      "Type" : "AWS::EC2::Instance",94      "Metadata": {95        "AWS::CloudFormation::Init": {96            "config": {97              "packages": {98                "yum": {99                  "httpd": [],100                  "php" : []101                }102              },103              "files" : {104                "/var/www/html/index.php" : {105                  "content" : { "Fn::Join" : ["", [ "<?php phpinfo(); ?>" ]]},106                  "mode"  : "000644",107                  "owner" : "root",108                  "group" : "root"                  109                }110              },111              "services" : {112                "sysvinit" : {  113                  "httpd" : {114                    "enabled" : "true",115                    "ensureRunning" : "true"                116                  }117                }118              }              119            }120          }121        },122        123      "Properties" : {124125        "ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" },{ "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : "InstanceType" },"Arch" ] } ] },126        "KeyName" : { "Ref" : "WebKeyName" },127		"NetworkInterfaces" : [{128          "AssociatePublicIpAddress" : "true",129          "GroupSet" : [{ "Ref" : "WebSecurityGroup" }],130          "SubnetId" : { "Ref" : "SubnetId" },131          "DeviceIndex"              : "0"132    	}],           133        "UserData"       : { "Fn::Base64" : { "Fn::Join" : ["", [134          "#!/bin/bash\n",135          "yum update -y aws-cfn-bootstrap \n",136137          "# Helper function\n",138          "function error_exit\n",139          "{\n",140          "  /opt/aws/bin/cfn-signal -e 1 -r \"$1\" '", { "Ref" : "WebHostHandle" }, "'\n",141          "  exit 1\n",142          "}\n",143144          "# Install the simple web page\n",145          "/opt/aws/bin/cfn-init -s ", { "Ref" : "AWS::StackId" }, " -r WebHost ",146          "         --region ", { "Ref" : "AWS::Region" }, " || error_exit 'Failed to run cfn-init'\n",147148          "# All done so signal success\n",149          "/opt/aws/bin/cfn-signal -e 0 -r \"WebHost setup complete\" '", { "Ref" : "WebHostHandle" }, "'\n"150        ]]}},      151        "Tags": [152          { "Key" : "Name", "Value": "WebHost" }153        ]        154      }155    },156             157    "WebHostHandle" : {158      "Type" : "AWS::CloudFormation::WaitConditionHandle"159    },160   161    "WebControllerCondition" : {162      "Type" : "AWS::CloudFormation::WaitCondition",163      "DependsOn" : "WebHost",164      "Properties" : {165        "Handle" : { "Ref" : "WebHostHandle" },166        "Timeout" : "600"167      }168    }169  },170171  "Outputs" : {172173    "WebInstanceID" : {174      "Description" : "Web Instance ID",175      "Value" : {"Ref": "WebHost"}176    },177    "AZ" : {178      "Description" : "Availability Zone of the newly created EC2 instance",179      "Value" : { "Fn::GetAtt" : [ "WebHost", "AvailabilityZone" ] }180    },181    "URL" : {182      "Description" : "URL of the sample website",183      "Value" : { "Fn::Join" : [ "", ["http://", { "Fn::GetAtt" : ["WebHost", "PublicIp"] }]]}184    }185    186  }187}

いかがでしたでしょうか?

次回は『CloudFormation編~CloudFormationでVPCパート④~』ということで、実際に今回のテンプレートを試してみたいと思います。

お楽しみに!

——————————————————————————————————

ナレコムクラウドのFacebookに『いいね!』をクリックして頂くと

最新のお役立ちレシピが配信されます★

┏━━━━━━━━━━━━━┓

┃ナレコムクラウド Facebook┃

┗━━━━━━━━━━━━━┛

——————————————————————————————————

この記事を書いた人

aws-recipe-user