gpt4 book ai didi

go - GCP 计算 API 在旧模式下创建 VPC

转载 作者:行者123 更新时间:2023-12-03 01:26:24 24 4
gpt4 key购买 nike

我正在使用以下 Go 程序在我的 Google Cloud Platform 项目中创建 VPC。

func CreateGCPClient(ctx context.Context) (*compute.Service, error) {
cred := option.WithCredentialsFile(path)
return compute.NewService(ctx, cred)
}

func CreateNetworksService(s *compute.Service) *compute.NetworksService {
return compute.NewNetworksService(s)
}

func CreateVPC(ctx context.Context, ns *compute.NetworksService, name string) (*compute.Operation, error) {
net := &compute.Network{
Name: name,
AutoCreateSubnetworks: false,
IPv4Range: "",
}
return ns.Insert(projectID, net).Context(ctx).Do()
}

func main() {
log.SetFlags(log.Lshortfile)
ctx := context.Background()
clt, err := CreateGCPClient(ctx)
if err != nil {
log.Fatal(err)
}
netserv := CreateNetworksService(clt)

out, err := CreateVPC(ctx, netserv, "test")
if err != nil {
log.Fatal(err)
}
log.Printf("Out: %+v\n", out)
}

这是在传统模式而不是自定义模式下创建VPC。 Documentation表示 IPv4Range 字段已弃用。事实上,首先我尝试从compute.Network结构中完全删除它。但它给出了相同的结果。

显然,每当该程序创建 VPC 时,GCP 都会自动为其分配默认私有(private) CIDR (10.240.0.0/16)。

我做错了什么?

最佳答案

Terraform 已找到此问题的修复程序:link 。显然,除非 ForceSendFields 属性明确告知,否则 AutoCreateSubnetworks 字段不包含在请求负载中。

实际上,这是有效的:

func CreateVPC(ctx context.Context, ns *compute.NetworksService, name string) (*compute.Operation, error) {
net := &compute.Network{
Name: name,
AutoCreateSubnetworks: false,
// make sure AutoCreateSubnetworks field is included in request
ForceSendFields: []string{"AutoCreateSubnetworks"},
}
return ns.Insert(projectID, net).Context(ctx).Do()
}

ForceSendFields 的文档明确指出,请求负载中会省略所有空字段。不幸的是,它没有说明的是,如果省略 AutoCreateSubnetworks ,则 VPC 将以旧模式创建。

By default, fields with empty values are omitted from API requests. However, any non-pointer, non-interface field appearing in ForceSendFields will be sent to the server regardless of whether the field is empty or not.

关于go - GCP 计算 API 在旧模式下创建 VPC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59058750/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com