Use kubectl or other ansible module like command, script to run shell command in a pod

4/23/2020

I have a playbook with kubectl command, when I want to run this command it cannot avoid quotes and understand this directory not exist

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

Here is the error:

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": []
}

So when I put this command in a python script ansible still manuplate quotes and got the same error. I already tried escape/quote but I think the problem is when I use '<' character after query where from insert data and ansible cannot understand entire command not finished yet. But I am not sure how can I tell with the correct way.Thanks

-- Bora Özkan
ansible
kubernetes
python

1 Answer

4/23/2020

You quoted the wrong characters; you want the interior quotes to be escaped, or sidestep that entire mess and use alternate characters for the outer from the inner:

- 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'
-- mdaniel
Source: StackOverflow