如何从(非主机)节点或遥控器访问Kubernetes API



我从外部设置对Kubernetes群集的访问遇到麻烦。这就是我要实现的目标: - 具有从外部访问Kube群集的能力(来自不是"主"甚至来自任何遥控器的节点)才能仅在特定名称空间上执行Kube操作。

我的逻辑是以下内容:

  • 创建新名称空间(我们称其为testns)
  • 创建服务帐户(testns-account)
  • 创建角色,可访问创建任何类型的kube资源,内部testns namespace
  • 创建角色绑定,将服务帐户与角色绑定
  • 从服务帐户生成令牌

现在,我的逻辑是,我需要具有令牌 API服务器URL才能使用有限的"权限"访问Kube群集,但这似乎还不够。

实现这一目标的最简单方法是什么?首先,我可以使用Kubectl访问,只是为了验证命名空间工作的有限权限,但最终,我将拥有一些访问权限的客户端代码,并使用这些有限的权限创建Kube资源。

您需要从令牌中生成kubeconfig。有脚本可以处理。这是为了后代:

!/usr/bin/env bash

# Copyright 2017, Z Lab Corporation. All rights reserved.
# Copyright 2017, Kubernetes scripts contributors
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
set -e
if [[ $# == 0 ]]; then
  echo "Usage: $0 SERVICEACCOUNT [kubectl options]" >&2
  echo "" >&2
  echo "This script creates a kubeconfig to access the apiserver with the specified serviceaccount and outputs it to stdout." >&2
  exit 1
fi
function _kubectl() {
  kubectl $@ $kubectl_options
}
serviceaccount="$1"
kubectl_options="${@:2}"
if ! secret="$(_kubectl get serviceaccount "$serviceaccount" -o 'jsonpath={.secrets[0].name}' 2>/dev/null)"; then
  echo "serviceaccounts "$serviceaccount" not found." >&2
  exit 2
fi
if [[ -z "$secret" ]]; then
  echo "serviceaccounts "$serviceaccount" doesn't have a serviceaccount token." >&2
  exit 2
fi
# context
context="$(_kubectl config current-context)"
# cluster
cluster="$(_kubectl config view -o "jsonpath={.contexts[?(@.name=="$context")].context.cluster}")"
server="$(_kubectl config view -o "jsonpath={.clusters[?(@.name=="$cluster")].cluster.server}")"
# token
ca_crt_data="$(_kubectl get secret "$secret" -o "jsonpath={.data.ca.crt}" | openssl enc -d -base64 -A)"
namespace="$(_kubectl get secret "$secret" -o "jsonpath={.data.namespace}" | openssl enc -d -base64 -A)"
token="$(_kubectl get secret "$secret" -o "jsonpath={.data.token}" | openssl enc -d -base64 -A)"
export KUBECONFIG="$(mktemp)"
kubectl config set-credentials "$serviceaccount" --token="$token" >/dev/null
ca_crt="$(mktemp)"; echo "$ca_crt_data" > $ca_crt
kubectl config set-cluster "$cluster" --server="$server" --certificate-authority="$ca_crt" --embed-certs >/dev/null
kubectl config set-context "$context" --cluster="$cluster" --namespace="$namespace" --user="$serviceaccount" >/dev/null
kubectl config use-context "$context" >/dev/null
cat "$KUBECONFIG"

最新更新