-
Notifications
You must be signed in to change notification settings - Fork 0
/
offline.js
73 lines (66 loc) · 2.43 KB
/
offline.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
const util = require('util');
const { spawn } = require('child_process');
const moment = require('moment');
const exec = util.promisify(require('child_process').exec);
const AWS = require('aws-sdk');
const sts = new AWS.STS();
const iam = new AWS.IAM();
const { table } = require('./config.json');
const tableNames = {};
Object.keys(table).forEach((k) => (tableNames[k] = k));
const indexNames = {};
Object.keys(table).forEach((k) => {
if (typeof table[k].GlobalSecondaryIndexes !== 'undefined') {
const gsi = table[k].GlobalSecondaryIndexes;
gsi.forEach((i) => {
indexNames[i.IndexName] = i.IndexName;
});
}
});
const stage = process.env.npm_lifecycle_event;
async function getCallerIdentityAccuont() {
try {
const callerIdentityPromise = await sts.getCallerIdentity().promise();
const callerIdentity = callerIdentityPromise.Account;
return callerIdentity;
} catch (e) {
console.error(e);
}
}
(async function () {
const accountId = await getCallerIdentityAccuont();
const roleName = 'YOUR_IAM_ROLE'; // You should put your iam role here if you need to assume role to make request to the cloud databases
let accessKeyId = process.env.AWS_ACCESS_KEY_ID;
let secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY;
let sessionToken;
if (roleName !== 'YOUR_IAM_ROLE') {
const getRole = await iam.getRole({ RoleName: roleName }).promise();
const timestamp = moment(new Date()).format('YYYY-MM-DD');
const { stdout } = await exec(
`aws sts assume-role --role-arn ${getRole.Role.Arn} --role-session-name deploy-${timestamp}`,
);
const result = JSON.parse(stdout);
const { AccessKeyId, SecretAccessKey, SessionToken } =
result.Credentials;
accessKeyId = AccessKeyId;
secretAccessKey = SecretAccessKey;
sessionToken = SessionToken;
}
const config = {
stdio: 'inherit',
env: {
stage: stage,
accountId,
...tableNames,
...indexNames,
AWS_ACCESS_KEY_ID: accessKeyId,
AWS_SECRET_ACCESS_KEY: secretAccessKey,
...(typeof sessionToken !== 'undefined' && {
AWS_SESSION_TOKEN: sessionToken,
}),
},
};
console.log(config);
const offline = spawn('serverless', ['offline'], config);
offline.on('error', (err) => console.error(err));
})();