Skip to content

Instantly share code, notes, and snippets.

@thomasmichaelwallace
Created May 8, 2024 10:36
Show Gist options
  • Save thomasmichaelwallace/8ec8bbc677a1f5cb427a0ec0b16e7b72 to your computer and use it in GitHub Desktop.
Save thomasmichaelwallace/8ec8bbc677a1f5cb427a0ec0b16e7b72 to your computer and use it in GitHub Desktop.
Convert an ECS task definition into a dot env file
import {
GetSecretValueCommand,
SecretsManagerClient,
} from '@aws-sdk/client-secrets-manager';
import fs from 'fs';
import path from 'path';
// usage npx tsx taskdef-to-env.ts path/to/ecs/task-definition.json
// outputs: /path/to/ecs/.env.local
// expects aws to be configured (see aws-vault)
const client = new SecretsManagerClient();
const taskDefPath: string = process.argv[2];
const dotEnvPath: string = path.join(path.dirname(taskDefPath), '.env.local');
async function getSecretFromValueFrom(valueFrom: string) {
let secretId = valueFrom;
let jsonKey: string | boolean = false;
if (valueFrom.endsWith('::')) {
// json key references end in ::
const [arn, aws, secretsmanager, region, accountId, secret, shortId, _jsonKey /* :: */] = valueFrom.split(':');
secretId = [arn, aws, secretsmanager, region, accountId, secret, shortId].join(':');
jsonKey = _jsonKey;
}
const command = new GetSecretValueCommand({
SecretId: secretId
});
const response = await client.send(command);
const raw = response.SecretString
if (raw === undefined) {
throw new Error(`Secret ${secretId} has no value`);
}
if (!jsonKey) { return raw; }
const json = JSON.parse(raw);
return json[jsonKey];
}
async function main() {
console.log('fetching', taskDefPath, 'to', dotEnvPath);
const json = fs.readFileSync(taskDefPath);
const task = JSON.parse(json.toString());
const envs: { name: string, value: string }[] = task.containerDefinitions[0].environment;
const secretRefs: { name: string, valueFrom: string }[] = task.containerDefinitions[0].secrets;
const secrets = await Promise.all(secretRefs.map(async (s: any) => {
const value = await getSecretFromValueFrom(s.valueFrom);
return { name: s.name, value };
}));
const dotEnv: string[] = [];
envs.forEach((e) => dotEnv.push(`${e.name}=${e.value}`));
secrets.forEach((s) => dotEnv.push(`${s.name}=${s.value}`));
fs.writeFileSync(dotEnvPath, dotEnv.join('\n'));
}
main().catch((err) => {
console.error('unhandled exception', err);
process.exit(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment