To enable APIs, you need the serviceusage.services.enable permission. If you
created the project, then you likely already have this permission through the
Owner role (roles/owner). Otherwise, you can get this permission through the
Service Usage Admin role (roles/serviceusage.serviceUsageAdmin).
Learn how to grant roles.
At the bottom of the Google Cloud console, a
Cloud Shell
session starts and displays a command-line prompt. Cloud Shell is a shell environment
with the Google Cloud CLI
already installed and with values already set for
your current project. It can take a few seconds for the session to initialize.
C#
To use the .NET samples on this page in a local development environment, install and
initialize the gcloud CLI, and then set up Application Default Credentials with
your user credentials.
To use the C++ samples on this page in a local development environment, install and
initialize the gcloud CLI, and then set up Application Default Credentials with
your user credentials.
To use the Go samples on this page in a local development environment, install and
initialize the gcloud CLI, and then set up Application Default Credentials with
your user credentials.
To use the Java samples on this page in a local development environment, install and
initialize the gcloud CLI, and then set up Application Default Credentials with
your user credentials.
To use the Python samples on this page in a local development environment, install and
initialize the gcloud CLI, and then set up Application Default Credentials with
your user credentials.
To get the permissions that
you need to create and delete service account keys,
ask your administrator to grant you the
Service Account Key Admin (roles/iam.serviceAccountKeyAdmin) IAM role on the project, or the service account whose keys you want
to manage.
For more information about granting roles, see Manage access to projects, folders, and organizations.
To get the permissions that
you need to allow service account keys to be created in a project,
ask your administrator to grant you the
following IAM roles on your organization:
These predefined roles contain
the permissions required to allow service account keys to be created in a project. To see the exact permissions that are
required, expand the Required permissions section:
Required permissions
The following permissions are required to allow service account keys to be created in a project:
Before you create a service account key, make sure that the
iam.disableServiceAccountKeyCreation organization policy constraint isn't
enforced for your project. If this constraint is enforced for your project,
you can't create service account keys in that project.
We recommend enforcing this constraint for most projects and only exempting
projects that truly require service account keys. For more information about
alternative authentication methods, see Choose the right authentication method
for your use case.
To exempt a project from the iam.disableServiceAccountKeyCreation organization
policy constraint, ask an organization policy administrator to do the following:
At the organization level, create a tag key and tag value that you will use to define whether
a resource should be exempt from the organization policy. We recommend creating a tag
with the key disableServiceAccountKeyCreation and the values enforced and
not_enforced.
Attach the disableServiceAccountKeyCreation tag to the organization and set its value to
enforced. All resources in the organization inherit this tag value,
unless it's overwritten with a different tag value.
For each project or folder that you want to exempt from the organization policy, attach the
disableServiceAccountKeyCreation tag and set its value to not_enforced. Setting
a tag value for a project or folder in this way overrides the tag value inherited from the
organization.
Create or
update the organization policy that prevents the creation of service account keys so that it doesn't
enforce the constraint for exempt resources.
This policy should have the following rules:
Configure the iam.disableServiceAccountKeyCreation constraint to not be
enforced on any resources with the disableServiceAccountKeyCreation:
not_enforced tag. The condition in this rule should look like the following:
Configure the iam.disableServiceAccountKeyCreation constraint to be enforced on
all other resources.
Create a service account key
To use a service account from outside of Google Cloud, such as on other
platforms or on-premises, you must first establish the identity of the service
account. Public/private key pairs provide a secure way of accomplishing this
goal. When you create a service account key, the public portion is stored on
Google Cloud, while the private portion is available only to you. For more
information about public/private key pairs, see
Service account keys.
In the examples below, SA_NAME is the name of your
service account, and PROJECT_ID is the ID of your
Google Cloud project. You can retrieve the
SA_NAME@PROJECT_ID.iam.gserviceaccount.com
string from the Service Accounts
page in the Google Cloud console.
Console
In the Google Cloud console, go to the Service accounts page.
Always store your service account keys in a secure location. If you don't store your keys securely,
then bad actors can find the keys and use them to access the resources that the service account can
access. We strongly recommend storing your keys in a hardware-based or software-based key store. For
more guidance on storing service account keys securely, see Protecting
against privilege escalation.
You can move and rename this file however you like.
KEY_FILE: The path to a new output file for the
private key—for example, ~/sa-private-key.json.
SA_NAME: The name of the service account
to create a key for.
PROJECT_ID: Your Google Cloud project ID.
gcloud iam service-accounts keys create KEY_FILE \
--iam-account=SA_NAME@PROJECT_ID.iam.gserviceaccount.com
Output:
created key [e44da1202f82f8f4bdd9d92bc412d1d8a837fa83] of type [json] as
[/usr/home/username/KEY_FILE] for
[SA_NAME@PROJECT_ID.iam.gserviceaccount.com]
The service account key file is now downloaded to your machine. After you
download the key file, you cannot download it again.
The downloaded key has the following format, where
PRIVATE_KEY is the private portion of the public/private
key pair:
Always store your service account keys in a secure location. If you don't store your keys securely,
then bad actors can find the keys and use them to access the resources that the service account can
access. We strongly recommend storing your keys in a hardware-based or software-based key store. For
more guidance on storing service account keys securely, see Protecting
against privilege escalation.
You can move and rename this file however you like.
To authenticate to IAM, set up Application Default Credentials.
For more information, see
Before you begin.
namespaceiam=::google::cloud::iam_admin_v1;return[](std::stringconst&name){iam::IAMClientclient(iam::MakeIAMConnection());autoresponse=client.CreateServiceAccountKey(name,google::iam::admin::v1::ServiceAccountPrivateKeyType::TYPE_GOOGLE_CREDENTIALS_FILE,google::iam::admin::v1::ServiceAccountKeyAlgorithm::KEY_ALG_RSA_2048);if(!response)throwstd::move(response).status();std::cout << "ServiceAccountKey successfully created: " << response->DebugString() << "\n" << "Please save the key in a secure location, as they cannot ""be downloaded later\n";returnresponse->name();}
To authenticate to IAM, set up Application Default Credentials.
For more information, see
Before you begin.
usingSystem;usingSystem.Text;usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.Iam.v1;usingGoogle.Apis.Iam.v1.Data;publicpartialclassServiceAccountKeys{publicstaticServiceAccountKeyCreateKey(stringserviceAccountEmail){varcredential=GoogleCredential.GetApplicationDefault().CreateScoped(IamService.Scope.CloudPlatform);varservice=newIamService(newIamService.Initializer{HttpClientInitializer=credential});varkey=service.Projects.ServiceAccounts.Keys.Create(newCreateServiceAccountKeyRequest(),"projects/-/serviceAccounts/"+serviceAccountEmail).Execute();// The PrivateKeyData field contains the base64-encoded service account key// in JSON format.// TODO(Developer): Save the below key (jsonKeyFile) to a secure location.// You cannot download it later.byte[]valueBytes=System.Convert.FromBase64String(key.PrivateKeyData);stringjsonKeyContent=Encoding.UTF8.GetString(valueBytes);Console.WriteLine("Key created successfully");returnkey;}}
To authenticate to IAM, set up Application Default Credentials.
For more information, see
Before you begin.
import("context"// "encoding/base64""fmt""io"iam"google.golang.org/api/iam/v1")// createKey creates a service account key.funccreateKey(wio.Writer,serviceAccountEmailstring)(*iam.ServiceAccountKey,error){ctx:=context.Background()service,err:=iam.NewService(ctx)iferr!=nil{returnnil,fmt.Errorf("iam.NewService: %w",err)}resource:="projects/-/serviceAccounts/"+serviceAccountEmailrequest:=&iam.CreateServiceAccountKeyRequest{}key,err:=service.Projects.ServiceAccounts.Keys.Create(resource,request).Do()iferr!=nil{returnnil,fmt.Errorf("Projects.ServiceAccounts.Keys.Create: %w",err)}// The PrivateKeyData field contains the base64-encoded service account key// in JSON format.// TODO(Developer): Save the below key (jsonKeyFile) to a secure location.// You cannot download it later.// jsonKeyFile, _ := base64.StdEncoding.DecodeString(key.PrivateKeyData)fmt.Fprintf(w,"Key created successfully")returnkey,nil}
To authenticate to IAM, set up Application Default Credentials.
For more information, see
Before you begin.
importcom.google.cloud.iam.admin.v1.IAMClient;importcom.google.gson.Gson;importcom.google.iam.admin.v1.CreateServiceAccountKeyRequest;importcom.google.iam.admin.v1.ServiceAccountKey;importjava.io.IOException;publicclassCreateServiceAccountKey{publicstaticvoidmain(String[]args)throwsIOException{// TODO(Developer): Replace the below variables before running.StringprojectId="your-project-id";StringserviceAccountName="your-service-account-name";ServiceAccountKeykey=createKey(projectId,serviceAccountName);Gsongson=newGson();// System.out.println("Service account key: " + gson.toJson(key));}// Creates a key for a service account.publicstaticServiceAccountKeycreateKey(StringprojectId,StringaccountName)throwsIOException{Stringemail=String.format("%s@%s.iam.gserviceaccount.com",accountName,projectId);// Initialize client that will be used to send requests.// This client only needs to be created once, and can be reused for multiple requests.try(IAMClientiamClient=IAMClient.create()){CreateServiceAccountKeyRequestreq=CreateServiceAccountKeyRequest.newBuilder().setName(String.format("projects/%s/serviceAccounts/%s",projectId,email)).build();ServiceAccountKeycreatedKey=iamClient.createServiceAccountKey(req);System.out.println("Key created successfully");returncreatedKey;}}}
To authenticate to IAM, set up Application Default Credentials.
For more information, see
Before you begin.
fromgoogle.cloudimportiam_admin_v1fromgoogle.cloud.iam_admin_v1importtypesdefcreate_key(project_id:str,account:str)-> types.ServiceAccountKey:""" Creates a key for a service account. project_id: ID or number of the Google Cloud project you want to use. account: ID or email which is unique identifier of the service account. """iam_admin_client=iam_admin_v1.IAMClient()request=types.CreateServiceAccountKeyRequest()request.name=f"projects/{project_id}/serviceAccounts/{account}"key=iam_admin_client.create_service_account_key(request=request)# The private_key_data field contains the stringified service account key# in JSON format. You cannot download it again later.# If you want to get the value, you can do it in a following way:# import json# json_key_data = json.loads(key.private_key_data)# key_id = json_key_data["private_key_id"]returnkey
Before using any of the request data,
make the following replacements:
PROJECT_ID: Your Google Cloud project
ID. Project IDs are alphanumeric strings, like my-project.
SA_NAME: The name of the service account that you want to create a key
for.
KEY_ALGORITHM: Optional. The key algorithm to use for
the key. The default, which is subject to change, is a 2,048-bit RSA key. For a list
of all possible values, see the
ServiceAccountKeyAlgorithm reference.
HTTP method and URL:
POST https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_NAME@PROJECT_ID.iam.gserviceaccount.com/keys
Request JSON body:
{
"keyAlgorithm": "KEY_ALGORITHM"
}
To send your request, expand one of these options:
curl (Linux, macOS, or Cloud Shell)
Save the request body in a file named request.json,
and execute the following command:
Copy the request body and open the
method reference page.
The APIs Explorer panel opens on the right side of the page.
You can interact with this tool to send requests.
Paste the request body in this tool, complete any other required fields, and click Execute.
The response contains a key for your service account. The returned key has the following format,
where ENCODED_PRIVATE_KEY is the private portion of the public/private key
pair, encoded in base64.
Always store your service account keys in a secure location. If you don't store your keys securely,
then bad actors can find the keys and use them to access the resources that the service account can
access. We strongly recommend storing your keys in a hardware-based or software-based key store. For
more guidance on storing service account keys securely, see Protecting
against privilege escalation.
Deleting a service account key permanently prevents you from using the key to
authenticate with Google APIs.
You cannot undelete a deleted key. Before you delete a key, we recommend that
you disable the key, then wait until you are sure that the key
is no longer needed. You can then delete the key.
As a best practice, rotate your service account keys regularly. To learn more about
rotating service account keys, see Service account key rotation.
Console
In the Google Cloud console, go to the Service accounts page.
KEY_ID: The ID of the key to delete. To find the
key's ID, list all keys for the service account, identify the
key that you want to delete, and then copy its ID.
SA_NAME: The name of the service account that the key
belongs to.
PROJECT_ID: Your Google Cloud project ID.
gcloud iam service-accounts keys delete KEY_ID \
--iam-account=SA_NAME@PROJECT_ID.iam.gserviceaccount.com
Output:
Deleted key [KEY_ID] for service account
[SA_NAME@PROJECT_ID.iam.gserviceaccount.com]
To authenticate to IAM, set up Application Default Credentials.
For more information, see
Before you begin.
importcom.google.cloud.iam.admin.v1.IAMClient;importcom.google.iam.admin.v1.DeleteServiceAccountKeyRequest;importcom.google.iam.admin.v1.KeyName;importjava.io.IOException;publicclassDeleteServiceAccountKey{publicstaticvoidmain(String[]args)throwsIOException{// TODO(developer): Replace the variables before running the sample.StringprojectId="your-project-id";StringserviceAccountName="my-service-account-name";StringserviceAccountKeyId="service-account-key-id";deleteKey(projectId,serviceAccountName,serviceAccountKeyId);}// Deletes a service account key.publicstaticvoiddeleteKey(StringprojectId,StringaccountName,StringserviceAccountKeyId)throwsIOException{//Initialize client that will be used to send requests.//This client only needs to be created once, and can be reused for multiple requests.try(IAMClientiamClient=IAMClient.create()){//Construct the service account email.//You can modify the ".iam.gserviceaccount.com" to match the service account name in which//you want to delete the key.//See, https://cloud.google.com/iam/docs/creating-managing-service-account-keys#deletingStringaccountEmail=String.format("%s@%s.iam.gserviceaccount.com",accountName,projectId);Stringname=KeyName.of(projectId,accountEmail,serviceAccountKeyId).toString();DeleteServiceAccountKeyRequestrequest=DeleteServiceAccountKeyRequest.newBuilder().setName(name).build();// Then you can delete the keyiamClient.deleteServiceAccountKey(request);System.out.println("Deleted key: "+serviceAccountKeyId);}}}
To authenticate to IAM, set up Application Default Credentials.
For more information, see
Before you begin.
fromgoogle.cloudimportiam_admin_v1fromgoogle.cloud.iam_admin_v1importtypesdefdelete_key(project_id:str,account:str,key_id:str)-> None:"""Deletes a key for a service account. project_id: ID or number of the Google Cloud project you want to use. account: ID or email which is unique identifier of the service account. key_id: unique ID of the key. """iam_admin_client=iam_admin_v1.IAMClient()request=types.DeleteServiceAccountKeyRequest()request.name=f"projects/{project_id}/serviceAccounts/{account}/keys/{key_id}"iam_admin_client.delete_service_account_key(request=request)print(f"Deleted key: {key_id}")
Before using any of the request data,
make the following replacements:
PROJECT_ID: Your Google Cloud project
ID. Project IDs are alphanumeric strings, like my-project.
SA_NAME: The name of the service account whose key you want to delete.
KEY_ID: The ID of the key that you want to delete. To find the key's
ID, list all keys for the service account, identify the key that you
want to delete, and then copy its ID from the end of the name field. The key's ID
is everything after keys/.
Open the
method reference page.
The APIs Explorer panel opens on the right side of the page.
You can interact with this tool to send requests.
Complete any required fields and click Execute.
You should receive a JSON response similar to the following:
If you're new to Google Cloud, create an account to evaluate how our
products perform in real-world scenarios. New customers also get $300 in
free credits to run, test, and deploy workloads.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2026-07-31 UTC."],[],[]]