|
| 1 | +import * as fs from 'fs' |
| 2 | +import * as yaml from 'yaml' |
| 3 | + |
| 4 | +interface DockerCompose { |
| 5 | + version: string |
| 6 | + services: Record<string, Service> |
| 7 | + networks: Record<string, Network> |
| 8 | +} |
| 9 | + |
| 10 | +interface Service { |
| 11 | + image?: string |
| 12 | + environment?: { [key: string]: string } |
| 13 | + volumes?: string[] |
| 14 | + ports?: string[] |
| 15 | + networks: string[] |
| 16 | +} |
| 17 | + |
| 18 | +interface Network { |
| 19 | + driver?: string |
| 20 | + external?: boolean |
| 21 | +} |
| 22 | + |
| 23 | +// Function to add networks to services and networks section |
| 24 | +function addNetworksToCompose(composeFile: string, networksList: string) { |
| 25 | + // Read and parse the existing docker-compose YAML file |
| 26 | + const fileContent = fs.readFileSync(composeFile, 'utf8') |
| 27 | + const composeObject = yaml.parse(fileContent) as DockerCompose |
| 28 | + |
| 29 | + // Convert the comma-separated networks list into an array |
| 30 | + const networksArray = networksList |
| 31 | + .split(',') |
| 32 | + .map((network) => network.trim()) |
| 33 | + .filter((network) => network.length > 0) |
| 34 | + .map((stack) => `${stack}_dependencies_net`) |
| 35 | + .concat('traefik_net') |
| 36 | + |
| 37 | + // Add networks to each service |
| 38 | + for (const serviceName in composeObject.services) { |
| 39 | + if (serviceName in composeObject.services) { |
| 40 | + const service = composeObject.services[serviceName] |
| 41 | + if (!service.networks) { |
| 42 | + service.networks = [] |
| 43 | + } |
| 44 | + networksArray.forEach((network) => { |
| 45 | + if (!service.networks.includes(network)) { |
| 46 | + service.networks.push(network) |
| 47 | + } |
| 48 | + }) |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + // Add networks to the global networks section |
| 53 | + if (!composeObject.networks) { |
| 54 | + composeObject.networks = {} |
| 55 | + } |
| 56 | + |
| 57 | + networksArray.forEach((network) => { |
| 58 | + if (!composeObject.networks[network]) { |
| 59 | + composeObject.networks[network] = { driver: 'overlay' } |
| 60 | + } |
| 61 | + }) |
| 62 | + |
| 63 | + // Convert the updated object back to YAML and output it |
| 64 | + const updatedComposeYaml = yaml.stringify(composeObject) |
| 65 | + console.log(updatedComposeYaml) |
| 66 | +} |
| 67 | + |
| 68 | +// Parse arguments from the command line |
| 69 | +const [composeFile, networksList] = process.argv.slice(2) |
| 70 | + |
| 71 | +if (!composeFile || !networksList) { |
| 72 | + console.error( |
| 73 | + 'Usage: ts-node script.ts <docker-compose-file> <networks-list>' |
| 74 | + ) |
| 75 | + process.exit(1) |
| 76 | +} |
| 77 | + |
| 78 | +// Call the function to update the compose file |
| 79 | +addNetworksToCompose(composeFile, networksList) |
0 commit comments