C# CDK Aspect

I recently stumbled across CDK Aspects on the AWS open source news and updates new letter. There was a link to an example Tag checker that I thought I would try out in C#.

I originally had the class defined as

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class TagAspect :  IAspect
{
private readonly IList<string> _requiredTags;

public TagAspect(IList<string> requiredTags)
{
_requiredTags = requiredTags;
}

public void Visit(IConstruct node)
{
if (node is Stack stack)
{
foreach (var requiredTag in _requiredTags)
{
if (!stack.Tags.TagValues().ContainsKey(requiredTag))
{
Annotations.Of(node).AddError($"Missing required tag {requiredTag} on stack with id {stack.StackName}");
}
}
}
}
}

But when I ran CDK synth I got this error

1
2
Unhandled exception. System.ArgumentException: Could not convert argument 'DeployLambda.TagAspect' to Jsii (Parameter 'arguments')
at Amazon.JSII.Runtime.Deputy.DeputyBase.<>c__DisplayClass20_0.<ConvertArguments>b__0(Parameter parameter, Object frameworkArgument)

After a bit of Googling I found there is a known issue with an easy fix. You just need to make sure the aspect class inherites from Amazon.Jsii.Runtime.Deputy.DeputyBase

The working code is

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class TagAspect : Amazon.JSII.Runtime.Deputy.DeputyBase, IAspect
{
private readonly IList<string> _requiredTags;

public TagAspect(IList<string> requiredTags)
{
_requiredTags = requiredTags;
}

public void Visit(IConstruct node)
{
if (node is Stack stack)
{
foreach (var requiredTag in _requiredTags)
{
if (!stack.Tags.TagValues().ContainsKey(requiredTag))
{
Annotations.Of(node).AddError($"Missing required tag {requiredTag} on stack with id {stack.StackName}");
}
}
}
}
}

You wire this in to the program.cs

1
Aspects.Of(app).Add(new TagAspect(new List<string>{"owner"}));

Which gives this error is we don’t have a owner tag set

1
2
[Error at /lambda-pipeline] Missing required tag owner on stack with id lambda-pipeline
Found errors

Excample code