如何在IamInstanceProfile中使用cdktf设置单元测试角色



我正在编写cdktf(在typescript中)来对组件进行单元测试,以组成一些基础设施。我想知道如何测试角色在IamInstanceProfile中是否正确设置。考虑到它是自动生成的(使用synth),似乎没有内置的方法来检查。

设置iamRole为iamInstanceProfile的代码

export class Roles extends Construct {
iamRole: IamRole;
iamInstanceProfile: IamInstanceProfile;
constructor(scope: Construct, id: string) {
super(scope, id);
this.iamRole = new IamRole(this, "xxx", {
assumeRolePolicy: this.getPolicy().json,
managedPolicyArns: [
"arn:aws:iam::aws:policy/xxx"
],
name: "xxx"
});
this.iamInstanceProfile = new IamInstanceProfile(this, "yyy", {
name: "test_profile",
role: this.iamRole.name
});
}

单元测试

const stack = Testing.synth( new MyStack(new App(), "RunnerTest", baseConfig));
expect(stack).toHaveResourceWithProperties(IamInstanceProfile, {
name: 'test_profile',
role: '<???HOW-TO-GET-THIS-VALUE???>'
});

误差

Error: Expected aws_iam_instance_profile with properties {"name":"test_profile","role":"<???HOW-TO-GET-THIS-VALUE???>"} to be present in synthesized stack.
Found 1 aws_iam_instance_profile resources instead:
[
{
"name": "test_profile",
"role": "<AUTO_GENERATED>"
}
]

不通过stackjson输出解析,是否可以找到角色的生成值?

.name是一个引用,将产生一个内容为${aws_iam_role.<ID>.name}的字符串。问题是这里的ID部分包含一个散列(以便这些id可以保持全局唯一,同时在构造内部和外部具有相同的名称),因此无法猜测。要找到它,您可以使用快照测试或控制台日志,但是为了适应更改,您要么需要构建一个找到它的函数,要么可以使用.overrideLogicalId("new_id")函数覆盖IAMRole的ID。如果您在类上公开角色,您甚至可以在测试用例中这样做。