AWS Systems ManagerChange Managern'est plus ouvert aux nouveaux clients. Les clients existants peuvent continuer à utiliser le service normalement. Pour plus d'informations, consultez AWS Systems ManagerChange Managerla section Modification de la disponibilité.
Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.
Utilisation CreateOpsItem avec un AWS SDK ou une CLI
Les exemples de code suivants illustrent comment utiliser CreateOpsItem.
Les exemples d’actions sont des extraits de code de programmes de plus grande envergure et doivent être exécutés en contexte. Vous pouvez voir cette action en contexte dans l’exemple de code suivant :
- CLI
-
- AWS CLI
-
Pour créer un OpsItems
L'create-ops-itemexemple suivant utilise la clé /aws/resources OperationalData pour créer un OpsItem avec une ressource associée à Amazon DynamoDB.
aws ssm create-ops-item \
--title "EC2 instance disk full" \
--description "Log clean up may have failed which caused the disk to be full" \
--priority 2 \
--source ec2 \
--operational-data '{"/aws/resources":{"Value":"[{\"arn\": \"arn:aws:dynamodb:us-west-2:12345678:table/OpsItems\"}]","Type":"SearchableString"}}' \
--notifications Arn="arn:aws:sns:us-west-2:12345678:TestUser"
Sortie :
{
"OpsItemId": "oi-1a2b3c4d5e6f"
}
Pour plus d'informations, voir Creating OpsItems in the AWS Systems Manager User Guide.
- Java
-
- SDK pour Java 2.x
-
/**
* Creates an SSM OpsItem asynchronously.
*
* @param title The title of the OpsItem.
* @param source The source of the OpsItem.
* @param category The category of the OpsItem.
* @param severity The severity of the OpsItem.
* @return The ID of the created OpsItem.
* <p>
* This method initiates an asynchronous request to create an SSM OpsItem.
* If the request is successful, it returns the OpsItem ID.
* If an exception occurs, it handles the error appropriately.
*/
public String createSSMOpsItem(String title, String source, String category, String severity) {
CreateOpsItemRequest opsItemRequest = CreateOpsItemRequest.builder()
.description("Created by the SSM Java API")
.title(title)
.source(source)
.category(category)
.severity(severity)
.build();
CompletableFuture<CreateOpsItemResponse> future = getAsyncClient().createOpsItem(opsItemRequest);
try {
CreateOpsItemResponse response = future.join();
return response.opsItemId();
} catch (CompletionException e) {
Throwable cause = e.getCause();
if (cause instanceof SsmException) {
throw (SsmException) cause;
} else {
throw new RuntimeException(cause);
}
}
}
- JavaScript
-
- SDK pour JavaScript (v3)
-
import { CreateOpsItemCommand, SSMClient } from "@aws-sdk/client-ssm";
import { parseArgs } from "node:util";
/**
* Create an SSM OpsItem.
* @param {{ title: string, source: string, category?: string, severity?: string }}
*/
export const main = async ({
title,
source,
category = undefined,
severity = undefined,
}) => {
const client = new SSMClient({});
try {
const { opsItemArn, opsItemId } = await client.send(
new CreateOpsItemCommand({
Title: title,
Source: source, // The origin of the OpsItem, such as Amazon EC2 or Systems Manager.
Category: category,
Severity: severity,
}),
);
console.log(`Ops item created with id: ${opsItemId}`);
return { OpsItemArn: opsItemArn, OpsItemId: opsItemId };
} catch (caught) {
if (caught instanceof Error && caught.name === "MissingParameter") {
console.warn(`${caught.message}. Did you provide these values?`);
} else {
throw caught;
}
}
};
- Python
-
- Kit SDK for Python (Boto3)
-
class OpsItemWrapper:
"""Encapsulates AWS Systems Manager OpsItem actions."""
def __init__(self, ssm_client):
"""
:param ssm_client: A Boto3 Systems Manager client.
"""
self.ssm_client = ssm_client
self.id = None
@classmethod
def from_client(cls):
"""
:return: A OpsItemWrapper instance.
"""
ssm_client = boto3.client("ssm")
return cls(ssm_client)
def create(self, title, source, category, severity, description):
"""
Create an OpsItem
:param title: The OpsItem title.
:param source: The OpsItem source.
:param category: The OpsItem category.
:param severity: The OpsItem severity.
:param description: The OpsItem description.
"""
try:
response = self.ssm_client.create_ops_item(
Title=title,
Source=source,
Category=category,
Severity=severity,
Description=description,
)
self.id = response["OpsItemId"]
except self.ssm_client.exceptions.OpsItemLimitExceededException as err:
logger.error(
"Couldn't create ops item because you have exceeded your open OpsItem limit. "
"Here's why: %s: %s",
err.response["Error"]["Code"],
err.response["Error"]["Message"],
)
raise
except ClientError as err:
logger.error(
"Couldn't create ops item %s. Here's why: %s: %s",
title,
err.response["Error"]["Code"],
err.response["Error"]["Message"],
)
raise
Pour obtenir la liste complète des guides de développement du AWS SDK et des exemples de code, consultezUtilisation de ce service avec un AWS SDK. Cette rubrique comprend également des informations sur le démarrage et sur les versions précédentes du kit SDK.