簡體   English   中英

在AWS CloudFormation中,是否可以使用Mappings中沒有AutoScaling組的值創建多個EC2實例?

[英]In AWS CloudFormation is it possible to create a number of EC2 instances with the values from Mappings without AutoScaling group?

假設我想為每個InstanceType創建一個EC2實例,否則它們是相同的。

所以我會像這樣創建一個映射:

 "Mappings" : { "MyAWSInstanceTypes" : [ "t1.micro", "m1.small", "m1.medium", "m1.large", "m1.xlarge", "m3.xlarge", "m3.2xlarge", "m2.xlarge", "m2.2xlarge", "m2.4xlarge", "c1.medium", "c1.xlarge", "cc1.4xlarge", "cc2.8xlarge", "cg1.4xlarge", "hi1.4xlarge", "hs1.8xlarge" ], 

后來我想擁有

  "Resources" : { "MyEc2Instances" : { "Type" : "AWS::EC2::Instance", 

我會神奇地獲取根據映射創建的所有實例類型。

沒有AutoScaling可以嗎?

聽起來你想循環遍歷每個實例類型,創建其中一個。 這在CloudFormation模板中是不可能的。

您可以以編程方式生成模板。 troposphere Python庫提供了一個很好的抽象來生成模板。 例如:

import json
from troposphere import Template, ec2


types = [
    "t1.micro",
    "m1.small",
    "m1.medium",
    "m1.large",
    "m1.xlarge",
    "m3.xlarge",
    "m3.2xlarge",
    "m2.xlarge",
    "m2.2xlarge",
    "m2.4xlarge",
    "c1.medium",
    "c1.xlarge",
    "cc1.4xlarge",
    "cc2.8xlarge",
    "cg1.4xlarge",
    "hi1.4xlarge",
    "hs1.8xlarge"]
ami = "ami-12345678"
t = Template()

for type in types:
    t.add_resource(ec2.Instance(
        type.replace('.', ''), #resource names must be alphanumeric
        ImageId=ami,
        InstanceType=type,
        ))

print t.to_json()

在為客戶端使用一些cloudformation模板后,我們也遇到了同樣的挑戰者。 本質上,我們想循環一個列表實例類型來生成spotfleet啟動配置,但我們不想在我們的模板中手動復制這些代碼。

我們已經嘗試過@Ben Whaley提到的對流層,但它不太適合我們的場景,因為我們需要用python重寫現有的cloudformation模板。

經過一番調查,我們決定使用帶有ejs-cli的EJS模板生成程序化的雲信息模板,它允許我們插入變量並將不同的片段包含在目標CFT中。

  • 片段管理

    Resources: <% include ./partials/resources.yml %> ...

  • 可變插值

    apiTaskDefinition: Type: AWS::ECS::TaskDefinition DependsOn: ECSTaskRole Properties: ContainerDefinitions: - Name: api Essential: true Image: <%= container_path %>/api Memory: <%= container.api.memory %>

  • 循環列表

    Properties: SpotFleetRequestConfigData: IamFleetRole: !GetAtt iamFleetRole.Arn SpotPrice: !Ref 'ECSSpotPrice' TargetCapacity: !Ref 'DesiredCapacity' TerminateInstancesWithExpiration: false AllocationStrategy: lowestPrice LaunchSpecifications: <% for(var i in instancesTypes) {%> <% include ./partials/instance-launch-specification.yml %> <% } %>

你可以在這里找到演示源代碼和我們的博客文章

不可能,您無法在模板中指定迭代。 但是,您可以為每個實例類型創建實例資源。 這是復制和粘貼的問題。 為了便於告知CloudFormation在堆棧創建時運行哪些實例,您可以在模板中指定函數條件 例如,您可以創建一個或多個參數來指示要啟動的實例類型,並使用條件僅啟動您指定的實例類型。

2018年9月6日推出了AWS CloudFormation宏,在AWS Reinvent:2018中進行了解釋。 現在,您可以將lambda函數添加到模板的部署中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM