### Get started with Amazon EC2 using JavaScript (v3) Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_ec2_code_examples.md This example demonstrates how to get started with Amazon EC2 by listing up to 10 security groups. Ensure you have the AWS SDK for JavaScript (v3) installed and configured. ```javascript import { DescribeSecurityGroupsCommand, EC2Client } from "@aws-sdk/client-ec2"; // Call DescribeSecurityGroups and display the result. export const main = async () => { const client = new EC2Client(); try { const { SecurityGroups } = await client.send( new DescribeSecurityGroupsCommand({}) ); const securityGroupList = SecurityGroups.slice(0, 9) .map((sg) => ` • ${sg.GroupId}: ${sg.GroupName}`) .join("\n"); console.log( "Hello, Amazon EC2! Let's list up to 10 of your security groups:" ); console.log(securityGroupList); } catch (err) { console.error(err); } }; // Call function if run directly. import { fileURLToPath } from "node:url"; if (process.argv[1] === fileURLToPath(import.meta.url)) { main(); } ``` -------------------------------- ### Get Started with AWS IoT SiteWise Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_iotsitewise_code_examples.md This example demonstrates how to get started with AWS IoT SiteWise by listing asset models. It uses the `paginateListAssetModels` function for handling pagination. Ensure you have the necessary AWS SDK for JavaScript V3 packages installed. ```javascript import { paginateListAssetModels, IoTSiteWiseClient, } from "@aws-sdk/client-iotsitewise"; // Call ListDocuments and display the result. export const main = async () => { const client = new IoTSiteWiseClient(); const listAssetModelsPaginated = []; console.log( "Hello, AWS Systems Manager! Let's list some of your documents:\n", ); try { // The paginate function is a wrapper around the base command. const paginator = paginateListAssetModels({ client }, { maxResults: 5 }); for await (const page of paginator) { listAssetModelsPaginated.push(...page.assetModelSummaries); } } catch (caught) { console.error(`There was a problem saying hello: ${caught.message}`); throw caught; } for (const { name, creationDate } of listAssetModelsPaginated) { console.log(`${name} - ${creationDate}`); } }; // Call function if run directly. import { fileURLToPath } from "node:url"; if (process.argv[1] === fileURLToPath(import.meta.url)) { main(); } ``` -------------------------------- ### Get Started with AWS Support Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_support_code_examples.md This example demonstrates how to initialize the Support client and retrieve the number of available services. It includes error handling for subscription-related exceptions. ```javascript import { DescribeServicesCommand, SupportClient, } from "@aws-sdk/client-support"; // Change the value of 'region' to your preferred AWS Region. const client = new SupportClient({ region: "us-east-1" }); const getServiceCount = async () => { try { const { services } = await client.send(new DescribeServicesCommand({})); return services.length; } catch (err) { if (err.name === "SubscriptionRequiredException") { throw new Error( "You must be subscribed to the AWS Support plan to use this feature." ); } throw err; } }; export const main = async () => { try { const count = await getServiceCount(); console.log(`Hello, AWS Support! There are ${count} services available.`); } catch (err) { console.error("Failed to get service count: ", err.message); } }; ``` -------------------------------- ### Get Started with Elastic Load Balancing V2 Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_elastic-load-balancing-v2_code_examples.md This example demonstrates how to initialize the ElasticLoadBalancingV2Client and list existing load balancers. It requires the `@aws-sdk/client-elastic-load-balancing-v2` package. ```javascript import { ElasticLoadBalancingV2Client, DescribeLoadBalancersCommand, } from "@aws-sdk/client-elastic-load-balancing-v2"; export async function main() { const client = new ElasticLoadBalancingV2Client({}); const { LoadBalancers } = await client.send( new DescribeLoadBalancersCommand({}) ); const loadBalancersList = LoadBalancers.map( (lb) => `• ${lb.LoadBalancerName}: ${lb.DNSName}` ).join("\n"); console.log( "Hello, Elastic Load Balancing! Let's list some of your load balancers:\n", loadBalancersList, ); } // Call function if run directly import { fileURLToPath } from "node:url"; if (process.argv[1] === fileURLToPath(import.meta.url)) { main(); } ``` -------------------------------- ### Hello Systems Manager: List Documents Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_ssm_code_examples.md This example demonstrates how to get started with AWS Systems Manager by listing documents. It uses the `paginateListDocuments` function to retrieve up to 5 documents and logs their names, formats, and creation dates. Ensure you have the necessary AWS SDK for JavaScript v3 packages installed. ```javascript import { paginateListDocuments, SSMClient } from "@aws-sdk/client-ssm"; // Call ListDocuments and display the result. export const main = async () => { const client = new SSMClient(); const listDocumentsPaginated = []; console.log( "Hello, AWS Systems Manager! Let's list some of your documents:\n", ); try { // The paginate function is a wrapper around the base command. const paginator = paginateListDocuments({ client }, { MaxResults: 5 }); for await (const page of paginator) { listDocumentsPaginated.push(...page.DocumentIdentifiers); } } catch (caught) { console.error(`There was a problem saying hello: ${caught.message}`); throw caught; } for (const { Name, DocumentFormat, CreatedDate } of listDocumentsPaginated) { console.log(`${Name} - ${DocumentFormat} - ${CreatedDate}`); } }; // Call function if run directly. import { fileURLToPath } from "node:url"; if (process.argv[1] === fileURLToPath(import.meta.url)) { main(); } ``` -------------------------------- ### Install Node.js Dependencies Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/getting-started-browser.md Install all the necessary Node.js packages required for the example application to run. This command should be executed within the example application's directory. ```bash npm install ``` -------------------------------- ### Hello SageMaker AI Example (JavaScript) Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_sagemaker_code_examples.md This example demonstrates how to get started with SageMaker AI by listing notebook instances. It requires the SageMakerClient and ListNotebookInstancesCommand from the AWS SDK for JavaScript (v3). ```javascript import { SageMakerClient, ListNotebookInstancesCommand, } from "@aws-sdk/client-sagemaker"; const client = new SageMakerClient({ region: "us-west-2", }); export const helloSagemaker = async () => { const command = new ListNotebookInstancesCommand({ MaxResults: 5 }); const response = await client.send(command); console.log( "Hello Amazon SageMaker! Let's list some of your notebook instances:" ); const instances = response.NotebookInstances || []; if (instances.length === 0) { console.log( "• No notebook instances found. Try creating one in the AWS Management Console or with the CreateNotebookInstanceCommand." ); } else { console.log( instances .map( (i) => `• Instance: ${i.NotebookInstanceName}\n Arn:${ i.NotebookInstanceArn } Creation Date: ${i.CreationTime.toISOString()}` ) .join("\n") ); } return response; }; ``` -------------------------------- ### Get Started with AWS Glue using JavaScript (v3) Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_glue_code_examples.md This example demonstrates how to initialize the AWS Glue client and list available jobs. It requires the `@aws-sdk/client-glue` package. For API details, refer to the ListJobs API documentation. ```javascript import { ListJobsCommand, GlueClient } from "@aws-sdk/client-glue"; const client = new GlueClient({}); export const main = async () => { const command = new ListJobsCommand({}); const { JobNames } = await client.send(command); const formattedJobNames = JobNames.join("\n"); console.log("Job names: "); console.log(formattedJobNames); return JobNames; }; ``` -------------------------------- ### Start Development Server Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/getting-started-browser.md Run the example application using the Vite development server. This command will start a local server and provide a URL to access the application in your browser. ```bash npm run dev ``` -------------------------------- ### StartInstances Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_ec2_code_examples.md This example demonstrates how to start previously stopped EC2 instances using the `StartInstancesCommand`. ```APIDOC ## StartInstances ### Description Starts one or more Amazon EBS-backed instances that you've previously stopped. ### Method `StartInstancesCommand` ### Parameters - **instanceIds** (string[]) - Required - The IDs of the instances to start. ### Request Example ```javascript import { EC2Client, StartInstancesCommand } from "@aws-sdk/client-ec2"; export const main = async ({ instanceIds }) => { const client = new EC2Client({}); const command = new StartInstancesCommand({ InstanceIds: instanceIds, }); const { StartingInstances } = await client.send(command); const instanceIdList = StartingInstances.map( (instance) => ` • ${instance.InstanceId}`, ); console.log("Starting instances:"); console.log(instanceIdList.join("\n")); }; ``` ### Response #### Success Response - **StartingInstances** (Array) - An array of objects describing the instances that are being started. #### Response Example ```json { "StartingInstances": [ { "InstanceId": "i-0123456789abcdef0", "PreviousState": { "Code": 0, "Name": "stopped" }, "CurrentState": { "Code": 0, "Name": "pending" } } ] } ``` ``` -------------------------------- ### Deploy Lambda Function Setup Script Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/api-gateway-invoking-lambda-example.md Use this command to deploy the Lambda function setup script. Ensure you have Node.js installed. ```bash node lambda-function-setup.ts ``` -------------------------------- ### Navigate to S3 List Objects Example Directory Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/getting-started-browser.md Change the current directory to the specific example application for listing S3 objects. This is necessary before installing dependencies or running the application. ```bash cd aws-doc-sdk-examples/javascriptv3/example_code/web/s3/list-objects/ ``` -------------------------------- ### Test Node.js Installation Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-up-node-on-ec2-instance.md Verifies that Node.js is installed and running correctly by displaying its version. This command confirms the successful setup of Node.js. ```javascript node -e "console.log('Running Node.js ' + process.version)" ``` -------------------------------- ### Start Step Functions Execution using SDK for JavaScript (v3) Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_sfn_code_examples.md Use this snippet to start a Step Functions state machine execution. Ensure the SFNClient and stateMachineArn are correctly configured. The example includes logging of the response and a call to the function if run directly. ```javascript import { SFNClient, StartExecutionCommand } from "@aws-sdk/client-sfn"; /** * @param {{ sfnClient: SFNClient, stateMachineArn: string }} */ export async function startExecution({ sfnClient, stateMachineArn }) { const response = await sfnClient.send( new StartExecutionCommand({ stateMachineArn, }), ); console.log(response); // Example response: // { // '$metadata': { // httpStatusCode: 200, // requestId: '202a9309-c16a-454b-adeb-c4d19afe3bf2', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // executionArn: 'arn:aws:states:us-east-1:000000000000:execution:MyStateMachine:aaaaaaaa-f787-49fb-a20c-1b61c64eafe6', // startDate: 2024-01-04T15:54:08.362Z // } return response; } // Call function if run directly import { fileURLToPath } from "node:url"; if (process.argv[1] === fileURLToPath(import.meta.url)) { startExecution({ sfnClient: new SFNClient({}), stateMachineArn: "ARN" }); } ``` -------------------------------- ### Node.js SDK Example with S3 Client Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/getting-started-nodejs.md Demonstrates creating an S3 bucket, putting and getting an object, and deleting resources. Requires Node.js and the AWS SDK for JavaScript V3. ```javascript // This is used for getting user input. import { createInterface } from "node:readline/promises"; import { S3Client, PutObjectCommand, CreateBucketCommand, DeleteObjectCommand, DeleteBucketCommand, paginateListObjectsV2, GetObjectCommand, } from "@aws-sdk/client-s3"; export async function main() { // A region and credentials can be declared explicitly. For example // `new S3Client({ region: 'us-east-1', credentials: {...} })` would //initialize the client with those settings. However, the SDK will // use your local configuration and credentials if those properties // are not defined here. const s3Client = new S3Client({}); // Create an Amazon S3 bucket. The epoch timestamp is appended // to the name to make it unique. const bucketName = `test-bucket-${Date.now()}`; await s3Client.send( new CreateBucketCommand({ Bucket: bucketName, }), ); // Put an object into an Amazon S3 bucket. await s3Client.send( new PutObjectCommand({ Bucket: bucketName, Key: "my-first-object.txt", Body: "Hello JavaScript SDK!", }), ); // Read the object. const { Body } = await s3Client.send( new GetObjectCommand({ Bucket: bucketName, Key: "my-first-object.txt", }), ); console.log(await Body.transformToString()); // Confirm resource deletion. const prompt = createInterface({ input: process.stdin, output: process.stdout, }); const result = await prompt.question("Empty and delete bucket? (y/n) "); prompt.close(); if (result === "y") { // Create an async iterator over lists of objects in a bucket. const paginator = paginateListObjectsV2( { client: s3Client }, { Bucket: bucketName }, ); for await (const page of paginator) { const objects = page.Contents; if (objects) { // For every object in each page, delete it. for (const object of objects) { await s3Client.send( new DeleteObjectCommand({ Bucket: bucketName, Key: object.Key }), ); } } } // Once all the objects are gone, the bucket can be deleted. await s3Client.send(new DeleteBucketCommand({ Bucket: bucketName })); } } ``` -------------------------------- ### StartMatchingJob Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_entityresolution_code_examples.md This example demonstrates how to start an Entity Resolution matching job using the AWS SDK for JavaScript v3. It requires a workflow name as input. ```APIDOC ## StartMatchingJob ### Description Starts an Entity Resolution matching job for a specified workflow. ### Method `StartMatchingJobCommand` ### Parameters #### Request Body - **workflowName** (string) - Required - The name of the workflow to start the matching job for. ### Request Example ```javascript // The default inputs for this demo are read from the ../inputs.json. import { StartMatchingJobCommand, EntityResolutionClient, } from "@aws-sdk/client-entityresolution"; import data from "../inputs.json" with { type: "json" }; const region = "eu-west-1"; const erClient = new EntityResolutionClient({ region: region }); export const main = async () => { const matchingJobOfWorkflowParams = { workflowName: `${data.inputs.workflowName}`, }; try { const command = new StartMatchingJobCommand(matchingJobOfWorkflowParams); const response = await erClient.send(command); console.log(`Job ID: ${response.jobID} \n The matching job was successfully started.`); } catch (caught) { console.error(caught.message); throw caught; } }; ``` ### Response #### Success Response (200) - **jobID** (string) - The unique identifier for the started matching job. #### Response Example ```json { "jobID": "example-job-id" } ``` ``` -------------------------------- ### Get Started with Amazon Cognito Identity Provider Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_cognito-identity-provider_code_examples.md This example demonstrates how to initialize the Cognito Identity Provider client and paginate through user pools to retrieve their names. It's a good starting point for understanding basic SDK usage. ```javascript import { paginateListUserPools, CognitoIdentityProviderClient, } from "@aws-sdk/client-cognito-identity-provider"; const client = new CognitoIdentityProviderClient({}); export const helloCognito = async () => { const paginator = paginateListUserPools({ client }, {}); const userPoolNames = []; for await (const page of paginator) { const names = page.UserPools.map((pool) => pool.Name); userPoolNames.push(...names); } console.log("User pool names: "); console.log(userPoolNames.join("\n")); return userPoolNames; }; ``` -------------------------------- ### Hello HealthImaging: List Datastores Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_medical-imaging_code_examples.md A basic example to get started with HealthImaging by listing available datastores. Ensure your AWS configuration (region and credentials) is set up. ```javascript import { ListDatastoresCommand, MedicalImagingClient, } from "@aws-sdk/client-medical-imaging"; // When no region or credentials are provided, the SDK will use the // region and credentials from the local AWS config. const client = new MedicalImagingClient({}); export const helloMedicalImaging = async () => { const command = new ListDatastoresCommand({}); const { datastoreSummaries } = await client.send(command); console.log("Datastores: "); console.log(datastoreSummaries.map((item) => item.datastoreName).join("\n")); return datastoreSummaries; }; ``` -------------------------------- ### SignUp Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_cognito-identity-provider_code_examples.md Example of how to sign up a new user using the SignUpCommand. ```APIDOC ## SignUp ### Description This function demonstrates how to use the `SignUpCommand` to create a new user in a Cognito User Pool. ### Method `SignUp` ### Parameters - `clientId` (string) - Required - The client ID of the application. - `username` (string) - Required - The username for the new user. - `password` (string) - Required - The password for the new user. - `email` (string) - Required - The email address of the new user. ### Request Example ```javascript const signUp = ({ clientId, username, password, email }) => { const client = new CognitoIdentityProviderClient({}); const command = new SignUpCommand({ ClientId: clientId, Username: username, Password: password, UserAttributes: [{ Name: "email", Value: email }], }); return client.send(command); }; ``` ### API Reference For API details, see [SignUp](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/SignUpCommand) in *AWS SDK for JavaScript API Reference*. ``` -------------------------------- ### Get Foundation Model Details Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_bedrock_code_examples.md This example retrieves detailed information about a specific Amazon Bedrock foundation model, identified by its model identifier. Ensure the `@aws-sdk/client-bedrock` package is installed. ```javascript import { fileURLToPath } from "node:url"; import { BedrockClient, GetFoundationModelCommand, } from "@aws-sdk/client-bedrock"; /** * Get details about an Amazon Bedrock foundation model. * * @return {FoundationModelDetails} - The list of available bedrock foundation models. */ export const getFoundationModel = async () => { const client = new BedrockClient(); const command = new GetFoundationModelCommand({ modelIdentifier: "amazon.titan-embed-text-v1", }); const response = await client.send(command); return response.modelDetails; }; // Invoke main function if this file was run directly. if (process.argv[1] === fileURLToPath(import.meta.url)) { const model = await getFoundationModel(); console.log(model); } ``` -------------------------------- ### Get Started with AWS Entity Resolution (JavaScript v3) Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_entityresolution_code_examples.md This example demonstrates how to initialize the EntityResolutionClient and list matching workflows. It requires the 'eu-west-1' region. Errors during the API call are caught and logged. ```javascript import { EntityResolutionClient, ListMatchingWorkflowsCommand, } from "@aws-sdk/client-entityresolution"; export const main = async () => { const region = "eu-west-1"; const erClient = new EntityResolutionClient({ region: region }); try { const command = new ListMatchingWorkflowsCommand({}); const response = await erClient.send(command); const workflowSummaries = response.workflowSummaries; for (const workflowSummary of workflowSummaries) { console.log(`Attribute name: ${workflowSummaries[0].workflowName} `); } if (workflowSummaries.length === 0) { console.log("No matching workflows found."); } } catch (error) { console.error( `An error occurred in listing the workflow summaries: ${error.message} \n Exiting program.`, ); return; } }; ``` -------------------------------- ### S3 Bucket and Object Setup Steps (JavaScript) Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_s3_code_examples.md Provides functions for setting up buckets and objects, including commands for creating buckets and putting objects. It imports necessary S3 client components and utility types. ```javascript import { ChecksumAlgorithm, CreateBucketCommand, PutObjectCommand, BucketAlreadyExists, BucketAlreadyOwnedByYou, S3ServiceException, waitUntilBucketExists, } from "@aws-sdk/client-s3"; /** * @typedef {import("@aws-doc-sdk-examples/lib/scenario/index.js")} Scenarios */ /** * @typedef {import("@aws-sdk/client-s3").S3Client} S3Client */ /** * @param {Scenarios} scenarios */ const getBucketPrefix = (scenarios) => ``` -------------------------------- ### Handle MFA Setup Challenge Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_cognito-identity-provider_code_examples.md Handles the MFA_SETUP challenge by logging the requirement and returning the session for further processing. ```javascript const handleMfaSetup = (session, username) => { // Store the Session for use with 'AdminRespondToAuthChallenge'. process.env.SESSION = session; // The 'otpauth://totp/${username}?secret=${SecretCode}' URI is used to configure an authenticator app. // For example, Google Authenticator. // The secret is provided in the response to 'AdminInitiateAuth'. // The following line is a placeholder and would typically involve retrieving the secret from the response. // For demonstration purposes, we'll log a placeholder URI. console.log( `otpauth://totp/${username}?secret=${'SecretCode'}`, // Replace 'SecretCode' with the actual secret { small: true }, console.log, ); }; ``` -------------------------------- ### Hello Amazon Bedrock Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_bedrock-runtime_code_examples.md Get started with Amazon Bedrock by invoking a model with a simple prompt. This example uses the Anthropic Claude 3 Haiku model and demonstrates basic request and response handling. ```javascript /** * @typedef {Object} Content * @property {string} text * * @typedef {Object} Usage * @property {number} input_tokens * @property {number} output_tokens * * @typedef {Object} ResponseBody * @property {Content[]} content * @property {Usage} usage */ import { fileURLToPath } from "node:url"; import { BedrockRuntimeClient, InvokeModelCommand, } from "@aws-sdk/client-bedrock-runtime"; const AWS_REGION = "us-east-1"; const MODEL_ID = "anthropic.claude-3-haiku-20240307-v1:0"; const PROMPT = "Hi. In a short paragraph, explain what you can do."; const hello = async () => { console.log("=".repeat(35)); console.log("Welcome to the Amazon Bedrock demo!"); console.log("=".repeat(35)); console.log("Model: Anthropic Claude 3 Haiku"); console.log(`Prompt: ${PROMPT}\n`); console.log("Invoking model...\n"); // Create a new Bedrock Runtime client instance. const client = new BedrockRuntimeClient({ region: AWS_REGION }); // Prepare the payload for the model. const payload = { anthropic_version: "bedrock-2023-05-31", max_tokens: 1000, messages: [{ role: "user", content: [{ type: "text", text: PROMPT }] }], }; // Invoke Claude with the payload and wait for the response. const apiResponse = await client.send( new InvokeModelCommand({ contentType: "application/json", body: JSON.stringify(payload), modelId: MODEL_ID, }), ); // Decode and return the response(s) const decodedResponseBody = new TextDecoder().decode(apiResponse.body); /** @type {ResponseBody} */ const responseBody = JSON.parse(decodedResponseBody); const responses = responseBody.content; if (responses.length === 1) { console.log(`Response: ${responses[0].text}`); } else { console.log("Haiku returned multiple responses:"); console.log(responses); } console.log(`\nNumber of input tokens: ${responseBody.usage.input_tokens}`); console.log(`Number of output tokens: ${responseBody.usage.output_tokens}`); }; if (process.argv[1] === fileURLToPath(import.meta.url)) { await hello(); } ``` -------------------------------- ### Describe Load Balancers with Elastic Load Balancing v2 SDK Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_elastic-load-balancing-v2_code_examples.md This example shows how to list all load balancers in your account. It imports necessary clients and commands, then logs the DNS name of each load balancer. ```javascript import { ElasticLoadBalancingV2Client, DescribeLoadBalancersCommand, } from "@aws-sdk/client-elastic-load-balancing-v2"; export async function main() { const client = new ElasticLoadBalancingV2Client({}); const { LoadBalancers } = await client.send( new DescribeLoadBalancersCommand({}), ); const loadBalancersList = LoadBalancers.map( (lb) => `• ${lb.LoadBalancerName}: ${lb.DNSName}`, ).join("\n"); console.log( "Hello, Elastic Load Balancing! Let's list some of your load balancers:\n", loadBalancersList, ); } // Call function if run directly import { fileURLToPath } from "node:url"; if (process.argv[1] === fileURLToPath(import.meta.url)) { main(); } ``` -------------------------------- ### StartLiveTail Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_cloudwatch-logs_code_examples.md Initiates a live tail session to stream log events in real-time. This example demonstrates how to set up the client, send the command with specified log group identifiers, log stream names, and a filter pattern, and then handle the incoming log events. ```APIDOC ## StartLiveTail ### Description Starts a live tail session to stream log events from specified log groups and streams in real-time. Handles session start, updates, and potential errors during the stream. ### Method ```javascript import { CloudWatchLogsClient, StartLiveTailCommand } from "@aws-sdk/client-cloudwatch-logs"; const client = new CloudWatchLogsClient(); const command = new StartLiveTailCommand({ logGroupIdentifiers: logGroupIdentifiers, // Replace with your log group identifiers logStreamNames: logStreamNames, // Replace with your log stream names filterPattern: filterPattern // Optional: Replace with your filter pattern }); async function handleResponseAsync(response) { try { for await (const event of response.responseStream) { if (event.sessionStart !== undefined) { console.log("Session started:", event.sessionStart); } else if (event.sessionUpdate !== undefined) { for (const logEvent of event.sessionUpdate.sessionResults) { const timestamp = logEvent.timestamp; const date = new Date(timestamp); console.log(`[${date.toISOString()}] ${logEvent.message}`); } } else { console.error("Unknown event type"); } } } catch (err) { // On-stream exceptions are captured here console.error("Error during stream:", err); } } try{ const response = await client.send(command); handleResponseAsync(response); } catch (err){ // Pre-stream exceptions are captured here console.error("Error starting live tail:", err); } /* Set a timeout to close the client. This will stop the Live Tail session. */ setTimeout(function() { console.log("Client timeout reached. Stopping live tail session."); client.destroy(); }, 10000); ``` ### Parameters * `logGroupIdentifiers` (Array) - Required - One or more identifiers of the log groups to stream from. * `logStreamNames` (Array) - Optional - Specific log streams within the log groups to stream from. * `filterPattern` (string) - Optional - A pattern to filter the log events. ### Request Example ```json { "logGroupIdentifiers": ["log-group-1", "log-group-2"], "logStreamNames": ["log-stream-a"], "filterPattern": "ERROR" } ``` ### Response #### Success Response (200) The response is a stream of events. Each event can be a `sessionStart` or `sessionUpdate`. #### Response Example ```json { "sessionStart": { "sessionId": "some-session-id" } } ``` ```json { "sessionUpdate": { "sessionResults": [ { "timestamp": 1678886400000, "message": "This is a log message." } ] } } ``` ``` -------------------------------- ### Run SES List Templates Example Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ses-examples-creating-template.md Command to execute the Node.js example for listing SES email templates. ```bash node ses_listtemplates.js ``` -------------------------------- ### Get Stack Outputs for Cognito Example Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_cognito-identity-provider_code_examples.md Fetches CloudFormation stack outputs required for the example. Ensures stack name and region are provided. ```javascript import { ScenarioAction, ScenarioInput, ScenarioOutput, } from "@aws-doc-sdk-examples/lib/scenario/scenario.js"; import { getCfnOutputs } from "@aws-doc-sdk-examples/lib/sdk/cfn-outputs.js"; export const skipWhenErrors = (state) => state.errors.length > 0; export const getStackOutputs = new ScenarioAction( "getStackOutputs", async (state) => { if (!state.stackName || !state.stackRegion) { state.errors.push( new Error( "No stack name or region provided. The stack name and \nregion are required to fetch CFN outputs relevant to this example.", ), ); return; } const outputs = await getCfnOutputs(state.stackName, state.stackRegion); Object.assign(state, outputs); }, ); export const promptForStackName = new ScenarioInput( "stackName", "Enter the name of the stack you deployed earlier.", { type: "input", default: "PoolsAndTriggersStack" }, ); export const promptForStackRegion = new ScenarioInput( "stackRegion", "Enter the region of the stack you deployed earlier.", { type: "input", default: "us-east-1" }, ); export const logCleanUpReminder = new ScenarioOutput( "logCleanUpReminder", "All done. Remember to run 'cdk destroy' to teardown the stack.", { skipWhen: skipWhenErrors }, ); ``` -------------------------------- ### Start the AWS SDK Demo Application Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_sqs_code_examples.md This is the main entry point for the application, orchestrating the setup and execution of various AWS SQS and SNS operations. It includes error handling and ensures resource cleanup. ```javascript async start() { console.clear(); try { this.logger.logSeparator(MESSAGES.headerWelcome); await this.welcome(); this.logger.logSeparator(MESSAGES.headerFifo); await this.confirmFifo(); this.logger.logSeparator(MESSAGES.headerCreateTopic); await this.createTopic(); this.logger.logSeparator(MESSAGES.headerCreateQueues); await this.createQueues(); this.logger.logSeparator(MESSAGES.headerAttachPolicy); await this.attachQueueIamPolicies(); this.logger.logSeparator(MESSAGES.headerSubscribeQueues); await this.subscribeQueuesToTopic(); this.logger.logSeparator(MESSAGES.headerPublishMessage); await this.publishMessages(); this.logger.logSeparator(MESSAGES.headerReceiveMessages); await this.receiveAndDeleteMessages(); } catch (err) { console.error(err); } finally { await this.destroyResources(); } } ``` -------------------------------- ### DynamoDB Set Operations Example Setup Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/dynamodb-example-query-scan.html Initializes the DynamoDB client and DocumentClient for performing set operations. This setup is common for various DynamoDB update commands. ```javascript const { DynamoDBClient } = require("@aws-sdk/client-dynamodb"); const { DynamoDBDocumentClient, UpdateCommand, GetCommand } = require("@aws-sdk/lib-dynamodb"); // Example parameters for client and document client initialization const client = new DynamoDBClient({ region: "us-west-2" }); const ddbDocClient = DynamoDBDocumentClient.from(client); ``` -------------------------------- ### DynamoDB Atomic Counter Operations Setup Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_dynamodb_code_examples.md Initializes the DynamoDBClient and DynamoDBDocumentClient for performing atomic counter operations. This setup is required before executing update or get commands. ```javascript const { DynamoDBClient } = require("@aws-sdk/client-dynamodb"); const { DynamoDBDocumentClient, UpdateCommand, GetCommand } = require("@aws-sdk/lib-dynamodb"); // Initialize clients for atomic counter operations ``` -------------------------------- ### Initialize Support Client and Verify Account Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_support_code_examples.md Initializes the Support client and verifies if the account has a Support plan. Throws an error if a subscription is required. ```javascript import { AddAttachmentsToSetCommand, AddCommunicationToCaseCommand, CreateCaseCommand, DescribeAttachmentCommand, DescribeCasesCommand, DescribeCommunicationsCommand, DescribeServicesCommand, DescribeSeverityLevelsCommand, ResolveCaseCommand, SupportClient, } from "@aws-sdk/client-support"; import * as inquirer from "@inquirer/prompts"; import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js"; const wrapText = (text, char = "=") => { const rule = char.repeat(80); return `${rule}\n ${text}\n${rule}\n`; }; const client = new SupportClient({ region: "us-east-1" }); // Verify that the account has a Support plan. export const verifyAccount = async () => { const command = new DescribeServicesCommand({}); try { await client.send(command); } catch (err) { if (err.name === "SubscriptionRequiredException") { throw new Error( "You must be subscribed to the AWS Support plan to use this feature." ); } throw err; } }; ``` -------------------------------- ### Initialize Deployment Steps for Resilient Service Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_iam_code_examples.md This script defines the initial steps for deploying resources for a resilient web service. It includes setup for DynamoDB, EC2, IAM, SSM, Auto Scaling, and Elastic Load Balancing. The steps involve user confirmation, handling confirmations, and initializing parameters. ```javascript import { join } from "node:path"; import { readFileSync, writeFileSync } from "node:fs"; import axios from "axios"; import { BatchWriteItemCommand, CreateTableCommand, DynamoDBClient, waitUntilTableExists, } from "@aws-sdk/client-dynamodb"; import { EC2Client, CreateKeyPairCommand, CreateLaunchTemplateCommand, DescribeAvailabilityZonesCommand, DescribeVpcsCommand, DescribeSubnetsCommand, DescribeSecurityGroupsCommand, AuthorizeSecurityGroupIngressCommand, } from "@aws-sdk/client-ec2"; import { IAMClient, CreatePolicyCommand, CreateRoleCommand, CreateInstanceProfileCommand, AddRoleToInstanceProfileCommand, AttachRolePolicyCommand, waitUntilInstanceProfileExists, } from "@aws-sdk/client-iam"; import { SSMClient, GetParameterCommand } from "@aws-sdk/client-ssm"; import { CreateAutoScalingGroupCommand, AutoScalingClient, AttachLoadBalancerTargetGroupsCommand, } from "@aws-sdk/client-auto-scaling"; import { CreateListenerCommand, CreateLoadBalancerCommand, CreateTargetGroupCommand, ElasticLoadBalancingV2Client, waitUntilLoadBalancerAvailable, } from "@aws-sdk/client-elastic-load-balancing-v2"; import { ScenarioOutput, ScenarioInput, ScenarioAction, } from "@aws-doc-sdk-examples/lib/scenario/index.js"; import { saveState } from "@aws-doc-sdk-examples/lib/scenario/steps-common.js"; import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js"; import { MESSAGES, NAMES, RESOURCES_PATH, ROOT } from "./constants.js"; import { initParamsSteps } from "./steps-reset-params.js"; /** * @type {import('@aws-doc-sdk-examples/lib/scenario.js').Step[]} */ export const deploySteps = [ new ScenarioOutput("introduction", MESSAGES.introduction, { header: true }), new ScenarioInput("confirmDeployment", MESSAGES.confirmDeployment, { type: "confirm" }), new ScenarioAction( "handleConfirmDeployment", ``` -------------------------------- ### RunInstances Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_ec2_code_examples.md This example demonstrates how to create new EC2 instances using the `RunInstancesCommand`. ```APIDOC ## RunInstances ### Description Creates new EC2 instances. ### Method `RunInstancesCommand` ### Parameters - **keyName** (string) - Required - The name of the key pair. - **securityGroupIds** (string[]) - Required - The IDs of the security groups. - **imageId** (string) - Required - The ID of the Amazon Machine Image (AMI). - **instanceType** (import('@aws-sdk/client-ec2')._InstanceType) - Required - The instance type. - **minCount** (number) - Optional - The minimum number of instances to launch. Defaults to 1. - **maxCount** (number) - Optional - The maximum number of instances to launch. Defaults to 1. ### Request Example ```javascript import { EC2Client, RunInstancesCommand } from "@aws-sdk/client-ec2"; export const main = async ({ keyName, securityGroupIds, imageId, instanceType, minCount = "1", maxCount = "1", }) => { const client = new EC2Client({}); minCount = Number.parseInt(minCount); maxCount = Number.parseInt(maxCount); const command = new RunInstancesCommand({ KeyName: keyName, SecurityGroupIds: securityGroupIds, ImageId: imageId, InstanceType: instanceType, MinCount: minCount, MaxCount: maxCount, }); const { Instances } = await client.send(command); const instanceList = Instances.map( (instance) => `• ${instance.InstanceId}`, ).join("\n"); console.log(`Launched instances:\n${instanceList}`); }; ``` ### Response #### Success Response - **Instances** (Array) - An array of EC2 instance objects. #### Response Example ```json { "Instances": [ { "InstanceId": "i-0123456789abcdef0" } ] } ``` ``` -------------------------------- ### GetFilteredRecommendations Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_personalize-runtime_code_examples.md This example demonstrates how to get filtered recommendations using a campaign ARN and a filter ARN. ```APIDOC ## GetFilteredRecommendations ### Description Retrieves a list of filtered recommendations for a user based on a campaign and a filter. ### Method `GetRecommendationsCommand` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **campaignArn** (string) - Required - The Amazon Resource Name (ARN) of the campaign to retrieve recommendations from. - **userId** (string) - Required - The user ID to provide recommendations for. - **numResults** (number) - Optional - The number of recommendations to retrieve. - **filterArn** (string) - Required - The ARN of the filter to apply to the recommendations. - **filterValues** (object) - Optional - A map of property names and values to use for filtering. Only required if your filter has a placeholder parameter. ### Request Example ```javascript // Get service clients module and commands using ES6 syntax. import { GetRecommendationsCommand } from "@aws-sdk/client-personalize-runtime"; import { personalizeRuntimeClient } from "./libs/personalizeClients.js"; // Or, create the client here: // const personalizeRuntimeClient = new PersonalizeRuntimeClient({ region: "REGION"}); // Set recommendation request parameters. export const getRecommendationsParam = { campaignArn: "CAMPAIGN_ARN" /* required */, userId: "USER_ID" /* required */, numResults: 15 /* optional */, filterArn: "FILTER_ARN" /* required to filter recommendations */, filterValues: { PROPERTY: '"VALUE"' /* Only required if your filter has a placeholder parameter */, }, }; export const run = async () => { try { const response = await personalizeRuntimeClient.send( new GetRecommendationsCommand(getRecommendationsParam), ); console.log("Success!", response); return response; // For unit tests. } catch (err) { console.log("Error", err); } }; run(); ``` ### Response #### Success Response (200) - **itemList** (array) - A list of recommended items. - **promotions** (array) - A list of promotions. - **recommendationId** (string) - The ID of the recommendation. #### Response Example ```json { "itemList": [ { "itemId": "item1", "score": 0.95 } ], "promotions": [], "recommendationId": "recommendation-id-789" } ``` ``` -------------------------------- ### ConfirmDevice Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_cognito-identity-provider_code_examples.md This example demonstrates how to use the `ConfirmDevice` function to confirm a user's device after it has been registered. ```APIDOC ## ConfirmDevice ### Description Confirms a user's device, typically after registration or when a new device needs to be verified. ### Method `ConfirmDeviceCommand` ### Parameters #### Request Body - **DeviceKey** (string) - Required - The key of the device to confirm. - **AccessToken** (string) - Required - The access token for the authenticated user. - **DeviceSecretVerifierConfig** (object) - Required - Configuration for verifying the device secret. - **PasswordVerifier** (string) - Required - The password verifier string. - **Salt** (string) - Required - The salt used in the password verification process. ### Request Example ```javascript const confirmDevice = ({ deviceKey, accessToken, passwordVerifier, salt }) => { const client = new CognitoIdentityProviderClient({}); const command = new ConfirmDeviceCommand({ DeviceKey: deviceKey, AccessToken: accessToken, DeviceSecretVerifierConfig: { PasswordVerifier: passwordVerifier, Salt: salt, }, }); return client.send(command); }; ``` ### Response #### Success Response (200) Returns a response object indicating the device has been successfully confirmed. ``` -------------------------------- ### Get Recommendations from a Recommender with AWS SDK for JavaScript v3 Source: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_personalize-runtime_code_examples.md This example shows how to get recommendations from a recommender, which is typically used with domain dataset groups. The recommender ARN and user ID are required. ```javascript // Get service clients module and commands using ES6 syntax. import { GetRecommendationsCommand } from "@aws-sdk/client-personalize-runtime"; import { personalizeRuntimeClient } from "./libs/personalizeClients.js"; // Or, create the client here. // const personalizeRuntimeClient = new PersonalizeRuntimeClient({ region: "REGION"}); // Set the recommendation request parameters. export const getRecommendationsParam = { recommenderArn: "RECOMMENDER_ARN" /* required */, userId: "USER_ID" /* required */, numResults: 15 /* optional */, }; export const run = async () => { try { const response = await personalizeRuntimeClient.send( new GetRecommendationsCommand(getRecommendationsParam), ); console.log("Success!", response); return response; // For unit tests. } catch (err) { console.log("Error", err); } }; run(); ```