File size: 2,366 Bytes
7b7bdab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env python3
"""
Google Cloud Authentication Helper
This script handles Google Cloud authentication using environment variables.
"""

import os
import json
import tempfile
from google.auth import default
from google.cloud import storage


def setup_gcp_credentials():
    """Setup Google Cloud credentials from environment variables."""
    
    # Get credentials content from environment variable
    creds_content = os.getenv('GOOGLE_APPLICATION_CREDENTIALS_CONTENT')
    
    if creds_content:
        # Parse JSON credentials
        try:
            creds_dict = json.loads(creds_content)
            
            # Create temporary credentials file
            with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
                json.dump(creds_dict, f)
                temp_creds_path = f.name
            
            # Set environment variable for Google Cloud SDK
            os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = temp_creds_path
            
            print(f"βœ… Google Cloud credentials configured successfully")
            print(f"πŸ“ Project ID: {creds_dict.get('project_id', 'N/A')}")
            print(f"πŸ“§ Client Email: {creds_dict.get('client_email', 'N/A')}")
            
            return temp_creds_path
            
        except json.JSONDecodeError as e:
            print(f"❌ Error parsing Google Cloud credentials: {e}")
            return None
    else:
        print("⚠️  No Google Cloud credentials found in environment variables")
        return None


def test_gcp_connection():
    """Test Google Cloud connection."""
    try:
        # Test authentication
        credentials, project = default()
        print(f"βœ… Google Cloud authentication successful")
        print(f"πŸ“ Project: {project}")
        
        # Test Cloud Storage access
        client = storage.Client()
        buckets = list(client.list_buckets())
        print(f"πŸ“¦ Found {len(buckets)} storage buckets")
        
        return True
    except Exception as e:
        print(f"❌ Google Cloud connection test failed: {e}")
        return False


if __name__ == "__main__":
    # Setup credentials
    creds_path = setup_gcp_credentials()
    
    if creds_path:
        # Test connection
        test_gcp_connection()
    else:
        print("❌ Failed to setup Google Cloud credentials")