Search code examples
bashubuntuazure-cliazure-container-instances

Automate az container exec


AZ CLI supports executing a single command in a running container.

az container exec -g myresourcegroup -n nginxtest --exec-command /bin/bash

Because of this, you cannot automate running multiple commands over existing container directly as you can with docker.

Is it possible to go around this with stdin, stdout, stderr redirection or multiplexing?


Solution

  • I learned how to do it with the screen multiplexer!

    Setup

    sudo screen -S azexec -dmL bash

    • This creates a new detached terminal running bash with name azexec
    • The -L argument makes all output to be be saved into a file screenlog.0
    • The -d argument makes the terminal detached
    • Right now it just starts a new bash terminal

    sudo screen -S azexec -p 0 -X stuff "az container exec -g myresourcegroup -n nginxtest --exec-command /bin/bash^M"

    • You send az container exec and after some time, the detached terminal switches to the container terminal
    • If you are trying to automate this, you need to sleep for some time to let the az command enter before running any other

    Run any commands

    sudo screen -S azexec -p 0 -X stuff "ANY_COMMAND^M"

    • don't forget the stuff keyword
    • don't forget to add ^M at the end of your commands, it simulates the enter key

    Warning

    • When using a multiplexer you have the control over the terminal, not over the commands that you run inside the terminal. You need to sleep or handle completion of your commands some other way.
    • If you just installed screen then you will not see the az package installed in its terminal. But after you install it once in the screen terminal with apt it stays there. It should be trivial to automate that process.
    • You also need to az login with --service-principal if you want to automate this with Azure Pipelines
    • I wrote a complete script to run in Azure Pipelines here: https://github.com/czmirek/stuff/blob/master/azexecmultiple/script.sh