# You could update instead of creategcloudcontainernode-poolscreate<nodepoolname>--cluster=<cluser_name>--workload-metadata=GKE_METADATA--region=us-central1
从 K8s 创建 GCP 服务账户以进行 impersonate,并赋予 GCP 权限:
# Create SA called "gsa2ksa"gcloudiamservice-accountscreategsa2ksa--project=<project-id># Give "roles/iam.securityReviewer" role to the SAgcloudprojectsadd-iam-policy-binding<project-id> \--member "serviceAccount:gsa2ksa@<project-id>.iam.gserviceaccount.com" \--role "roles/iam.securityReviewer"
连接到集群并创建要使用的服务账户
# Get k8s credsgcloudcontainerclustersget-credentials<cluster_name>--region=us-central1# Generate our testing namespacekubectlcreatenamespacetesting# Create the KSAkubectlcreateserviceaccountksa2gcp-ntesting
将GSA与KSA绑定
# Allow the KSA to access the GSA in GCP IAMgcloudiamservice-accountsadd-iam-policy-bindinggsa2ksa@<project-id.iam.gserviceaccount.com \--role roles/iam.workloadIdentityUser \--member "serviceAccount:<project-id>.svc.id.goog[<namespace>/ksa2gcp]"# Indicate to K8s that the SA is able to impersonate the GSAkubectlannotateserviceaccountksa2gcp \--namespace testing \iam.gke.io/gcp-service-account=gsa2ksa@security-devbox.iam.gserviceaccount.com
运行一个 pod,使用 KSA 并检查对 GSA 的 访问:
# If using Autopilot remove the nodeSelector stuff!echo"apiVersion: v1kind: Podmetadata:name: workload-identity-testnamespace: <namespace>spec:containers:- image: google/cloud-sdk:slimname: workload-identity-testcommand: ['sleep','infinity']serviceAccountName: ksa2gcpnodeSelector:iam.gke.io/gke-metadata-server-enabled: 'true'"|kubectlapply-f-# Get inside the podkubectlexec-itworkload-identity-test \--namespace testing \-- /bin/bash# Check you can access the GSA from insie the pod withcurl-H"Metadata-Flavor: Google"http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/emailgcloudauthlist
for ns in`kubectlgetnamespaces-ocustom-columns=NAME:.metadata.name|grep-vNAME`; dofor pod in`kubectlgetpods-n "$ns" -ocustom-columns=NAME:.metadata.name|grep-vNAME`; doecho"Pod: $ns/$pod"kubectlgetpod"$pod"-n"$ns"-oyaml|grep"gcp-service-account"echo""echo""donedone|grep-B1"gcp-service-account"
# Create a service account with a rolecat>my-service-account.yaml<<EOFapiVersion: v1kind: ServiceAccountmetadata:name: my-service-accountnamespace: defaultannotations:eks.amazonaws.com/role-arn: arn:aws:iam::318142138553:role/EKSOIDCTestingEOFkubectlapply-fmy-service-account.yaml# Add a role to an existent service accountkubectlannotateserviceaccount-n $namespace $service_account eks.amazonaws.com/role-arn=arn:aws:iam::$account_id:role/my-role