amazon-web-servicesboto3aws-cliaws-ssm

boto3: How to receive output after calling ecs execute_command


I want to send commands to a ecs/FARGATE container using python/boto3. I can successfully open a session using execute_command.

But how can I get output of the command? And wait until its done?

I find a a lot about the aws cli and the session-manager-plugin. So one way would be to run the aws cli from python. But is there also a way to get the output of the command from native python?


Solution

  • You can re-implement the same procedure that aws execute-command uses internally:

                # making an execute-command call to connect to an
                # active session on a container would require
                # session-manager-plugin to be installed on the client machine.
                # Hence, making this empty session-manager-plugin call
                # before calling execute-command to ensure that
                # session-manager-plugin is installed
                # before execute-command-command is made
                check_call(["session-manager-plugin"])
                client = self._session.create_client(
                ...
                response = client.execute_command(**parameters)
                ...
                ssm_request_params = build_ssm_request_paramaters(response, client)
                # ignore_user_entered_signals ignores these signals
                # because if signals which kills the process are not
                # captured would kill the foreground process but not the
                # background one. Capturing these would prevents process
                # from getting killed and these signals are input to plugin
                # and handling in there
                with ignore_user_entered_signals():
                    # call executable with necessary input
                    check_call(["session-manager-plugin",
                    ...
    

    The commit message by the author of this code summarizes the approach:

    https://github.com/aws/aws-cli/commit/ba4163d46969a8aba0e4712852aba9ad5a3f3667

    CLI CUSTOMIZATION FOR ECS EXECUTE-COMMAND API

    • ECS execute-command API returns a streamUrl and a token-value using a user can connect to a session inside a running container by calling session-manager-plugin with those values.
    • This CLI customization makes this call for the user, thus internally making two calls.