1

I want to run two commands in a remote server. The first checks if a service is active. I want to run the second only if the service is active, but I don’t know how to get the status from the first command.

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

func InstallRke2(ctx *pulumi.Context, connection *remote.ConnectionArgs) {
    ...

    statusRes, _ := remote.NewCommand(ctx, "is-rke2-server-active", &remote.CommandArgs{
        Connection: connection,
        Create:     pulumi.String("systemctl is-active rke2-server.service"),
    })

    // How do I get the result of the `systemctl` command at this point?
    // Do I use `ApplyT` on `res1.Stdout`?

    // The command below should run only if the service is `active`
    tokenRes, _ := remote.NewCommand(ctx, "get-registration-token", &remote.CommandArgs{
        Connection: connection,
        Create:     pulumi.String("cat /var/lib/rancher/rke2/server/node-token"),
        Triggers:   pulumi.All(statusRes.Create, statusRes.Stdin),
    }, pulumi.DependsOn([]pulumi.Resource{statusRes}))

...
}

I’ve read the command package docs and looked through all the examples but couldn’t find a solution.

Update: 3 May 2023, 14:40

Here's my solution using ApplyT and channels:

statusRes, _ := remote.NewCommand(ctx, "is-rke2-server-active"...)

statusChan := make(chan string)

statusRes.Stdout.ApplyT(func(status string) string {
    statusChan <- strings.TrimRight(status, "\n")
    return status
})

rke2Status := <-statusChan

close(statusChan)

if rke2Status == "active" {
    // get the token
}

Is this how most people do it or should we be doing something else?

nusantara
  • 1,109
  • 1
  • 15
  • 38

0 Answers0