我应该将什么类类型传递给 Pulumi 参数以使其工作?

问题描述

我试图将标签作为自定义对象类作为参数传递给 Pulumi,因为我可以根据需要设置 Name 属性。问题是它不起作用。由于缺乏 JS/TS 知识,我不明白它想从我这里得到什么。

谁能给我一个线索?

import * as aws from "@pulumi/aws";

class Common_tags_test {
  
  Name!: string;
  Owner: string = 'test';
  ManagedBy: string =  'Pulumi';

  constructor() {}

  set_name(name: string) {
    this.Name = name
  }

}


// const common_tags = {
//   Owner: 'test',//   ManagedBy: 'Pulumi'
// };

const main_vpc = new aws.ec2.Vpc("Test_VPC",{
  cidrBlock: "10.10.0.0/16",// tags: {...common_tags,...{Name: 'Test_VPC'}}
  tags: new Common_tags_test()
});

错误

    TSError: ⨯ Unable to compile TypeScript:
    index.ts(29,3): error TS2322: Type 'Common_tags_test' is not assignable to type '{ [key: string]: Input<string>; } | Promise<{ [key: string]: Input<string>; }> | OutputInstance<{ [key: string]: Input<string>; }> | undefined'.
      Type 'Common_tags_test' is not assignable to type '{ [key: string]: Input<string>; }'.
        Index signature is missing in type 'Common_tags_test'.
``

解决方法

因为 typescript 允许强类型属性,所以 Common_tags_test 属性不期望存在 import * as aws from "@pulumi/aws"; const baseTags = { Owner: "test",ManagedBy: "Pulumi" }; const vpc = new aws.ec2.Vpc("vpc",{ tags: { ...baseTags,Name: "my-vpc" },cidrBlock: "10.10.0.0/" }) 类型。

你以前有正确的想法,做类似的事情

import * as aws from "@pulumi/aws";

class CommonTags {
  Name!: string;
  Owner: string = "test";
  ManagedBy: string = "Pulumi";

  constructor() {}

  setTags(name: string) :any {
      return {
          Name: name,Owner: this.Owner,ManagedBy: this.ManagedBy
      }
  }

}

let mytags = new CommonTags();

const vpc = new aws.ec2.Vpc("vpc",{
  tags: {
    ...mytags.setTags("My-VPC")
  },cidrBlock: "10.10.0.0/16",});

如果你真的想使用一个类,你可以执行以下操作:

ssd_resnet50_v1_fpn_640x640_coco17_tpu-8

就我个人而言,我会使用第一种方式。仍然可以通过将它们放在一个模块中并共享来重复使用它们。