【问题标题】:How to access kubernetes API from the (non-master) nodes or remote如何从(非主)节点或远程访问 Kubernetes API
【发布时间】:2019-07-13 11:44:24
【问题描述】:
我在设置从外部访问 Kubernetes 集群时遇到问题。这就是我想要实现的目标:
- 能够从外部(从非“主”节点,甚至从任何远程节点)访问 kube 集群,以便仅在特定命名空间上执行 kube 操作。
我的逻辑是:
- 创建新的命名空间(我们称之为 testns)
- 创建服务帐号 (testns-account)
- 创建角色,授予在 testns 命名空间内创建任何类型的 kube 资源的访问权限
- 创建将服务帐户与角色绑定的角色绑定
- 从服务帐户生成令牌
现在,我的逻辑是我需要令牌 + api 服务器 URL 才能访问具有有限“权限”的 kube 集群,但这似乎还不够。
实现这一目标的最简单方法是什么?首先,我可以使用 kubectl 访问,只是为了验证对命名空间的有限权限是否有效,但最终,我会有一些客户端代码来执行访问并创建具有这些有限权限的 kube 资源。
【问题讨论】:
标签:
kubernetes
kubernetes-apiserver
【解决方案1】:
您需要从令牌生成 kubeconfig。有scripts 来处理这个问题。这是为了后代:
!/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"