filekubernetespostexec

C# Kubernetes Client Exec Command into Pod Container Issue


I have a custom web application written in .NET7 and I am using Kubernetes Client (C#) to interact with a Kubernetes Cluster (Azure). So far so good, everything is working as expected unit I reached the point where I need to communicate with a Pod Container.

Let' start with an easy example by just creating a new file:

The following command returns BadRequest regardless what I have tried so far:

string command_test = "touch servers_.json";
var stream_test = client.CoreV1.ConnectPostNamespacedPodExec(podname, space, command_test, container, true, true, false, false);

Then switched to WebSocketNamespacedPodExecAsync instead of ConnectPostNamespacedPodExec (uses vargs) and then I noticed the following (in this example I try to make a file with content):

//string[] command_test = { "touch servers_.json" }; //DOES NOT WORK
//string[] command_test = { "touch", "servers_.json" }; //DOES WORK
client.WebSocketNamespacedPodExecAsync(podname, space, command_test, container, true, true, false, false).Result;

In the above example seems that the touch command works when every word is separated by comma and quotes.

//string[] command_test = { "echo 'test' > servers_.json" }; //DOES NOT WORK
//string[] command_test = { "echo", "'test' > servers_.json" }; //DOES NOT WORK
//string[] command_test = { "echo", "'test'", ">", "servers_.json" }; //DOES NOT WORK
//var websocket_test = client.WebSocketNamespacedPodExecAsync(podname, space, command_test, container, true, true, false, false).Result;

But the same scenario using echo does not work whatever I tried even by splitting the words like the touch command.

Any ideas?


Solution

  • Finally I found the answers: This is because the redirection operator (>) is interpreted by the shell, not by the echo command. Therefore, you need to invoke a shell to execute your command with the redirection. For example, you can try this:

    string[] command_test = { "/bin/sh", "-c", "echo 'test' > servers_.json" };