typescript - Pulumi 在运行时获取 Kubernetes 上下文
是否有一种方法可以在运行时获取当前的 Kubernetes 上下文,以防止在使用 pulumi up 时使用错误的上下文?我特别希望确保我的本地 Kubernetes 部署逻辑不会最终运行在本地集群以外的任何环境中。
我已经看过这些示例,但没有看到任何做这个的:https://github.com/pulumi/examples/search?l=TypeScript&p=2&q=context&type=(也许我是在用错误的方式考虑我的问题)。
答案#1
如这里所解释的,首先你必须为你的集群创建一个将被使用的上下文,例如:
kubectl config \
set-context <my-context> \
--cluster=<my-cluster> \
--user=<my-user>
然后运行 pulumi stack init new-kube-stack,系统会要求你输入访问令牌,最后运行 pulumi config set kubernetes:context my-context 以在先前创建的上下文中定义的集群中工作。
答案#2
编辑 您可以使用 kubeProvider 动态设置 kubeconfig
// Define k8sProvider based on the stack
let k8sProvider: k8s.Provider;
if (stackName === "local") {
const kubeConfigPath = path.join(os.homedir(), ".kube", "config"); // Path to the kubeconfig file assuming ~/.kube/config
const kubeconfig = fs.readFileSync(kubeConfigPath, 'utf8');
k8sProvider = new k8s.Provider("k8sProvider", {
kubeconfig: kubeconfig
});
} else {
const label = "cluster-label";
const lkePool: linode.types.input.LkeClusterPool[] = [{ type: "g6-standard-4", count: 2, autoscaler: { min: 2, max: 6 } }]
const lkeCluster = new linode.LkeCluster("cluster-label", { label: label, pools: lkePool, region: "us-ord", k8sVersion: "1.29" })
const kubeconfig = lkeCluster.id.apply(async (id) => {
const cluster = await linode.getLkeCluster({ id: Number(id) });
return Buffer.from(cluster.kubeconfig, "base64").toString();
});
k8sProvider = new k8s.Provider("k8sProvider", {
kubeconfig: kubeconfig
});
}
这样你就可以像这样将 k8sProvider 传递给你的 Kubernetes 对象 { provider: k8sProvider }:
const dockerSecret = new k8s.core.v1.Secret("regcred", {
metadata: { name: "regcred" },
type: "kubernetes.io/dockerconfigjson",
data: {".dockerconfigjson": Buffer.from(dockerConfigJson, 'utf8').toString('base64'),
}
}, { provider: k8sProvider });
我遇到过类似的问题。我管理不同的 Kubernetes 集群,并且希望确保将 Pulumi 应用于正确的上下文。
import * as pulumi from "@pulumi/pulumi";
import * as child_process from "child_process";
import { promisify } from "util";
const exec = promisify(child_process.exec);
async function getCurrentKubectlContext() {
try {
// Using kubectl to get the current context
const { stdout, stderr } = await exec("kubectl config current-context");
if (stderr) {
console.error("Error fetching current kubectl context:", stderr);
return null;
}
return stdout.trim();
} catch (error) {
console.error("Failed to fetch current kubectl context:", error);
return null;
}
}
它运行 kubectl config current-context,该命令会显示 kubectl 当前使用的上下文。
然后在我的 index.ts 中,我这样执行它:
// Fetch and log the current Kubernetes context
getCurrentKubectlContext().then(context => {
if (context) {
// console.log(`Current Kubernetes context : ${context }`);
pulumi.log.info(`Current Kubernetes context : ${context}`);
}
}).catch(error => {
console.error("Failed to fetch current kubectl context:", error);
});
然后在运行 pulumi up 并选择 yes 或 no 之前,它会打印出你当前的上下文。
