AWS CDK:将字符串映射到 EC2 InstanceSize
AWS CDK: Mapping of string to EC2 InstanceSize
我正在尝试在 CDK 中进行构建。它应该启动一个 EC2 实例,它的大小应该取决于输入字符串。所以 string="micro" 应该创建一个 MICRO 实例,而 string="medium" 应该创建一个 MEDIUM 实例。我想我应该使用映射,所以我尝试了不同的组合:
const partitionMapping = new cdk.CfnMapping(this, 'PartitionMapping', {
mapping: {
'type': {"micro" : ec2.InstanceSize.MICRO, "medium" : ec2.InstanceSize.MEDIUM}},
}
});
但是当我尝试将映射用于字符串设置为“micro”的 ec2 实例时:
const inst = new ec2.Instance(this, 'persinst', {
instanceType: ec2.InstanceType.of(ec2.InstanceClass.T2, partitionMapping.findInMap("type", string),
machineImage: new ec2.AmazonLinuxImage({
generation: ec2.AmazonLinuxGeneration.AMAZON_LINUX_2
}),
vpc,
vpcSubnets: {
subnets: [subnets_ids.subnets[0]]
}
});
我收到错误:
lib/create-ec2-stack.ts:43:61 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'InstanceSize'.
43 instanceType: ec2.InstanceType.of(ec2.InstanceClass.T2, partitionMapping.findInMap("type", "micro")),
我期待它从与“micro”关联的“type”映射中获取值,“micro”是 EC2 的 InstanceSize。
如何确保 EC2 实例的实例大小直接取决于我的输入参数“string”?
我想你要找的是输入参数而不是映射。无论哪种方式InstanceType
都可以通过两种方式创建
静态方法InstanceType.of
或将类型作为字符串传递给构造函数new InstanceType()
假设类型作为输入参数进入 cdk
const instanceSizeParm = new cdk.CfnParameter(this, "instance-size", {
allowedValues: ["micro", "medium", "large"],
type: "String",
});
我们可以通过将连接值作为字符串传递给构造函数来创建 InstanceType 对象。
instanceType: new ec2.InstanceType(
`${ec2.InstanceClass.T2}.${instanceSizeParm.valueAsString}`
),
我正在尝试在 CDK 中进行构建。它应该启动一个 EC2 实例,它的大小应该取决于输入字符串。所以 string="micro" 应该创建一个 MICRO 实例,而 string="medium" 应该创建一个 MEDIUM 实例。我想我应该使用映射,所以我尝试了不同的组合:
const partitionMapping = new cdk.CfnMapping(this, 'PartitionMapping', {
mapping: {
'type': {"micro" : ec2.InstanceSize.MICRO, "medium" : ec2.InstanceSize.MEDIUM}},
}
});
但是当我尝试将映射用于字符串设置为“micro”的 ec2 实例时:
const inst = new ec2.Instance(this, 'persinst', {
instanceType: ec2.InstanceType.of(ec2.InstanceClass.T2, partitionMapping.findInMap("type", string),
machineImage: new ec2.AmazonLinuxImage({
generation: ec2.AmazonLinuxGeneration.AMAZON_LINUX_2
}),
vpc,
vpcSubnets: {
subnets: [subnets_ids.subnets[0]]
}
});
我收到错误:
lib/create-ec2-stack.ts:43:61 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'InstanceSize'.
43 instanceType: ec2.InstanceType.of(ec2.InstanceClass.T2, partitionMapping.findInMap("type", "micro")),
我期待它从与“micro”关联的“type”映射中获取值,“micro”是 EC2 的 InstanceSize。
如何确保 EC2 实例的实例大小直接取决于我的输入参数“string”?
我想你要找的是输入参数而不是映射。无论哪种方式InstanceType
都可以通过两种方式创建
静态方法InstanceType.of
或将类型作为字符串传递给构造函数new InstanceType()
假设类型作为输入参数进入 cdk
const instanceSizeParm = new cdk.CfnParameter(this, "instance-size", {
allowedValues: ["micro", "medium", "large"],
type: "String",
});
我们可以通过将连接值作为字符串传递给构造函数来创建 InstanceType 对象。
instanceType: new ec2.InstanceType(
`${ec2.InstanceClass.T2}.${instanceSizeParm.valueAsString}`
),