首页 > 解决方案 > 使用 kubectl 或其他 ansible 模块(如命令、脚本)在 pod 中运行 shell 命令

问题描述

我有一本带有 kubectl 命令的剧本,当我想运行此命令时,它无法避免引号并理解此目录不存在

--- 
    - 
      hosts: localhost

      vars_files: 
        - vars/main.yaml 


      tasks:     
        -
         shell:
           cmd: |
               kubectl exec -it -n {{ namespace }} {{ pod_name }} -- bash -c \"clickhouse-client --query "INSERT INTO customer FORMAT CSV" --user=test --password=test < /mnt/azure/azure/test/test.tbl\"
         register: output2

这是错误:

fatal: [127.0.0.1]: FAILED! => {
    "changed": true,
    "cmd": "kubectl exec -it -n ch-test04 chi-test-dashboard-sharded1-dashboard03-3-0-0 -- bash -c \\\"clickhouse-client --query \"INSERT INTO customer FORMAT CSV\" --user=test --password=test < mnt/azure/azure/test/test.tbl\\\"\n",
    "delta": "0:00:00.002088",
    "end": "2020-04-23 13:30:00.456263",
    "invocation": {
        "module_args": {
            "_raw_params": "kubectl exec -it -n ch-test04 chi-test-dashboard-sharded1-dashboard03-3-0-0 -- bash -c \\\"clickhouse-client --query \"INSERT INTO customer FORMAT CSV\" --user=test --password=test < mnt/azure/azure/test/test.tbl\\\"\n",
            "_uses_shell": true,
            "argv": null,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "stdin": null,
            "stdin_add_newline": true,
            "strip_empty_ends": true,
            "warn": true
        }
    },
    "msg": "non-zero return code",
    "rc": 2,
    "start": "2020-04-23 13:30:00.454175",
    "stderr": "/bin/sh: 1: cannot open mnt/azure/azure/test/test.tbl\": No such file",
    "stderr_lines": [
        "/bin/sh: 1: cannot open mnt/azure/azure/test/test.tbl\": No such file"
    ],
    "stdout": "",
    "stdout_lines": []
}

因此,当我将此命令放在 python 脚本中时,ansible 仍然会使用引号并得到相同的错误。我已经尝试过转义/引用,但我认为问题是当我在查询后使用“<”字符时,从插入数据和ansible 无法理解整个命令尚未完成。但我不确定如何用正确的方式分辨。谢谢

标签: pythonkubernetesansible

解决方案


你引用了错误的字符;您希望内部引号被转义,或者回避整个混乱并使用内部外部的替代字符:

- shell: |
    kubectl exec -i -n {{ namespace }} {{ pod_name }} -- bash -c 'clickhouse-client --query "INSERT INTO customer FORMAT CSV" --user=test --password=test < /mnt/azure/azure/test/test.tbl'

推荐阅读