UNPKG

@mesh-tech/mesh-cli

Version:

CLI for Mesh platform development utilities

75 lines (74 loc) 2.52 kB
import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; export function buildKubeconfig(cluster, region) { return `apiVersion: v1 kind: Config clusters: - cluster: server: ${cluster.clusterEndpoint} certificate-authority-data: ${cluster.clusterCaData} name: eks-cluster contexts: - context: cluster: eks-cluster user: eks-user name: eks-context current-context: eks-context users: - name: eks-user user: exec: apiVersion: client.authentication.k8s.io/v1beta1 command: aws args: - eks - get-token - --cluster-name - ${cluster.clusterName} - --region - ${region} `; } export function sessionKubeconfigPath(sessionName) { return path.join(os.tmpdir(), 'mesh-dev-sessions', `${sessionName}.kubeconfig`); } export function resolveHubPlatformName(platform) { return platform?.name ?? 'mesh'; } async function ssmGetParameter(name) { const { SSMClient, GetParameterCommand } = await import('@aws-sdk/client-ssm'); const ssm = new SSMClient({ region: process.env.AWS_REGION || 'us-east-2' }); const resp = await ssm.send(new GetParameterCommand({ Name: name, WithDecryption: true })); return resp.Parameter?.Value; } export async function ensureKubeconfig(platformName, env, sessionName, deps = {}) { const parameter = `/mesh-platform/${platformName}/${env}/core/eks`; const getParameter = deps.getParameter ?? ssmGetParameter; let cluster; try { const value = await getParameter(parameter); if (!value) throw new Error('parameter is empty or missing'); const parsed = JSON.parse(value); if (!parsed.clusterEndpoint || !parsed.clusterCaData || !parsed.clusterName) { throw new Error('cluster data is missing clusterEndpoint/clusterCaData/clusterName'); } cluster = { clusterEndpoint: parsed.clusterEndpoint, clusterCaData: parsed.clusterCaData, clusterName: parsed.clusterName, }; } catch (error) { deps.onError?.({ parameter, error }); return null; } const region = process.env.AWS_REGION || 'us-east-2'; const kubeconfigPath = sessionKubeconfigPath(sessionName); if (!fs.existsSync(path.dirname(kubeconfigPath))) { fs.mkdirSync(path.dirname(kubeconfigPath), { recursive: true }); } fs.writeFileSync(kubeconfigPath, buildKubeconfig(cluster, region), { mode: 0o600 }); return kubeconfigPath; }