Instances should not be configured to allow project-wide SSH keys. To support the principle of least privilege and prevent potential privilege escalation, instances should not be given access to project-wide SSH keys.
Once you have generated the SSH key pair, you need to add the public key to the instance’s metadata. You can use the google-auth and google-api-python-client libraries in Python to interact with GCP APIs.
Copy
Ask AI
from google.oauth2 import service_accountfrom googleapiclient.discovery import buildcredentials = service_account.Credentials.from_service_account_file('path/to/credentials.json')compute = build('compute', 'v1', credentials=credentials)project_id = 'your-project-id'zone = 'instance-zone'instance_name = 'instance-name'instance = compute.instances().get(project=project_id, zone=zone, instance=instance_name).execute()metadata = instance['metadata']items = metadata.get('items', [])# Remove any existing SSH keysitems = [item for item in items if item['key'] != 'ssh-keys']# Add the new SSH keyssh_key = 'ssh-rsa <public-key> instance-specific-key'items.append({'key': 'ssh-keys', 'value': ssh_key})# Update the instance metadatametadata['items'] = itemscompute.instances().setMetadata(project=project_id, zone=zone, instance=instance_name, body={'metadata': metadata}).execute()
Finally, you can test the new SSH key by connecting to the instance using the private key.