Cannot write commands to Azure CLI Image
- Dominant language
- C#
- Stars
- 2.4k
- Forks
- 416
- PR merge metrics
- No merged PRs in 30d
Description
I am using the [Azure CLI Docker Image](https://hub.docker.com/r/microsoft/azure-cli) with the Docker.DotNet.
I would like to pass command line commands to the CLI and get the response.
**Code So Far**
```
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Docker.DotNet;
using Docker.DotNet.Models;
using Docker.Services;
namespace Docker
{
class Program
{
const string deamonUrl = "tcp://localhost:2375";
private static DockerClient _client;
static async Task Main(string[] args)
{
_client = new DockerClientConfiguration(
new Uri(deamonUrl))
.CreateClient();
var imageName = "mcr.microsoft.com/azure-cli:latest";
var images = new Images(_client);
Console.WriteLine($"Create Image {imageName}");
await images.CreateImage(imageName);
var createContainerParams = new CreateContainerParameters
{
Image = imageName,
ArgsEscaped = true,
AttachStderr = true,
AttachStdin = true,
AttachStdout = true,
OpenStdin = true,
Entrypoint = new []{"bash"}
};
Console.WriteLine($"Create Container {imageName}");
var container = await _client.Containers.CreateContainerAsync(createContainerParams);
Console.WriteLine($"Container ID: ${container.ID}");
if (container.Warnings.Any())
foreach (var warning in container.Warnings)
Console.WriteLine($"Warning (${container.ID}): ${warning} ");
Console.WriteLine($"Start Container {container.ID}");
var containerStarted =
await _client.Containers.StartContainerAsync(container.ID, new ContainerStartParameters());
Console.WriteLine($"Container {container.ID} Started ${containerStarted}");
const string appUser = "";
const string appPassword = "";
const string appTenant = "";
var servicePrincipalSignIn =
$"az login --service-principal -u {appUser} -p {appPassword} --tenant {appTenant}";
var servicePrincipalSignInCommands = servicePrincipalSignIn.Split(" ").ToList();
Console.WriteLine(" ------ LOGIN ------ ");
await WriteExec(container.ID, servicePrincipalSignInCommands );
var userScript = $"az account list{Environment.NewLine}rgName=\"nancytest\" {Environment.NewLine} vmlist=$(az account list) {Environment.NewLine} echo $vmlist {Environment.NewLine} echo 'script has run'";
var userCommands = userScript.Split(Environment.NewLine).ToList();
var bashCommands = new List{"bash"};
Console.WriteLine(" ------ WRITE STREAM ------ ");
await dockerExec.WriteExec(containerId, bashCommands,"",userScript);
Console.WriteLine(" ------ WRITE COMMAND ------ ");
await dockerExec.WriteExec(containerId, userCommands);
}
private static async Task WriteExec(string containerId, List commands, string commandStr = "")
{
var containerExecCreate = new ContainerExecCreateParameters
{
AttachStderr = true,
AttachStdin = true,
AttachStdout = true,
Cmd = commands,
Detach = true,
Tty = true,
Privileged = true
};
var execCreateResponse = await _client.Exec.ExecCreateContainerAsync(containerId, containerExecCreate);
using var multiplexedStream = await _client.Exec.StartWithConfigContainerExecAsync(execCreateResponse.ID,
new ContainerExecStartParameters { Detach=false,Tty=false});
if (!string.IsNullOrEmpty(commandStr))
await WriteCommandToStream(multiplexedStream, commandStr);
await ReadOutputAsync(multiplexedStream);
multiplexedStream.CloseWrite();
multiplexedStream.Dispose();
}
private static async Task WriteCommandToStream(MultiplexedStream multiplexedStream, string command, CancellationToken cancellationToken = default)
{
Console.WriteLine("Write Command");
var wsBuffer = Encoding.UTF8.GetBytes(command);
await multiplexedStream.WriteAsync(wsBuffer.Concat(Encoding.ASCII.GetBytes(Environment.NewLine)).ToArray(), 0, wsBuffer.Length, default);
}
private static async Task ReadOutputAsync(MultiplexedStream multiplexedStream, CancellationToken cancellationToken = default)
{
Console.WriteLine("Read OutPut");
var dockerBuffer = System.Buffers.ArrayPool.Shared.Rent(81920);
try
{
while (true)
{
// Clear buffer
Array.Clear(dockerBuffer, 0, dockerBuffer.Length);
var dockerReadResult = await multiplexedStream.ReadOutputAsync(dockerBuffer, 0, dockerBuffer.Length, cancellationToken);
if (dockerReadResult.EOF)
break;
if (dockerReadResult.Count > 0)
{
var responseLine = Encoding.Default.GetString(dockerBuffer, 0, dockerReadResult.Count);
responseLine = responseLine
.Replace(@"\?\[0m", "")
.Replace("?[m", "")
.Replace("?[1;34", "");
Console.WriteLine(responseLine);
}
else
break;
}
}
catch (Exception ex)
{
//_logger.LogError(ex, "Failure during Read from Docker Exec to WebSocket");
}
System.Buffers.ArrayPool.Shared.Return(dockerBuffer);
}
}
}
```
**Output of `dotnet --info`:**
```
.NET SDK (reflecting any global.json):
Version: 5.0.101
Commit: d05174dc5a
Runtime Environment:
OS Name: Windows
OS Version: 10.0.18363
OS Platform: Windows
RID: win10-x64
Base Path: C:\Program Files\dotnet\sdk\5.0.101\
Host (useful for support):
Version: 5.0.1
Commit: b02e13abab
.NET SDKs installed:
2.1.511 [C:\Program Files\dotnet\sdk]
3.1.101 [C:\Program Files\dotnet\sdk]
3.1.102 [C:\Program Files\dotnet\sdk]
3.1.301 [C:\Program Files\dotnet\sdk]
5.0.101 [C:\Program Files\dotnet\sdk]
.NET runtimes installed:
Microsoft.AspNetCore.All 2.1.15 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
Microsoft.AspNetCore.App 2.1.15 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
Microsoft.AspNetCore.App 3.1.1 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
Microsoft.AspNetCore.App 3.1.2 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
Microsoft.AspNetCore.App 3.1.5 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
Microsoft.AspNetCore.App 5.0.1 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
Microsoft.NETCore.App 2.1.15 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.NETCore.App 3.1.1 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.NETCore.App 3.1.2 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.NETCore.App 3.1.5 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.NETCore.App 5.0.1 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
Microsoft.WindowsDesktop.App 3.1.1 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]
Microsoft.WindowsDesktop.App 3.1.2 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]
Microsoft.WindowsDesktop.App 3.1.5 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]
Microsoft.WindowsDesktop.App 5.0.1 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]
```
**What version of Docker.DotNet?:**
```
Version=3.125.0.0
```
**Steps to reproduce the issue:**
1. run the code above (sorry if can't copy/paste to run I have it in a larger project)
2.
3.
**What actually happened?:**
The WRITE COMMAND failed as below
```
------ LOGIN -----
Read OutPut
[
{
"cloudName": "AzureCloud",
"homeTenantId": "00000-a490-4728-00000-1d1446b68e5e",
"id": "00000-1e7c-408e-00000-eee54781a586",
"isDefault": true,
"managedByTenants": [],
"name": "Development",
"state": "Enabled",
"tenantId": "00000-a490-4728-00000-1d1446b68e5e",
"user": {
"name": "00000-1143-4d84-00000-d792cda35e29",
"type": "servicePrincipal"
}
}
]
?[0m
------ WRITE COMMAND ------
Read OutPut
OCI runtime exec failed: exec failed: container_linux.go:370: starting container process caused: exec: "$Accounts=$(ac account list)": executable file not found in $PATH: unknown
```
The WRITE STREAM fails as it stops after the last command in the `ReadOutputAsync` and no breakpoints in the method get hit after running this and the program does not complete.
**What did you expect to happen?:**
It to run each command given to it.
**Additional information:**
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.