簡體   English   中英

如何從(非主)節點或遠程訪問kubernetes API

[英]How to access kubernetes API from the (non-master) nodes or remote

我無法從外部設置對kubernetes集群的訪問。 這是我要實現的目標:-能夠從外部(不是“主”節點,甚至從任何遠程節點)訪問kube集群,以便僅在特定名稱空間上執行kube操作。

我的邏輯是執行以下操作:

  • 創建新的名稱空間(我們稱之為testns)
  • 創建服務帳戶(testns帳戶)
  • 創建角色,可提供在testns名稱空間內創建任何類型的kube資源的訪問權限
  • 創建角色綁定,該綁定將服務帳戶與角色綁定
  • 從服務帳戶生成令牌

現在,我的邏輯是我需要具有令牌+ 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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM