Generating Client Configuration JSON File with GCP using Python

Abstract: Generate a GCP client configuration JSON file in Python to enable automated authentication for services like Storage and BigQuery.

Created: 2026-10-05 by
To generate a Google Cloud Platform client configuration JSON file using Python, you must first authenticate your environment or manually construct the service account key. The most robust method involves using the google-auth library to retrieve credentials programmatically and saving them as a valid JSON structure that other GCP libraries can consume for automated tasks.

Understanding the Client Configuration File

The client configuration file is typically a JSON file containing private keys, project IDs, and authentication endpoints. It serves as the bridge between your Python application and Google Cloud services like Storage, Compute Engine, or BigQuery. When you create a Service Account in the GCP Console and download its key, you receive this exact JSON structure. In many development scenarios, you do not need to manually download this file; instead, you can generate it dynamically within your script if you have the necessary permissions. This approach is particularly useful for CI/CD pipelines where hardcoding secrets is discouraged, but temporary credentials are needed.

Prerequisites and Environment Setup

Before writing the code, ensure your Python environment has the necessary packages installed. You will primarily need the google-cloud-core and google-auth libraries. If you are working in a managed environment like Cloud Run or App Engine, these might already be available. For local development, install them via pip:
pip install google-cloud-core google-auth
Additionally, you must have a valid Google Cloud Project ID. You can find this in the GCP Console under "IAM & Admin" > "Settings". If you are running this locally, ensure you have authenticated with gcloud auth application-default login so that the Python libraries can locate your user credentials. This step is crucial because the code relies on finding existing credentials to either export them or validate access before generating new configurations.

Method 1: Exporting Existing Credentials

If your goal is simply to save the currently active credentials to a JSON file for use by another process, you can use the google.auth.default() function. This function searches the standard locations for credentials, such as environment variables or the default application credentials file. Once retrieved, you can serialize the relevant parts of the credential object into a dictionary and write it to a file. Note that not all credential types support full serialization, especially those involving OAuth tokens which expire quickly. Service account keys, however, are static and safe to save.
import json
import google.auth
from google.oauth2 import service_account

# Attempt to get default credentials
credentials, project_id = google.auth.default()

# If credentials are a service account key, we can extract info
if hasattr(credentials, 'service_account_email'):
    config = {
        "type": "service_account",
        "project_id": project_id,
        "private_key_id": getattr(credentials, 'private_key_id', 'unknown'),
        "client_email": credentials.service_account_email,
        # Note: Private key is usually not exposed via .default() unless loaded from a file
    }
    
    with open('client_config.json', 'w') as f:
        json.dump(config, f, indent=4)
This method is limited because google.auth.default() often returns an GoogleCredentials object that does not contain the private key itself. Therefore, this approach is best for verifying identity rather than creating a reusable key file. To create a full, usable key file, you typically need to start with the raw key data.

Method 2: Generating a New Service Account Key

For a complete solution that generates a new JSON configuration file from scratch, you need to interact with the IAM API. This requires a parent service account with the Service Account Actor role. You cannot generate keys for yourself; you must act as an administrator of a service account. First, initialize the IAM client. Then, call the create_service_account_key method. This method returns a CreateServiceAccountKeyResponse object which contains the private key material. You then format this data into the standard JSON structure expected by GCP clients.
from google.cloud import iam_credentials
import json

def generate_client_config_json(project_id, target_service_account_email):
    # Initialize the IAM Credentials client
    client = iam_credentials.IAMCredentialsClient()
    
    # Name of the service account
    name = f"projects/{project_id}/serviceAccounts/{target_service_account_email}"
    
    # Create the key
    response = client.create_service_account_key(
        request={
            "name": name,
            "key_algorithm": iam_credentials.types.KeyAlgorithm.KEY_ALGORITHM_UNSPECIFIED
        }
    )
    
    # Extract the key data
    key_data = {
        "type": "service_account",
        "project_id": project_id,
        "private_key_id": response.private_key_id,
        "private_key": response.private_key_data,
        "client_email": target_service_account_email,
        "client_id": response.key_metadata.unique_id,
        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        "token_uri": "https://oauth2.googleapis.com/token",
        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
        "client_x509_cert_url": f"https://www.googleapis.com/robot/v1/metadata/x509/{target_service_account_email.replace('@', '%40')}"
    }
    
    return key_data

# Usage
config = generate_client_config_json("your-project-id", "[email protected]")
with open('new_client_config.json', 'w') as f:
    json.dump(config, f, indent=4)
This script creates a brand new key for the specified service account. The resulting JSON file can be used immediately to authenticate subsequent API calls. Be aware that each time you run this, a new key is added to the service account. You should manage these keys carefully, as having too many active keys increases security risks.

Security Best Practices

Never commit the generated JSON file to version control systems like Git. These files contain private keys that grant access to your cloud resources. Use environment variables or secret management tools like HashiCorp Vault or AWS Secrets Manager to inject these values at runtime. Additionally, set appropriate scopes when initializing clients to follow the principle of least privilege. If you only need access to Cloud Storage, do not grant broad IAM roles. Instead, use specific bucket-level policies. Regularly audit your service accounts and rotate keys periodically to maintain a secure posture.

Handling Errors and Edge Cases

When generating these files, you may encounter permission errors if the executing identity lacks the roles/iam.serviceAccountKeyAdmin role. Always check your IAM bindings before running the generation script. Furthermore, ensure that the email address provided matches exactly with the one registered in GCP. Typos in the email address will result in 403 Forbidden errors. If you are running this in a containerized environment, ensure the container has network access to Google's metadata servers if relying on implicit credentials.

Frequently Asked Questions

Can I use this JSON file with non-Google libraries?

Yes, the standard service account JSON format is widely supported across various programming languages and third-party tools. Many libraries, including those for Terraform and Kubernetes, expect this exact structure to authenticate against GCP APIs.

How often should I rotate these service account keys?

It is recommended to rotate keys every 90 days or immediately if there is any suspicion of compromise. GCP provides tools to list and delete old keys, so you can automate this process using scheduled jobs or CI/CD pipelines.

What if I don't have permission to create new keys?

If you lack the necessary IAM permissions, you cannot generate keys programmatically. In this case, you must request an administrator to create and share the key file, or use Application Default Credentials if you are accessing resources within the same project.

Is it safe to store the JSON file in plain text?

No, storing private keys in plain text is a significant security risk. Always encrypt sensitive files at rest and use secure transmission methods. Consider using GCP Secret Manager to store and retrieve these keys dynamically instead of keeping them on disk.

Why does my generated JSON fail to authenticate?

This usually happens if the client_email does not match the service account associated with the private key, or if the project ID is incorrect. Verify the fields in the JSON against the GCP Console details. Also, ensure the service account has the required roles for the specific API you are trying to access.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More