Skip to content

An automated Terraform and Python template for accessing shared Google Workspace documents (Docs, Sheets, Drive) via a service account.

Notifications You must be signed in to change notification settings

h0ffmann/tf-gcp-workspace

Repository files navigation

Google Workspace Integration via Service Account and Terraform

This repository provides a streamlined solution for allowing a Python application to access Google Workspace APIs (like Google Docs, Sheets, and Drive) using a service account approach where clients share documents with your service account.

The infrastructure, including API enablement and service account creation, is managed by Terraform.

How It Works

This project uses a service account approach for secure document access:

  1. Terraform Manages Infrastructure: Deploys all the necessary GCP resources, including a service account with Google Workspace API access.
  2. Service Account Creation: Terraform creates a service account and generates credentials locally for your Python application.
  3. Document Sharing: Clients share their Google Docs, Sheets, or Drive folders with the service account email address.
  4. Python App Access: Your Python application uses the service account credentials to access shared documents.

This method provides secure access to client documents without requiring individual user authentication, making it ideal for applications that need to process documents shared by clients.

🚀 Installation and Setup Guide

Step 1: Prerequisites

  1. Clone this repository.
  2. Install just: A command runner used for convenience. (e.g., brew install just).
  3. Google Cloud SDK: Make sure you have the gcloud CLI installed and authenticated:
    gcloud auth login
    gcloud auth application-default login

Step 2: Configure Your Project

  1. Copy the example configuration file:
    cp terraform.tfvars.example terraform.tfvars
  2. Edit terraform.tfvars and set your project_id.

Step 3: Deploy the Infrastructure

Deploy the GCP resources using a single command:

just deploy

This will:

  • Enable the necessary APIs (Docs, Drive, Sheets) for your project
  • Create a service account for document access
  • Generate service account credentials locally

Step 4: Get the Service Account Email

Get the service account email that clients should share documents with:

terraform output service_account_email

Step 5: Share Documents (For Clients)

Clients should share their Google Docs, Sheets, or Drive folders with the service account email:

  1. Open the document/folder in Google Drive
  2. Click "Share"
  3. Add the service account email address
  4. Set permissions to "Viewer" or "Editor" as needed
  5. Click "Send"

Step 6: Test the Integration

  1. Install Python Dependencies:

    pip install -r requirements.txt
  2. Set the Document ID (Optional): If you want to test with a specific document, export its ID as an environment variable:

    export GOOGLE_DOC_ID="your-google-document-id"
  3. Run the Test Script:

    just test
    • This will test access to shared documents using the service account credentials.
    • The script will show any documents shared with the service account.
    • The content of the document will be converted to Markdown, preserving headings, bold, italics, and lists.

✅ Example of a Successful Test Run

Important Notes:

  • Share Documents First: Before running the test, ensure the Google Document you want to access has been shared with the service account email (terraform output service_account_email). Otherwise, you will encounter a permission error.
  • Unsupported File Types: The script can identify non-native Google Docs (like .docx files) but cannot read their content directly with the Google Docs API. The test will show a warning for these files.
  • Formatting: The script now converts the document's structure (headings, lists, bold, italics) into Markdown for a more readable output.

Here is an example of a successful run where the GOOGLE_DOC_ID environment variable was set to a native Google Doc that had been shared with the service account:

$ just test
🐍 Virtual environment already exists.
📦 Installing Python dependencies with uv...
Audited 3 packages in 3ms
🧪 Running integration test...
🔍 Testing Google Workspace API access with service account...

1. Testing Google Drive access:
✅ Service account credentials loaded successfully.
📁 Found 4 shared files:
   • FAQs (application/vnd.google-apps.document)
   • FAQs.docx (application/vnd.openxmlformats-officedocument.wordprocessingml.document)
   • EXP (application/vnd.google-apps.document)
   • Documento sem título (application/vnd.google-apps.document)

2. Testing Google Docs access:
✅ Service account credentials loaded successfully.
🔍 Checking file type for Document ID: 1ViLz8iOIgeuLKlqqxaK8bt1WqwhjCJ76CDS8iUQ1qQo...
✅ 'FAQs' is a native Google Doc. Proceeding to read content...
✅ Successfully accessed document: FAQs
📄 Document ID: 1ViLz8iOIgeuLKlqqxaK8bt1WqwhjCJ76CDS8iUQ1qQo
📝 Document has 147 content elements

📖 Full document content (Markdown format):
# 🌿 FAQs – HOSPEDAGEM
## 🧭 Intenção do Espaço: O que posso viver, sentir e transformar ao me hospedar na Casa Örüm?

- **🌀 O que posso esperar da experiência de hospedagem na Casa Örüm?**
A Casa Örüm é mais do que um lugar para dormir — é um espaço de acolhimento, reconexão com a natureza e convivência consciente.
... (content redacted for brevity) ...

🗄️ Terraform State Management

This project defaults to using a local state file (terraform.tfstate), which is suitable for individual use. For team collaboration, it is highly recommended to use a remote backend like Google Cloud Storage.

🛠️ Available Commands

  • just setup: Sets up the environment and dependencies.
  • just deploy: Deploys the infrastructure.
  • just destroy: Destroys all created resources.
  • just plan: Shows a plan of changes.
  • just validate: Validates the Terraform code.
  • just fmt: Formats the Terraform code.
  • just outputs: Shows the Terraform outputs.
  • just clean: Removes temporary files.

📤 Outputs

  • service_account_email - Email to share documents with
  • credentials_file_path - Path to generated credentials file

🔐 Usage in Python

from google.oauth2 import service_account
from googleapiclient.discovery import build

# Load credentials
credentials = service_account.Credentials.from_service_account_file(
    './service-account-credentials.json',
    scopes=['https://www.googleapis.com/auth/documents.readonly']
)

# Build service
service = build('docs', 'v1', credentials=credentials)

# Access shared document
document = service.documents().get(documentId='your-doc-id').execute()

🛠️ Troubleshooting

Run just health for comprehensive diagnostics.

For document access issues:

  1. Verify the document is shared with the service account email
  2. Check that the service account has appropriate permissions
  3. Ensure the document ID is correct
  4. Review the test script output for specific error messages

About

An automated Terraform and Python template for accessing shared Google Workspace documents (Docs, Sheets, Drive) via a service account.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors