Use CreateDocument com um AWS SDK ou CLI - AWS SDK Exemplos de código

Há mais AWS SDK exemplos disponíveis no GitHub repositório AWS Doc SDK Examples.

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Use CreateDocument com um AWS SDK ou CLI

Os exemplos de códigos a seguir mostram como usar CreateDocument.

Exemplos de ações são trechos de código de programas maiores e devem ser executados em contexto. É possível ver essa ação no contexto no seguinte exemplo de código:

CLI
AWS CLI

Para criar um documento

O exemplo de create-document a seguir cria um documento do Systems Manager.

aws ssm create-document \ --content file://exampleDocument.yml \ --name "Example" \ --document-type "Automation" \ --document-format YAML

Saída:

{ "DocumentDescription": { "Hash": "fc2410281f40779e694a8b95975d0f9f316da8a153daa94e3d9921102EXAMPLE", "HashType": "Sha256", "Name": "Example", "Owner": "29884EXAMPLE", "CreatedDate": 1583256349.452, "Status": "Creating", "DocumentVersion": "1", "Description": "Document Example", "Parameters": [ { "Name": "AutomationAssumeRole", "Type": "String", "Description": "(Required) The ARN of the role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to execute this document.", "DefaultValue": "" }, { "Name": "InstanceId", "Type": "String", "Description": "(Required) The ID of the Amazon EC2 instance.", "DefaultValue": "" } ], "PlatformTypes": [ "Windows", "Linux" ], "DocumentType": "Automation", "SchemaVersion": "0.3", "LatestVersion": "1", "DefaultVersion": "1", "DocumentFormat": "YAML", "Tags": [] } }

Para obter mais informações, consulte Criar documentos do Systems Manager no Guia do usuário do AWS Systems Manager.

  • Para API obter detalhes, consulte CreateDocumentna Referência de AWS CLI Comandos.

Java
SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

/** * Creates an AWS SSM document asynchronously. * * @param docName The name of the document to create. * <p> * This method initiates an asynchronous request to create an SSM document. * If the request is successful, it prints the document status. * If an exception occurs, it handles the error appropriately. */ public void createSSMDoc(String docName) throws SsmException { String jsonData = """ { "schemaVersion": "2.2", "description": "Run a simple shell command", "mainSteps": [ { "action": "aws:runShellScript", "name": "runEchoCommand", "inputs": { "runCommand": [ "echo 'Hello, world!'" ] } } ] } """; CreateDocumentRequest request = CreateDocumentRequest.builder() .content(jsonData) .name(docName) .documentType(DocumentType.COMMAND) .build(); CompletableFuture<CreateDocumentResponse> future = getAsyncClient().createDocument(request); future.thenAccept(response -> { System.out.println("The status of the SSM document is " + response.documentDescription().status()); }).exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof DocumentAlreadyExistsException) { throw new CompletionException(cause); } else if (cause instanceof SsmException) { throw new CompletionException(cause); } else { throw new RuntimeException(cause); } }).join(); }
  • Para API obter detalhes, consulte CreateDocumentem AWS SDK for Java 2.x APIReferência.

PowerShell
Ferramentas para PowerShell

Exemplo 1: esse exemplo cria um documento na sua conta. O documento deve estar em JSON formato. Para obter mais informações sobre como escrever um documento de configuração, consulte Documento de configuração na SSM API Referência.

New-SSMDocument -Content (Get-Content -Raw "c:\temp\RunShellScript.json") -Name "RunShellScript" -DocumentType "Command"

Saída:

CreatedDate : 3/1/2017 1:21:33 AM DefaultVersion : 1 Description : Run an updated script DocumentType : Command DocumentVersion : 1 Hash : 1d5ce820e999ff051eb4841ed887593daf77120fd76cae0d18a53cc42e4e22c1 HashType : Sha256 LatestVersion : 1 Name : RunShellScript Owner : 809632081692 Parameters : {commands} PlatformTypes : {Linux} SchemaVersion : 2.0 Sha1 : Status : Creating
  • Para API obter detalhes, consulte CreateDocumentem Referência de AWS Tools for PowerShell cmdlet.

Python
SDKpara Python (Boto3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

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 create(self, content, name): """ Creates a document. :param content: The content of the document. :param name: The name of the document. """ try: self.ssm_client.create_document( Name=name, Content=content, DocumentType="Command" ) self.name = name except self.ssm_client.exceptions.DocumentAlreadyExists: print(f"Document {name} already exists.") self.name = name except ClientError as err: logger.error( "Couldn't create %s. Here's why: %s: %s", name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise
  • Para API obter detalhes, consulte a CreateDocumentReferência AWS SDK do Python (Boto3). API