Skip to content

Instantly share code, notes, and snippets.

@manchuwook
Last active March 12, 2024 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manchuwook/36f06264d53a58f15547db69ebf242c0 to your computer and use it in GitHub Desktop.
Save manchuwook/36f06264d53a58f15547db69ebf242c0 to your computer and use it in GitHub Desktop.
Generate a kubernetes secret yaml using a certificate
const fs = require('fs');
const path = require('path');
function encodeFileContent(filePath) {
return new Promise((resolve, reject) => {
fs.readFile(filePath, { encoding: 'base64' }, (err, data) => {
if (err) {
reject(`Error reading file ${filePath}: ${err}`);
} else {
resolve(data);
}
});
});
}
async function createK8sSecretYaml(certFile, keyFile, secretName, namespace = 'default') {
try {
const encodedCert = await encodeFileContent(certFile);
const encodedKey = await encodeFileContent(keyFile);
const secretYaml = `apiVersion: v1
kind: Secret
metadata:
name: ${secretName}
namespace: ${namespace}
type: kubernetes.io/tls
data:
tls.crt: ${encodedCert}
tls.key: ${encodedKey}
`;
return secretYaml;
} catch (error) {
console.error(error);
process.exit(1);
}
}
function saveSecretYaml(yamlContent, outputFilePath) {
fs.writeFile(outputFilePath, yamlContent, (err) => {
if (err) {
console.error(`Failed to save the Kubernetes secret YAML: ${err}`);
process.exit(1);
} else {
console.log(`Kubernetes secret YAML has been saved to ${outputFilePath}`);
}
});
}
function main() {
const args = process.argv.slice(2);
if (args.length < 3) {
console.error('Usage: node generateSecret.js <certFile> <keyFile> <secretName> [namespace]');
process.exit(1);
}
const [certFile, keyFile, secretName, namespace = 'default'] = args;
createK8sSecretYaml(certFile, keyFile, secretName, namespace)
.then((yamlContent) => {
const outputFilePath = path.join(process.cwd(), 'k8s-secret.yaml');
saveSecretYaml(yamlContent, outputFilePath);
})
.catch((error) => {
console.error(`Error generating Kubernetes secret YAML: ${error}`);
process.exit(1);
});
}
main();
import base64
import os
import argparse
def file_exists(file_path):
"""Check if a file exists."""
return os.path.isfile(file_path)
def encode_file_content(file_path):
"""Reads a file and returns its base64 encoded content."""
if not file_exists(file_path):
raise FileNotFoundError(f"The file {file_path} does not exist.")
try:
with open(file_path, 'rb') as file:
return base64.b64encode(file.read()).decode('utf-8')
except Exception as e:
raise Exception(f"Failed to encode file {file_path}: {e}")
def create_k8s_secret_yaml(cert_file, key_file, secret_name, namespace="default"):
"""Generates a Kubernetes secret YAML from certificate and key files."""
try:
encoded_cert = encode_file_content(cert_file)
encoded_key = encode_file_content(key_file)
except Exception as e:
print(e)
return None
secret_yaml = f"""apiVersion: v1
kind: Secret
metadata:
name: {secret_name}
namespace: {namespace}
type: kubernetes.io/tls
data:
tls.crt: {encoded_cert}
tls.key: {encoded_key}
"""
return secret_yaml
def save_secret_yaml(yaml_content, output_file="k8s-secret.yaml"):
"""Saves the YAML content to a file."""
if yaml_content is None:
print("No YAML content to save.")
return
try:
with open(output_file, 'w') as file:
file.write(yaml_content)
print(f"Kubernetes secret YAML has been saved to {output_file}")
except Exception as e:
print(f"Failed to save the Kubernetes secret YAML: {e}")
def main():
parser = argparse.ArgumentParser(description="Generate a Kubernetes secret YAML from certificate and key files.")
parser.add_argument("cert_file", help="Path to the certificate file.")
parser.add_argument("key_file", help="Path to the key file.")
parser.add_argument("secret_name", help="Name of the Kubernetes secret.")
parser.add_argument("--namespace", default="default", help="Namespace for the Kubernetes secret. Defaults to 'default'.")
args = parser.parse_args()
# Generate and save the Kubernetes secret YAML
k8s_secret_yaml = create_k8s_secret_yaml(args.cert_file, args.key_file, args.secret_name, args.namespace)
save_secret_yaml(k8s_secret_yaml)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment