登录
首页 >  Golang >  Go问答

解析 Pulumi 自动结果对象的结构或映射

来源:stackoverflow

时间:2024-03-27 08:51:36 128浏览 收藏

在 Pulumi 中使用 Go 自动化 API 部署服务器时,可以通过解析结果对象的映射结构来获取连接信息。首先,从 `res.outputs` 中检索结果,其为一个字符串,然后将其转换为映射。通过访问映射中的键,可以提取所需信息,例如主机地址、端口、私钥和用户。这种方式对于在 Go 测试中验证连接详细信息也很有用。

问题内容

我正在 go 中使用 pulumi 的自动化 api 将服务器部署到 hetzner,但不知道如何从部署结果中获取生成的连接信息。

这是截断的代码:

import (
    ...

    "github.com/pulumi/pulumi-command/sdk/go/command/remote"
    "github.com/pulumi/pulumi/sdk/v3/go/auto"
    "github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)

...

deployfunc := func(ctx *pulumi.context) error {
        // create ssh key pair, upload them to hetzner, get back a `*hcloud.sshkey`
        ...
        
        // `server` is a *hcloud.server object
        server, _ := deployservertohetzner(ctx, sshkey)

        // this is the info i want to retrieve from the result
        connectinfo := remote.connectionargs{
            host:       server.ipv4address,
            port:       pulumi.float64(22),
            user:       pulumi.string("root"),
            privatekey: sshkeypair.private,
        }

        ctx.export("server-connect-info", connectinfo)

        return nil
    }

stack, _ := auto.upsertstackinlinesource(ctx, stackname, projectname, deployfunc, opts...)

res, _ := stack.up(ctx)

// this is a string but i need it as either map or struct
serverconnectinfo := fmt.sprintf("%v", res.outputs["server-connect-info"].value)

我能够从 res.outputs 检索结果,但它是一个字符串。我知道服务器部署和带有连接详细信息的响应是成功的,因为当我登录 serverconnectinfo 时,它看起来像这样:

serverconnectinfo map[host:123.456.789.10 port:22 privatekey:-----begin openssh private key-----
b3blbnnza...
-----end openssh private key-----
user:root]

基于网上一些可疑的解决方案,我尝试像 json 一样对其进行编组,然后将其解组到 pulumi remote.connectionargs 实例中。这显然不起作用,因为结构如下所示:

// From https://pkg.go.dev/github.com/pulumi/pulumi-command/[email protected]/go/command/remote#ConnectionArgs

type ConnectionArgs struct {
    ...
    Host pulumi.StringInput `pulumi:"host"`
    Port pulumi.Float64PtrInput `pulumi:"port"`
    PrivateKey pulumi.StringPtrInput `pulumi:"privateKey"`
    User pulumi.StringPtrInput `pulumi:"user"`
}

我正在考虑构建自己的结构,然后重试 json 解组和编组解决方案,但似乎如果 connectionargs 结构已经具有 pulumi 标签,则应该在某处存在某种 pulumi.unmarshal 方法。我错了吗?反正我没找到。

我也查看了文档,但没有看到任何有帮助的内容。也许我漏掉了一页?


正确答案


正如 peter 在评论中指出的那样, res.outputs["server-connect-info"].value 是一个映射,并且正确地猜测我通过 fmt.sprintf 运行它。我真是太傻了。

这有效:

serverconnectinfo := res.outputs["server-connect-info"].value.(map[string]interface{})

使用内置测试包在 go 测试中也能很好地工作:

assert.NotEmpty(t, serverConnectInfo["host"])
assert.Equal(t, serverConnectInfo["user"], "root")

以上就是《解析 Pulumi 自动结果对象的结构或映射》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>