Skip to content

Instantly share code, notes, and snippets.

@ricardopadua
Last active December 2, 2021 01:52
Show Gist options
  • Save ricardopadua/1cb795ec9d30ca299757f79316e99f1e to your computer and use it in GitHub Desktop.
Save ricardopadua/1cb795ec9d30ca299757f79316e99f1e to your computer and use it in GitHub Desktop.
aws tricks
USERID=
PASSWORD=
PROJECT_ID=
CLIENT_ID=
AWS_CREDENTIAL_OUTPUT=
AWS_CREDENTIAL_REGION_NON_PROD=
AWS_CREDENTIAL_REGION_PROD=
URL_AUTH=
URL_VAULT=
URL_REFERRER=
import { chromium } from "playwright";
import inquirer from 'inquirer';
import fetch from "node-fetch";
import fs from "fs";
import os from "os";
import dotenv from "dotenv";
import log from "./log.js";
dotenv.config();
const getUserRelatedInformation = () => {
const user = process.env.USERID ?? null;
const password = process.env.PASSWORD ?? null;
const projectId = process.env.PROJECT_ID ?? null;
const clientId = process.env.CLIENT_ID ?? null;
const awsOutput = process.env.AWS_CREDENTIAL_OUTPUT ?? null;
const awsRegionNonProd = process.env.AWS_CREDENTIAL_REGION_NON_PROD ?? null;
const awsRegionProd = process.env.AWS_CREDENTIAL_REGION_PROD ?? null;
const awsPath = `${os.homedir()}/.aws/credentials`;
if (!user) log.break('USERID NOT FOUND IN YOUR ENVIRONMENT!');
if (!password) log.break('PASSWORD NOT FOUND IN YOUR ENVIRONMENT!');
if (!projectId) log.break('PROJECTID NOT FOUND IN YOUR ENVIRONMENT!');
if (!clientId) log.break('CLIENTID NOT FOUND IN YOUR ENVIRONMENT!');
if (!awsOutput) log.break('AWS OUTPUT NOT FOUND IN YOUR ENVIRONMENT!');
if (!awsRegionNonProd) log.break('AWS REGION NON PROD NOT FOUND IN YOUR ENVIRONMENT!');
if (!awsRegionProd) log.break('AWS REGION PROD NOT FOUND IN YOUR ENVIRONMENT!');
return { user, password, projectId, clientId, awsPath, awsOutput, awsRegion: null };
};
const getSelectedEnvironment = async ({ userInfo }) => {
const { environment } = await inquirer
.prompt([
{
type: 'list',
name: 'environment',
message: 'WHICH ENVIRONMENT DO YOU WANT TO USE?',
choices: [ "DEV", "QA", "HML", "PRD" ]
}
]);
if (environment.toString() === "PRD") {
userInfo.awsRegion = process.env.AWS_CREDENTIAL_REGION_PROD;
} else {
userInfo.awsRegion = process.env.AWS_CREDENTIAL_REGION_NON_PROD;
}
return environment.toString().toLowerCase();
};
const getAccessToken = async ({ userInfo }) => {
try {
const browser = await chromium.launch({ headless: true });
const page = await browser.newPage();
await page.goto(`${process.env.URL_AUTH}`);
await page.type("#codCN", userInfo.user);
await page.type("#password", userInfo.password);
await page.click("button[type=submit]");
await page.waitForTimeout(5000);
const accessToken = await page.evaluate(() => window.sessionStorage.getItem("@devops-fe/accessToken"));
await browser.close();
if (!accessToken) log.break(`ACCESSTOKEN NOT FOUND IN SESSIONSTORAGE ${process.env.URL_AUTH}`);
delete userInfo.password;
return accessToken;
} catch (error) {
}
};
const getRolesFromVault = async ({ userInfo }) => {
try {
const config = {
headers: {
"access_token": userInfo.accessToken,
"client_id": userInfo.clientId,
"project_id": userInfo.projectId,
"user_id": userInfo.user,
"environment": userInfo.environment
},
referrer: `${process.env.URL_REFERRER}`,
referrerPolicy: "strict-origin-when-cross-origin",
method: "GET",
mode: "cors",
}
const url = `${process.env.URL_VAULT}`;
const res = await fetch(url, config);
const data = await res.json();
if (!data?.length) log.break(`ROLES NOT FOUND FOR USERID ${userInfo.user} FROM VAULT`);
return data;
} catch (error) {
}
};
const getSelectedRole = async ({ userInfo }) => {
const { environment } = await inquirer
.prompt([
{
type: 'list',
name: 'environment',
message: 'WHICH ROLE DO YOU WANT TO USE?',
choices: userInfo.roles
}
]);
return environment.toString().toLowerCase();
};
const generateCredential = async ({ userInfo }) => {
try {
const config = {
headers: {
"content-type": "application/json;charset=UTF-8",
"access_token": userInfo.accessToken,
"client_id": userInfo.clientId,
"project_id": userInfo.projectId,
"user_id": userInfo.user,
"environment": userInfo.environment,
"role": userInfo.selectedRole
},
referrer: `${process.env.URL_REFERRER}`,
referrerPolicy: "strict-origin-when-cross-origin",
body: '{"reason":"cred"}',
method: "POST",
mode: "cors",
}
const url = `${process.env.URL_VAULT}`;
const res = await fetch(url, config);
const data = await res.json();
if (!data?.access_key || !data?.secret_key || !data?.security_token) {
return log.break(`CREDENTIAL NOT GENERATED FOR USERID: ${userInfo.user}!`);
}
let _output = userInfo.awsOutput;
let _region = userInfo.awsRegion;
delete userInfo.awsOutput;
delete userInfo.awsRegion;
return {
output: _output,
region: _region,
accessKey: data.access_key,
secretKey: data.secret_key,
securityToken: data.security_token
}
} catch (error) {
}
};
const createCredentialFileInAwsPath = ({ userInfo }) => {
userInfo.fileContent = `[default]
output = ${userInfo.credential.output}
region = ${userInfo.credential.region}
aws_access_key_id = ${userInfo.credential.accessKey}
aws_secret_access_key = ${userInfo.credential.secretKey}
aws_session_token = ${userInfo.credential.securityToken}
aws_security_token = ${userInfo.credential.securityToken}
`;
if(fs.existsSync(userInfo.awsPath)) {
fs.unlinkSync(userInfo.awsPath);
}
fs.writeFileSync(userInfo.awsPath, userInfo.fileContent);
fs.chmodSync(userInfo.awsPath, '775');
if(!fs.existsSync(userInfo.awsPath)) log.break('YOUR CREDENTIAL HAS NOT BEEN UPDATED!');
return true;
};
(async (userInfo = {}) => {
userInfo = getUserRelatedInformation();
userInfo.environment = await getSelectedEnvironment({ userInfo });
userInfo.accessToken = await getAccessToken({ userInfo });
userInfo.roles = await getRolesFromVault({ userInfo });
userInfo.selectedRole = await getSelectedRole({ userInfo });
userInfo.credential = await generateCredential({ userInfo });
userInfo.credentialUpdated = createCredentialFileInAwsPath({ userInfo });
log.success("SUCCESS OF BAHIA!");
})();
const Reset = "\x1b[0m";
const Bright = "\x1b[1m";
const Dim = "\x1b[2m";
const Underscore = "\x1b[4m";
const Blink = "\x1b[5m";
const Reverse = "\x1b[7m";
const Hidden = "\x1b[8m";
const FgRed = "\x1b[31m";
const FgGreen = "\x1b[32m";
const FgBlue = "\x1b[34m";
const FgYellow = "\x1b[33m";
const BgRed = "\x1b[41m";
const BgGreen = "\x1b[42m";
const BgBlue = "\x1b[44m";
const BgYellow = "\x1b[43m";
const time = new Date().toISOString();
const log = {
warning: (message) => console.warn(Bright, BgYellow, `[WARNING]`, Reset, Bright, `🀫 - ${time}`, message),
error: (message) => console.error(Bright, BgRed, `[ERROR]`, Reset, Bright, `πŸ˜– - ${time}`, message),
info: (message) => console.info(Bright, BgBlue, `[INFO]`, Reset, Bright, `😌 - ${time}`, message),
success: (message) => console.info(Bright, BgGreen, `[SUCCESS]`, Reset, Bright, `😎 - ${time}`, message),
break: (message) => process.exit(console.error(Bright, BgRed, `[ERROR]`, Reset, Bright, `πŸ’© - ${time}`, message))
};
export default log;
{
"name": "aws-tricks",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"start": "node generate-credentials.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {},
"devDependencies": {
"@playwright/test": "^1.17.0",
"dotenv": "^10.0.0",
"inquirer": "^8.2.0",
"node-fetch": "^3.1.0",
"playwright": "^1.16.3"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment