• 沒有找到結果。

AWS SDK for JavaScript

N/A
N/A
Protected

Academic year: 2022

Share "AWS SDK for JavaScript"

Copied!
265
0
0

加載中.... (立即查看全文)

全文

(1)

AWS SDK for JavaScript

Developer Guide for SDK v2

(2)

AWS SDK for JavaScript: Developer Guide for SDK v2

Copyright © Amazon Web Services, Inc. and/or its affiliates. All rights reserved.

Amazon's trademarks and trade dress may not be used in connection with any product or service that is not Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may or may not be affiliated with, connected to, or sponsored by Amazon.

(3)

Table of Contents

... vii

What Is the AWS SDK for JavaScript? ... 1

Maintenance and support for SDK major versions ... 1

Using the SDK with Node.js ... 1

Using the SDK with AWS Cloud9 ... 1

Using the SDK with AWS Amplify ... 2

Using the SDK with Web Browsers ... 2

Common Use Cases ... 2

About the Examples ... 2

Getting Started ... 3

Getting Started in a Browser Script ... 3

The Scenario ... 3

Step 1: Create an Amazon Cognito Identity Pool ... 4

Step 2: Add a Policy to the Created IAM Role ... 4

Step 3: Create the HTML Page ... 5

Step 4: Write the Browser Script ... 5

Step 5: Run the Sample ... 7

Full Sample ... 7

Possible Enhancements ... 8

Getting Started in Node.js ... 8

The Scenario ... 8

Prerequisite Tasks ... 8

Step 1: Install the SDK and Dependencies ... 9

Step 2: Configure Your Credentials ... 9

Step 3: Create the Package JSON for the Project ... 10

Step 4: Write the Node.js Code ... 10

Step 5: Run the Sample ... 11

Using AWS Cloud9 with the SDK for JavaScript ... 12

Step 1: Set up Your AWS Account to Use AWS Cloud9 ... 12

Step 2: Set up Your AWS Cloud9 Development Environment ... 12

Step 3: Set up the SDK for JavaScript ... 13

To set up the SDK for JavaScript for Node.js ... 13

To set up the SDK for JavaScript in the browser ... 13

Step 4: Download Example Code ... 13

Step 5: Run and Debug Example Code ... 14

Setting Up the SDK for JavaScript ... 15

Prerequisites ... 15

Setting Up an AWS Node.js Environment ... 15

Web Browsers Supported ... 16

Installing the SDK ... 16

Installing Using Bower ... 17

Loading the SDK ... 17

Upgrading From Version 1 ... 18

Automatic Conversion of Base64 and Timestamp Types on Input/Output ... 18

Moved response.data.RequestId to response.requestId ... 18

Exposed Wrapper Elements ... 19

Dropped Client Properties ... 21

Configuring the SDK for JavaScript ... 23

Using the Global Configuration Object ... 23

Setting Global Configuration ... 23

Setting Configuration Per Service ... 25

Immutable Configuration Data ... 25

Setting the AWS Region ... 25

In a Client Class Constructor ... 25

(4)

Using the Global Configuration Object ... 26

Using an Environment Variable ... 26

Using a Shared Config File ... 26

Order of Precedence for Setting the Region ... 26

Specifying Custom Endpoints ... 27

Endpoint String Format ... 27

Endpoints for the ap-northeast-3 Region ... 27

Endpoints for MediaConvert ... 27

Getting Your Credentials ... 27

Setting Credentials ... 28

Best Practices for Credentials ... 29

Setting Credentials in Node.js ... 29

Setting Credentials in a Web Browser ... 32

Locking API Versions ... 39

Getting API Versions ... 39

Node.js Considerations ... 39

Using Built-In Node.js Modules ... 40

Using NPM Packages ... 40

Configuring maxSockets in Node.js ... 40

Reusing Connections with Keep-Alive in Node.js ... 41

Configuring Proxies for Node.js ... 42

Registering Certificate Bundles in Node.js ... 42

Browser Script Considerations ... 43

Building the SDK for Browsers ... 43

Cross-Origin Resource Sharing (CORS) ... 45

Bundling with Webpack ... 48

Installing Webpack ... 48

Configuring Webpack ... 48

Running Webpack ... 49

Using the Webpack Bundle ... 50

Importing Individual Services ... 50

Bundling for Node.js ... 50

Working with Services ... 52

Creating and Calling Service Objects ... 52

Requiring Individual Services ... 53

Creating Service Objects ... 54

Locking the API Version of a Service Object ... 54

Specifying Service Object Parameters ... 54

Logging AWS SDK for JavaScript Calls ... 55

Using a Third-Party Logger ... 55

Calling Services Asychronously ... 56

Managing Asychronous Calls ... 56

Using a Callback Function ... 57

Using a Request Object Event Listener ... 58

Using async/await ... 62

Using Promises ... 62

Using the Response Object ... 64

Accessing Data Returned in the Response Object ... 64

Paging Through Returned Data ... 65

Accessing Error Information from a Response Object ... 65

Accessing the Originating Request Object ... 65

Working with JSON ... 65

JSON as Service Object Parameters ... 66

Returning Data as JSON ... 67

SDK for JavaScript Code Examples ... 68

Amazon CloudWatch Examples ... 68

Creating Alarms in Amazon CloudWatch ... 69

(5)

Using Alarm Actions in Amazon CloudWatch ... 71

Getting Metrics from Amazon CloudWatch ... 74

Sending Events to Amazon CloudWatch Events ... 76

Using Subscription Filters in Amazon CloudWatch Logs ... 80

Amazon DynamoDB Examples ... 83

Creating and Using Tables in DynamoDB ... 83

Reading and Writing A Single Item in DynamoDB ... 87

Reading and Writing Items in Batch in DynamoDB ... 89

Querying and Scanning a DynamoDB Table ... 92

Using the DynamoDB Document Client ... 94

Amazon EC2 Examples ... 98

Creating an Amazon EC2 Instance ... 99

Managing Amazon EC2 Instances ... 101

Working with Amazon EC2 Key Pairs ... 105

Using Regions and Availability Zones with Amazon EC2 ... 107

Working with Security Groups in Amazon EC2 ... 109

Using Elastic IP Addresses in Amazon EC2 ... 112

MediaConvert Examples ... 115

Getting Your Account-Specific Endpoint ... 115

Creating and Managing Jobs ... 117

Using Job Templates ... 122

Amazon S3 Glacier Examples ... 128

Creating a S3 Glacier Vault ... 128

Uploading an Archive to S3 Glacier ... 129

Doing a Multipart Upload to S3 Glacier ... 130

AWS IAM Examples ... 131

Managing IAM Users ... 131

Working with IAM Policies ... 135

Managing IAM Access Keys ... 139

Working with IAM Server Certificates ... 142

Managing IAM Account Aliases ... 145

Amazon Kinesis Example ... 147

Capturing Web Page Scroll Progress with Amazon Kinesis ... 148

AWS Lambda Examples ... 152

Amazon S3 Examples ... 152

Amazon S3 Browser Examples ... 153

Amazon S3 Node.js Examples ... 172

Amazon SES Examples ... 186

Managing Identities ... 187

Working with Email Templates ... 190

Sending Email Using Amazon SES ... 194

Using IP Address Filters ... 198

Using Receipt Rules ... 201

Amazon SNS Examples ... 204

Managing Topics ... 205

Publishing Messages to a Topic ... 209

Managing Subscriptions ... 210

Sending SMS Messages ... 214

Amazon SQS Examples ... 218

Using Queues in Amazon SQS ... 219

Sending and Receiving Messages in Amazon SQS ... 222

Managing Visibility Timeout in Amazon SQS ... 225

Enabling Long Polling in Amazon SQS ... 226

Using Dead Letter Queues in Amazon SQS ... 229

Tutorials ... 231

Tutorial: Setting Up Node.js on an Amazon EC2 Instance ... 231

Prerequisites ... 231

(6)

Procedure ... 231

Creating an Amazon Machine Image ... 232

Related Resources ... 232

Tutorial: Creating and Using Lambda Functions ... 232

The Scenario ... 232

Prerequisites ... 233

Tutorial Steps ... 233

Create an Amazon S3 Bucket Configured as a Static Website ... 234

Prepare the Browser Script ... 235

Create a Lambda Execution Role in IAM ... 236

Create and Populate a DynamoDB Table ... 238

Prepare and Create the Lambda Function ... 242

Run the Lambda Function ... 244

API Reference and Changelog ... 247

SDK Changelog on GitHub ... 247

Security ... 248

Data protection ... 248

Identity and Access Management ... 249

Compliance Validation ... 249

Resilience ... 250

Infrastructure Security ... 250

Enforcing TLS 1.2 ... 250

Verify and enforce TLS in Node.js ... 251

Verify and enforce TLS in a browser script ... 252

Additional Resources ... 253

JavaScript SDK Forum ... 253

JavaScript SDK and Developer Guide on GitHub ... 253

JavaScript SDK on Gitter ... 253

Document History ... 254

Document History ... 254

Earlier Updates ... 255

(7)

The AWS SDK for JavaScript version 3 (v3) is a rewrite of v2 with some great new features, including modular architecture. For more information, see the AWS SDK for JavaScript v3 Developer Guide.

(8)

Maintenance and support for SDK major versions

What Is the AWS SDK for JavaScript?

The AWS SDK for JavaScript (p. 247) provides a JavaScript API for AWS services. You can use the JavaScript API to build libraries or applications for Node.js or the browser.

Not all services are immediately available in the SDK. To find out which services are currently supported by the AWS SDK for JavaScript, see https://github.com/aws/aws-sdk-js/blob/master/SERVICES.md. For information about the SDK for JavaScript on GitHub, see Additional Resources (p. 253).

Maintenance and support for SDK major versions

For information about maintenance and support for SDK major versions and their underlying dependencies, see the following in the AWS SDKs and Tools Reference Guide:

• AWS SDKs and tools maintenance policy

• AWS SDKs and tools version support matrix

Using the SDK with Node.js

Node.js is a cross-platform runtime for running server-side JavaScript applications. You can set up Node.js on an Amazon EC2 instance to run on a server. You can also use Node.js to write on-demand AWS Lambda functions.

Using the SDK for Node.js differs from the way in which you use it for JavaScript in a web browser. The difference comes from the way in which you load the SDK and in how you obtain the credentials needed to access specific web services. When use of particular APIs differs between Node.js and the browser, those differences will be called out.

Using the SDK with AWS Cloud9

You can also develop Node.js applications using the SDK for JavaScript in the AWS Cloud9 IDE. For a sample of how to use AWS Cloud9 for Node.js development, see Node.js Sample for AWS Cloud9 in the AWS Cloud9 User Guide. For more information on using AWS Cloud9 with the SDK for JavaScript, see Using AWS Cloud9 with the AWS SDK for JavaScript (p. 12).

(9)

Using the SDK with AWS Amplify

Using the SDK with AWS Amplify

For browser-based web, mobile, and hybrid apps, you can also use the AWS Amplify Library on GitHub, which extends the SDK for JavaScript, providing a declarative interface.

NoteFrameworks such as AWS Amplify might not offer the same browser support as the SDK for JavaScript. Check a framework's documentation for details.

Using the SDK with Web Browsers

All major web browsers support execution of JavaScript. JavaScript code that is running in a web browser is often called client-side JavaScript.

Using the SDK for JavaScript in a web browser differs from the way in which you use it for Node.js. The difference comes from the way in which you load the SDK and in how you obtain the credentials needed to access specific web services. When use of particular APIs differs between Node.js and the browser, those differences will be called out.

For a list of browsers that are supported by the AWS SDK for JavaScript, see Web Browsers Supported (p. 16).

Common Use Cases

Using the SDK for JavaScript in browser scripts makes it possible to realize a number of compelling use cases. Here are several ideas for things you can build in a browser application by using the SDK for JavaScript to access various web services.

• Build a custom console to AWS services in which you access and combine features across Regions and services to best meet your organizational or project needs.

• Use Amazon Cognito Identity to enable authenticated user access to your browser applications and websites, including use of third-party authentication from Facebook and others.

• Use Amazon Kinesis to process click streams or other marketing data in real time.

• Use Amazon DynamoDB for serverless data persistence such as individual user preferences for website visitors or application users.

• Use AWS Lambda to encapsulate proprietary logic that you can invoke from browser scripts without downloading and revealing your intellectual property to users.

About the Examples

You can browse the SDK for JavaScript examples in the AWS Code Sample Catalog.

(10)

Getting Started in a Browser Script

Getting Started with the AWS SDK for JavaScript

The AWS SDK for JavaScript provides access to web services in either browser scripts or Node.js. This section has two getting started exercises that show you how to work with the SDK for JavaScript in each of these JavaScript environments.

You can also develop Node.js applications using the SDK for JavaScript in the AWS Cloud9 IDE. For a sample of how to use AWS Cloud9 for Node.js development, see Node.js Sample for AWS Cloud9 in the AWS Cloud9 User Guide.

Topics

• Getting Started in a Browser Script (p. 3)

• Getting Started in Node.js (p. 8)

Getting Started in a Browser Script

This browser script example shows you:

• How to access AWS services from a browser script using Amazon Cognito Identity.

• How to turn text into synthesized speech using Amazon Polly.

• How to use a presigner object to create a presigned URL.

The Scenario

Amazon Polly is a cloud service that converts text into lifelike speech. You can use Amazon Polly to develop applications that increase engagement and accessibility. Amazon Polly supports multiple languages and includes a variety of lifelike voices. For more information about Amazon Polly, see the Amazon Polly Developer Guide.

The example shows how to set up and run a simple browser script that takes text you enter, sends that text to Amazon Polly, and then returns the URL of the synthesized audio of the text for you to play. The browser script uses Amazon Cognito Identity to provide credentials needed to access AWS services. You will see the basic patterns for loading and using the SDK for JavaScript in browser scripts.

NotePlayback of the synthesized speech in this example depends on running in a browser that supports HTML 5 audio.

(11)

Step 1: Create an Amazon Cognito Identity Pool

The browser script uses the SDK for JavaScript to synthesize text by using these APIs:

• AWS.CognitoIdentityCredentials constructor

• AWS.Polly.Presigner constructor

• getSynthesizeSpeechUrl

Step 1: Create an Amazon Cognito Identity Pool

In this exercise, you create and use an Amazon Cognito identity pool to provide unauthenticated access to your browser script for the Amazon Polly service. Creating an identity pool also creates two IAM roles, one to support users authenticated by an identity provider and the other to support unauthenticated guest users.

In this exercise, we will only work with the unauthenticated user role to keep the task focused. You can integrate support for an identity provider and authenticated users later.

To create an Amazon Cognito identity pool

1. Sign in to the AWS Management Console and open the Amazon Cognito console at Amazon Web Services Console.

2. Choose Manage Identity Pools on the console opening page.

3. On the next page, choose Create new identity pool.

NoteIf there are no other identity pools, the Amazon Cognito console will skip this page and open the next page instead.

4. In the Getting started wizard, type a name for your identity pool in Identity pool name.

5. Choose Enable access to unauthenticated identities.

6. Choose Create Pool.

7. On the next page, choose View Details to see the names of the two IAM roles created for your identity pool. Make a note of the name of the role for unauthenticated identities. You need this name to add the required policy for Amazon Polly.

8. Choose Allow.

9. On the Sample code page, select the Platform of JavaScript. Then, copy or write down the identity pool ID and the Region. You need these values to replace REGION and IDENTITY_POOL_ID in your browser script.

After you create your Amazon Cognito identity pool, you're ready to add permissions for Amazon Polly that are needed by your browser script.

Step 2: Add a Policy to the Created IAM Role

To enable browser script access to Amazon Polly for speech synthesis, use the unauthenticated IAM role created for your Amazon Cognito identity pool. This requires you to add an IAM policy to the role. For

(12)

Step 3: Create the HTML Page

more information on IAM roles, see Creating a Role to Delegate Permissions to an AWS Service in the IAM User Guide.

To add an Amazon Polly policy to the IAM role associated with unauthenticated users 1. Sign in to the AWS Management Console and open the IAM console at https://

console.aws.amazon.com/iam/.

2. In the navigation panel on the left of the page, choose Roles.

3. In the list of IAM roles, click on the link for the unauthenticated identities role previously created by Amazon Cognito.

4. In the Summary page for this role, choose Attach policies.

5. In the Attach Permissions page for this role, find and then select the check box for AmazonPollyFullAccess.

NoteYou can use this process to enable access to any Amazon service.

6. Choose Attach policy.

After you create your Amazon Cognito identity pool and add permissions for Amazon Polly to your IAM role for unauthenticated users, you are ready to build the webpage and browser script.

Step 3: Create the HTML Page

The sample app consists of a single HTML page that contains the user interface and browser script. To begin, create an HTML document and copy the following contents into it. The page includes an input field and button, an <audio> element to play the synthesized speech, and a <p> element to display messages. (Note that the full example is shown at the bottom of this page.)

For more information on the <audio> element, see audio.

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>AWS SDK for JavaScript - Browser Getting Started Application</title>

</head>

<body>

<div id="textToSynth">

<input autofocus size="23" type="text" id="textEntry" value="It's very good to meet you."/>

<button class="btn default" onClick="speakText()">Synthesize</button>

<p id="result">Enter text above then click Synthesize</p>

</div>

<audio id="audioPlayback" controls>

<source id="audioSource" type="audio/mp3" src="">

</audio>

<!-- (script elements go here) -->

</body>

</html>

Save the HTML file, naming it polly.html. After you have created the user interface for the application, you're ready to add the browser script code that runs the application.

Step 4: Write the Browser Script

The first thing to do when creating the browser script is to include the SDK for JavaScript by adding a

<script> element after the <audio> element in the page:

(13)

Step 4: Write the Browser Script

<script src="https://sdk.amazonaws.com/js/aws-sdk-SDK_VERSION_NUMBER.min.js"></script>

(To find the current SDK_VERSION_NUMBER, see the API Reference for the SDK for JavaScript at AWS SDK for JavaScript API Reference Guide.

Then add a new <script type="text/javascript"> element after the SDK entry. You'll add the browser script to this element. Set the AWS Region and credentials for the SDK. Next, create a function named speakText() that will be invoked as an event handler by the button.

To synthesize speech with Amazon Polly, you must provide a variety of parameters including the sound format of the output, the sampling rate, the ID of the voice to use, and the text to play back. When you initially create the parameters, set the Text: parameter to an empty string; the Text: parameter will be set to the value you retrieve from the <input> element in the webpage.

<script type="text/javascript">

// Initialize the Amazon Cognito credentials provider AWS.config.region = 'REGION';

AWS.config.credentials = new AWS.CognitoIdentityCredentials({IdentityPoolId:

'IDENTITY_POOL_ID'});

// Function invoked by button click function speakText() {

// Create the JSON parameters for getSynthesizeSpeechUrl var speechParams = {

OutputFormat: "mp3", SampleRate: "16000", Text: "",

TextType: "text", VoiceId: "Matthew"

};

speechParams.Text = document.getElementById("textEntry").value;

Amazon Polly returns synthesized speech as an audio stream. The easiest way to play that audio in a browser is to have Amazon Polly make the audio available at a presigned URL you can then set as the src attribute of the <audio> element in the webpage.

Create a new AWS.Polly service object. Then create the AWS.Polly.Presigner object you'll use to create the presigned URL from which the synthesized speech audio can be retrieved. You must pass the speech parameters that you defined as well as the AWS.Polly service object that you created to the AWS.Polly.Presigner constructor.

After you create the presigner object, call the getSynthesizeSpeechUrl method of that object, passing the speech parameters. If successful, this method returns the URL of the synthesized speech, which you then assign to the <audio> element for playback.

// Create the Polly service object and presigner object var polly = new AWS.Polly({apiVersion: '2016-06-10'});

var signer = new AWS.Polly.Presigner(speechParams, polly) // Create presigned URL of synthesized speech file

signer.getSynthesizeSpeechUrl(speechParams, function(error, url) { if (error) {

document.getElementById('result').innerHTML = error;

} else {

document.getElementById('audioSource').src = url;

document.getElementById('audioPlayback').load();

document.getElementById('result').innerHTML = "Speech ready to play.";

} });

(14)

Step 5: Run the Sample

} </script>

Step 5: Run the Sample

To run the sample app, load polly.html into a web browser. This is what the browser presentation should resemble.

Enter a phrase you want turned to speech in the input box, then choose Synthesize. When the audio is ready to play, a message appears. Use the audio player controls to hear the synthesized speech.

Full Sample

Here is the full HTML page with the browser script. It's also available here on GitHub.

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>AWS SDK for JavaScript - Browser Getting Started Application</title>

</head>

<body>

<div id="textToSynth">

<input autofocus size="23" type="text" id="textEntry" value="It's very good to meet you."/>

<button class="btn default" onClick="speakText()">Synthesize</button>

<p id="result">Enter text above then click Synthesize</p>

</div>

<audio id="audioPlayback" controls>

<source id="audioSource" type="audio/mp3" src="">

</audio>

<script src="https://sdk.amazonaws.com/js/aws-sdk-2.410.0.min.js"></script>

<script type="text/javascript">

// Initialize the Amazon Cognito credentials provider AWS.config.region = 'REGION';

AWS.config.credentials = new AWS.CognitoIdentityCredentials({IdentityPoolId:

'IDENTITY_POOL_ID'});

// Function invoked by button click function speakText() {

// Create the JSON parameters for getSynthesizeSpeechUrl var speechParams = {

OutputFormat: "mp3", SampleRate: "16000", Text: "",

TextType: "text", VoiceId: "Matthew"

};

speechParams.Text = document.getElementById("textEntry").value;

// Create the Polly service object and presigner object var polly = new AWS.Polly({apiVersion: '2016-06-10'});

var signer = new AWS.Polly.Presigner(speechParams, polly)

(15)

Possible Enhancements

// Create presigned URL of synthesized speech file

signer.getSynthesizeSpeechUrl(speechParams, function(error, url) { if (error) {

document.getElementById('result').innerHTML = error;

} else {

document.getElementById('audioSource').src = url;

document.getElementById('audioPlayback').load();

document.getElementById('result').innerHTML = "Speech ready to play.";

} });

} </script>

</body>

</html>

Possible Enhancements

Here are variations on this application you can use to further explore using the SDK for JavaScript in a browser script.

• Experiment with other sound output formats.

• Add the option to select any of the various voices provided by Amazon Polly.

• Integrate an identity provider like Facebook or Amazon to use with the authenticated IAM role.

Getting Started in Node.js

This Node.js code example shows:

• How to create the package.json manifest for your project.

• How to install and include the modules that your project uses.

• How to create an Amazon Simple Storage Service (Amazon S3) service object from the AWS.S3 client class.

• How to create an Amazon S3 bucket and upload an object to that bucket.

The Scenario

The example shows how to set up and run a simple Node.js module that creates an Amazon S3 bucket, then adds a text object to it.

Because bucket names in Amazon S3 must be globally unique, this example includes a third-party Node.js module that generates a unique ID value that you can incorporate into the bucket name. This additional module is named uuid.

Prerequisite Tasks

To set up and run this example, you must first complete these tasks:

(16)

Step 1: Install the SDK and Dependencies

• Create a working directory for developing your Node.js module. Name this directory awsnodesample.

Note that the directory must be created in a location that can be updated by applications. For example, in Windows, do not create the directory under "C:\Program Files".

• Install Node.js. For more information, see the Node.js website. You can find downloads of the current and LTS versions of Node.js for a variety of operating systems at https://nodejs.org/en/download/

current/.

Contents

• Step 1: Install the SDK and Dependencies (p. 9)

• Step 2: Configure Your Credentials (p. 9)

• Step 3: Create the Package JSON for the Project (p. 10)

• Step 4: Write the Node.js Code (p. 10)

• Step 5: Run the Sample (p. 11)

Step 1: Install the SDK and Dependencies

You install the SDK for JavaScript package using npm (the Node.js package manager).

From the awsnodesample directory in the package, type the following at the command line.

npm install aws-sdk

This command installs the SDK for JavaScript in your project, and updates package.json to list the SDK as a project dependency. You can find information about this package by searching for "aws-sdk" on the npm website.

Next, install the uuid module to the project by typing the following at the command line, which installs the module and updates package.json. For more information about uuid, see the module's page at https://www.npmjs.com/package/uuid.

npm install uuid

These packages and their associated code are installed in the node_modules subdirectory of your project.

For more information on installing Node.js packages, see Downloading and installing packages locally and Creating Node.js Modules on the npm (Node.js package manager) website. For information about downloading and installing the AWS SDK for JavaScript, see Installing the SDK for JavaScript (p. 16).

Step 2: Configure Your Credentials

You need to provide credentials to AWS so that only your account and its resources are accessed by the SDK. For more information about obtaining your account credentials, see Getting Your Credentials (p. 27).

To hold this information, we recommend you create a shared credentials file. To learn how, see Loading Credentials in Node.js from the Shared Credentials File (p. 30). Your credentials file should resemble the following example.

[default]

aws_access_key_id = YOUR_ACCESS_KEY_ID

(17)

Step 3: Create the Package JSON for the Project

aws_secret_access_key = YOUR_SECRET_ACCESS_KEY

You can determine whether you have set your credentials correctly by executing the following code with node:

var AWS = require("aws-sdk");

AWS.config.getCredentials(function(err) { if (err) console.log(err.stack);

// credentials not loaded else {

console.log("Access key:", AWS.config.credentials.accessKeyId);

} });

Similarly, if you have set your region correctly in your config file, you can display that value by setting the AWS_SDK_LOAD_CONFIG environment variable to a truthy value and using the following code:

var AWS = require("aws-sdk");

console.log("Region: ", AWS.config.region);

Step 3: Create the Package JSON for the Project

After you create the awsnodesample project directory, you create and add a package.json file for holding the metadata for your Node.js project. For details about using package.json in a Node.js project, see What is the file package.json?.

In the project directory, create a new file named package.json. Then add this JSON to the file.

{ "dependencies": {},

"name": "aws-nodejs-sample",

"description": "A simple Node.js application illustrating usage of the SDK for JavaScript.",

"version": "1.0.1", "main": "sample.js", "devDependencies": {}, "scripts": {

"test": "echo \"Error: no test specified\" && exit 1"

}, "author": "NAME", "license": "ISC"

}

Save the file. As you install the modules you need, the dependencies portion of the file will be completed. You can find a JSON file that shows an example of these dependencies here on GitHub.

Step 4: Write the Node.js Code

Create a new file named sample.js to contain the example code. Begin by adding the require function calls to include the SDK for JavaScript and uuid modules so that they are available for you to use.

Build a unique bucket name that is used to create an Amazon S3 bucket by appending a unique ID value to a recognizable prefix, in this case 'node-sdk-sample-'. You generate the unique ID by calling the uuid module. Then create a name for the Key parameter used to upload an object to the bucket.

(18)

Step 5: Run the Sample

Create a promise object to call the createBucket method of the AWS.S3 service object. On a successful response, create the parameters needed to upload text to the newly created bucket. Using another promise, call the putObject method to upload the text object to the bucket.

// Load the SDK and UUID var AWS = require('aws-sdk');

var uuid = require('uuid');

// Create unique bucket name

var bucketName = 'node-sdk-sample-' + uuid.v4();

// Create name for uploaded object key var keyName = 'hello_world.txt';

// Create a promise on S3 service object

var bucketPromise = new AWS.S3({apiVersion: '2006-03-01'}).createBucket({Bucket:

bucketName}).promise();

// Handle promise fulfilled/rejected states bucketPromise.then(

function(data) {

// Create params for putObject call

var objectParams = {Bucket: bucketName, Key: keyName, Body: 'Hello World!'};

// Create object upload promise

var uploadPromise = new AWS.S3({apiVersion:

'2006-03-01'}).putObject(objectParams).promise();

uploadPromise.then(

function(data) {

console.log("Successfully uploaded data to " + bucketName + "/" + keyName);

});

}).catch(

function(err) {

console.error(err, err.stack);

});

This sample code can be found here on GitHub.

Step 5: Run the Sample

Type the following command to run the sample.

node sample.js

If the upload is successful, you'll see a confirmation message at the command line. You can also find the bucket and the uploaded text object in the Amazon S3 console.

(19)

Step 1: Set up Your AWS Account to Use AWS Cloud9

Using AWS Cloud9 with the AWS SDK for JavaScript

You can use AWS Cloud9 with the AWS SDK for JavaScript to write and run your JavaScript in the browser code —as well as write, run, and debug your Node.js code—using just a browser. AWS Cloud9 includes tools such as a code editor and terminal, plus a debugger for Node.js code. Because the AWS Cloud9 IDE is cloud based, you can work on your projects from your office, home, or anywhere using an internet-connected machine. For general information about AWS Cloud9, see the AWS Cloud9 User Guide.

Follow these steps to set up AWS Cloud9 with the SDK for JavaScript:

Contents

• Step 1: Set up Your AWS Account to Use AWS Cloud9 (p. 12)

• Step 2: Set up Your AWS Cloud9 Development Environment (p. 12)

• Step 3: Set up the SDK for JavaScript (p. 13)

• To set up the SDK for JavaScript for Node.js (p. 13)

• To set up the SDK for JavaScript in the browser (p. 13)

• Step 4: Download Example Code (p. 13)

• Step 5: Run and Debug Example Code (p. 14)

Step 1: Set up Your AWS Account to Use AWS Cloud9

Start to use AWS Cloud9 by signing in to the AWS Cloud9 console as an AWS Identity and Access Management (IAM) entity (for example, an IAM user) who has access permissions for AWS Cloud9 in your AWS account.

To set up an IAM entity in your AWS account to access AWS Cloud9, and to sign in to the AWS Cloud9 console, see Team Setup for AWS Cloud9 in the AWS Cloud9 User Guide.

Step 2: Set up Your AWS Cloud9 Development Environment

After you sign in to the AWS Cloud9 console, use the console to create an AWS Cloud9 development environment. After you create the environment, AWS Cloud9 opens the IDE for that environment.

See Creating an Environment in AWS Cloud9 in the AWS Cloud9 User Guide for details.

Note

As you create your environment in the console for the first time, we recommend that you choose the option to Create a new instance for environment (EC2). This option tells AWS Cloud9 to create an environment, launch an Amazon EC2 instance, and then connect the new instance to the new environment. This is the fastest way to begin using AWS Cloud9.

(20)

Step 3: Set up the SDK for JavaScript

Step 3: Set up the SDK for JavaScript

After AWS Cloud9 opens the IDE for your development environment, follow one or both of the following procedures to use the IDE to set up the SDK for JavaScript in your environment.

To set up the SDK for JavaScript for Node.js

1. If the terminal isn't already open in the IDE, open it. To do this, on the menu bar in the IDE, choose Window, New Terminal.

2. Run the following command to use npm to install the SDK for JavaScript.

npm install aws-sdk

If the IDE can't find npm, run the following commands, one at a time in the following order, to install npm. (These commands assume you chose the option to Create a new instance for environment (EC2), earlier in this topic.)

Warning

AWS does not control the following code. Before you run it, be sure to verify its authenticity and integrity. More information about this code can be found in the nvm GitHub repository.

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash # Download and install Node Version Manager (nvm).

. ~/.bashrc # Activate nvm.

nvm install node # Use nvm to install npm (and Node.js at the same time).

To set up the SDK for JavaScript in the browser

You don't have to install the SDK for JavaScript to use it in browser scripts. You can load the hosted SDK for JavaScript package directly from AWS with a script in your HTML pages.

You can download minified and non-minified distributable versions of the current SDK for JavaScript from GitHub at https://github.com/aws/aws-sdk-js/tree/master/dist.

Step 4: Download Example Code

Use the terminal you opened in the previous step to download example code for the SDK for JavaScript into the AWS Cloud9 development environment. (If the terminal isn't already open in the IDE, open it by choosing Window, New Terminal on the menu bar in the IDE.)

To download the example code, run the following command. This command downloads a copy of all of the code examples used in the official AWS SDK documentation into your environment's root directory.

git clone https://github.com/awsdocs/aws-doc-sdk-examples.git

To find code examples for the SDK for JavaScript, use the Environment window to open the ENVIRONMENT_NAME\aws-doc-sdk-examples\javascript\example_code, where ENVIRONMENT_NAME is the name of your AWS Cloud9 development environment.

To learn how to work with these and other code examples, see SDK for JavaScript Code Examples.

(21)

Step 5: Run and Debug Example Code

Step 5: Run and Debug Example Code

To run code in your AWS Cloud9 development environment, see Run Your Code in the AWS Cloud9 User Guide.

To debug Node.js code, see Debug Your Code in the AWS Cloud9 User Guide.

(22)

Prerequisites

Setting Up the SDK for JavaScript

The topics in this section explain how to install the SDK for JavaScript for use in web browsers and with Node.js. It also shows how to load the SDK so you can access the web services supported by the SDK.

NoteReact Native developers should use AWS Amplify to create new projects on AWS. See the aws- sdk-react-native archive for details.

Topics

• Prerequisites (p. 15)

• Installing the SDK for JavaScript (p. 16)

• Loading the SDK for JavaScript (p. 17)

• Upgrading the SDK for JavaScript from Version 1 (p. 18)

Prerequisites

Before you use the AWS SDK for JavaScript, determine whether your code needs to run in Node.js or web browsers. After that, do the following:

• For Node.js, install Node.js on your servers if it is not already installed.

• For web browsers, identify the browser versions you need to support.

Topics

• Setting Up an AWS Node.js Environment (p. 15)

• Web Browsers Supported (p. 16)

Setting Up an AWS Node.js Environment

To set up an AWS Node.js environment in which you can run your application, use any of the following methods:

• Choose an Amazon Machine Image (AMI) with Node.js pre-installed and create an Amazon EC2 instance using that AMI. When creating your Amazon EC2 instance, choose your AMI from the AWS Marketplace. Search the AWS Marketplace for Node.js and choose an AMI option that includes a version of Node.js (32-bit or 64-bit) pre-installed.

• Create an Amazon EC2 instance and install Node.js on it. For more information about how to install Node.js on an Amazon Linux instance, see Tutorial: Setting Up Node.js on an Amazon EC2 Instance (p. 231).

• Create a serverless environment using AWS Lambda to run Node.js as a Lambda function. For more information about using Node.js within a Lambda function, see Programming Model (Node.js) in the AWS Lambda Developer Guide.

• Deploy your Node.js application to AWS Elastic Beanstalk. For more information on using Node.js with Elastic Beanstalk, see Deploying Node.js Applications to AWS Elastic Beanstalk in the AWS Elastic Beanstalk Developer Guide.

• Create a Node.js application server using AWS OpsWorks. For more information on using Node.js with AWS OpsWorks, see Creating Your First Node.js Stack in the AWS OpsWorks User Guide.

(23)

Web Browsers Supported

Web Browsers Supported

The SDK for JavaScript supports all modern web browsers, including these minimum versions:

Browser Version

Google Chrome 28.0+

Mozilla Firefox 26.0+

Opera 17.0+

Microsoft Edge 25.10+

Windows Internet Explorer N/A

Apple Safari 5+

Android Browser 4.3+

Note

Frameworks such as AWS Amplify might not offer the same browser support as the SDK for JavaScript. Check a framework's documentation for details.

Installing the SDK for JavaScript

Whether and how you install the AWS SDK for JavaScript depends whether the code executes in Node.js modules or browser scripts.

Not all services are immediately available in the SDK. To find out which services are currently supported by the AWS SDK for JavaScript, see https://github.com/aws/aws-sdk-js/blob/master/SERVICES.md Node

The preferred way to install the AWS SDK for JavaScript for Node.js is to use npm, the Node.js package manager. To do so, type this at the command line.

npm install aws-sdk

In the event you see this error message:

npm WARN deprecated [email protected]: Use uuid module instead

Type these commands at the command line:

npm uninstall --save node-uuid npm install --save uuid

Browser

You don't have to install the SDK to use it in browser scripts. You can load the hosted SDK package directly from Amazon Web Services with a script in your HTML pages. The hosted SDK package supports the subset of AWS services that enforce cross-origin resource sharing (CORS). For more information, see Loading the SDK for JavaScript (p. 17).

(24)

Installing Using Bower

You can create a custom build of the SDK in which you select the specific web services and versions that you want to use. You then download your custom SDK package for local development and host it for your application to use. For more information about creating a custom build of the SDK, see Building the SDK for Browsers (p. 43).

You can download minified and non-minified distributable versions of the current AWS SDK for JavaScript from GitHub at:

https://github.com/aws/aws-sdk-js/tree/master/dist

Installing Using Bower

Bower is a package manager for the web. After you install Bower, you can use it to install the SDK. To install the SDK using Bower, type the following into a terminal window:

bower install aws-sdk-js

Loading the SDK for JavaScript

How you load the SDK for JavaScript depends on whether you are loading it to run in a web browser or in Node.js.

Not all services are immediately available in the SDK. To find out which services are currently supported by the AWS SDK for JavaScript, see https://github.com/aws/aws-sdk-js/blob/master/SERVICES.md Node.js

After you install the SDK, you can load the AWS package in your node application using require.

var AWS = require('aws-sdk');

React Native

To use the SDK in a React Native project, first install the SDK using npm:

npm install aws-sdk

In your application, reference the React Native compatible version of the SDK with the following code:

var AWS = require('aws-sdk/dist/aws-sdk-react-native');

Browser

The quickest way to get started with the SDK is to load the hosted SDK package directly from Amazon Web Services. To do this, add a <script> element to your HTML pages in the following form:

<script src="https://sdk.amazonaws.com/js/aws-sdk-SDK_VERSION_NUMBER.min.js"></script>

To find the current SDK_VERSION_NUMBER, see the API Reference for the SDK for JavaScript at AWS SDK for JavaScript API Reference Guide.

After the SDK loads in your page, the SDK is available from the global variable AWS (or window.AWS).

(25)

Upgrading From Version 1

If you bundle your code and module dependencies using browserify, you load the SDK using require, just as you do in Node.js.

Upgrading the SDK for JavaScript from Version 1

The following notes help you upgrade the SDK for JavaScript from version 1 to version 2.

Automatic Conversion of Base64 and Timestamp Types on Input/Output

The SDK now automatically encodes and decodes base64-encoded values, as well as timestamp values, on the user's behalf. This change affects any operation where base64 or timestamp values were sent by a request or returned in a response that allows for base64-encoded values.

User code that previously converted base64 is no longer required. Values encoded as base64 are now returned as buffer objects from server responses and can also be passed as buffer input. For example, the following version 1 SQS.sendMessage parameters:

var params = {

MessageBody: 'Some Message', MessageAttributes: {

attrName: {

DataType: 'Binary',

BinaryValue: new Buffer('example text').toString('base64') }

}};

Can be rewritten as follows.

var params = {

MessageBody: 'Some Message', MessageAttributes: {

attrName: {

DataType: 'Binary',

BinaryValue: 'example text' }

} };

Here is how the message is read.

sqs.receiveMessage(params, function(err, data) {

// buf is <Buffer 65 78 61 6d 70 6c 65 20 74 65 78 74>

var buf = data.Messages[0].MessageAttributes.attrName.BinaryValue;

console.log(buf.toString()); // "example text"

});

Moved response.data.RequestId to response.requestId

The SDK now stores request IDs for all services in a consistent place on the response object, rather than inside the response.data property. This improves consistency across services that expose request IDs in different ways. This is also a breaking change that renames the response.data.RequestId property to response.requestId (this.requestId inside a callback function).

(26)

Exposed Wrapper Elements

In your code, change the following:

svc.operation(params, function (err, data) { console.log('Request ID:', data.RequestId);

});

To the following:

svc.operation(params, function () {

console.log('Request ID:', this.requestId);

});

Exposed Wrapper Elements

If you use AWS.ElastiCache, AWS.RDS, or AWS.Redshift, you must access the response through the top-level output property in the response for some operations.

For example, the RDS.describeEngineDefaultParameters method used to return the following.

{ Parameters: [ ... ] } It now returns the following.

{ EngineDefaults: { Parameters: [ ... ] } }

The list of affected operations for each service are shown in the following table.

Client Class Operations

AWS.ElastiCache authorizeCacheSecurityGroupIngress

createCacheCluster

createCacheParameterGroup createCacheSecurityGroup createCacheSubnetGroup createReplicationGroup deleteCacheCluster deleteReplicationGroup

describeEngineDefaultParameters modifyCacheCluster

modifyCacheSubnetGroup modifyReplicationGroup

purchaseReservedCacheNodesOffering rebootCacheCluster

revokeCacheSecurityGroupIngress

(27)

Exposed Wrapper Elements

Client Class Operations

AWS.RDS addSourceIdentifierToSubscription

authorizeDBSecurityGroupIngress copyDBSnapshot createDBInstance createDBInstanceReadReplica createDBParameterGroup createDBSecurityGroup createDBSnapshot createDBSubnetGroup createEventSubscription createOptionGroup deleteDBInstance deleteDBSnapshot

deleteEventSubscription

describeEngineDefaultParameters modifyDBInstance

modifyDBSubnetGroup modifyEventSubscription modifyOptionGroup promoteReadReplica

purchaseReservedDBInstancesOffering rebootDBInstance

removeSourceIdentifierFromSubscription restoreDBInstanceFromDBSnapshot

restoreDBInstanceToPointInTime revokeDBSecurityGroupIngress

(28)

Dropped Client Properties

Client Class Operations

AWS.Redshift authorizeClusterSecurityGroupIngress

authorizeSnapshotAccess copyClusterSnapshot createCluster

createClusterParameterGroup createClusterSecurityGroup createClusterSnapshot createClusterSubnetGroup createEventSubscription createHsmClientCertificate createHsmConfiguration deleteCluster

deleteClusterSnapshot

describeDefaultClusterParameters disableSnapshotCopy

enableSnapshotCopy modifyCluster

modifyClusterSubnetGroup modifyEventSubscription

modifySnapshotCopyRetentionPeriod purchaseReservedNodeOffering rebootCluster

restoreFromClusterSnapshot

revokeClusterSecurityGroupIngress revokeSnapshotAccess

rotateEncryptionKey

Dropped Client Properties

The .Client and .client properties have been removed from service objects. If you use the .Client property on a service class or a .client property on a service object instance, remove these properties from your code.

(29)

Dropped Client Properties

The following code used with version 1 of the SDK for JavaScript:

var sts = new AWS.STS.Client();

// or

var sts = new AWS.STS();

sts.client.operation(...);

Should be changed to the following code.

var sts = new AWS.STS();

sts.operation(...)

(30)

Using the Global Configuration Object

Configuring the SDK for JavaScript

Before you use the SDK for JavaScript to invoke web services using the API, you must configure the SDK.

At a minimum, you must configure these settings:

• The Region in which you will request services.

• The credentials that authorize your access to SDK resources.

In addition to these settings, you may also have to configure permissions for your AWS resources. For example, you can limit access to an Amazon S3 bucket or restrict an Amazon DynamoDB table for read- only access.

The topics in this section describe various ways to configure the SDK for JavaScript for Node.js and JavaScript running in a web browser.

Topics

• Using the Global Configuration Object (p. 23)

• Setting the AWS Region (p. 25)

• Specifying Custom Endpoints (p. 27)

• Getting Your Credentials (p. 27)

• Setting Credentials (p. 28)

• Locking API Versions (p. 39)

• Node.js Considerations (p. 39)

• Browser Script Considerations (p. 43)

• Bundling Applications with Webpack (p. 48)

Using the Global Configuration Object

There are two ways to configure the SDK:

• Set the global configuration using AWS.Config.

• Pass extra configuration information to a service object.

Setting global configuration with AWS.Config is often easier to get started, but service-level configuration can provide more control over individual services. The global configuration specified by AWS.Config provides default settings for service objects that you create subsequently, simplifying their configuration. However, you can update the configuration of individual service objects when your needs vary from the global configuration.

Setting Global Configuration

After you load the aws-sdk package in your code you can use the AWS global variable to access the SDK's classes and interact with individual services. The SDK includes a global configuration object, AWS.Config, that you can use to specify the SDK configuration settings required by your application.

(31)

Setting Global Configuration

Configure the SDK by setting AWS.Config properties according to your application needs. The following table summarizes AWS.Config properties commonly used to set the configuration of the SDK.

Configuration Options Description

credentials Required. Specifies the credentials used to

determine access to services and resources.

region Required. Specifies the Region in which requests

for services are made.

maxRetries Optional. Specifies the maximum number of times

a given request is retried.

logger Optional. Specifies a logger object to which

debugging information is written.

update Optional. Updates the current configuration with

new values.

For more information about the configuration object, see Class: AWS.Config in the API Reference.

Global Configuration Examples

You must set the Region and the credentials in AWS.Config. You can set these properties as part of the AWS.Config constructor, as shown in the following browser script example:

var myCredentials = new

AWS.CognitoIdentityCredentials({IdentityPoolId:'IDENTITY_POOL_ID'});

var myConfig = new AWS.Config({

credentials: myCredentials, region: 'us-west-2' });

You can also set these properties after creating AWS.Config using the update method, as shown in the following example that updates the Region:

myConfig = new AWS.Config();

myConfig.update({region: 'us-east-1'});

You can get your default credentials by calling the static getCredentials method of AWS.config:

var AWS = require("aws-sdk");

AWS.config.getCredentials(function(err) { if (err) console.log(err.stack);

// credentials not loaded else {

console.log("Access key:", AWS.config.credentials.accessKeyId);

} });

Similarly, if you have set your region correctly in your config file, you get that value by setting the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value and calling the static region property of AWS.config:

var AWS = require("aws-sdk");

(32)

Setting Configuration Per Service

console.log("Region: ", AWS.config.region);

Setting Configuration Per Service

Each service that you use in the SDK for JavaScript is accessed through a service object that is part of the API for that service. For example, to access the Amazon S3 service you create the Amazon S3 service object. You can specify configuration settings that are specific to a service as part of the constructor for that service object. When you set configuration values on a service object, the constructor takes all of the configuration values used by AWS.Config, including credentials.

For example, if you need to access Amazon EC2 objects in multiple Regions, create an Amazon EC2 service object for each Region and then set the Region configuration of each service object accordingly.

var ec2_regionA = new AWS.EC2({region: 'ap-southeast-2', maxRetries: 15, apiVersion:

'2014-10-01'});

var ec2_regionB = new AWS.EC2({region: 'us-east-1', maxRetries: 15, apiVersion:

'2014-10-01'});

You can also set configuration values specific to a service when configuring the SDK with AWS.Config.

The global configuration object supports many service-specific configuration options. For more information about service-specific configuration, see Class: AWS.Config in the AWS SDK for JavaScript API Reference.

Immutable Configuration Data

Global configuration changes apply to requests for all newly created service objects. Newly created service objects are configured with the current global configuration data first and then any local configuration options. Updates you make to the global AWS.config object don't apply to previously created service objects.

Existing service objects must be manually updated with new configuration data or you must create and use a new service object that has the new configuration data. The following example creates a new Amazon S3 service object with new configuration data:

s3 = new AWS.S3(s3.config);

Setting the AWS Region

A Region is a named set of AWS resources in the same geographical area. An example of a Region is us- east-1, which is the US East (N. Virginia) Region. You specify a Region when configuring the SDK for JavaScript so that the SDK accesses the resources in that Region. Some services are available only in specific Regions.

The SDK for JavaScript doesn't select a Region by default. However, you can set the Region using an environment variable, a shared config file, or the global configuration object.

In a Client Class Constructor

When you instantiate a service object, you can specify the Region for that resource as part of the client class constructor, as shown here.

var s3 = new AWS.S3({apiVersion: '2006-03-01', region: 'us-east-1'});

(33)

Using the Global Configuration Object

Using the Global Configuration Object

To set the Region in your JavaScript code, update the AWS.Config global configuration object as shown here.

AWS.config.update({region: 'us-east-1'});

For more information about current Regions and available services in each Region, see AWS Regions and Endpoints in the AWS General Reference.

Using an Environment Variable

You can set the Region using the AWS_REGION environment variable. If you define this variable, the SDK for JavaScript reads it and uses it.

Using a Shared Config File

Much like the shared credentials file lets you store credentials for use by the SDK, you can keep your Region and other configuration settings in a shared file named config that is used by SDKs. If the AWS_SDK_LOAD_CONFIG environment variable has been set to a truthy value, the SDK for JavaScript automatically searches for a config file when it loads. Where you save the config file depends on your operating system:

• Linux, macOS, or Unix users: ~/.aws/config

• Windows users: C:\Users\USER_NAME\.aws\config

If you don't already have a shared config file, you can create one in the designated directory. In the following example, the config file sets both the Region and the output format.

[default]

region=us-east-1 output=json

For more information about using shared config and credentials files, see Loading Credentials in Node.js from the Shared Credentials File (p. 30) or Configuration and Credential Files in the AWS Command Line Interface User Guide.

Order of Precedence for Setting the Region

The order of precedence for Region setting is as follows:

• If a Region is passed to a client class constructor, that Region is used. If not, then...

• If a Region is set on the global configuration object, that Region is used. If not, then...

• If the AWS_REGION environment variable is a truthy value, that Region is used. If not, then...

• If the AMAZON_REGION environment variable is a truthy value, that Region is used. If not, then...

• If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value and the shared credentials file (~/.aws/credentials or the path indicated by AWS_SHARED_CREDENTIALS_FILE) contains a Region for the configured profile, that Region is used. If not, then...

• If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value and the config file (~/.aws/config or the path indicated by AWS_CONFIG_FILE) contains a Region for the configured profile, that Region is used.

(34)

Specifying Custom Endpoints

Specifying Custom Endpoints

Calls to API methods in the SDK for JavaScript are made to service endpoint URIs. By default, these endpoints are built from the Region you have configured for your code. However, there are situations in which you need to specify a custom endpoint for your API calls.

Endpoint String Format

Endpoint values should be a string in the format:

https://{service}.{region}.amazonaws.com

Endpoints for the ap-northeast-3 Region

The ap-northeast-3 Region in Japan is not returned by Region enumeration APIs, such as

EC2.describeRegions. To define endpoints for this Region, follow the format described previously. So the Amazon EC2 endpoint for this Region would be

ec2.ap-northeast-3.amazonaws.com

Endpoints for MediaConvert

You need to create a custom endpoint to use with MediaConvert. Each customer account is assigned its own endpoint, which you must use. Here is an example of how to use a custom endpoint with MediaConvert.

// Create MediaConvert service object using custom endpoint

var mcClient = new AWS.MediaConvert({endpoint: 'https://abcd1234.mediaconvert.us- west-1.amazonaws.com'});

var getJobParams = {Id: 'job_ID'};

mcClient.getJob(getJobParams, function(err, data)) {

if (err) console.log(err, err.stack); // an error occurred else console.log(data); // successful response

};

To get your account API endpoint, see MediaConvert.describeEndpoints in the API Reference.

Make sure you specify the same Region in your code as the Region in the custom endpoint URI. A mismatch between the Region setting and the custom endpoint URI can cause API calls to fail.

For more information on MediaConvert, see the AWS.MediaConvert class in the API Reference or the AWS Elemental MediaConvert User Guide.

Getting Your Credentials

When you create an AWS account, your account is provided with root credentials. Those credentials consist of two access keys:

• Access key ID

• Secret access key

(35)

Setting Credentials

For more information on your access keys, see Understanding and Getting Your Security Credentials in the AWS General Reference.

Access keys consist of an access key ID and secret access key, which are used to sign programmatic requests that you make to AWS. If you don't have access keys, you can create them from the AWS Management Console. As a best practice, do not use the AWS account root user access keys for any task where it's not required. Instead, create a new administrator IAM user with access keys for yourself.

The only time that you can view or download the secret access key is when you create the keys. You cannot recover them later. However, you can create new access keys at any time. You must also have permissions to perform the required IAM actions. For more information, see Permissions required to access IAM resources in the IAM User Guide.

To create access keys for an IAM user

1. Sign in to the AWS Management Console and open the IAM console at https://

console.aws.amazon.com/iam/.

2. In the navigation pane, choose Users.

3. Choose the name of the user whose access keys you want to create, and then choose the Security credentials tab.

4. In the Access keys section, choose Create access key.

5. To view the new access key pair, choose Show. You will not have access to the secret access key again after this dialog box closes. Your credentials will look something like this:

• Access key ID: AKIAIOSFODNN7EXAMPLE

• Secret access key: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY

6. To download the key pair, choose Download .csv file. Store the keys in a secure location. You will not have access to the secret access key again after this dialog box closes.

Keep the keys confidential in order to protect your AWS account and never email them. Do not share them outside your organization, even if an inquiry appears to come from AWS or Amazon.com. No one who legitimately represents Amazon will ever ask you for your secret key.

7. After you download the .csv file, choose Close. When you create an access key, the key pair is active by default, and you can use the pair right away.

Related topics

• What is IAM? in the IAM User Guide

• AWS security credentials in AWS General Reference

Setting Credentials

AWS uses credentials to identify who is calling services and whether access to the requested resources is allowed. In AWS, these credentials are typically the access key ID and the secret access key that were created along with your account.

Whether running in a web browser or in a Node.js server, your JavaScript code must obtain valid credentials before it can access services through the API. Credentials can be set globally on the configuration object, using AWS.Config, or per service, by passing credentials directly to a service object.

There are several ways to set credentials that differ between Node.js and JavaScript in web browsers. The topics in this section describe how to set credentials in Node.js or web browsers. In each case, the options are presented in recommended order.

(36)

Best Practices for Credentials

Best Practices for Credentials

Properly setting credentials ensures that your application or browser script can access the services and resources needed while minimizing exposure to security issues that may impact mission critical applications or compromise sensitive data.

An important principle to apply when setting credentials is to always grant the least privilege required for your task. It's more secure to provide minimal permissions on your resources and add further permissions as needed, rather than provide permissions that exceed the least privilege and, as a result, be required to fix security issues you might discover later. For example, unless you have a need to read and write individual resources, such as objects in an Amazon S3 bucket or a DynamoDB table, set those permissions to read only.

For more information on granting the least privilege, see the Grant Least Privilege section of the Best Practices topic in the IAM User Guide.

Warning

While it is possible to do so, we recommend you not hard code credentials inside an application or browser script. Hard coding credentials poses a risk of exposing your access key ID and secret access key.

For more information about how to manage your access keys, see Best Practices for Managing AWS Access Keys in the AWS General Reference.

Topics

• Setting Credentials in Node.js (p. 29)

• Setting Credentials in a Web Browser (p. 32)

Setting Credentials in Node.js

There are several ways in Node.js to supply your credentials to the SDK. Some of these are more secure and others afford greater convenience while developing an application. When obtaining credentials in Node.js, be careful about relying on more than one source such as an environment variable and a JSON file you load. You can change the permissions under which your code runs without realizing the change has happened.

Here are the ways you can supply your credentials in order of recommendation:

1. Loaded from AWS Identity and Access Management (IAM) roles for Amazon EC2 2. Loaded from the shared credentials file (~/.aws/credentials)

3. Loaded from environment variables 4. Loaded from a JSON file on disk

5. Other credential-provider classes provided by the JavaScript SDK

If more than one credential source is available to the SDK, the default precedence of selection is as follows:

1. Credentials that are explicitly set through the service-client constructor 2. Environment variables

3. The shared credentials file

4. Credentials loaded from the ECS credentials provider (if applicable)

5. Credentials that are obtained by using a credential process specified in the shared AWS config file or the shared credentials file. For more information, see the section called “Credentials using a Configured Credential Process” (p. 32).

(37)

Setting Credentials in Node.js

6. Credentials loaded from AWS IAM using the credentials provider of the Amazon EC2 instance (if configured in the instance metadata)

For more information, see Class: AWS.Credentials and Class:

AWS.CredentialProviderChain in the API reference.

Warning

While it is possible to do so, we do not recommend hard-coding your AWS credentials in your application. Hard-coding credentials poses a risk of exposing your access key ID and secret access key.

The topics in this section describe how to load credentials into Node.js.

Topics

• Loading Credentials in Node.js from IAM roles for Amazon EC2 (p. 30)

• Loading Credentials for a Node.js Lambda Function (p. 30)

• Loading Credentials in Node.js from the Shared Credentials File (p. 30)

• Loading Credentials in Node.js from Environment Variables (p. 31)

• Loading Credentials in Node.js from a JSON File (p. 32)

• Loading Credentials in Node.js using a Configured Credential Process (p. 32)

Loading Credentials in Node.js from IAM roles for Amazon EC2

If you run your Node.js application on an Amazon EC2 instance, you can leverage IAM roles for Amazon EC2 to automatically provide credentials to the instance. If you configure your instance to use IAM roles, the SDK automatically selects the IAM credentials for your application, eliminating the need to manually provide credentials.

For more information on adding IAM roles to an Amazon EC2 instance, see IAM Roles for Amazon EC2.

Loading Credentials for a Node.js Lambda Function

When you create an AWS Lambda function, you must create a special IAM role that has permission to execute the function. This role is called the execution role. When you set up a Lambda function, you must specify the IAM role you created as the corresponding execution role.

The execution role provides the Lambda function with the credentials it needs to run and to invoke other web services. As a result, you do not need to provide credentials to the Node.js code you write within a Lambda function.

For more information about creating a Lambda execution role, see Manage Permissions: Using an IAM Role (Execution Role) in the AWS Lambda Developer Guide.

Loading Credentials in Node.js from the Shared Credentials File

You can keep your AWS credentials data in a shared file used by SDKs and the command line interface.

When the SDK for JavaScript loads, it automatically searches the shared credentials file, which is named

"credentials". Where you keep the shared credentials file depends on your operating system:

• The shared credentials file on Linux, Unix, and macOS: ~/.aws/credentials

• The shared credentials file on Windows: C:\Users\USER_NAME\.aws\credentials

If you do not already have a shared credentials file, see Getting Your Credentials (p. 27). Once you follow those instructions, you should see text similar to the following in the credentials file, where

參考文獻

相關文件

In the third paragraph, please write a 100-word paragraph to talk about what you’d do in the future to make this research better and some important citations if any.. Please help

Like regular full-time teachers, regular part-time teachers within the approved teaching establishment are subject to the provisions under the Code of Aid, including (a)

Like regular full-time teachers, regular part-time teachers within the approved teaching establishment are subject to the provisions under the Code of Aid, including (a)

 The TRG consists of two components: a basic component which is an annual recurrent cash grant provided to schools for the appointment of supply teachers to cover approved

In the event that reduction of staff entitlement affects the number of senior teachers (i.e. teachers appointed at promotion ranks) and/or the headship entitlement of a school, a

After teaching the use and importance of rhyme and rhythm in chants, an English teacher designs a choice board for students to create a new verse about transport based on the chant

Creative approach for counseling individual children in the school setting... Creative approach for counseling individual children in the

In case of non UPnP AV scenario, any application (acting as a Control Point) can invoke the QosManager service for setting up the Quality of Service for a particular traffic..