Equivalent to cat <<EOF in golang

huangapple go评论90阅读模式
英文:

Equivalent to cat <<EOF in golang

问题

我正在尝试执行以下代码的等效操作:

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

在golang中。

我目前的尝试可以简化为:

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))
}

我并不感到特别惊讶它没有起作用,出现了错误:

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

我意识到我正在将它们作为参数传递,而kubectl期望一个文件,但我完全不知道如何继续下去。

我不想创建一个临时文件或调用一个单独的bash脚本,因为这似乎比我希望的更混乱。

英文:

I am trying to perform the equiavalent of this:

cat &lt;&lt;EOF | kubectl apply -f -
apiVersion: v1
kind: ConfigMap
metadata:
  name: testMap
  namespace: default
data:
  details:
    host: &quot;localhost:${reg_port}&quot;
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: &quot;localhost:&quot; + port`
}

func main() {
  exec.Command(&quot;kubectl&quot;, &quot;apply&quot;, &quot;-f&quot;, &quot;-&quot;, 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: &quot;localhost:5000&quot;]

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.

答案1

得分: 5

这里是将命令的标准输入(stdin)设置为generateConfig函数结果的方法:

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

if err := cmd.Run(); err != nil {
    // 处理错误
}

在这里,shell的here document被重定向到命令的stdin。

英文:

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(&quot;kubectl&quot;, &quot;apply&quot;, &quot;-f&quot;, &quot;-&quot;)
cmd.Stdin = strings.NewReader(generateConfig(&quot;5000&quot;))

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

huangapple
  • 本文由 发表于 2021年11月21日 02:41:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/70048852.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定