首页 > 解决方案 > 在 C# 中使用 CDK 将 EC2 实例分配给现有 VPC

问题描述

我想使用现有 VPC 启动 EC2 实例。在Vpc参数中,我传递了现有的 VPC Id。当我为以下代码执行cdk synth时,我收到Vpc.fromLookup() 的所有参数必须是具体的(无令牌)错误

using Amazon.CDK;
using Amazon.CDK.AWS.EC2;
using System.Collections.Generic;
using Amazon.CDK.AWS.S3;
using Amazon.CDK.AWS.S3.Assets;
using System.IO;

namespace StandardCf
{
    public class StandardCfStack : Stack
    {
        internal StandardCfStack(Construct scope, string id, IStackProps props) : base(scope, id, props)
        {
            string[] instancetypeArray = new string[] { "t2.large","t3.large" };

            //Parameters
            //1. Key Pair Name
            var keyPairName = new CfnParameter(this, "Key Pair Name", new CfnParameterProps { Type = "String", Description = "The name of the Existing Key Pair. This key pair will be added to the set of keys authorized for this instance." });
            //2. Instance Type
            var InstanceType = new CfnParameter( this, "InstanceLauncherType", new CfnParameterProps { Type = "String", Description= "Amazon EC2 instance type for the Instance, Choose t3.large for regions US East, Africa (Cape Town), Middle East (Bahrain), Asia Pacific (Hong Kong), EU (Milan) and EU (Stockholm)", AllowedValues = instancetypeArray, Default = "t2.large"} );
            //3. Existing VPC Id
            var ExistingVPCId = new CfnParameter(this, "VpcID", new CfnParameterProps { Type = "AWS::EC2::VPC::Id", Description = "Please enter the VPC ID to choose existing VPC"});

            // VPC Creation
            var vpc = Vpc.FromLookup(this, "VPC", new VpcLookupOptions
            {
                VpcId = ExistingVPCId.ValueAsString
            });

            // Security Group Creation
            var InstanceSecurityGroup = new SecurityGroup(this, "SecurityGroup", new SecurityGroupProps
            {
                Vpc = vpc,
                 SecurityGroupName = "STANDARD-SG",
                Description = "Security Group for Standard Instance",
                AllowAllOutbound = true
            });
            // Security Group's Inbound and Outbound rules
            InstanceSecurityGroup.AddIngressRule(Peer.AnyIpv4(), Port.Tcp(22), "Allows public SSH access");
            InstanceSecurityGroup.AddIngressRule(Peer.AnyIpv4(), Port.Tcp(80), "Apache Web Server Access");
            InstanceSecurityGroup.AddIngressRule(Peer.AnyIpv6(), Port.Tcp(80), "Apache Web Server Access");
            InstanceSecurityGroup.AddIngressRule(Peer.AnyIpv4(), Port.Tcp(8080), "Apache Tomcat Access");
            InstanceSecurityGroup.AddIngressRule(Peer.AnyIpv6(), Port.Tcp(8080), "Apache Tomcat Access");
            InstanceSecurityGroup.AddIngressRule(Peer.AnyIpv4(), Port.Tcp(8161), "Apache ActiveMQ Web UI Access");
            InstanceSecurityGroup.AddIngressRule(Peer.AnyIpv6(), Port.Tcp(8161), "Apache ActiveMQ Web UI Access");
            InstanceSecurityGroup.AddIngressRule(Peer.AnyIpv4(), Port.Tcp(61616), "Apache ActiveMQ Broker Access");
            InstanceSecurityGroup.AddIngressRule(Peer.AnyIpv6(), Port.Tcp(61616), "Apache ActiveMQ Broker Access");

            // Configuring custom CENOTS AMI
            IDictionary<string, string> d = new Dictionary<string, string>();
           
            d.Add(new KeyValuePair<string, string>(Region,"ami-026f33d38b6410e30"));
          
            var customAWSAMI = MachineImage.GenericLinux(d);

            var path = Directory.GetCurrentDirectory();

            // Comments for user data script
            var userdata = UserData.ForLinux();
            userdata.AddCommands("yum install -y wget", "cd /tmp/", "mkdir user-data-script", "cd user-data-script/", "wget some-url-for-shell-file", "cd ../../", "sh /tmp/user-data-script/shell-script.sh");
            

            // Instance Detail Configuration
            var ec2Instance = new Instance_(this, "Instance", new InstanceProps
            {
                Vpc = vpc,
                InstanceType = new InstanceType(InstanceType.ValueAsString),
                MachineImage = customAWSAMI,
                SecurityGroup = InstanceSecurityGroup,
                
                KeyName = keyPairName.ValueAsString,
                InstanceName = "STANDARD",
                UserData = userdata
            });
        }
    }
}

如何传递 EC2 实例的现有 VPC Id?

标签: c#amazon-web-servicesamazon-ec2aws-cdk

解决方案


我遇到了这种确切的情况,发现您需要能够在合成/部署期间使用 --context (-c) 选项传递字符串。有一些方法可以从范围中获取上下文。

所以我的代码是这样来获取 VPC 实例的:

 var vpcLookupOptions = new VpcLookupOptions
 {
     VpcId = scope.Node.TryGetContext("vpcId").ToString()
 };
 var vpc = Vpc.FromLookup(this, id, vpcLookupOptions);

合成模板的命令如下所示:

cdk synth StandardStack -c vpcId="vpc-1234567a"

如果要传递多个上下文值,请再次为每个键/值对使用 --context 选项。

cdk synth -c key1="value1" -c key2="value2"

在引导和部署时,您也将使用相同的 --context 值。

这篇文章非常有用:https ://stackoverflow.com/a/64576653/3870069


推荐阅读