-
Notifications
You must be signed in to change notification settings - Fork 158
/
autotag_default_worker.js
195 lines (169 loc) · 5.88 KB
/
autotag_default_worker.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import get from 'lodash/get.js';
import { STS } from "@aws-sdk/client-sts";
import SETTINGS from '../autotag_settings.js';
export const AUTOTAG_TAG_NAME_PREFIX = 'AutoTag_';
const AUTOTAG_CREATOR_TAG_NAME = `${AUTOTAG_TAG_NAME_PREFIX}Creator`;
const AUTOTAG_CREATE_TIME_TAG_NAME = `${AUTOTAG_TAG_NAME_PREFIX}CreateTime`;
const AUTOTAG_INVOKED_BY_TAG_NAME = `${AUTOTAG_TAG_NAME_PREFIX}InvokedBy`;
const ROLE_PREFIX = 'arn:aws:iam::';
const ROLE_SUFFIX = ':role';
// const MASTER_ROLE_NAME = 'AutoTagMasterRole';
const MASTER_ROLE_PATH = '/gorillastack/autotag/master/';
class AutotagDefaultWorker {
constructor(event, s3Region) {
this.event = event;
this.s3Region = s3Region;
this.region = process.env.AWS_REGION;
this.roleName = process.env.ROLE_NAME;
// increase the retries for all AWS worker calls to be more resilient
// AWS.config.update({
// retryDelayOptions: {base: 300},
// maxRetries: 8
// });
}
/* tagResource
** method: tagResource
**
** Do nothing
*/
tagResource() {
return new Promise((resolve, reject) => {
try {
// Do nothing
resolve(true);
} catch (e) {
reject(e);
}
});
}
assumeRole(roleName) {
return new Promise((resolve, reject) => {
try {
//Uncomment line below for AWS STS logging
//AWS.config.logger = console;
const sts = new STS();
sts.assumeRole({
RoleArn: this.getAssumeRoleArn(roleName),
RoleSessionName: `AutoTag-${(new Date()).getTime()}`,
DurationSeconds: 900
}, (err, data) => {
if (err) {
reject(err);
} else {
const credentials = {
accessKeyId: data.Credentials.AccessKeyId,
secretAccessKey: data.Credentials.SecretAccessKey,
sessionToken: data.Credentials.SessionToken
};
resolve(credentials);
}
});
} catch (err) {
reject(err);
}
});
}
dumpEventInfo() {
console.log(`Event Name: ${this.event.eventName}`);
console.log(`Event Type: ${this.event.eventType}`);
console.log(`Event Source: ${this.event.eventSource}`);
console.log(`AWS Region: ${this.event.awsRegion}`);
console.log('---');
}
logTags(resources, tags, worker) {
console.log(`\nTagging ${resources} with the ${worker} in ${this.getAccountId()} (${this.s3Region}):`);
console.log(JSON.stringify(tags, null, 2));
}
getAssumeRoleArn(roleName) {
const accountId = this.getAccountId();
return ROLE_PREFIX + accountId + ROLE_SUFFIX + MASTER_ROLE_PATH + roleName;
}
// support for older CloudTrail logs
getAccountId() {
return (this.event.recipientAccountId ? this.event.recipientAccountId : this.event.userIdentity.accountId);
}
getAutotagTags() {
return [
this.getAutotagCreatorTag(),
...(SETTINGS.AutoTags.CreateTime ? [this.getAutotagCreateTimeTag()] : []),
...(this.getInvokedByTagValue() && SETTINGS.AutoTags.InvokedBy ? [this.getAutotagInvokedByTag()] : []),
...this.getCustomTags()
];
}
getAutotagCreatorTag() {
return {
Key: this.getCreatorTagName(),
Value: this.getCreatorTagValue()
};
}
getAutotagCreateTimeTag() {
return {
Key: this.getCreateTimeTagName(),
Value: this.getCreateTimeTagValue()
};
}
getAutotagInvokedByTag() {
return {
Key: this.getInvokedByTagName(),
Value: this.getInvokedByTagValue()
};
}
getCreatorTagName() {
return AUTOTAG_CREATOR_TAG_NAME;
}
getCreatorTagValue() {
// prefer the this field for Federated Users
// because it is the actual aws user and isn't truncated
if (this.event.userIdentity.type === 'FederatedUser'
&& this.event.userIdentity.sessionContext
&& this.event.userIdentity.sessionContext.sessionIssuer
&& this.event.userIdentity.sessionContext.sessionIssuer.arn) {
return this.event.userIdentity.sessionContext.sessionIssuer.arn;
} else {
return this.event.userIdentity.arn;
}
}
getCreateTimeTagName() {
return AUTOTAG_CREATE_TIME_TAG_NAME;
}
getCreateTimeTagValue() {
return this.event.eventTime;
}
getInvokedByTagName() {
return AUTOTAG_INVOKED_BY_TAG_NAME;
}
getInvokedByTagValue() {
return (this.event.userIdentity && this.event.userIdentity.invokedBy ? this.event.userIdentity.invokedBy : false);
}
getCustomTags() {
const keyword = '$event.';
// substitute any word starting with the keyword in the tag value with the actual value from the event
return this.objectMap(JSON.parse(SETTINGS.CustomTags), tagValue => {
let newTagValue = tagValue;
// split up the tag value by any character except these
const tagValueVariables = tagValue.match(/\$[A-Za-z0-9.]+/g) || [];
tagValueVariables.forEach(tagValueVariable => {
const tagValueVariableReplacement = get(this.event, tagValueVariable.replace(keyword, ''), undefined);
if (tagValueVariableReplacement === undefined) {
console.log(`WARN: Failed to perform the variable substitution for ${tagValueVariable}`);
}
// replace the variable in the tag value with the associated event value
newTagValue = newTagValue.replace(tagValueVariable, tagValueVariableReplacement);
});
// if all of the variable substitutions in the tag value have failed drop the entire tag
if (tagValueVariables.length > 0 && tagValueVariables.length === (newTagValue.match(/undefined/g) || []).length) {
return false;
}
return newTagValue;
});
}
// returns a new array with the values at each key mapped using mapFn(value)
objectMap(object, mapFn) {
return Object.keys(object).reduce((result, key) => {
const newValue = mapFn(object[key]);
if (newValue) result.push({ Key: key, Value: newValue });
return result;
}, []);
}
}
export default AutotagDefaultWorker;