Executing a Command in an Anbox Container using AMS SDK

Hello everyone,

I wanted to share a useful snippet of Go code that I’ve found helpful in my project. This demonstrates how you can execute a command in an Anbox container using the Anbox Cloud AMS SDK.

First, we assume that you have a valid instance of the clientImpl (which implements the client interface in the Anbox Cloud AMS SDK).

c := &clientImpl{}

Next, you should define the container ID where you want to run the command. For example:

id := "your-container-id"

Then, define the command details that you want to run in the container.

details := &api.ContainerExecPost{
	Command:     []string{"ls", "-la"},
	Environment: map[string]string{"HOME": "/root"},
	WaitForWS:   true,
	Interactive: true,
}

Here, we want to run the ls -la command.

Prepare your input/output streams. In this example, we are redirecting the output to the console.

stdin, _ := io.Pipe()

args := &ContainerExecArgs{
	Stdin:  stdin,
	Stdout: os.Stdout, // redirecting the command output to the console
	Stderr: os.Stderr, // redirecting the errors to the console
	Control: func(conn *websocket.Conn) {
		defer conn.Close()

		for {
			_, _, err := conn.ReadMessage()
			if err != nil {
				log.Println("error reading websocket message:", err)
				break
			}
		}
	},
	DataDone: make(chan bool),
}

Now we are ready to run the command in the container:

op, err := c.ExecuteContainer(id, details, args)
if err != nil {
	log.Fatalf("failed to execute command in container: %s", err)
}

err = op.Wait()
if err != nil {
	log.Fatalf("operation failed: %s", err)
}

This block of code will execute the command in the container and wait for the operation to complete.

I hope you find this useful! Let me know if you have any questions or suggestions.

Best,
Paolo

1 Like

this example is what i need!!! great! thanks a lot!

You’re welcome! I’m really glad you found the example helpful. If you have any more questions or need further assistance, please don’t hesitate to ask. Happy coding!

1 Like

@kernelmode I have moved the post under the Anbox Cloud > users category which is a place for all user discussions and questions from the Anbox Cloud user community.

Hi @keirthana,

Thank you for rearranging the post. I appreciate your efforts to keep the forum organized and ensuring that the information is in the correct place. This will undoubtedly make it easier for others in the community to find and benefit from.

Thanks again for your assistance!

Best,
Paolo