.NET - 使用 AWS CDK 为 .NET 的低级 CloudFormation 资源构造标记 EC2 实例

.NET - Tagging an EC2 Instance using AWS CDK for .NET's low-level CloudFormation Resource constructs

趁着大家都在等更高阶/手写Construct to be available for creating an EC2 instance using AWS CDK, I'm trying to use the auto-generated low-level CloudFormation Resource available at Amazon.CDK.AWS.EC2.cloudformation.InstanceResource_ in the Amazon.CDK.AWS.EC2 NuGet package.

我的测试应用程序是一个 .NET Core 控制台应用程序,Amazon.CDK.AWS.EC2 NuGet package 作为唯一的其他依赖项。这是代码:

using System;
using System.Linq;

namespace AWSCDKEval
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new app. The first argument is used to display a usage message for this app.
            var appArgs = new [] { $"dotnet ${nameof(AWSCDKEval)}" }
                .Concat(args)
                .ToArray();
            var app = new Amazon.CDK.App(appArgs);

            new TestStack(app, "test-aws-cdk-stack-1", new Amazon.CDK.StackProps());

            // Your app must write the return value of app.Run() to standard output. The `cdk init`
            // and `cdk synth` commands require this output.
            Console.WriteLine(app.Run());
        }
    }

    public class TestStack : Amazon.CDK.Stack
    {
        public TestStack(Amazon.CDK.App parent, string name, Amazon.CDK.IStackProps props) : base(parent, name, props)
        {
            new Amazon.CDK.AWS.EC2.cloudformation.InstanceResource_(
                this, 
                "testInstance1", 
                new Amazon.CDK.AWS.EC2.cloudformation.InstanceResourceProps
                {
                    ImageId = "ami-0f1155cc2cb6b0cfd", // Microsoft Windows Server 2016 Base
                    InstanceType = "t2.micro",
                    KeyName = "my_key",
                    Tags = new []
                    {
                        new Amazon.CDK.Tag { Key = "Name", Value = "test-instance-1" },
                        new Amazon.CDK.Tag { Key = "foo", Value = "bar" }
                    }
                });
        }
    }
}

然后您编译项目并使用 CDK synth 将其 synth 到 CloudFormation 模板和所有设置中,但 tags 成功。

dotnet build <folder-with-code>
cdk synth --output <folder-where-to-write-cf-templates>

并且输出:

Resources:
    testInstance1:
        Type: 'AWS::EC2::Instance'
        Properties:
            ImageId: ami-0f1155cc2cb6b0cfd
            InstanceType: t2.micro
            KeyName: my_key
    CDKMetadata:
        Type: 'AWS::CDK::Metadata'
        Properties:
            Modules: '@aws-cdk/aws-ec2=0.9.1,@aws-cdk/aws-iam=0.9.1,@aws-cdk/cdk=0.9.1,@aws-cdk/cx-api=0.9.1,js-base64=2.4.9'

现在,我完全理解 CDK 处于非常早期的阶段,不推荐用于任何开发工作,但最好的部分是我计划使用的 cloudformation 命名空间下的所有本机资源的可用性在 CDK 增长的同时。

如能提供正确方向的帮助,我们将不胜感激!

原来,这也是currently a bug in AWS CDK and does work if you use typescript instead of any C# .NET. I've logged an issue