テンプレートパラメータに従って、Cloudformationテンプレートで可変数のEC2インスタンスリソースを作成するにはどうすればよいですか?
EC2 APIと管理ツールを使用すると、同じAMIの複数のインスタンスを起動できますが、Cloudformationを使用してこれを行う方法がわかりません。
テンプレートパラメータに従って、Cloudformationテンプレートで可変数のEC2インスタンスリソースを作成するにはどうすればよいですか?
EC2 APIと管理ツールを使用すると、同じAMIの複数のインスタンスを起動できますが、Cloudformationを使用してこれを行う方法がわかりません。
Resource は基礎となる API の/パラメータをAWS::EC2::Instance
サポートしていないため、このResource の 1 つのコピーにパラメータを渡すことによって可変数の EC2 インスタンスを作成することはできません。MinCount
MaxCount
RunInstances
テンプレート パラメータに従って CloudFormation テンプレートに可変数の EC2 インスタンス リソースを作成し、代わりに Auto Scaling グループをデプロイしない場合は、次の 2 つのオプションがあります。
パラメータに応じてConditions
可変数のリソースを作成するために使用できます。AWS::EC2::Instance
少し冗長ですが ( を使用する必要があるためFn::Equals
)、機能します。
ユーザーが最大5 つのインスタンスを指定できる実際の例を次に示します。
Description: Create a variable number of EC2 instance resources.
Parameters:
InstanceCount:
Description: Number of EC2 instances (must be between 1 and 5).
Type: Number
Default: 1
MinValue: 1
MaxValue: 5
ConstraintDescription: Must be a number between 1 and 5.
ImageId:
Description: Image ID to launch EC2 instances.
Type: AWS::EC2::Image::Id
# amzn-ami-hvm-2016.09.1.20161221-x86_64-gp2
Default: ami-9be6f38c
InstanceType:
Description: Instance type to launch EC2 instances.
Type: String
Default: m3.medium
AllowedValues: [ m3.medium, m3.large, m3.xlarge, m3.2xlarge ]
Conditions:
Launch1: !Equals [1, 1]
Launch2: !Not [!Equals [1, !Ref InstanceCount]]
Launch3: !And
- !Not [!Equals [1, !Ref InstanceCount]]
- !Not [!Equals [2, !Ref InstanceCount]]
Launch4: !Or
- !Equals [4, !Ref InstanceCount]
- !Equals [5, !Ref InstanceCount]
Launch5: !Equals [5, !Ref InstanceCount]
Resources:
Instance1:
Condition: Launch1
Type: AWS::EC2::Instance
Properties:
ImageId: !Ref ImageId
InstanceType: !Ref InstanceType
Instance2:
Condition: Launch2
Type: AWS::EC2::Instance
Properties:
ImageId: !Ref ImageId
InstanceType: !Ref InstanceType
Instance3:
Condition: Launch3
Type: AWS::EC2::Instance
Properties:
ImageId: !Ref ImageId
InstanceType: !Ref InstanceType
Instance4:
Condition: Launch4
Type: AWS::EC2::Instance
Properties:
ImageId: !Ref ImageId
InstanceType: !Ref InstanceType
Instance5:
Condition: Launch5
Type: AWS::EC2::Instance
Properties:
ImageId: !Ref ImageId
InstanceType: !Ref InstanceType
上記のバリエーションとして、Ruby のErbのようなテンプレート プリプロセッサを使用して、指定された最大数に基づいて上記のテンプレートを生成し、ソース コードをよりコンパクトにして重複を排除することができます。
<%max = 10-%>
Description: Create a variable number of EC2 instance resources.
Parameters:
InstanceCount:
Description: Number of EC2 instances (must be between 1 and <%=max%>).
Type: Number
Default: 1
MinValue: 1
MaxValue: <%=max%>
ConstraintDescription: Must be a number between 1 and <%=max%>.
ImageId:
Description: Image ID to launch EC2 instances.
Type: AWS::EC2::Image::Id
# amzn-ami-hvm-2016.09.1.20161221-x86_64-gp2
Default: ami-9be6f38c
InstanceType:
Description: Instance type to launch EC2 instances.
Type: String
Default: m3.medium
AllowedValues: [ m3.medium, m3.large, m3.xlarge, m3.2xlarge ]
Conditions:
Launch1: !Equals [1, 1]
Launch2: !Not [!Equals [1, !Ref InstanceCount]]
<%(3..max-1).each do |x|
low = (max-1)/(x-1) <= 1-%>
Launch<%=x%>: !<%=low ? 'Or' : 'And'%>
<% (1..max).each do |i|
if low && i >= x-%>
- !Equals [<%=i%>, !Ref InstanceCount]
<% elsif !low && i < x-%>
- !Not [!Equals [<%=i%>, !Ref InstanceCount]]
<% end
end
end-%>
Launch<%=max%>: !Equals [<%=max%>, !Ref InstanceCount]
Resources:
<%(1..max).each do |x|-%>
Instance<%=x%>:
Condition: Launch<%=x%>
Type: AWS::EC2::Instance
Properties:
ImageId: !Ref ImageId
InstanceType: !Ref InstanceType
<%end-%>
上記のソースを CloudFormation 互換のテンプレートに処理するには、次を実行します。
ruby -rerb -e "puts ERB.new(ARGF.read, nil, '-').result" < template.yml > template-out.yml
便宜上、10 個の変数 EC2 インスタンスに対して生成された出力 YAML の要点を次に示します。
/ API を直接呼び出すカスタム リソースを実装する別の方法もあります。RunInstances
TerminateInstances
Description: Create a variable number of EC2 instance resources.
Parameters:
InstanceCount:
Description: Number of EC2 instances (must be between 1 and 10).
Type: Number
Default: 1
MinValue: 1
MaxValue: 10
ConstraintDescription: Must be a number between 1 and 10.
ImageId:
Description: Image ID to launch EC2 instances.
Type: AWS::EC2::Image::Id
# amzn-ami-hvm-2016.09.1.20161221-x86_64-gp2
Default: ami-9be6f38c
InstanceType:
Description: Instance type to launch EC2 instances.
Type: String
Default: m3.medium
AllowedValues: [ m3.medium, m3.large, m3.xlarge, m3.2xlarge ]
Resources:
EC2Instances:
Type: Custom::EC2Instances
Properties:
ServiceToken: !GetAtt EC2InstancesFunction.Arn
ImageId: !Ref ImageId
InstanceType: !Ref InstanceType
MinCount: !Ref InstanceCount
MaxCount: !Ref InstanceCount
EC2InstancesFunction:
Type: AWS::Lambda::Function
Properties:
Handler: index.handler
Role: !GetAtt LambdaExecutionRole.Arn
Code:
ZipFile: !Sub |
var response = require('cfn-response');
var AWS = require('aws-sdk');
exports.handler = function(event, context) {
var physicalId = event.PhysicalResourceId || 'none';
function success(data) {
return response.send(event, context, response.SUCCESS, data, physicalId);
}
function failed(e) {
return response.send(event, context, response.FAILED, e, physicalId);
}
var ec2 = new AWS.EC2();
var instances;
if (event.RequestType == 'Create') {
var launchParams = event.ResourceProperties;
delete launchParams.ServiceToken;
ec2.runInstances(launchParams).promise().then((data)=> {
instances = data.Instances.map((data)=> data.InstanceId);
physicalId = instances.join(':');
return ec2.waitFor('instanceRunning', {InstanceIds: instances}).promise();
}).then((data)=> success({Instances: instances})
).catch((e)=> failed(e));
} else if (event.RequestType == 'Delete') {
if (physicalId == 'none') {return success({});}
var deleteParams = {InstanceIds: physicalId.split(':')};
ec2.terminateInstances(deleteParams).promise().then((data)=>
ec2.waitFor('instanceTerminated', deleteParams).promise()
).then((data)=>success({})
).catch((e)=>failed(e));
} else {
return failed({Error: "In-place updates not supported."});
}
};
Runtime: nodejs4.3
Timeout: 300
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal: {Service: [lambda.amazonaws.com]}
Action: ['sts:AssumeRole']
Path: /
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: EC2Policy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- 'ec2:RunInstances'
- 'ec2:DescribeInstances'
- 'ec2:DescribeInstanceStatus'
- 'ec2:TerminateInstances'
Resource: ['*']
Outputs:
Instances:
Value: !Join [',', !GetAtt EC2Instances.Instances]
元のポスターが後になっていたのは次のようなものだと思います。
"Parameters" : {
"InstanceCount" : {
"Description" : "Number of instances to start",
"Type" : "String"
},
..。
"MyAutoScalingGroup" : {
"Type" : "AWS::AutoScaling::AutoScalingGroup",
"Properties" : {
"AvailabilityZones" : {"Fn::GetAZs" : ""},
"LaunchConfigurationName" : { "Ref" : "MyLaunchConfiguration" },
"MinSize" : "1",
"MaxSize" : "2",
"DesiredCapacity" : **{ "Ref" : "InstanceCount" }**,
}
},
...つまり、パラメータから初期インスタンスの数(容量)を挿入します。
一方、利用可能なAWS CloudFormation サンプル テンプレートは多数あり、通常は他の機能を並行してデモンストレーションしますが、複数のインスタンスを起動するものもいくつかあります。たとえば、AutoScalingKeepAtNSample.templateは、負荷分散された Auto Scaled サンプル Web サイトを作成し、このテンプレートの抜粋に従って、この目的のために 2 つの EC2 インスタンスを開始するように構成されています。
"WebServerGroup": {
"Type": "AWS::AutoScaling::AutoScalingGroup",
"Properties": {
"AvailabilityZones": {
"Fn::GetAZs": ""
},
"LaunchConfigurationName": {
"Ref": "LaunchConfig"
},
"MinSize": "2",
"MaxSize": "2",
"LoadBalancerNames": [
{
"Ref": "ElasticLoadBalancer"
}
]
}
},
より高度な/完全なサンプルも利用できます。たとえば、マルチ AZ Amazon RDS データベース インスタンスを備えた高可用性 Web サーバーの Drupal テンプレートや、ファイル コンテンツの保存に S3 を使用するなどです。これは現在、1 ~ 5 個の Web サーバー インスタンスが通信できるように構成されています。マルチ AZ MySQL Amazon RDSデータベース インスタンスに接続し、 Auto Scalingを介してウェブ サーバー インスタンスを調整するElastic Load Balancerの背後で実行されます。
機能を使用してくださいRef
。
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-ref.html
ユーザー定義変数は、"Parameters"
構成ファイルのセクションで定義されます。構成ファイルの"Resources"
セクションでは、これらのパラメーターへの参照を使用して値を入力できます。
{
"AWSTemplateFormatVersion": "2010-09-09",
...
"Parameters": {
"MinNumInstances": {
"Type": "Number",
"Description": "Minimum number of instances to run.",
"Default": "1",
"ConstraintDescription": "Must be an integer less than MaxNumInstances."
},
"MaxNumInstances": {
"Type": "Number",
"Description": "Maximum number of instances to run.",
"Default": "5",
"ConstraintDescription": "Must be an integer greater than MinNumInstances."
},
"DesiredNumInstances": {
"Type": "Number",
"Description": "Number of instances that need to be running before creation is marked as complete in CloudFormation management console.",
"Default": "1",
"ConstraintDescription": "Must be an integer in the range specified by MinNumInstances..MaxNumInstances."
}
},
"Resources": {
"MyAutoScalingGroup": {
"Type": "AWS::AutoScaling::AutoScalingGroup",
"Properties": {
...
"MinSize": { "Ref": "MinNumInstances" },
"MaxSize": { "Ref": "MaxNumInstances" },
"DesiredCapacity": { "Ref": "DesiredNumInstances" },
...
},
},
...
},
...
}
上記の例{ "Ref": ... }
では、テンプレートに値を入力するために使用されています。この場合、"MinSize"
との値として整数を提供しています"MaxSize"
。