
上QQ阅读APP看书,第一时间看更新
AWS SDKs
The SDK is the best way to manage your AWS resources through reusable code. Using the SDK, you can automate your infrastructure and handle errors using very simple commands. There are SDKs for many different programming languages like Java, Python, Ruby, and others. In this book, we will use exclusively the SDK for Node.js. The official documentation is available at http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/index.html.
All code examples in this book use Node.js, which is a cross-platform JavaScript runtime with an event-driven model. Basic knowledge of Node.js is expected from the reader since we will not cover the basics. Also, we will use Node's default package manager, npm, to install dependencies.
Let's learn about using the SDK for Node.js by performing the following steps:
- Start a new Node project using npm init and run the npm command to install the AWS SDK:
npm install aws-sdk --save
- After installing, you need to set the access keys that will be used by the SDK to connect to AWS. These keys were generated in the previous section, when we created a new user.
- The following are a few options to set the credentials:
- Setting the credentials with hardcoded keys
- Loading a JSON file on disk
- Setting a credentials file
- Setting environment variables
You should always avoid hardcoding AWS keys, especially in open source projects on GitHub. You don't want to risk accidentally committing your private keys.
- I prefer to configure them through environment variables. If you are running on macOS or Linux, add the following lines to the ~/.bash_profile file. Replace YOUR-KEY and YOUR-REGION by the real values:
export AWS_ACCESS_KEY_ID=YOUR-KEY
export AWS_SECRET_ACCESS_KEY=YOUR-KEY
export AWS_REGION=YOUR-REGION
- If you are running on Windows, execute the following commands on command prompt as the admin, replacing the values of the keys and region:
setx AWS_ACCESS_KEY_ID YOUR-KEY
setx AWS_SECRET_ACCESS_KEY YOUR-KEY
setx AWS_REGION YOUR-REGION
- If you don't have a preferred region, you can use us-east-1 (Northern Virginia, US East). When you use the AWS Management Console, you can set the region where you are going to manage the resources through the upper-right drop-down menu.
Both the configurations are persistent, but they will work only for the next time that you open the command line.
- You can test your setup creating a new file named index.js and running the following code to list your S3 buckets. As a simplified definition, you can consider a bucket as a repository of files. Now, if you have proper access, this example will return your bucket list or an empty array, if there is none. If you don't have access or had a problem setting the credentials, it will return an error:
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
s3.listBuckets((err, data) => {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data.Buckets); // successful response
});