Skip to content

Instantly share code, notes, and snippets.

@nooptr
Last active April 10, 2020 06:12
Show Gist options
  • Save nooptr/55905638f49a7912de5cebf22974e37d to your computer and use it in GitHub Desktop.
Save nooptr/55905638f49a7912de5cebf22974e37d to your computer and use it in GitHub Desktop.
nodejs aws credentials
Thứ thự load credentials sẽ như sau:
1. Load từ role IAM của Amazon EC2
2. Load từ file (~/.aws/credentials)
3. Load từ biến môi trường
4. Load từ file json ở trên disk
5. Thông tin credential được định nghĩa trực tiếp trong file JS
====
Có 1 số cách có thể load được cấu hình IAM của aws vào trong nodejs
Cách 1. Truyền trực tiếp biến môi trường vào trong command line khi chạy
```bash
AWS_REGION=ap-northeast-1 AWS_PROFILE=nooptr node index.js
```
Cách 2. Load file credentials.json vào trong js
Thêm đoạn code sau vào đầu file js
```
const AWS = require("aws-sdk");
AWS.config.loadFromPath("/Users/nooptr/project/sample-nodejs/credentials.json");
```
Nội dung file credentials.json sẽ như sau:
``
{
"accessKeyId": "XXX",
"secretAccessKey": "XXX",
"region": "ap-northeast-1"
}
```
Cách 3. Thêm thông tin vào trong file ~/.aws/credentials
Chạy dòng lệnh sau ở terminal:
```
$ aws configure
AWS Access Key ID [****************73NA]: XXXX
AWS Secret Access Key [****************90em]: XXXX
Default region name [ap-northeast-1]: ap-northeast-1
Default output format [json]: json
```
Khi đó nội dung file ~/.aws/credentials sẽ như sau:
```
# ~/.aws/credentials
[default]
aws_access_key_id = XXXX
aws_secret_access_key = XXXX
region=ap-northeast-1
```
Khi đó nó sẽ được thêm phần [default] vào trong file ~/.aws/credentials. Từ bây giờ chúng ta có thể chạy lệnh node index.js là ok
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment