创建对指定namespace有所有权限的kube-config(在已有的namespace中创建)

    1. #!/bin/bash
    2. BASEDIR="$(dirname "$0")"
    3. folder="$BASEDIR/kube_config"
    4. echo -e "All namespaces is here: \n$(kubectl get ns|awk 'NR!=1{print $1}')"
    5. echo "endpoint server if local network you can use $(kubectl cluster-info |awk '/Kubernetes/{print $NF}')"
    6. namespace=$1
    7. endpoint=$(echo "$2" | sed -e 's,https\?://,,g')
    8. if [[ -z "$endpoint" || -z "$namespace" ]]; then
    9. echo "Use "$(basename "$0")" NAMESPACE ENDPOINT";
    10. exit 1;
    11. fi
    12. echo "---
    13. apiVersion: v1
    14. kind: ServiceAccount
    15. metadata:
    16. name: $namespace-user
    17. namespace: $namespace
    18. ---
    19. kind: Role
    20. apiVersion: rbac.authorization.k8s.io/v1beta1
    21. metadata:
    22. name: $namespace-user-full-access
    23. namespace: $namespace
    24. rules:
    25. - apiGroups: ['', 'extensions', 'apps', 'metrics.k8s.io']
    26. resources: ['*']
    27. verbs: ['*']
    28. - apiGroups: ['batch']
    29. resources:
    30. - jobs
    31. - cronjobs
    32. verbs: ['*']
    33. ---
    34. kind: RoleBinding
    35. apiVersion: rbac.authorization.k8s.io/v1beta1
    36. metadata:
    37. name: $namespace-user-view
    38. namespace: $namespace
    39. subjects:
    40. - kind: ServiceAccount
    41. name: $namespace-user
    42. namespace: $namespace
    43. roleRef:
    44. apiGroup: rbac.authorization.k8s.io
    45. kind: Role
    46. name: $namespace-user-full-access" | kubectl apply -f -
    47. mkdir -p $folder
    48. tokenName=$(kubectl get sa $namespace-user -n $namespace -o "jsonpath={.secrets[0].name}")
    49. token=$(kubectl get secret $tokenName -n $namespace -o "jsonpath={.data.token}" | base64 --decode)
    50. certificate=$(kubectl get secret $tokenName -n $namespace -o "jsonpath={.data['ca\.crt']}")
    51. echo "apiVersion: v1
    52. kind: Config
    53. preferences: {}
    54. clusters:
    55. - cluster:
    56. certificate-authority-data: $certificate
    57. server: https://$endpoint
    58. name: $namespace-cluster
    59. users:
    60. - name: $namespace-user
    61. user:
    62. as-user-extra: {}
    63. client-key-data: $certificate
    64. token: $token
    65. contexts:
    66. - context:
    67. cluster: $namespace-cluster
    68. namespace: $namespace
    69. user: $namespace-user
    70. name: $namespace
    71. current-context: $namespace" > $folder/$namespace.kube.conf