Uso de ListCommandInvocations con un AWS SDK o la CLI - AWS Systems Manager

Uso de ListCommandInvocations con un AWS SDK o la CLI

En los siguientes ejemplos de código, se muestra cómo utilizar ListCommandInvocations.

Los ejemplos de acciones son extractos de código de programas más grandes y deben ejecutarse en contexto. Puede ver esta acción en contexto en el siguiente ejemplo de código:

CLI
AWS CLI

Enumeración de las invocaciones de un comando específico

En el siguiente ejemplo de list-command-invocations se enumeran todas las invocaciones de un comando.

aws ssm list-command-invocations \ --command-id "ef7fdfd8-9b57-4151-a15c-db9a12345678" \ --details

Salida:

{ "CommandInvocations": [ { "CommandId": "ef7fdfd8-9b57-4151-a15c-db9a12345678", "InstanceId": "i-02573cafcfEXAMPLE", "InstanceName": "", "Comment": "b48291dd-ba76-43e0-b9df-13e11ddaac26:6960febb-2907-4b59-8e1a-d6ce8EXAMPLE", "DocumentName": "AWS-UpdateSSMAgent", "DocumentVersion": "", "RequestedDateTime": 1582136283.089, "Status": "Success", "StatusDetails": "Success", "StandardOutputUrl": "", "StandardErrorUrl": "", "CommandPlugins": [ { "Name": "aws:updateSsmAgent", "Status": "Success", "StatusDetails": "Success", "ResponseCode": 0, "ResponseStartDateTime": 1582136283.419, "ResponseFinishDateTime": 1582136283.51, "Output": "Updating amazon-ssm-agent from 2.3.842.0 to latest\nSuccessfully downloaded https://s3.us-east-2.amazonaws.com/amazon-ssm-us-east-2/ssm-agent-manifest.json\namazon-ssm-agent 2.3.842.0 has already been installed, update skipped\n", "StandardOutputUrl": "", "StandardErrorUrl": "", "OutputS3Region": "us-east-2", "OutputS3BucketName": "", "OutputS3KeyPrefix": "" } ], "ServiceRole": "", "NotificationConfig": { "NotificationArn": "", "NotificationEvents": [], "NotificationType": "" }, "CloudWatchOutputConfig": { "CloudWatchLogGroupName": "", "CloudWatchOutputEnabled": false } }, { "CommandId": "ef7fdfd8-9b57-4151-a15c-db9a12345678", "InstanceId": "i-0471e04240EXAMPLE", "InstanceName": "", "Comment": "b48291dd-ba76-43e0-b9df-13e11ddaac26:6960febb-2907-4b59-8e1a-d6ce8EXAMPLE", "DocumentName": "AWS-UpdateSSMAgent", "DocumentVersion": "", "RequestedDateTime": 1582136283.02, "Status": "Success", "StatusDetails": "Success", "StandardOutputUrl": "", "StandardErrorUrl": "", "CommandPlugins": [ { "Name": "aws:updateSsmAgent", "Status": "Success", "StatusDetails": "Success", "ResponseCode": 0, "ResponseStartDateTime": 1582136283.812, "ResponseFinishDateTime": 1582136295.031, "Output": "Updating amazon-ssm-agent from 2.3.672.0 to latest\nSuccessfully downloaded https://s3.us-east-2.amazonaws.com/amazon-ssm-us-east-2/ssm-agent-manifest.json\nSuccessfully downloaded https://s3.us-east-2.amazonaws.com/amazon-ssm-us-east-2/amazon-ssm-agent-updater/2.3.842.0/amazon-ssm-agent-updater-snap-amd64.tar.gz\nSuccessfully downloaded https://s3.us-east-2.amazonaws.com/amazon-ssm-us-east-2/amazon-ssm-agent/2.3.672.0/amazon-ssm-agent-snap-amd64.tar.gz\nSuccessfully downloaded https://s3.us-east-2.amazonaws.com/amazon-ssm-us-east-2/amazon-ssm-agent/2.3.842.0/amazon-ssm-agent-snap-amd64.tar.gz\nInitiating amazon-ssm-agent update to 2.3.842.0\namazon-ssm-agent updated successfully to 2.3.842.0", "StandardOutputUrl": "", "StandardErrorUrl": "", "OutputS3Region": "us-east-2", "OutputS3BucketName": "", "OutputS3KeyPrefix": "8bee3135-398c-4d31-99b6-e42d2EXAMPLE/i-0471e04240EXAMPLE/awsupdateSsmAgent" } ], "ServiceRole": "", "NotificationConfig": { "NotificationArn": "", "NotificationEvents": [], "NotificationType": "" }, "CloudWatchOutputConfig": { "CloudWatchLogGroupName": "", "CloudWatchOutputEnabled": false } } ] }

Para obtener más información, consulte Descripción de los estados del comando en la Guía del usuario de AWS Systems Manager.

  • Para obtener información sobre la API, consulte ListCommandInvocations en la Referencia de comandos de la AWS CLI.

JavaScript
SDK para JavaScript (v3)
nota

Hay más en GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import { paginateListCommandInvocations, SSMClient } from "@aws-sdk/client-ssm"; import { parseArgs } from "node:util"; /** * List SSM command invocations on an instance. * @param {{ instanceId: string }} */ export const main = async ({ instanceId }) => { const client = new SSMClient({}); try { const listCommandInvocationsPaginated = []; // The paginate function is a wrapper around the base command. const paginator = paginateListCommandInvocations( { client }, { InstanceId: instanceId, }, ); for await (const page of paginator) { listCommandInvocationsPaginated.push(...page.CommandInvocations); } console.log("Here is the list of command invocations:"); console.log(listCommandInvocationsPaginated); return { CommandInvocations: listCommandInvocationsPaginated }; } catch (caught) { if (caught instanceof Error && caught.name === "ValidationError") { console.warn(`${caught.message}. Did you provide a valid instance ID?`); } throw caught; } };
  • Para obtener detalles sobre la API, consulte ListCommandInvocations en la Referencia de la API deAWS SDK for JavaScript.

PowerShell
Herramientas para PowerShell

Ejemplo 1: en este ejemplo se enumeran todas las invocaciones de un comando.

Get-SSMCommandInvocation -CommandId "b8eac879-0541-439d-94ec-47a80d554f44" -Detail $true

Salida:

CommandId : b8eac879-0541-439d-94ec-47a80d554f44 CommandPlugins : {aws:runShellScript} Comment : IP config DocumentName : AWS-RunShellScript InstanceId : i-0cb2b964d3e14fd9f InstanceName : NotificationConfig : Amazon.SimpleSystemsManagement.Model.NotificationConfig RequestedDateTime : 2/22/2017 8:13:16 PM ServiceRole : StandardErrorUrl : StandardOutputUrl : Status : Success StatusDetails : Success TraceOutput :

Ejemplo 2: en este ejemplo se enumeran los CommandPlugins para la invocación del comando con el identificador e1eb2e3c-ed4c-5123-45c1-234f5612345f

Get-SSMCommandInvocation -CommandId e1eb2e3c-ed4c-5123-45c1-234f5612345f -Detail:$true | Select-Object -ExpandProperty CommandPlugins

Salida:

Name : aws:runPowerShellScript Output : Completed 17.7 KiB/17.7 KiB (40.1 KiB/s) with 1 file(s) remainingdownload: s3://dd-aess-r-ctmer/KUMO.png to ..\..\programdata\KUMO.png kumo available OutputS3BucketName : OutputS3KeyPrefix : OutputS3Region : eu-west-1 ResponseCode : 0 ResponseFinishDateTime : 4/3/2019 11:53:23 AM ResponseStartDateTime : 4/3/2019 11:53:21 AM StandardErrorUrl : StandardOutputUrl : Status : Success StatusDetails : Success
  • Para obtener información sobre la API, consulte ListCommandInvocations en la Referencia de Cmdlet de AWS Tools for PowerShell.

Python
SDK para Python (Boto3)
nota

Hay más en GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

class DocumentWrapper: """Encapsulates AWS Systems Manager Document actions.""" def __init__(self, ssm_client): """ :param ssm_client: A Boto3 Systems Manager client. """ self.ssm_client = ssm_client self.name = None @classmethod def from_client(cls): ssm_client = boto3.client("ssm") return cls(ssm_client) def list_command_invocations(self, instance_id): """ Lists the commands for an instance. :param instance_id: The ID of the instance. :return: The list of commands. """ try: paginator = self.ssm_client.get_paginator("list_command_invocations") command_invocations = [] for page in paginator.paginate(InstanceId=instance_id): command_invocations.extend(page["CommandInvocations"]) num_of_commands = len(command_invocations) print( f"{num_of_commands} command invocation(s) found for instance {instance_id}." ) if num_of_commands > 10: print("Displaying the first 10 commands:") num_of_commands = 10 date_format = "%A, %d %B %Y %I:%M%p" for command in command_invocations[:num_of_commands]: print( f" The time of command invocation is {command['RequestedDateTime'].strftime(date_format)}" ) except ClientError as err: logger.error( "Couldn't list commands for %s. Here's why: %s: %s", instance_id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise
  • Para obtener información sobre la API, consulte ListCommandInvocations en la Referencia de la API del AWSSDK para Python (Boto3).

Para obtener una lista completa de las guías para desarrolladores de AWS SDK y ejemplos de código, consulte Uso de este servicio con un AWS SDK. En este tema también se incluye información sobre cómo comenzar a utilizar el SDK y detalles sobre sus versiones anteriores.