@cloud-carbon-footprint/aws
Version:
The core logic to get cloud usage data and estimate energy and carbon emissions from Amazon Web Services.
58 lines • 2.46 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const aws_sdk_1 = require("aws-sdk");
const iam_credentials_1 = require("@google-cloud/iam-credentials");
const google_auth_library_1 = require("google-auth-library");
class GCPCredentials extends aws_sdk_1.Credentials {
constructor(accountId, targetRoleName, proxyAccountId, proxyRoleName) {
super(undefined);
this.accountId = accountId;
this.targetRoleName = targetRoleName;
this.proxyAccountId = proxyAccountId;
this.proxyRoleName = proxyRoleName;
}
async refresh(callback) {
try {
const token = await this.getTokenId();
const credentials = new aws_sdk_1.ChainableTemporaryCredentials({
params: {
RoleArn: `arn:aws:iam::${this.accountId}:role/${this.targetRoleName}`,
RoleSessionName: this.targetRoleName,
},
masterCredentials: new aws_sdk_1.WebIdentityCredentials({
RoleArn: `arn:aws:iam::${this.proxyAccountId}:role/${this.proxyRoleName}`,
RoleSessionName: this.proxyRoleName,
WebIdentityToken: token,
}),
});
await credentials.getPromise();
this.accessKeyId = credentials.accessKeyId;
this.secretAccessKey = credentials.secretAccessKey;
this.sessionToken = credentials.sessionToken;
this.expireTime = new Date(Date.now() + 1000 * 60 * 60);
callback();
}
catch (e) {
callback(e);
}
}
async getTokenId() {
const auth = new google_auth_library_1.GoogleAuth({
scopes: 'https://www.googleapis.com/auth/cloud-platform',
});
const authClient = await auth.getClient();
const iamCredentials = new iam_credentials_1.IAMCredentialsClient({ auth: auth });
const projectId = await auth.getProjectId();
const authClientEmail = authClient.email
? authClient.email
: `${projectId}@appspot.gserviceaccount.com`;
const [res] = await iamCredentials.generateIdToken({
name: `projects/-/serviceAccounts/${authClientEmail}`,
audience: `${authClientEmail}`,
includeEmail: true,
});
return res.token;
}
}
exports.default = GCPCredentials;
//# sourceMappingURL=GCPCredentials.js.map