Home > OS >  Equivalent to cat <<EOF in golang
Equivalent to cat <<EOF in golang

Time:11-22

I am trying to perform the equiavalent of this:

cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: ConfigMap
metadata:
  name: testMap
  namespace: default
data:
  details:
    host: "localhost:${reg_port}"
EOF

in golang.

My current attempt boils down to:

func generateConfig(port string) string {
    return `
apiVersion: v1
kind: ConfigMap
metadata:
  name: testMap
  namespace: default
data:
  details:
    host: "localhost:"   port`
}

func main() {
  exec.Command("kubectl", "apply", "-f", "-", generateConfig(5000))
}

I was not particularly surprised to find it did not work, with error:

error: Unexpected args: [
apiVersion: v1
kind: ConfigMap
metadata:
    name: testMap
    namespace: default
data:
    details:
        host: "localhost:5000"]

I recognise that I am passing these as args and that kubectl expects a file, however I find myself at a complete loss at how I might continue.

I would rather not make a temporary file or call a separate bash script since this seems messier than I would hope is necessary.

CodePudding user response:

The shell here document is directed to the command's stdin.

Here's how to set the command's stdin to the result of generateConfig:

cmd := exec.Command("kubectl", "apply", "-f", "-")
cmd.Stdin = strings.NewReader(generateConfig("5000"))

if err := cmd.Run(); err != nil {
    // handle error
}
  • Related