-
Notifications
You must be signed in to change notification settings - Fork 30
Infrastructure as Code in CLI #449
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
veimox
wants to merge
13
commits into
bojanbass:master
Choose a base branch
from
veimox:feat/cdk-stack
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
93534be
feat: added `nx-aws-cache-iac` with the main commands
veimox bbcdfa8
feat: publishes new `@nx-aws-plugin/nx-aws-cache-iac` package
veimox b73e6b1
docs: updated main `README.md`
veimox c260e4f
chore: set commands as the author prefers
veimox 8760a27
chore: removed common `esModuleInterop`
veimox 5a2db42
docs: improved package description to hopefully be more clear
veimox 4d50740
ci: building all packages before releasing
veimox dc1a200
Merge remote-tracking branch 'upstream/master' into feat/cdk-stack
veimox ead6b7e
docs: reverted back to original REAMDE
veimox db93906
chore: avoid upgrading deprecated packages
veimox fe7a7d1
chore: reverted commands to its initial values
veimox 0d6405f
feat: using latest cdk cli
veimox 9b89cef
chore: updated dependencies
veimox File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,6 +4,8 @@ | |
/dist | ||
/tmp | ||
/out-tsc | ||
/cdk-out | ||
/cdk.out | ||
**/dist | ||
|
||
# dependencies | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
{ | ||
"extends": ["../../.eslintrc.json"], | ||
"ignorePatterns": ["!**/*"], | ||
"rules": { | ||
"@typescript-eslint/ban-types": "off", | ||
"@typescript-eslint/no-non-null-assertion": "off", | ||
"no-new": "off", | ||
"no-console": "off", | ||
"import/no-internal-modules": "off", | ||
"max-lines-per-function": "off" | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
# NX AWS Cache Infrastructure as Code | ||
|
||
The plugin does not enforce any specific infrastructure. It does require you to have certain elements (e.g. an S3 bucket, a user with access to it, etc.). You can create such infrastructure manually or you can use the provided IaC (Infrastructure as Code) to create it automatically. | ||
|
||
In order to ease the process of creating the infrastructure, this package provides a CLI that will create the infrastructure for you. It contains the IaC for creating the infrastructure and you can run it by just calling a command. It uses AWS CDK (Cloud Development Kit) to create the infrastructure. The infrastructure is defined in the `lib/nx-aws-cache-iac-stack.ts` file. | ||
|
||
The CLI will create a new Stack in your AWS account. The Stack will create a new S3 bucket and an IAM user with access to it. The credentials for the user will be stored in the AWS Secrets Manager. | ||
|
||
## How to deploy the infrastructure | ||
|
||
This command will deploy a new Stack that creates a S3 bucket for the cache and an IAM user with access to it. | ||
This user will have the credentials stored in the AWS Secrets Manager. | ||
|
||
```bash | ||
# Login into AWS, then run | ||
npx @nx-aws-plugin/nx-aws-cache-iac cdk deploy | ||
|
||
# NOTE that you can also run `diff` and `destroy` | ||
``` | ||
|
||
## How to retrieve secrets | ||
|
||
To download the credentials for the IAM user, run the following command which will store the credentials in the `.env.local` file. | ||
|
||
```bash | ||
# Login into AWS, then run | ||
npx @nx-aws-plugin/nx-aws-cache-iac config-to-env | ||
``` | ||
|
||
## How to use the cache | ||
|
||
Follow the instructions of the project. Note that the environment variables are already set in the `.env.local` file. After you source such file, you only have to set the runner in the `nx.json` file like this: | ||
|
||
```json | ||
{ | ||
"tasksRunnerOptions": { | ||
"default": { | ||
"runner": "@nx-aws-plugin/nx-aws-cache" | ||
} | ||
} | ||
} | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
import { App } from 'aws-cdk-lib'; | ||
import { AppStack } from '../src/nx-aws-cache'; | ||
|
||
const app = new App(); | ||
new AppStack(app, 'NxAwsCache'); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
#!/usr/bin/env node | ||
|
||
import { spawn } from 'child_process'; | ||
import path from 'path'; | ||
|
||
const main = async () => { | ||
const [, , command] = process.argv; | ||
|
||
if (command !== 'deploy' && command !== 'destroy' && command !== 'diff') { | ||
console.error('Command must be one of `deploy`, `destroy`, or `diff`'); | ||
return; | ||
} | ||
|
||
const appPath = path.resolve(__dirname, 'cdk-app.cjs'); | ||
|
||
const spawnedProcess = spawn('npx', ['cdk@latest', command, '--all', '--app', `node ${appPath}`], { | ||
cwd: __dirname, | ||
stdio: 'inherit', | ||
}); | ||
|
||
const promise = new Promise<void>((resolve, reject) => { | ||
spawnedProcess.on('close', (code) => | ||
code === 0 ? resolve() : reject(new Error(`Process exited with code ${code}`)), | ||
); | ||
}); | ||
|
||
await promise; | ||
|
||
if (command === 'deploy') | ||
console.info( | ||
'Deployment complete. You can now run `npx @nx-aws-plugin/nx-aws-cache-iac config-to-env` to configure your Nx AWS Cache.', | ||
); | ||
}; | ||
|
||
main(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
#!/usr/bin/env node | ||
|
||
import { GetSecretValueCommand, SecretsManagerClient } from '@aws-sdk/client-secrets-manager'; | ||
import { readFileSync, writeFileSync, existsSync } from 'node:fs'; | ||
import { resolve } from 'node:path'; | ||
import { parse } from 'dotenv'; | ||
import { exit } from 'node:process'; | ||
|
||
const getAWSSecretConfiguration = async (value: string) => { | ||
const secretsmanager = new SecretsManagerClient({}); | ||
|
||
const getSecretCmd = new GetSecretValueCommand({ | ||
SecretId: value, | ||
}); | ||
|
||
const secretString = (await secretsmanager.send(getSecretCmd)).SecretString!; | ||
|
||
return JSON.parse(secretString) as Record<string, string>; | ||
}; | ||
|
||
export const createEnvFileFromPairs = ( | ||
environmentPairs: Record<string, string>, | ||
directory: string, | ||
fileName: string, | ||
) => { | ||
const dotenvPath = resolve(directory, fileName); | ||
console.log(` 📚 Exporting vars into ${dotenvPath}`); | ||
|
||
const encoding = 'utf8'; | ||
|
||
let currentData: { [value: string]: string } = {}; | ||
|
||
try { | ||
if (existsSync(dotenvPath)) currentData = parse(readFileSync(dotenvPath, { encoding })); | ||
} catch (error: unknown) { | ||
throw new Error(`Failed to read ${dotenvPath}`); | ||
} | ||
|
||
// NOTE: we don't override existing values | ||
const combined = { ...currentData, ...environmentPairs }; | ||
|
||
let fileData = Object.entries(combined) | ||
.map(([key, value]) => { | ||
try { | ||
JSON.parse(value); | ||
|
||
return `${key}='${value}'`; | ||
} catch (error) { | ||
return `${key}=${JSON.stringify(value)}`; | ||
} | ||
}) | ||
.join('\n'); | ||
|
||
fileData += '\n'; | ||
|
||
const newEntries = Math.abs(Object.entries(currentData).length - Object.entries(combined).length); | ||
|
||
console.log(newEntries > 0 ? ` ✅ Added ${newEntries} new entries` : ' ✅ No new entries'); | ||
|
||
writeFileSync(dotenvPath, fileData, { encoding }); | ||
}; | ||
|
||
async function main() { | ||
try { | ||
const secretName = '/nx-aws-cache/configuration'; | ||
const secrets = await getAWSSecretConfiguration(secretName); | ||
|
||
createEnvFileFromPairs(secrets, process.cwd(), '.env.local'); | ||
} catch (err) { | ||
console.error('Failed:', err); | ||
exit(1); | ||
} | ||
} | ||
|
||
main(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
{ | ||
"versionReporting": false, | ||
"output": "../../dist/cdk", | ||
"requireApproval": "never", | ||
"context": {} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
{ | ||
"name": "@nx-aws-plugin/nx-aws-cache-iac", | ||
"version": "3.0.0", | ||
"description": "Creates the infrastructure for the AWS S3 Cache plugin for Nx", | ||
"keywords": [ | ||
"AWS", | ||
"S3", | ||
"Tasks", | ||
"Runner", | ||
"Cache", | ||
"Workspace", | ||
"Nrwl", | ||
"Nx", | ||
"Monorepo", | ||
"CDK", | ||
"IaC" | ||
], | ||
"license": "MIT", | ||
"author": "Bojan Bratuz", | ||
"files": [ | ||
"./cdk.cjs", | ||
"./cdk-app.cjs", | ||
"./config-to-env.cjs" | ||
], | ||
"bin": { | ||
"cdk": "./cdk.cjs", | ||
"config-to-env": "./config-to-env.cjs" | ||
}, | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/bojanbass/nx-aws" | ||
}, | ||
"homepage": "https://github.com/bojanbass/nx-aws" | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
{ | ||
"name": "nx-aws-cache-iac", | ||
"$schema": "../../node_modules/nx/schemas/project-schema.json", | ||
"sourceRoot": "nx-aws-cache-iac/src", | ||
"projectType": "application", | ||
"targets": { | ||
"build": { | ||
"executor": "@nx/esbuild:esbuild", | ||
"outputs": ["{options.outputPath}"], | ||
"options": { | ||
"main": "packages/nx-aws-cache-iac/bin/cdk.ts", | ||
"additionalEntryPoints": [ | ||
"packages/nx-aws-cache-iac/bin/config-to-env.ts", | ||
"packages/nx-aws-cache-iac/bin/cdk-app.ts" | ||
], | ||
"assets": ["README.md"], | ||
"tsConfig": "packages/nx-aws-cache-iac/tsconfig.lib.json", | ||
"outputPath": "dist/packages/nx-aws-cache-iac", | ||
"platform": "node", | ||
"format": ["cjs"], | ||
"skipTypeCheck": true, | ||
"thirdParty": true, | ||
"bundle": true | ||
} | ||
}, | ||
"lint": { | ||
"executor": "@nx/linter:eslint", | ||
"outputs": ["{options.outputFile}"], | ||
"options": { | ||
"lintFilePatterns": [ | ||
"packages/nx-aws-cache-iac/**/*.ts", | ||
"packages/nx-aws-cache-iac/*.json" | ||
] | ||
} | ||
} | ||
}, | ||
"tags": [] | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.