Service Account Unable to Interact with GKE Cluster in Another Project - kubernetes

A service account ($SERVICE_ACCOUNT_A) from one Google Cloud Platform (GCP) project ($PROJECT_A) is unable to interact with a Google Kubernetes Engine (GKE) cluster ($GKE_CLUSTER_B) within another GCP project ($PROJECT_B); where:
$PROJECT_A is the name of the project $SERVICE_ACCOUNT_A lives within
$SERVICE_ACCOUNT_A is of the form some-name#some-project-name#.iam.gserviceaccount.com
$PROJECT_B is the name of the project the $GKE_CLUSTER_B cluster lives within
$GKE_CLUSTER_B is a GKE cluster name, not context, of the form: some_cluster
$SERVICE_ACCOUNT_A is unable to interact with a $GKE_CLUSTER_B despite possessing roles from $PROJECT_B containing permissions that should allow it to do so.
I.e., first I created a custom role $ROLE:
gcloud iam roles create $ROLE \
--description="$ROLE_DESCRIPTION" \
--permissions=container.clusters.get,container.clusters.list \
--project=$PROJECT_B \
--title='$ROLE_TITLE'
#=>
Created role [$ROLE].
description: $ROLE_DESCRIPTION
etag: . . .
includedPermissions:
- container.clusters.get
- container.clusters.list
name: projects/$PROJECT_B/roles/$ROLE
stage: . . .
title: $ROLE_TITLE
then I associated $ROLE, from $PROJECT_B, with $SERVICE_ACCOUNT_A:
gcloud projects add-iam-policy-binding $PROJECT_B \
--member=serviceAccount:$SERVICE_ACCOUNT_A \
--role=projects/$PROJECT_B/roles/$ROLE
#=>
Updated IAM policy for project [$PROJECT_B].
auditConfigs:
. . .
and I am able to see $ROLE under $SERVICE_ACCOUNT_A:
gcloud projects get-iam-policy $PROJECT_B \
--flatten='bindings[].members' \
--format='value(bindings.role)' \
--filter="bindings.members:${SERVICE_ACCOUNT_A}"
#=>
projects/$PROJECT_B/roles/$ROLE
with the proper permissions:
gcloud iam roles describe $ROLE \
--flatten='includedPermissions' \
--format='value(includedPermissions)' \
--project=$PROJECT_B
#=>
container.clusters.get
container.clusters.list
but still unable to get $SERVICE_ACCOUNT_A to interact with $GKE_CLUSTER_B.
Why?

You need to enable the Kubernetes Engine API (found here) for $PROJECT_A, even if $PROJECT_A doesn't have or need a GKE cluster.
You can confirm this by creating a new JSON key for $SERVICE_ACCOUNT_A:
gcloud iam service-accounts keys create \
./some-key.json \
--iam-account="${SERVICE_ACCOUNT_A}" \
--key-file-type="json"
#=>
created key [$KEY_ID] of type [json] as [./some-key.json] for [$SERVICE_ACCOUNT_A]
activate the service account:
gcloud auth activate-service-account \
"${SERVICE_ACCOUNT_A}" \
--key-file=./some-key.json
#=>
Activated service account credentials for: [$SERVICE_ACCOUNT_A]
confirm it's active:
cloud auth list
Credentialed Accounts
ACTIVE ACCOUNT
. . .
* $SERVICE_ACCOUNT_A
your#account.user
. . .
To set the active account, run:
$ gcloud config set account `ACCOUNT`
and attempt to interact with $GKE_CLUSTER_B:
gcloud container clusters list --project=$PROJECT_B
#=>
ERROR: (gcloud.container.clusters.list) ResponseError: code=403, message=Kubernetes Engine API has not
been used in project $PROJECT_A_ID before or it is disabled. Enable it by visiting
https://console.developers.google.com/apis/api/container.googleapis.com/overview?project=$PROJECT_A_ID
then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our
systems and retry.
where $PROJECT_A_ID is a numeric id of the form: xxxxxxxxxxxxx.
Visit the address returned along with the 403 above (here) and enable the Kubernetes Engine API. $SERVICE_ACCOUNT_A should now be able to interact with GKE clusters within $PROJECT_B:
gcloud container clusters list \
--project=$PROJECT_B \
--format='value(name)
#=>
. . .
some_cluster
. . .
including $GKE_CLUSTER_B.

Related

How to create the GCP workload identity IAM bindings in Terraform?

GCP allows the Kubernetes service account to impersonate the IAM service account by adding an IAM policy binding between the two service accounts. This binding allows the Kubernetes service account to act as the IAM service account.
gcloud iam service-accounts add-iam-policy-binding GSA_NAME#GSA_PROJECT.iam.gserviceaccount.com \
--role roles/iam.workloadIdentityUser \
--member "serviceAccount:PROJECT_ID.svc.id.goog[NAMESPACE/KSA_NAME]"
We would like to create the same via Terraform resource and we tried this way, refer: article
resource "google_service_account_iam_binding" "service-account-iam" {
service_account_id = "GSA_NAME#GSA_PROJECT.iam.gserviceaccount.com"
role = "roles/iam.workloadIdentityUser"
members = [
"serviceAccount:PROJECT_ID.svc.id.goog[NAMESPACE/KSA_NAME]",
]
}
But we received the below error:
Error: "service_account_id" ("XXX#XXX.iam.gserviceaccount.com") doesn't match regexp "projects/(?:(?:[-a-z0-9]{1,63}\.)(?:a-z?):)?(?:[0-9]{1,19}|(?:a-z0-9?)|-)/serviceAccounts/((?:(?:[-a-z0-9]{1,63}\.)(?:a-z?):)?(?:[0-9]{1,19}|(?:a-z0-9?))#[a-z]+.gserviceaccount.com$|[0-9]{1,20}-compute#developer.gserviceaccount.com|a-z#[-a-z0-9\.]{1,63}\.iam\.gserviceaccount\.com$)"
What's wrong here?
service_account_id is the fully-qualified name of the service account to apply the policy to.
projects/PROJECT_ID/serviceAccounts/SERVICE_ACCOUNT_EMAIL

error in add-iam-policy-binding to ESP end point service GCloud

I am trying to create an end point for an API to be deployed into existing GKE cluster by following the instructions in Getting started with Cloud Endpoints for GKE with ESPv2
I clone the sample code in the repo and modified the content of openapi.yaml:
# [START swagger]
swagger: "2.0"
info:
description: "A simple Google Cloud Endpoints API example."
title: "Endpoints Example"
version: "1.0.0"
host: "my-api.endpoints.my-project.cloud.goog"
I then deployed it via the command:
endpoints/getting-started (master) $ gcloud endpoints services deploy openapi.yaml
Now I can see that it has been created:
$ gcloud endpoints services list
NAME TITLE
my-api.endpoints.my-project.cloud.goog
I also have postgreSQL service account:
$ gcloud iam service-accounts list
DISPLAY NAME EMAIL DISABLED
my-postgresql-service-account my-postgresql-service-acco#my-project.iam.gserviceaccount.com False
In the section Endpoint Service Configuration of documentation it says to add the role to the attached service account for the endpoint service as follows, but I get this error:
$ gcloud endpoints services add-iam-policy-binding my-api.endpoints.my-project.cloud.goog
--member serviceAccount:my-postgresql-service-acco#my-project.iam.gserviceaccount.com
--role roles/servicemanagement.serviceController
ERROR: (gcloud.endpoints.services.add-iam-policy-binding) User [myusername#mycompany.com] does not have permission to access services instance [my-api.endpoints.my-project.cloud.goog:getIamPolicy] (or it may not exist): No access to resource: services/my-api.my-project.cloud.goog
The previous lines show the service exits, I guess? Now I am not sure how to resolve this? What permissions do I need? who can give me permission and what permissions he should have? how can I check? Is there any other solution?
The issue got resolved after I was assigned the role of "Project_Admin". It was not ideal as it was giving too much permission to me. The role "roles/endpoints.portalAdmin" was also tried but did not help.

gcloud pubsub publish message issue

I am trying to publish the message on topic but I am not able to publish the message. I am using laravelframework. My subscription is push type.
I have used $ composer require google/cloud-pubsub from https://github.com/googleapis/google-cloud-php-pubsub link
I have followed this link: (https://cloud.google.com/pubsub/docs/publisher#php)
**use Google\Cloud\PubSub\PubSubClient;**
function publish_message($projectId, $topicName, $message)
{
$pubsub = new PubSubClient([\[][1]
'projectId' => $projectId,
]);
$topic = $pubsub->topic($topicName);
$topic->publish(['data' => $message]);
print('Message published' . PHP_EOL);
}
I am getting this error (open this link : https://i.stack.imgur.com/XXHZ5.png.
[1]: https://i.stack.imgur.com/XXHZ5.png
Your question would benefit from a more detailed explanation.
As it is, the code you show is the same code as published by Google.
Assuming (!?) Google's code works (probable but not certain), your code should work.
Since we know your code doesn't work, it's probably something else.
I suspect you've missed one or more of the following possibly the last steps:
created a Google Cloud Platform project ($projectId)?
enabled the Pub/Sub API?
created a Pub/Sub topic [and >=1 subscriber] ($topicName)?
created (service account) credentials permitted to publish to this topic?
set GOOGLE_APPLICATION_CREDENTIALS to point to the account's key?
How are you running the code?
If possible please also print the ClientException that you show in the image.
Update
I tested Google's code and it works for me:
BILLING_ID=[[YOUR-BILLING]]
PROJECT_ID=[[YOUR-PROJECT]]
TOPIC_NAME=[[YOUR-TOPIC-NAME]]
gcloud projects create ${PROJECT}
gcloud beta billing projects link ${PROJECT} \
--billing-account=${BILLING}
# Enabled Pub/Sub and create topic=subscription=${TOPIC_NAME}
gcloud services enable pubsub.googleapis.com \
--project=${PROJECT}
gcloud pubsub topics create ${TOPIC_NAME} \
--project=${PROJECT}
gcloud pubsub subscriptions create ${TOPIC_NAME} \
--topic=${TOPIC_NAME} \
--project=${PROJECT}
# Create service account ${ROBOT} and key `./${ROBOT}.json`
# Grant the account `publisher` permissions
ROBOT=[[YOUR-ACCOUNT-NAME]]
gcloud iam service-accounts create ${ROBOT} \
--project=${PROJECT}
gcloud iam service-accounts keys create ./${ROBOT}.json \
--iam-account=${ROBOT}#${PROJECT}.iam.gserviceaccount.com \
--project=${PROJECT}
gcloud projects add-iam-policy-binding ${PROJECT} \
--member=serviceAccount:${ROBOT}#${PROJECT}.iam.gserviceaccount.com \
--role=roles/pubsub.publisher
Then -- and apologies, I'm no PHP developer -- here's what I did:
composer.json:
{ "require": { "google/cloud-pubsub": "1.24.1" } }
pubsub.php:
<?php
require_once 'vendor/autoload.php';
use Google\Cloud\PubSub\PubSubClient;
// Expects Env PROJECT_ID, TOPIC_NAME **and** GOOGLE_APPLICATION_CREDENTIALS
$projectId = getenv("PROJECT_ID");
$topicName = getenv("TOPIC_NAME");
$pubsub = new PubSubClient([
"projectId" => $projectId
]);
$topic = $pubsub->topic($topicName);
$topic->publish(["data"=>"Hello Freddie!"]);
print("Message published" . PHP_EOL);
?>
Then:
export GOOGLE_APPLICATION_CREDENTIALS=./${ROBOT}.json
export PROJECT_ID
export TOPIC_NAME
php pubsub.php
NOTE the code implicitly assumes GOOGLE_APPLICATION_CREDENTIALS to authenticate against the service, see Application Default Credentials
yields:
Message published
And:
gcloud pubsub subscriptions pull ${TOPIC_NAME} \
--project=${PROJECT} \
--format="value(message.data)"
Hello Freddie!
I am guessing the issue you are faced is because of you must have missed the authentication step. Have you created a SA and downloaded the json file to authenticate? If so, double check that you have this line in your filesystem:
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-credentials.json

Keep getting permissions error gcloud.container.clusters.get-credentials

I am trying to integrate CircleCi with gcloud Kubernetes engine.
I created a service account with Kubernetes Engine Developer and Storage Admin roles.
Created CircleCi yaml file and configured CI.
Part of my yaml file includes:
docker:
- image: google/cloud-sdk
environment:
- PROJECT_NAME: 'my-project'
- GOOGLE_PROJECT_ID: 'my-project-112233'
- GOOGLE_COMPUTE_ZONE: 'us-central1-a'
- GOOGLE_CLUSTER_NAME: 'my-project-bed'
steps:
- checkout
- run:
name: Setup Google Cloud SDK
command: |
apt-get install -qq -y gettext
echo $GCLOUD_SERVICE_KEY > ${HOME}/gcloud-service-key.json
gcloud auth activate-service-account --key-file=${HOME}/gcloud-service-key.json
gcloud --quiet config set project ${GOOGLE_PROJECT_ID}
gcloud --quiet config set compute/zone ${GOOGLE_COMPUTE_ZONE}
gcloud --quiet container clusters get-credentials ${GOOGLE_CLUSTER_NAME}
Everything runs perfectly except that the last command:
gcloud --quiet container clusters get-credentials ${GOOGLE_CLUSTER_NAME}
It keeps failing with the error:
ERROR: (gcloud.container.clusters.get-credentials) ResponseError: code=403, message=Required "container.clusters.get" permission(s) for "projects/my-project-112233/zones/us-central1-a/clusters/my-project-bed". See https://cloud.google.com/kubernetes-engine/docs/troubleshooting#gke_service_account_deleted for more info.
I tried to give the ci account the role of project owner but I still got that error.
I tried to disable and re-enable the Kubernetes Service but it didn't help.
Any idea how to solve this? I am trying to solve it for 4 days...
This is an old thread, this is how this issue handled today in case using cloud build :
Granting Cloud Build access to GKE
To deploy the application in your Kubernetes cluster, Cloud Build needs the Kubernetes Engine Developer Identity and Access Management Role.
Get Project Number:
PROJECT_NUMBER="$(gcloud projects describe ${PROJECT_ID} --format='get(projectNumber)')"
Add IAM Policy bindings:
gcloud projects add-iam-policy-binding ${PROJECT_NUMBER} \
--member=serviceAccount:${PROJECT_NUMBER}#cloudbuild.gserviceaccount.com \
--role=roles/container.developer
More info can be found here.
I believe it's not the CI Service account but the k8s service account used to manage your GKE cluster, where its email should look like this (Somebody must have deleted it):
k8s-service-account#<project-id>.iam.gserviceaccount.com
You can re-create it an give it project owner permissions.
Step 1 : gcloud init
Step 2 : Select [2] Create a new configuration
Step 3 : Enter configuration name. Names start with a lower case letter and
contain only lower case letters a-z, digits 0-9, and hyphens '-': kubernetes-service-account
Step 4 : Choose the account you would like to use to perform operations for
this configuration:[2] Log in with a new account
Step 5 : Do you want to continue (Y/n)? y
Step 6 : Copy paste the link to brwoser and login with the ID which is used to create your google Cloud Account
Step 7 : Copy the verification code provided by google after login and paste it in to the console.
Step 8 : Pick cloud project to use:
Step 9: Do you want to configure a default Compute Region and Zone? (Y/n)? y
Step 10 : Please enter numeric choice or text value (must exactly match list item): 8
Your Google Cloud SDK is configured and ready to use!
The details of the above mentioned errors are explained in this help center article.
To add the Kubernetes Engine Service account (if you don't have it), please run the following command, in order to properly recreate the Kubernetes Service Account with the "Kubernetes Engine Service Agent" role,
gcloud services enable container.googleapis.com
In my case, these 2 steps solved my issue:
In the command,
gcloud container clusters get-credentials my-cluster-1 --zone=asia-south1-a --
project=thelab-240901
the --project should have the projectID value, not the project name
In the your travis account, go to your project repository -> more options -> settings -> Environment Variables. Now make sure you have only one set of encrypted_iv and encrypted_key environment variables as follows:
If you have encrypted different service accounts (json key files), this could add more than one set of encrypted_iv and encrypted_key environment variables. So, delete all those variables and freshly create the encrypted keys, may be by using travis encrypt-file --pro yourServiceAccountJSONFile.json --add
I had this problem using gcloud with my main owner account (!)
What fixed it was including --zone and --project params in the command to get the kubectl credentials.
I faced this issue with different scenarios, Listing it down below hope it will help someone.
1. If you did a fresh installation of google-cloud-sdk then you must login
with gcloud using the below command.
gcloud auth login
The above command will open ur browser and ask for login with your GCP account.
2. Sometimes provisioning is not reflected. Hence i revoke my provision and granted access (In this case my role is Owner) again. Then it worked.
I was getting the same error when trying to connect to my newly created cluster:
gcloud container clusters get-credentials <foo-cluster> --zone europe-central2-a --project <foo-project>
Fetching cluster endpoint and auth data.
ERROR: (gcloud.container.clusters.get-credentials) ResponseError: code=403, message=Required "container.clusters.get" permission(s) for "projects/foo-project/zones/europe-central2-a/clusters/foo-cluster".
I tried a few things:
I enabled Kuberentes API - no success
I added a key to service account and loged in using downloaded key:
gcloud auth activate-service-account --key-file=<path-to-the-downloaded-json-file>/foo-project-xxxx.json
Activated service account credentials for: [xxxx-compute#developer.gserviceaccount.com]
I run:
gcloud components update
However, I had a problem retriving data, all kubectl command were giving TLS handshake timeout, for example: kubectl get namespace was giving an error:
Unable to connect to the server: net/http: TLS handshake timeout
This is when I tried again:
gcloud container clusters get-credentials <foo-cluster> --zone europe-central2-a --project <foo-project>
and it worked
Fetching cluster endpoint and auth data.
kubeconfig entry generated for foo-project.

Google Cloud Service Account with 'roles/container.admin'

I am trying to create a Service Account with 'roles/container.admin' and i get an error saying that the role is not supported for this resource.
$ gcloud iam service-accounts add-iam-policy-binding sa-ci-vm#PROJECT-ID.iam.gserviceaccount.com --member='serviceAccount:sa-ci-vm#PROJECT-ID.iam.gserviceaccount.com' --role='roles/container.admin'
ERROR: (gcloud.iam.service-accounts.add-iam-policy-binding) INVALID_ARGUMENT: Role roles/container.admin is not supported for this resource.
If I create a Service Account from the CONSOLE UI I can add this role without a problem.
You have to use gcloud projects to add roles for a service account at a project level as shown here.
This works for me:
gcloud projects add-iam-policy-binding PROJECT_ID \
--member serviceAccount:sa-ci-vm#PROJECT-ID.iam.gserviceaccount.com \
--role roles/container.admin
I got the same error. You have to give the absolute path to the role.
cloud iam service-accounts add-iam-policy-binding SERVICEACCOUNT --member=SERVICEACCOUNT_EMAIL --role=projects/PROJECTNAME/roles/ROLENAME