@eserstack/cs 0.0.0-bootstrap.0 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +13 -0
- package/README.md +252 -0
- package/dist/cli.d.ts +21 -0
- package/dist/cli.js +221 -0
- package/dist/ffi-client.d.ts +8 -0
- package/dist/ffi-client.js +9 -0
- package/dist/generate.d.ts +47 -0
- package/dist/generate.js +71 -0
- package/dist/mod.d.ts +21 -0
- package/dist/mod.js +22 -0
- package/dist/sync.d.ts +88 -0
- package/dist/sync.js +320 -0
- package/dist/types.d.ts +119 -0
- package/dist/types.js +2 -0
- package/package.json +39 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Copyright 2023-present Eser Ozvataf and other contributors.
|
|
2
|
+
|
|
3
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
you may not use this file except in compliance with the License.
|
|
5
|
+
You may obtain a copy of the License at
|
|
6
|
+
|
|
7
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
|
|
9
|
+
Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
See the License for the specific language governing permissions and
|
|
13
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
# ⚙️ [@eserstack/cs](./)
|
|
2
|
+
|
|
3
|
+
> **Note:** JSR is frozen at 4.5.x. From 5.0.0, `@eserstack/cs` is published on
|
|
4
|
+
> npm under the same name (`pnpm add @eserstack/cs`); the JSR versions stay
|
|
5
|
+
> available but get no updates.
|
|
6
|
+
|
|
7
|
+
> **eserstack Library** — [eser/stack on GitHub](https://github.com/eser/stack)
|
|
8
|
+
> **Install:** `pnpm add @eserstack/cs`
|
|
9
|
+
|
|
10
|
+
`@eserstack/cs` is a Kubernetes ConfigMap and Secret synchronization tool that
|
|
11
|
+
simplifies the management of configuration data and secrets in Kubernetes
|
|
12
|
+
environments. It works with both environment files and Kubernetes resources and
|
|
13
|
+
includes a CLI.
|
|
14
|
+
|
|
15
|
+
## 🚀 Getting Started with Kubernetes ConfigMaps and Secrets
|
|
16
|
+
|
|
17
|
+
ConfigMaps and Secrets are fundamental Kubernetes resources for managing
|
|
18
|
+
configuration data and sensitive information:
|
|
19
|
+
|
|
20
|
+
### ConfigMaps
|
|
21
|
+
|
|
22
|
+
ConfigMaps store configuration data in key-value pairs. They allow you to
|
|
23
|
+
decouple configuration artifacts from image content to keep containerized
|
|
24
|
+
applications portable.
|
|
25
|
+
|
|
26
|
+
### Secrets
|
|
27
|
+
|
|
28
|
+
Secrets are similar to ConfigMaps but are specifically intended to hold
|
|
29
|
+
confidential data such as passwords, OAuth tokens, and SSH keys.
|
|
30
|
+
|
|
31
|
+
### The Cloud Native Approach
|
|
32
|
+
|
|
33
|
+
Following cloud-native best practices, `@eserstack/cs` helps you manage
|
|
34
|
+
configurations using the **12-Factor App** methodology, particularly the
|
|
35
|
+
principle of storing configuration in environment variables.
|
|
36
|
+
|
|
37
|
+
## 🤔 What @eserstack/cs offers?
|
|
38
|
+
|
|
39
|
+
`@eserstack/cs` manages Kubernetes configuration resources:
|
|
40
|
+
|
|
41
|
+
- **Environment File Integration**: Load configuration from `.env` files and
|
|
42
|
+
environment variables
|
|
43
|
+
- **Multiple Output Formats**: Generate YAML or JSON output for Kubernetes
|
|
44
|
+
resources
|
|
45
|
+
- **CLI Interface**: Command-line tool for generating manifests and patches
|
|
46
|
+
- **Sync Capabilities**: Synchronize with existing Kubernetes resources using
|
|
47
|
+
kubectl
|
|
48
|
+
- **Namespaces**: Put the resource in a namespace, or leave it in the namespace
|
|
49
|
+
of the current kubectl context
|
|
50
|
+
- **Type Safety**: Built with TypeScript
|
|
51
|
+
|
|
52
|
+
`sync` reads values from these sources, and a later source overrides an earlier
|
|
53
|
+
one:
|
|
54
|
+
|
|
55
|
+
1. `.env`
|
|
56
|
+
2. `.env.<environment>`
|
|
57
|
+
3. `.env.local` (skipped when the environment is `test`)
|
|
58
|
+
4. `.env.<environment>.local`
|
|
59
|
+
5. Process environment variables
|
|
60
|
+
|
|
61
|
+
The environment name comes from `-e` (or the `env` option), then from the `ENV`,
|
|
62
|
+
`APP_ENV` or `NODE_ENV` variable, then defaults to `development`.
|
|
63
|
+
`generate` reads the `.env` files of the environment and no process environment
|
|
64
|
+
variables, whether it runs on the native ajan library or in TypeScript.
|
|
65
|
+
|
|
66
|
+
The data keys of a generated resource are sorted, and Secret values are the
|
|
67
|
+
base64 of their UTF-8 bytes. A YAML manifest is one document. The Go `eser cs`
|
|
68
|
+
in `cmd/eser` takes the same commands and flags.
|
|
69
|
+
|
|
70
|
+
## 🛠 Usage
|
|
71
|
+
|
|
72
|
+
Here you'll find examples of how to use `@eserstack/cs` for different scenarios.
|
|
73
|
+
|
|
74
|
+
### CLI Usage
|
|
75
|
+
|
|
76
|
+
The `eser` CLI runs these commands as `eser cs`. From a checkout of this
|
|
77
|
+
package, `node cli.ts` takes the same commands and flags.
|
|
78
|
+
|
|
79
|
+
**Generate a ConfigMap from the `.env` files of an environment:**
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
eser cs generate cm/my-config -e development
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
**Generate a Secret with specific namespace:**
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
eser cs generate secret/api-keys -n production -e production
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
**Save output to a file:**
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
eser cs generate cm/my-config -e development > configmap.yaml
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
**Sync with existing Kubernetes resource:**
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
eser cs sync configmap/my-existing-config -e production
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
`sync` prints a warning on stderr for each key of the resource that the
|
|
104
|
+
environment does not define, and leaves that key out of the patch.
|
|
105
|
+
|
|
106
|
+
**Generate patch string only (for saving to file):**
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
eser cs sync secret/api-keys -e production -s > patch.json
|
|
110
|
+
kubectl patch secret api-keys --type=merge --patch-file=patch.json
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### Programmatic Usage
|
|
114
|
+
|
|
115
|
+
**Generate ConfigMap programmatically:**
|
|
116
|
+
|
|
117
|
+
```typescript
|
|
118
|
+
import * as cs from "@eserstack/cs";
|
|
119
|
+
|
|
120
|
+
const configMapYaml = await cs.generate({
|
|
121
|
+
resource: { type: "configmap", name: "my-app-config" },
|
|
122
|
+
namespace: "default",
|
|
123
|
+
env: "development",
|
|
124
|
+
format: "yaml",
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
console.log(configMapYaml);
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
**Sync with existing resource:**
|
|
131
|
+
|
|
132
|
+
`sync()` reads the keys of the resource with `kubectl get` and returns a
|
|
133
|
+
`kubectl patch` command that sets those keys from the environment.
|
|
134
|
+
|
|
135
|
+
```typescript
|
|
136
|
+
import * as cs from "@eserstack/cs";
|
|
137
|
+
|
|
138
|
+
const command = await cs.sync({
|
|
139
|
+
resource: {
|
|
140
|
+
type: "configmap",
|
|
141
|
+
name: "existing-config",
|
|
142
|
+
namespace: "production",
|
|
143
|
+
},
|
|
144
|
+
env: "production",
|
|
145
|
+
format: "yaml",
|
|
146
|
+
onMissingKey: (key) => console.warn(`${key} is not set; left out`),
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
console.log(command);
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
**Sync without kubectl:**
|
|
153
|
+
|
|
154
|
+
Pass `getResourceKeys` to read the keys some other way, for example from another
|
|
155
|
+
Kubernetes client or a fixed list in a test, and `cwd` to read the `.env` files
|
|
156
|
+
from another directory.
|
|
157
|
+
|
|
158
|
+
```typescript
|
|
159
|
+
import * as cs from "@eserstack/cs";
|
|
160
|
+
|
|
161
|
+
const patch = await cs.sync({
|
|
162
|
+
resource: { type: "configmap", name: "app-config" },
|
|
163
|
+
cwd: "./fixtures",
|
|
164
|
+
stringOnly: true,
|
|
165
|
+
getResourceKeys: () => Promise.resolve(["DATABASE_URL", "PORT"]),
|
|
166
|
+
});
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
### Environment File Example
|
|
170
|
+
|
|
171
|
+
Create a `.env` file:
|
|
172
|
+
|
|
173
|
+
```env
|
|
174
|
+
DATABASE_URL=postgresql://localhost:5432/mydb
|
|
175
|
+
API_KEY=your-secret-api-key
|
|
176
|
+
DEBUG=true
|
|
177
|
+
PORT=3000
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
This will generate appropriate ConfigMap or Secret resources with the specified
|
|
181
|
+
key-value pairs.
|
|
182
|
+
|
|
183
|
+
## 📕 API Reference
|
|
184
|
+
|
|
185
|
+
### CLI Commands
|
|
186
|
+
|
|
187
|
+
**generate**
|
|
188
|
+
|
|
189
|
+
- `<resource>`: Resource reference (e.g., `cm/name`, `configmap/name`,
|
|
190
|
+
`secret/name`)
|
|
191
|
+
- `--namespace <ns>`: Kubernetes namespace
|
|
192
|
+
- `-e, --env <name>`: Environment name
|
|
193
|
+
- `-o, --output <format>`: Output format (yaml/json)
|
|
194
|
+
|
|
195
|
+
YAML output is one document, which `kubectl apply -f` reads as it is. JSON
|
|
196
|
+
output is a one-item array (`[{...}]`), the shape `serialize()` gives a list of
|
|
197
|
+
resources, and scripts read it as such; `kubectl apply` takes one object, so
|
|
198
|
+
pick it first: `... -o json | jq '.[0]' | kubectl apply -f -`.
|
|
199
|
+
|
|
200
|
+
**sync**
|
|
201
|
+
|
|
202
|
+
- `<resource>`: Resource reference (e.g., `configmap/name`, `secret/name`)
|
|
203
|
+
- `--namespace <ns>`: Kubernetes namespace
|
|
204
|
+
- `-e, --env <name>`: Environment name
|
|
205
|
+
- `-o, --output <format>`: Output format (yaml/json)
|
|
206
|
+
|
|
207
|
+
### Functions
|
|
208
|
+
|
|
209
|
+
**generate(options): Promise<string>** Generates Kubernetes ConfigMap or
|
|
210
|
+
Secret YAML/JSON from environment data.
|
|
211
|
+
|
|
212
|
+
**sync(options): Promise<string>** Synchronizes environment data with
|
|
213
|
+
existing Kubernetes resources using kubectl: returns the `kubectl patch`
|
|
214
|
+
command, or only the patch with `stringOnly`.
|
|
215
|
+
|
|
216
|
+
### Types
|
|
217
|
+
|
|
218
|
+
**SyncConfig** Configuration interface for defining ConfigMap/Secret properties,
|
|
219
|
+
labels, annotations, and output format.
|
|
220
|
+
|
|
221
|
+
**ConfigMap / Secret** Kubernetes resource type definitions following the
|
|
222
|
+
official API specifications.
|
|
223
|
+
|
|
224
|
+
**SyncOptions** Options for synchronizing with existing Kubernetes resources.
|
|
225
|
+
`onMissingKey(key)` is called for each key of the resource that the environment
|
|
226
|
+
does not define; the key is left out of the patch. `getResourceKeys(resource)`
|
|
227
|
+
replaces the `kubectl get` key lookup, and `cwd` sets the directory the `.env`
|
|
228
|
+
files are read from.
|
|
229
|
+
|
|
230
|
+
## Upgrading from 4.x
|
|
231
|
+
|
|
232
|
+
These changes since 4.5.2 need a change in code, commands or files that use this
|
|
233
|
+
package. The [changelog](https://github.com/eser/stack/blob/main/CHANGELOG.md)
|
|
234
|
+
lists the changes in every package.
|
|
235
|
+
|
|
236
|
+
- `sync()` no longer writes a console warning for a key the environment lacks,
|
|
237
|
+
and no longer goes through the Go `csSync` path. Pass `onMissingKey`
|
|
238
|
+
to be told:
|
|
239
|
+
|
|
240
|
+
```typescript
|
|
241
|
+
import * as cs from "@eserstack/cs";
|
|
242
|
+
|
|
243
|
+
const command = await cs.sync({
|
|
244
|
+
resource: { type: "configmap", name: "app-config" },
|
|
245
|
+
onMissingKey: (key) => console.warn(`${key} is not set; left out`), // After
|
|
246
|
+
});
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
---
|
|
250
|
+
|
|
251
|
+
🔗 For further details, visit the
|
|
252
|
+
[eserstack repository](https://github.com/eser/stack).
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
#!/usr/bin/env -S node
|
|
2
|
+
import type { KubectlResourceReference } from "./types.ts";
|
|
3
|
+
/** The options of the cs CLI. */
|
|
4
|
+
export interface CliOptions {
|
|
5
|
+
namespace?: string;
|
|
6
|
+
env?: string;
|
|
7
|
+
output?: "yaml" | "json";
|
|
8
|
+
stringOnly?: boolean;
|
|
9
|
+
help?: boolean;
|
|
10
|
+
version?: boolean;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Parse the cs arguments: the command, its resource, `--namespace` (`-n`),
|
|
14
|
+
* `--env` (`-e`), `--output` (`-o`), `--string-only` (`-s`), `--help` (`-h`)
|
|
15
|
+
* and `--version` (`-v`).
|
|
16
|
+
*/
|
|
17
|
+
export declare function parseCliArgs(cliArgs: readonly string[]): {
|
|
18
|
+
command: string | undefined;
|
|
19
|
+
options: CliOptions;
|
|
20
|
+
kubectlResource?: KubectlResourceReference;
|
|
21
|
+
};
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
#!/usr/bin/env -S node
|
|
2
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
3
|
+
// This CLI prints manifests and kubectl commands on stdout for piping and
|
|
4
|
+
// eval, and its errors and warnings on stderr, so it writes through console.
|
|
5
|
+
/* oxlint-disable no-console */
|
|
6
|
+
import * as shellFlags from "@eserstack/shell/args/flags";
|
|
7
|
+
import * as results from "@eserstack/primitives/results";
|
|
8
|
+
import { runtime } from "@eserstack/standards/cross-runtime";
|
|
9
|
+
import * as generate from "./generate.js";
|
|
10
|
+
import * as sync from "./sync.js";
|
|
11
|
+
const VERSION = "0.1.0";
|
|
12
|
+
const HELP_TEXT = `
|
|
13
|
+
@eserstack/cs - Kubernetes ConfigMap/Secret Sync Tool
|
|
14
|
+
|
|
15
|
+
USAGE:
|
|
16
|
+
eser cs [COMMAND] [OPTIONS]
|
|
17
|
+
node cli.ts [COMMAND] [OPTIONS] (from this package; same commands)
|
|
18
|
+
|
|
19
|
+
COMMANDS:
|
|
20
|
+
generate Generate ConfigMap/Secret YAML/JSON from .env files (requires -e flag)
|
|
21
|
+
Usage: generate [cm|configmap|secret]/name -e <env-name>
|
|
22
|
+
sync Generate kubectl patch commands to sync with existing Kubernetes resources
|
|
23
|
+
Usage: sync [cm|configmap|secret]/name [-e <env-name>]
|
|
24
|
+
|
|
25
|
+
OPTIONS:
|
|
26
|
+
-e, --env <name> Environment name
|
|
27
|
+
-n, --namespace <ns> Kubernetes namespace
|
|
28
|
+
-o, --output <format> Output format (yaml/json) [default: json]
|
|
29
|
+
-s, --string-only Output only patch string (no kubectl command)
|
|
30
|
+
-h, --help Show this help message
|
|
31
|
+
-v, --version Show version information
|
|
32
|
+
|
|
33
|
+
EXAMPLES:
|
|
34
|
+
# Generate ConfigMap from environment
|
|
35
|
+
eser cs generate cm/my-config -e development
|
|
36
|
+
|
|
37
|
+
# Generate Secret and save to file
|
|
38
|
+
eser cs generate secret/api-keys -n production -e production > secret.yaml
|
|
39
|
+
|
|
40
|
+
# Generate kubectl patch command for ConfigMap (JSON format)
|
|
41
|
+
eser cs sync cm/default -n development -e development
|
|
42
|
+
|
|
43
|
+
# Generate YAML format patch command
|
|
44
|
+
eser cs sync cm/default -n development -e development -o yaml
|
|
45
|
+
|
|
46
|
+
# Output only patch string for saving to file
|
|
47
|
+
eser cs sync secret/default -e development -s > patch.json
|
|
48
|
+
|
|
49
|
+
# Execute sync command directly
|
|
50
|
+
eval "$(eser cs sync secret/default -n development -e development)"
|
|
51
|
+
`;
|
|
52
|
+
function showHelp() {
|
|
53
|
+
console.log(HELP_TEXT);
|
|
54
|
+
}
|
|
55
|
+
function showVersion() {
|
|
56
|
+
console.log(`@eserstack/cs v${VERSION}`);
|
|
57
|
+
}
|
|
58
|
+
function parseKubectlResource(resourceArg) {
|
|
59
|
+
const parts = resourceArg.split("/");
|
|
60
|
+
if (parts.length !== 2) {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
const [typeStr, name] = parts;
|
|
64
|
+
let type;
|
|
65
|
+
if (typeStr === "cm" || typeStr === "configmap") {
|
|
66
|
+
type = "configmap";
|
|
67
|
+
}
|
|
68
|
+
else if (typeStr === "secret") {
|
|
69
|
+
type = "secret";
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
if (name === undefined) {
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
return { type, name };
|
|
78
|
+
}
|
|
79
|
+
const stringValue = (value) => typeof value === "string" ? value : undefined;
|
|
80
|
+
/**
|
|
81
|
+
* Parse the cs arguments: the command, its resource, `--namespace` (`-n`),
|
|
82
|
+
* `--env` (`-e`), `--output` (`-o`), `--string-only` (`-s`), `--help` (`-h`)
|
|
83
|
+
* and `--version` (`-v`).
|
|
84
|
+
*/
|
|
85
|
+
export function parseCliArgs(cliArgs) {
|
|
86
|
+
const { values, positionals } = shellFlags.parseArgs(cliArgs, {
|
|
87
|
+
options: {
|
|
88
|
+
namespace: { type: "string", short: "n" },
|
|
89
|
+
env: { type: "string", short: "e" },
|
|
90
|
+
output: { type: "string", short: "o" },
|
|
91
|
+
help: { type: "boolean", short: "h" },
|
|
92
|
+
version: { type: "boolean", short: "v" },
|
|
93
|
+
"string-only": { type: "boolean", short: "s" },
|
|
94
|
+
},
|
|
95
|
+
});
|
|
96
|
+
const command = positionals[0];
|
|
97
|
+
let kubectlResource;
|
|
98
|
+
// For sync and generate commands, parse the second argument as resource reference
|
|
99
|
+
const resourceArg = positionals[1];
|
|
100
|
+
if ((command === "sync" || command === "generate") &&
|
|
101
|
+
resourceArg !== undefined) {
|
|
102
|
+
kubectlResource = parseKubectlResource(resourceArg) ?? undefined;
|
|
103
|
+
}
|
|
104
|
+
const options = {
|
|
105
|
+
namespace: stringValue(values["namespace"]),
|
|
106
|
+
env: stringValue(values["env"]),
|
|
107
|
+
output: stringValue(values["output"]),
|
|
108
|
+
stringOnly: values["string-only"] === true,
|
|
109
|
+
help: values["help"] === true,
|
|
110
|
+
version: values["version"] === true,
|
|
111
|
+
};
|
|
112
|
+
return { command, options, kubectlResource };
|
|
113
|
+
}
|
|
114
|
+
function validateOptions(command, options, kubectlResource) {
|
|
115
|
+
// Validate output format
|
|
116
|
+
if (![undefined, "yaml", "json"].includes(options.output)) {
|
|
117
|
+
return results.fail({
|
|
118
|
+
message: "Error: output format must be 'yaml' or 'json'",
|
|
119
|
+
exitCode: 1,
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
// Validate required options for specific commands
|
|
123
|
+
if (command === "generate" || command === "sync") {
|
|
124
|
+
if (kubectlResource === undefined) {
|
|
125
|
+
return results.fail({
|
|
126
|
+
message: `Error: ${command} command requires a resource (e.g., cm/default, secret/default)`,
|
|
127
|
+
exitCode: 1,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
// For commands that require a resource, we've validated it exists above
|
|
132
|
+
return results.ok(undefined);
|
|
133
|
+
}
|
|
134
|
+
async function handleGenerate(options, kubectlResource) {
|
|
135
|
+
try {
|
|
136
|
+
const result = await generate.generate({
|
|
137
|
+
format: options.output ?? "yaml",
|
|
138
|
+
resource: kubectlResource,
|
|
139
|
+
namespace: options.namespace,
|
|
140
|
+
env: options.env,
|
|
141
|
+
});
|
|
142
|
+
console.log(result);
|
|
143
|
+
return results.ok(undefined);
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
return results.fail({
|
|
147
|
+
message: `Error generating resource: ${error instanceof Error ? error.message : String(error)}`,
|
|
148
|
+
exitCode: 1,
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
async function handleSync(options, kubectlResource) {
|
|
153
|
+
try {
|
|
154
|
+
const kubectlOptions = {
|
|
155
|
+
resource: {
|
|
156
|
+
type: kubectlResource.type,
|
|
157
|
+
name: kubectlResource.name,
|
|
158
|
+
namespace: options.namespace,
|
|
159
|
+
},
|
|
160
|
+
env: options.env,
|
|
161
|
+
format: options.output,
|
|
162
|
+
stringOnly: options.stringOnly,
|
|
163
|
+
onMissingKey: (key) => {
|
|
164
|
+
console.warn(`Warning: ${key} is in ${kubectlResource.type}/${kubectlResource.name} but not in the environment, so the patch leaves it out; define it in the .env file to sync it.`);
|
|
165
|
+
},
|
|
166
|
+
};
|
|
167
|
+
const result = await sync.sync(kubectlOptions);
|
|
168
|
+
console.log(result);
|
|
169
|
+
return results.ok(undefined);
|
|
170
|
+
}
|
|
171
|
+
catch (error) {
|
|
172
|
+
return results.fail({
|
|
173
|
+
message: `Error syncing with kubectl: ${error instanceof Error ? error.message : String(error)}`,
|
|
174
|
+
exitCode: 1,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
async function main() {
|
|
179
|
+
const { command, options, kubectlResource } = parseCliArgs(runtime.process.args);
|
|
180
|
+
// Handle help and version flags
|
|
181
|
+
if (options.version === true) {
|
|
182
|
+
showVersion();
|
|
183
|
+
return results.ok(undefined);
|
|
184
|
+
}
|
|
185
|
+
if (options.help === true || command === undefined) {
|
|
186
|
+
showHelp();
|
|
187
|
+
return results.ok(undefined);
|
|
188
|
+
}
|
|
189
|
+
// Validate options
|
|
190
|
+
const validationResult = validateOptions(command, options, kubectlResource);
|
|
191
|
+
if (results.isFail(validationResult)) {
|
|
192
|
+
return validationResult;
|
|
193
|
+
}
|
|
194
|
+
// Handle commands
|
|
195
|
+
switch (command) {
|
|
196
|
+
case "generate":
|
|
197
|
+
return await handleGenerate(options, kubectlResource);
|
|
198
|
+
case "sync":
|
|
199
|
+
return await handleSync(options, kubectlResource);
|
|
200
|
+
default:
|
|
201
|
+
return results.fail({
|
|
202
|
+
message: `Unknown command: ${command}`,
|
|
203
|
+
exitCode: 1,
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
// Run the CLI if this file is executed directly
|
|
208
|
+
if (import.meta.main) {
|
|
209
|
+
// CLI entry point: runs only when executed directly, never on import.
|
|
210
|
+
// oxlint-disable-next-line node/no-top-level-await
|
|
211
|
+
const result = await main();
|
|
212
|
+
results.match(result, {
|
|
213
|
+
ok: () => { },
|
|
214
|
+
fail: (error) => {
|
|
215
|
+
if (error.message !== undefined) {
|
|
216
|
+
console.error(error.message);
|
|
217
|
+
}
|
|
218
|
+
runtime.process.setExitCode(error.exitCode);
|
|
219
|
+
},
|
|
220
|
+
});
|
|
221
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This package's view of the Go bridge.
|
|
3
|
+
*
|
|
4
|
+
* The loader itself lives in `@eserstack/ajan/ffi/client` and is shared with
|
|
5
|
+
* every other package, so the whole process opens the library once. This module
|
|
6
|
+
* stays as the import path the package's own code already uses.
|
|
7
|
+
*/
|
|
8
|
+
export { ensureLib, getLib, getLoadError } from "@eserstack/ajan/ffi/client";
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* This package's view of the Go bridge.
|
|
4
|
+
*
|
|
5
|
+
* The loader itself lives in `@eserstack/ajan/ffi/client` and is shared with
|
|
6
|
+
* every other package, so the whole process opens the library once. This module
|
|
7
|
+
* stays as the import path the package's own code already uses.
|
|
8
|
+
*/
|
|
9
|
+
export { ensureLib, getLib, getLoadError } from "@eserstack/ajan/ffi/client";
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { KubectlResourceReference } from "./types.ts";
|
|
2
|
+
/** Options for `generate()`. */
|
|
3
|
+
export interface GenerateOptions {
|
|
4
|
+
/** Output format of the manifest. */
|
|
5
|
+
format: "yaml" | "json";
|
|
6
|
+
/** Kind and name of the resource to generate. */
|
|
7
|
+
resource: KubectlResourceReference;
|
|
8
|
+
/** Namespace to use when `resource.namespace` is absent. */
|
|
9
|
+
namespace?: string;
|
|
10
|
+
/**
|
|
11
|
+
* Environment name, such as `"production"`, which selects the
|
|
12
|
+
* `.env.<name>` file. When `undefined`, the `.env` files of the default
|
|
13
|
+
* environment are read.
|
|
14
|
+
*/
|
|
15
|
+
env: string | undefined;
|
|
16
|
+
/**
|
|
17
|
+
* Directory to resolve `.env` files from. Defaults to the process cwd.
|
|
18
|
+
*
|
|
19
|
+
* Exists so a caller can point at a directory WITHOUT calling chdir. chdir is
|
|
20
|
+
* process-global, so a test that chdir'd into a temp directory changed the
|
|
21
|
+
* cwd of every other test running in that process at that moment -- and
|
|
22
|
+
* deleted it on the way out. Anything that spawned a subprocess or resolved
|
|
23
|
+
* a relative path in that window failed for reasons having nothing to do
|
|
24
|
+
* with itself.
|
|
25
|
+
*/
|
|
26
|
+
cwd?: string;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Generates a ConfigMap or Secret manifest from the `.env` files of an
|
|
30
|
+
* environment. Secret values are Base64-encoded, which is not encryption.
|
|
31
|
+
*
|
|
32
|
+
* @param options - Resource, environment, directory and output format
|
|
33
|
+
* @returns The manifest as YAML or JSON, or a `#` comment line when the
|
|
34
|
+
* environment has no values
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```typescript
|
|
38
|
+
* import * as cs from "@eserstack/cs";
|
|
39
|
+
*
|
|
40
|
+
* const manifest = await cs.generate({
|
|
41
|
+
* resource: { type: "configmap", name: "my-app-config" },
|
|
42
|
+
* env: "production",
|
|
43
|
+
* format: "yaml",
|
|
44
|
+
* });
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
47
|
+
export declare const generate: (options: GenerateOptions) => Promise<string>;
|
package/dist/generate.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
import * as formats from "@eserstack/formats";
|
|
3
|
+
import * as dotenv from "@eserstack/config/dotenv";
|
|
4
|
+
import * as sync from "./sync.js";
|
|
5
|
+
import * as ffiClient from "./ffi-client.js";
|
|
6
|
+
import { runtime } from "@eserstack/standards/cross-runtime";
|
|
7
|
+
/**
|
|
8
|
+
* Generates a ConfigMap or Secret manifest from the `.env` files of an
|
|
9
|
+
* environment. Secret values are Base64-encoded, which is not encryption.
|
|
10
|
+
*
|
|
11
|
+
* @param options - Resource, environment, directory and output format
|
|
12
|
+
* @returns The manifest as YAML or JSON, or a `#` comment line when the
|
|
13
|
+
* environment has no values
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```typescript
|
|
17
|
+
* import * as cs from "@eserstack/cs";
|
|
18
|
+
*
|
|
19
|
+
* const manifest = await cs.generate({
|
|
20
|
+
* resource: { type: "configmap", name: "my-app-config" },
|
|
21
|
+
* env: "production",
|
|
22
|
+
* format: "yaml",
|
|
23
|
+
* });
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
export const generate = async (options) => {
|
|
27
|
+
await ffiClient.ensureLib();
|
|
28
|
+
// FFI path: when env is undefined, bridge auto-discovers .env + .env.local from CWD.
|
|
29
|
+
const lib = ffiClient.getLib();
|
|
30
|
+
if (lib !== null) {
|
|
31
|
+
try {
|
|
32
|
+
// Go reads the same layered .env files as the TypeScript loader below:
|
|
33
|
+
// .env, .env.<env>, .env.local and .env.<env>.local.
|
|
34
|
+
const parsed = lib.call("csGenerate", {
|
|
35
|
+
resource: options.resource,
|
|
36
|
+
env: options.env ?? "",
|
|
37
|
+
cwd: options.cwd ?? runtime.process.cwd(),
|
|
38
|
+
format: options.format,
|
|
39
|
+
namespace: options.namespace ?? "",
|
|
40
|
+
});
|
|
41
|
+
if (!parsed.error) {
|
|
42
|
+
return parsed.result ?? "";
|
|
43
|
+
}
|
|
44
|
+
// Non-fatal: fall through to TS fallback
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
// Fall through to TS fallback
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
// TS fallback: handles FFI error recovery.
|
|
51
|
+
formats.registerBuiltinFormats();
|
|
52
|
+
const resourceType = options.resource.type;
|
|
53
|
+
const resourceName = options.resource.name;
|
|
54
|
+
const resourceNamespace = options.resource.namespace ?? options.namespace;
|
|
55
|
+
const envMap = await dotenv.load({
|
|
56
|
+
baseDir: options.cwd ?? ".",
|
|
57
|
+
env: options.env,
|
|
58
|
+
loadProcessEnv: false,
|
|
59
|
+
});
|
|
60
|
+
if (envMap.size === 0) {
|
|
61
|
+
return `# No environment data found to generate ${resourceType}/${resourceName}`;
|
|
62
|
+
}
|
|
63
|
+
let resource;
|
|
64
|
+
if (resourceType === "secret") {
|
|
65
|
+
resource = sync.buildSecretFromContext(resourceName, resourceNamespace, envMap);
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
resource = sync.buildConfigMapFromContext(resourceName, resourceNamespace, envMap);
|
|
69
|
+
}
|
|
70
|
+
return await formats.serialize([resource], options.format, { pretty: true });
|
|
71
|
+
};
|
package/dist/mod.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Builds Kubernetes ConfigMaps and Secrets from `.env` files and environment
|
|
3
|
+
* variables, and generates `kubectl patch` commands that bring an existing
|
|
4
|
+
* resource in line with the environment.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```typescript
|
|
8
|
+
* import * as cs from "@eserstack/cs";
|
|
9
|
+
*
|
|
10
|
+
* const manifest = await cs.generate({
|
|
11
|
+
* resource: { type: "configmap", name: "app-config" },
|
|
12
|
+
* env: "production",
|
|
13
|
+
* format: "yaml",
|
|
14
|
+
* });
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* @module
|
|
18
|
+
*/
|
|
19
|
+
export { generate, type GenerateOptions } from "./generate.ts";
|
|
20
|
+
export { buildConfigMapFromContext, buildSecretFromContext, executeKubectl, KubernetesResourceNameError, sync, syncApply, validateKubernetesResourceName, validateResourceReference, } from "./sync.ts";
|
|
21
|
+
export { type ConfigMap, type ConfigMapBuilder, type ConfigMapContext, type KubectlResourceReference, type Secret, type SecretBuilder, type SyncConfig, type SyncOptions, } from "./types.ts";
|
package/dist/mod.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* Builds Kubernetes ConfigMaps and Secrets from `.env` files and environment
|
|
4
|
+
* variables, and generates `kubectl patch` commands that bring an existing
|
|
5
|
+
* resource in line with the environment.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import * as cs from "@eserstack/cs";
|
|
10
|
+
*
|
|
11
|
+
* const manifest = await cs.generate({
|
|
12
|
+
* resource: { type: "configmap", name: "app-config" },
|
|
13
|
+
* env: "production",
|
|
14
|
+
* format: "yaml",
|
|
15
|
+
* });
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* @module
|
|
19
|
+
*/
|
|
20
|
+
export { generate } from "./generate.js";
|
|
21
|
+
export { buildConfigMapFromContext, buildSecretFromContext, executeKubectl, KubernetesResourceNameError, sync, syncApply, validateKubernetesResourceName, validateResourceReference, } from "./sync.js";
|
|
22
|
+
export {} from "./types.js";
|
package/dist/sync.d.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import * as dotenv from "@eserstack/config/dotenv";
|
|
2
|
+
import type { ConfigMap, KubectlResourceReference, Secret, SyncOptions } from "./types.ts";
|
|
3
|
+
/**
|
|
4
|
+
* Thrown when a Kubernetes resource name or namespace breaks the RFC 1123 DNS
|
|
5
|
+
* subdomain rules, before any command runs.
|
|
6
|
+
*/
|
|
7
|
+
export declare class KubernetesResourceNameError extends Error {
|
|
8
|
+
/** Creates the error with a message that names the field and the value. */
|
|
9
|
+
constructor(message: string);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Validates a Kubernetes resource name according to RFC 1123 DNS subdomain naming rules.
|
|
13
|
+
* - Must be 253 characters or less
|
|
14
|
+
* - Must contain only lowercase alphanumeric characters, '-', or '.'
|
|
15
|
+
* - Must start and end with an alphanumeric character
|
|
16
|
+
*
|
|
17
|
+
* @param name - The resource name to validate
|
|
18
|
+
* @param fieldName - The field name for error messages (e.g., "resource name", "namespace")
|
|
19
|
+
* @throws {KubernetesResourceNameError} If the name is invalid
|
|
20
|
+
*/
|
|
21
|
+
export declare const validateKubernetesResourceName: (name: string, fieldName?: string) => void;
|
|
22
|
+
/**
|
|
23
|
+
* Validates a KubectlResourceReference, checking both name and namespace if provided.
|
|
24
|
+
*
|
|
25
|
+
* @param resource - The resource reference to validate
|
|
26
|
+
* @throws {KubernetesResourceNameError} If validation fails
|
|
27
|
+
*/
|
|
28
|
+
export declare const validateResourceReference: (resource: KubectlResourceReference) => void;
|
|
29
|
+
/**
|
|
30
|
+
* Executes a kubectl get command to retrieve keys from a Kubernetes resource.
|
|
31
|
+
* Uses direct command invocation (no shell) for security.
|
|
32
|
+
*
|
|
33
|
+
* @param resource - The Kubernetes resource reference
|
|
34
|
+
* @returns Array of data keys from the resource
|
|
35
|
+
* @throws {Error} If kubectl command fails
|
|
36
|
+
* @throws {KubernetesResourceNameError} If resource name/namespace is invalid
|
|
37
|
+
*/
|
|
38
|
+
export declare const executeKubectl: (resource: KubectlResourceReference) => Promise<string[]>;
|
|
39
|
+
export declare const buildSecretFromContext: (name: string, namespace: string | undefined, data: dotenv.EnvMap) => Secret;
|
|
40
|
+
/**
|
|
41
|
+
* Builds a Kubernetes ConfigMap resource from the given context.
|
|
42
|
+
*
|
|
43
|
+
* @param name - The ConfigMap name
|
|
44
|
+
* @param namespace - The namespace; left out of the metadata when it is
|
|
45
|
+
* absent, empty or `"default"`
|
|
46
|
+
* @param data - Map of key-value pairs to include in the ConfigMap
|
|
47
|
+
* @returns A Kubernetes ConfigMap resource object
|
|
48
|
+
*/
|
|
49
|
+
export declare const buildConfigMapFromContext: (name: string, namespace: string | undefined, data: dotenv.EnvMap) => ConfigMap;
|
|
50
|
+
/**
|
|
51
|
+
* Synchronizes environment variables with a Kubernetes ConfigMap or Secret.
|
|
52
|
+
* Generates a kubectl patch command that can be executed to update the resource.
|
|
53
|
+
*
|
|
54
|
+
* The patch holds only the keys the resource already has. A key with no value
|
|
55
|
+
* in the environment is left out and reported through `onMissingKey`.
|
|
56
|
+
*
|
|
57
|
+
* @param options - Sync configuration options
|
|
58
|
+
* @returns A kubectl patch command string or the patch data (if stringOnly is true)
|
|
59
|
+
* @throws {KubernetesResourceNameError} If resource name/namespace is invalid
|
|
60
|
+
* @throws {Error} If kubectl command fails or sync operation fails
|
|
61
|
+
*
|
|
62
|
+
* @example
|
|
63
|
+
* ```typescript
|
|
64
|
+
* import * as cs from "@eserstack/cs";
|
|
65
|
+
*
|
|
66
|
+
* const command = await cs.sync({
|
|
67
|
+
* resource: { type: "configmap", name: "my-config", namespace: "staging" },
|
|
68
|
+
* env: "staging",
|
|
69
|
+
* format: "json",
|
|
70
|
+
* });
|
|
71
|
+
* // kubectl patch cm my-config -n staging --type=merge -p '{"data":{...}}'
|
|
72
|
+
* ```
|
|
73
|
+
*/
|
|
74
|
+
export declare const sync: (options: SyncOptions) => Promise<string>;
|
|
75
|
+
/**
|
|
76
|
+
* Generates the `kubectl patch` command that applies the sync patch.
|
|
77
|
+
*
|
|
78
|
+
* @param options - Sync configuration options
|
|
79
|
+
* @returns A shell command string that applies the patch
|
|
80
|
+
* @throws {KubernetesResourceNameError} If resource name/namespace is invalid
|
|
81
|
+
* @throws {Error} If sync operation fails
|
|
82
|
+
*
|
|
83
|
+
* @remarks
|
|
84
|
+
* This function generates a shell command string. The resource name and namespace
|
|
85
|
+
* are validated according to RFC 1123 DNS subdomain naming rules before being
|
|
86
|
+
* included in the output.
|
|
87
|
+
*/
|
|
88
|
+
export declare const syncApply: (options: SyncOptions) => Promise<string>;
|
package/dist/sync.js
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
import * as formats from "@eserstack/formats";
|
|
3
|
+
import * as dotenv from "@eserstack/config/dotenv";
|
|
4
|
+
import * as shellExec from "@eserstack/shell/exec";
|
|
5
|
+
// Constants
|
|
6
|
+
const K8S_MAX_NAME_LENGTH = 253; // RFC 1123 DNS subdomain max length
|
|
7
|
+
const ERROR_PREVIEW_LENGTH = 100; // Characters to show in error previews
|
|
8
|
+
/**
|
|
9
|
+
* Thrown when a Kubernetes resource name or namespace breaks the RFC 1123 DNS
|
|
10
|
+
* subdomain rules, before any command runs.
|
|
11
|
+
*/
|
|
12
|
+
export class KubernetesResourceNameError extends Error {
|
|
13
|
+
/** Creates the error with a message that names the field and the value. */
|
|
14
|
+
constructor(message) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = "KubernetesResourceNameError";
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Validates a Kubernetes resource name according to RFC 1123 DNS subdomain naming rules.
|
|
21
|
+
* - Must be 253 characters or less
|
|
22
|
+
* - Must contain only lowercase alphanumeric characters, '-', or '.'
|
|
23
|
+
* - Must start and end with an alphanumeric character
|
|
24
|
+
*
|
|
25
|
+
* @param name - The resource name to validate
|
|
26
|
+
* @param fieldName - The field name for error messages (e.g., "resource name", "namespace")
|
|
27
|
+
* @throws {KubernetesResourceNameError} If the name is invalid
|
|
28
|
+
*/
|
|
29
|
+
export const validateKubernetesResourceName = (name, fieldName = "resource name") => {
|
|
30
|
+
if (name === undefined || name === null) {
|
|
31
|
+
throw new KubernetesResourceNameError(`${fieldName} is required`);
|
|
32
|
+
}
|
|
33
|
+
if (typeof name !== "string") {
|
|
34
|
+
throw new KubernetesResourceNameError(`${fieldName} must be a string`);
|
|
35
|
+
}
|
|
36
|
+
if (name.length === 0) {
|
|
37
|
+
throw new KubernetesResourceNameError(`${fieldName} cannot be empty`);
|
|
38
|
+
}
|
|
39
|
+
if (name.length > K8S_MAX_NAME_LENGTH) {
|
|
40
|
+
throw new KubernetesResourceNameError(`${fieldName} must be 253 characters or less (got ${name.length})`);
|
|
41
|
+
}
|
|
42
|
+
// RFC 1123 DNS subdomain: lowercase alphanumeric, '-', or '.'
|
|
43
|
+
// Must start and end with alphanumeric
|
|
44
|
+
const validPattern = /^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/;
|
|
45
|
+
if (!validPattern.test(name)) {
|
|
46
|
+
throw new KubernetesResourceNameError(`${fieldName} "${name}" is invalid. Must contain only lowercase alphanumeric characters, '-', or '.', and must start and end with an alphanumeric character`);
|
|
47
|
+
}
|
|
48
|
+
// Check for consecutive dots or dashes which are not allowed
|
|
49
|
+
if (name.includes("..") || name.includes("--")) {
|
|
50
|
+
throw new KubernetesResourceNameError(`${fieldName} "${name}" cannot contain consecutive dots or dashes`);
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* Validates a KubectlResourceReference, checking both name and namespace if provided.
|
|
55
|
+
*
|
|
56
|
+
* @param resource - The resource reference to validate
|
|
57
|
+
* @throws {KubernetesResourceNameError} If validation fails
|
|
58
|
+
*/
|
|
59
|
+
export const validateResourceReference = (resource) => {
|
|
60
|
+
validateKubernetesResourceName(resource.name, "resource name");
|
|
61
|
+
if (resource.namespace !== undefined && resource.namespace !== null) {
|
|
62
|
+
validateKubernetesResourceName(resource.namespace, "namespace");
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* Executes a kubectl get command to retrieve keys from a Kubernetes resource.
|
|
67
|
+
* Uses direct command invocation (no shell) for security.
|
|
68
|
+
*
|
|
69
|
+
* @param resource - The Kubernetes resource reference
|
|
70
|
+
* @returns Array of data keys from the resource
|
|
71
|
+
* @throws {Error} If kubectl command fails
|
|
72
|
+
* @throws {KubernetesResourceNameError} If resource name/namespace is invalid
|
|
73
|
+
*/
|
|
74
|
+
export const executeKubectl = async (resource) => {
|
|
75
|
+
// Validate inputs before executing any commands
|
|
76
|
+
validateResourceReference(resource);
|
|
77
|
+
const resourceType = resource.type === "configmap" ? "cm" : "secret";
|
|
78
|
+
// Build command arguments array (safe from injection)
|
|
79
|
+
const args = ["get", `${resourceType}/${resource.name}`];
|
|
80
|
+
if (resource.namespace !== undefined) {
|
|
81
|
+
args.push("-n", resource.namespace);
|
|
82
|
+
}
|
|
83
|
+
args.push("-o", "json");
|
|
84
|
+
// Execute kubectl directly without shell wrapper
|
|
85
|
+
const result = await shellExec.exec `kubectl ${args}`.noThrow().spawn();
|
|
86
|
+
const { success, stdout, stderr } = result;
|
|
87
|
+
if (!success) {
|
|
88
|
+
const errorMessage = new TextDecoder().decode(stderr);
|
|
89
|
+
throw new Error(`kubectl command failed: ${errorMessage}`);
|
|
90
|
+
}
|
|
91
|
+
// Parse JSON in JavaScript instead of using jq (removes external dependency)
|
|
92
|
+
const output = new TextDecoder().decode(stdout);
|
|
93
|
+
try {
|
|
94
|
+
const resourceData = JSON.parse(output);
|
|
95
|
+
const data = resourceData.data ?? {};
|
|
96
|
+
return Object.keys(data);
|
|
97
|
+
}
|
|
98
|
+
catch (_parseError) {
|
|
99
|
+
throw new Error(`Failed to parse kubectl output as JSON: ${output.slice(0, ERROR_PREVIEW_LENGTH)}...`);
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
// A manifest leaves out an empty or "default" namespace, as the Go builder
|
|
103
|
+
// does, so kubectl uses the namespace of its current context.
|
|
104
|
+
const isNamedNamespace = (namespace) => namespace !== undefined && namespace !== "" && namespace !== "default";
|
|
105
|
+
/**
|
|
106
|
+
* Builds a Kubernetes Secret resource from the given context.
|
|
107
|
+
*
|
|
108
|
+
* @param name - The Secret name
|
|
109
|
+
* @param namespace - The namespace; left out of the metadata when it is
|
|
110
|
+
* absent, empty or `"default"`
|
|
111
|
+
* @param data - Map of key-value pairs to include in the Secret
|
|
112
|
+
* @returns A Kubernetes Secret resource object
|
|
113
|
+
*
|
|
114
|
+
* @remarks
|
|
115
|
+
* **Security Note:** Base64 encoding is NOT encryption.
|
|
116
|
+
* Kubernetes Secrets are stored unencrypted in etcd by default. Base64 encoding is used
|
|
117
|
+
* to support binary data and is required by the Kubernetes API, but it provides no
|
|
118
|
+
* confidentiality. For sensitive data, consider:
|
|
119
|
+
* - Enabling etcd encryption at rest
|
|
120
|
+
* - Using external secret management (HashiCorp Vault, AWS Secrets Manager, etc.)
|
|
121
|
+
* - Using sealed-secrets or similar solutions
|
|
122
|
+
*/
|
|
123
|
+
/**
|
|
124
|
+
* Base64 of the UTF-8 bytes of a value, the bytes Kubernetes hands back
|
|
125
|
+
* (btoa encodes Latin-1 and throws above U+00FF).
|
|
126
|
+
*/
|
|
127
|
+
const encodeBase64 = (value) => {
|
|
128
|
+
let binary = "";
|
|
129
|
+
for (const byte of new TextEncoder().encode(value)) {
|
|
130
|
+
binary += String.fromCharCode(byte);
|
|
131
|
+
}
|
|
132
|
+
return btoa(binary);
|
|
133
|
+
};
|
|
134
|
+
/**
|
|
135
|
+
* The variables of an env map sorted by key, as the Go csfx writes them,
|
|
136
|
+
* without the loader's symbol-keyed environment name.
|
|
137
|
+
*/
|
|
138
|
+
const sortedVariables = (data) => {
|
|
139
|
+
const entries = [];
|
|
140
|
+
for (const [key, value] of data) {
|
|
141
|
+
if (typeof key === "string") {
|
|
142
|
+
entries.push([key, value]);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
146
|
+
};
|
|
147
|
+
export const buildSecretFromContext = (name, namespace, data) => {
|
|
148
|
+
const encodedData = {};
|
|
149
|
+
// Base64 encode data for Kubernetes API compatibility (NOT for security)
|
|
150
|
+
for (const [key, value] of sortedVariables(data)) {
|
|
151
|
+
encodedData[key] = encodeBase64(value);
|
|
152
|
+
}
|
|
153
|
+
return {
|
|
154
|
+
apiVersion: "v1",
|
|
155
|
+
kind: "Secret",
|
|
156
|
+
metadata: {
|
|
157
|
+
name,
|
|
158
|
+
...(isNamedNamespace(namespace) ? { namespace } : {}),
|
|
159
|
+
},
|
|
160
|
+
data: encodedData,
|
|
161
|
+
type: "Opaque",
|
|
162
|
+
};
|
|
163
|
+
};
|
|
164
|
+
/**
|
|
165
|
+
* Builds a Kubernetes ConfigMap resource from the given context.
|
|
166
|
+
*
|
|
167
|
+
* @param name - The ConfigMap name
|
|
168
|
+
* @param namespace - The namespace; left out of the metadata when it is
|
|
169
|
+
* absent, empty or `"default"`
|
|
170
|
+
* @param data - Map of key-value pairs to include in the ConfigMap
|
|
171
|
+
* @returns A Kubernetes ConfigMap resource object
|
|
172
|
+
*/
|
|
173
|
+
export const buildConfigMapFromContext = (name, namespace, data) => {
|
|
174
|
+
return {
|
|
175
|
+
apiVersion: "v1",
|
|
176
|
+
kind: "ConfigMap",
|
|
177
|
+
metadata: {
|
|
178
|
+
name,
|
|
179
|
+
...(isNamedNamespace(namespace) ? { namespace } : {}),
|
|
180
|
+
},
|
|
181
|
+
data: Object.fromEntries(sortedVariables(data)),
|
|
182
|
+
};
|
|
183
|
+
};
|
|
184
|
+
/**
|
|
185
|
+
* Synchronizes environment variables with a Kubernetes ConfigMap or Secret.
|
|
186
|
+
* Generates a kubectl patch command that can be executed to update the resource.
|
|
187
|
+
*
|
|
188
|
+
* The patch holds only the keys the resource already has. A key with no value
|
|
189
|
+
* in the environment is left out and reported through `onMissingKey`.
|
|
190
|
+
*
|
|
191
|
+
* @param options - Sync configuration options
|
|
192
|
+
* @returns A kubectl patch command string or the patch data (if stringOnly is true)
|
|
193
|
+
* @throws {KubernetesResourceNameError} If resource name/namespace is invalid
|
|
194
|
+
* @throws {Error} If kubectl command fails or sync operation fails
|
|
195
|
+
*
|
|
196
|
+
* @example
|
|
197
|
+
* ```typescript
|
|
198
|
+
* import * as cs from "@eserstack/cs";
|
|
199
|
+
*
|
|
200
|
+
* const command = await cs.sync({
|
|
201
|
+
* resource: { type: "configmap", name: "my-config", namespace: "staging" },
|
|
202
|
+
* env: "staging",
|
|
203
|
+
* format: "json",
|
|
204
|
+
* });
|
|
205
|
+
* // kubectl patch cm my-config -n staging --type=merge -p '{"data":{...}}'
|
|
206
|
+
* ```
|
|
207
|
+
*/
|
|
208
|
+
export const sync = async (options) => {
|
|
209
|
+
// This stays in TypeScript when the Go library is loaded. The Go csfx.Sync
|
|
210
|
+
// reads one env file by path and no process environment, while `env` here is
|
|
211
|
+
// an environment name that selects layered .env files, and Go can neither
|
|
212
|
+
// report missing keys nor use getResourceKeys.
|
|
213
|
+
try {
|
|
214
|
+
// Validate resource reference early (defense in depth)
|
|
215
|
+
// executeKubectl also validates, but we validate here for early failure
|
|
216
|
+
validateResourceReference(options.resource);
|
|
217
|
+
// Get keys from Kubernetes resource
|
|
218
|
+
const getResourceKeys = options.getResourceKeys ?? executeKubectl;
|
|
219
|
+
const keys = await getResourceKeys(options.resource);
|
|
220
|
+
if (keys.length === 0) {
|
|
221
|
+
return `# No data found in ${options.resource.type}/${options.resource.name}`;
|
|
222
|
+
}
|
|
223
|
+
// Load environment data using @eserstack/config
|
|
224
|
+
const envMap = await dotenv.load({
|
|
225
|
+
baseDir: options.cwd ?? ".",
|
|
226
|
+
env: options.env,
|
|
227
|
+
});
|
|
228
|
+
// Convert Map to Record and filter for the keys we need
|
|
229
|
+
const envData = {};
|
|
230
|
+
for (const key of keys) {
|
|
231
|
+
const value = envMap.get(key);
|
|
232
|
+
if (value !== undefined) {
|
|
233
|
+
envData[key] = value;
|
|
234
|
+
}
|
|
235
|
+
else {
|
|
236
|
+
options.onMissingKey?.(key);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
if (Object.keys(envData).length === 0) {
|
|
240
|
+
return `# No matching environment variables found for ${options.resource.type}/${options.resource.name}`;
|
|
241
|
+
}
|
|
242
|
+
// Prepare data for patch
|
|
243
|
+
let patchData;
|
|
244
|
+
if (options.resource.type === "secret") {
|
|
245
|
+
// Base64 encode values for Kubernetes API (NOT for security - see buildSecretFromContext docs)
|
|
246
|
+
patchData = {};
|
|
247
|
+
for (const [key, value] of Object.entries(envData)) {
|
|
248
|
+
patchData[key] = encodeBase64(value);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
else {
|
|
252
|
+
// Use values as-is for configmaps
|
|
253
|
+
patchData = envData;
|
|
254
|
+
}
|
|
255
|
+
// Generate patch content based on format
|
|
256
|
+
const format = options.format ?? "json";
|
|
257
|
+
const patchObject = { data: patchData };
|
|
258
|
+
let patchString;
|
|
259
|
+
if (format === "yaml") {
|
|
260
|
+
// A merge patch must be a mapping. serialize() writes its items as a
|
|
261
|
+
// YAML sequence, so the patch goes through the YAML format's writeItem,
|
|
262
|
+
// which writes one document followed by a "---" separator.
|
|
263
|
+
patchString = formats.yamlFormat
|
|
264
|
+
.writeItem(patchObject)
|
|
265
|
+
.replace(/\n---\n$/, "")
|
|
266
|
+
.trim();
|
|
267
|
+
}
|
|
268
|
+
else {
|
|
269
|
+
patchString = JSON.stringify(patchObject);
|
|
270
|
+
}
|
|
271
|
+
// Return string-only if requested
|
|
272
|
+
if (options.stringOnly) {
|
|
273
|
+
return patchString;
|
|
274
|
+
}
|
|
275
|
+
// Generate kubectl patch command
|
|
276
|
+
// Resource name and namespace have been validated above (RFC 1123 compliant)
|
|
277
|
+
// so they are safe to include in the command string
|
|
278
|
+
const resourceType = options.resource.type === "configmap" ? "cm" : "secret";
|
|
279
|
+
const namespaceFlag = options.resource.namespace !== undefined
|
|
280
|
+
? ` -n ${options.resource.namespace}`
|
|
281
|
+
: "";
|
|
282
|
+
// Escape single quotes in the patch data for shell usage
|
|
283
|
+
const escapedPatch = patchString.replace(/'/g, "'\"'\"'");
|
|
284
|
+
return `kubectl patch ${resourceType} ${options.resource.name}${namespaceFlag} --type=merge -p '${escapedPatch}'`;
|
|
285
|
+
}
|
|
286
|
+
catch (error) {
|
|
287
|
+
if (error instanceof KubernetesResourceNameError) {
|
|
288
|
+
throw error; // Re-throw validation errors as-is
|
|
289
|
+
}
|
|
290
|
+
throw new Error(`Failed to sync with kubectl: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
/**
|
|
294
|
+
* Generates the `kubectl patch` command that applies the sync patch.
|
|
295
|
+
*
|
|
296
|
+
* @param options - Sync configuration options
|
|
297
|
+
* @returns A shell command string that applies the patch
|
|
298
|
+
* @throws {KubernetesResourceNameError} If resource name/namespace is invalid
|
|
299
|
+
* @throws {Error} If sync operation fails
|
|
300
|
+
*
|
|
301
|
+
* @remarks
|
|
302
|
+
* This function generates a shell command string. The resource name and namespace
|
|
303
|
+
* are validated according to RFC 1123 DNS subdomain naming rules before being
|
|
304
|
+
* included in the output.
|
|
305
|
+
*/
|
|
306
|
+
export const syncApply = async (options) => {
|
|
307
|
+
// Validate early for better error messages
|
|
308
|
+
validateResourceReference(options.resource);
|
|
309
|
+
const manifest = await sync({ ...options, stringOnly: true });
|
|
310
|
+
if (manifest.startsWith("# No")) {
|
|
311
|
+
return manifest;
|
|
312
|
+
}
|
|
313
|
+
// Quote the patch for a POSIX shell. Resource name and namespace are already
|
|
314
|
+
// validated by sync()
|
|
315
|
+
const resourceType = options.resource.type === "configmap" ? "cm" : "secret";
|
|
316
|
+
const namespaceFlag = options.resource.namespace !== undefined
|
|
317
|
+
? ` -n ${options.resource.namespace}`
|
|
318
|
+
: "";
|
|
319
|
+
return `kubectl patch ${resourceType} ${options.resource.name}${namespaceFlag} --type=merge -p '${manifest.replace(/'/g, "'\"'\"'")}'`;
|
|
320
|
+
};
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Settings for building a ConfigMap: its name and metadata, where its data
|
|
3
|
+
* comes from, and how the output is written.
|
|
4
|
+
*/
|
|
5
|
+
export interface SyncConfig {
|
|
6
|
+
/** The ConfigMap to build: name, namespace, data source and metadata. */
|
|
7
|
+
configMap: {
|
|
8
|
+
name: string;
|
|
9
|
+
namespace?: string;
|
|
10
|
+
envFile?: string;
|
|
11
|
+
data?: Record<string, string>;
|
|
12
|
+
labels?: Record<string, string>;
|
|
13
|
+
annotations?: Record<string, string>;
|
|
14
|
+
};
|
|
15
|
+
/** Output format, and whether the output is pretty-printed. */
|
|
16
|
+
output?: {
|
|
17
|
+
format?: "yaml" | "json";
|
|
18
|
+
pretty?: boolean;
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
/** A Kubernetes ConfigMap resource, as the `v1` API defines it. */
|
|
22
|
+
export interface ConfigMap {
|
|
23
|
+
/** Always `"v1"`. */
|
|
24
|
+
apiVersion: "v1";
|
|
25
|
+
/** Always `"ConfigMap"`. */
|
|
26
|
+
kind: "ConfigMap";
|
|
27
|
+
/** Name, namespace, labels and annotations of the resource. */
|
|
28
|
+
metadata: {
|
|
29
|
+
name: string;
|
|
30
|
+
namespace?: string;
|
|
31
|
+
labels?: Record<string, string>;
|
|
32
|
+
annotations?: Record<string, string>;
|
|
33
|
+
};
|
|
34
|
+
/** UTF-8 values by key. */
|
|
35
|
+
data?: Record<string, string>;
|
|
36
|
+
/** Base64-encoded binary values by key. */
|
|
37
|
+
binaryData?: Record<string, string>;
|
|
38
|
+
}
|
|
39
|
+
/** A Kubernetes Secret resource, as the `v1` API defines it. */
|
|
40
|
+
export interface Secret {
|
|
41
|
+
/** Always `"v1"`. */
|
|
42
|
+
apiVersion: "v1";
|
|
43
|
+
/** Always `"Secret"`. */
|
|
44
|
+
kind: "Secret";
|
|
45
|
+
/** Name, namespace, labels and annotations of the resource. */
|
|
46
|
+
metadata: {
|
|
47
|
+
name: string;
|
|
48
|
+
namespace?: string;
|
|
49
|
+
labels?: Record<string, string>;
|
|
50
|
+
annotations?: Record<string, string>;
|
|
51
|
+
};
|
|
52
|
+
/** Base64-encoded values by key. */
|
|
53
|
+
data?: Record<string, string>;
|
|
54
|
+
/** Plain values by key, which the API server encodes on write. */
|
|
55
|
+
stringData?: Record<string, string>;
|
|
56
|
+
/** The Secret type, such as `"Opaque"`. */
|
|
57
|
+
type?: string;
|
|
58
|
+
}
|
|
59
|
+
/** The values a {@link ConfigMapBuilder} or {@link SecretBuilder} builds from. */
|
|
60
|
+
export interface ConfigMapContext {
|
|
61
|
+
/** The settings the build started from. */
|
|
62
|
+
config: SyncConfig;
|
|
63
|
+
/** Name of the resource to build. */
|
|
64
|
+
name: string;
|
|
65
|
+
/** Namespace of the resource; absent for the default namespace. */
|
|
66
|
+
namespace?: string;
|
|
67
|
+
/** Values to put in the resource, by key. */
|
|
68
|
+
data: Record<string, string>;
|
|
69
|
+
/** Labels to put in the resource metadata. */
|
|
70
|
+
labels: Record<string, string>;
|
|
71
|
+
/** Annotations to put in the resource metadata. */
|
|
72
|
+
annotations: Record<string, string>;
|
|
73
|
+
}
|
|
74
|
+
/** Builds a ConfigMap from a context, or returns `null` to build nothing. */
|
|
75
|
+
export type ConfigMapBuilder = (context: ConfigMapContext) => ConfigMap | null;
|
|
76
|
+
/** Builds a Secret from a context, or returns `null` to build nothing. */
|
|
77
|
+
export type SecretBuilder = (context: ConfigMapContext) => Secret | null;
|
|
78
|
+
/** Points at one ConfigMap or Secret in a cluster. */
|
|
79
|
+
export interface KubectlResourceReference {
|
|
80
|
+
/** Whether the resource is a ConfigMap or a Secret. */
|
|
81
|
+
type: "configmap" | "secret";
|
|
82
|
+
/** Resource name; must be a valid RFC 1123 DNS subdomain. */
|
|
83
|
+
name: string;
|
|
84
|
+
/** Namespace of the resource; kubectl's current namespace when absent. */
|
|
85
|
+
namespace?: string;
|
|
86
|
+
}
|
|
87
|
+
/** Options for `sync()` and `syncApply()`. */
|
|
88
|
+
export interface SyncOptions {
|
|
89
|
+
/** The ConfigMap or Secret to patch. */
|
|
90
|
+
resource: KubectlResourceReference;
|
|
91
|
+
/**
|
|
92
|
+
* Environment name, such as `"production"`. It selects the `.env.<name>`
|
|
93
|
+
* and `.env.<name>.local` files; when absent, the name comes from the
|
|
94
|
+
* `ENV`, `APP_ENV` or `NODE_ENV` variable, then `"development"`.
|
|
95
|
+
*/
|
|
96
|
+
env?: string;
|
|
97
|
+
/** Format of the patch: `"json"` (the default) or `"yaml"`. */
|
|
98
|
+
format?: "yaml" | "json";
|
|
99
|
+
/** Return only the patch, without the `kubectl patch` command around it. */
|
|
100
|
+
stringOnly?: boolean;
|
|
101
|
+
/**
|
|
102
|
+
* Directory to read the `.env` files from. Defaults to the working
|
|
103
|
+
* directory. Set it to read another directory without calling chdir, which
|
|
104
|
+
* changes the working directory of the whole process.
|
|
105
|
+
*/
|
|
106
|
+
cwd?: string;
|
|
107
|
+
/**
|
|
108
|
+
* Reads the data keys of the resource. Defaults to `executeKubectl()`,
|
|
109
|
+
* which runs `kubectl get`. Pass your own function to read the keys through
|
|
110
|
+
* another client, or to test without a cluster.
|
|
111
|
+
*/
|
|
112
|
+
getResourceKeys?: (resource: KubectlResourceReference) => Promise<ReadonlyArray<string>>;
|
|
113
|
+
/**
|
|
114
|
+
* Called for each key of the Kubernetes resource that has no value in the
|
|
115
|
+
* loaded environment. The key is left out of the patch either way; the CLI
|
|
116
|
+
* uses this to print a warning on stderr.
|
|
117
|
+
*/
|
|
118
|
+
onMissingKey?: (key: string) => void;
|
|
119
|
+
}
|
package/dist/types.js
ADDED
package/package.json
CHANGED
|
@@ -1 +1,39 @@
|
|
|
1
|
-
{
|
|
1
|
+
{
|
|
2
|
+
"name": "@eserstack/cs",
|
|
3
|
+
"version": "5.0.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "https://github.com/eser/stack",
|
|
8
|
+
"directory": "pkg/@eserstack/cs"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist/**/*.js",
|
|
12
|
+
"dist/**/*.d.ts",
|
|
13
|
+
"dist/**/*.json"
|
|
14
|
+
],
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./dist/mod.d.ts",
|
|
18
|
+
"import": "./dist/mod.js"
|
|
19
|
+
},
|
|
20
|
+
"./cli": {
|
|
21
|
+
"types": "./dist/cli.d.ts",
|
|
22
|
+
"import": "./dist/cli.js"
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"@eserstack/ajan": "5.0.0",
|
|
27
|
+
"@eserstack/formats": "5.0.0",
|
|
28
|
+
"@eserstack/config": "5.0.0",
|
|
29
|
+
"@eserstack/primitives": "5.0.0",
|
|
30
|
+
"@eserstack/shell": "5.0.0",
|
|
31
|
+
"@eserstack/standards": "5.0.0"
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"@eserstack/test-kit": "5.0.0"
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"build": "node ../../../etc/scripts/build-library.ts"
|
|
38
|
+
}
|
|
39
|
+
}
|