resource "tencentcloud_instance" "cvm" { tags = { key1: "val1", key2: "val2" }}
一、Tag 代码实现
通过云 API 对资源添加 Tag 有两种实现方式。第一种是通过 CreateAPI 参数传入,代码如下:
rsType := "instance"request := cvm.NewRunInstanceRequest()request.TagSpecification = append(request.TagSpecification, &cvm.TagSpecification{ ResourceType: &rsType, Tags: []*cvm.Tag{ { Key: &key, Value: &value, }, },})
需要注意的是,目前仅有部分资源的创建 API 支持传入 Tag,且数据结构也有所不同。为了统一管理 Tag 代码,我们采用第二种方式,即创建后单独调用 Tag API 关联,入参为 资源六段式,格式为:
qcs:<project_id,此处置空>:<模块>:<地域>:<账号/uin>:<资源/ID>
以 VPC 举例,如要修改 VPC 实例关联的 Tag,入参如下:
qcs::vpc:ap-singapore:uin/:vpc/vpc-xxxxxxxx
代码中则调用封装好的 ModifyTags 即可:
package mainfunc ResourceTencentCloudVPCUpdate(d *schema.ResourceData, meta interface{}) { ctx := context.TODO() region := meta.(*TencentCloudClient).apiV3Conn.Region id := d.Id() resourceName := fmt.Sprintf("qcs::vpc:%s:uin/:vpc/%s", region, id) replaceTags, deleteTags := diffTags(oldTags.(map[string]interface{}), newTags.(map[string]interface{})) if err := tagService.ModifyTags(ctx, resourceName, replaceTags, deleteTags); err != nil { return err }}