Managing Instance Access with SSH Keys

This guide shows you how to control access to a Linux instance by creating SSH keys and editing public SSH key metadata. If you simply need to connect to a Linux instance, see Connecting to Linux Instances. If you need to connect to a Windows instance, see Connecting to Windows Instances.

To connect to a Linux VM instance, you must have an SSH key. Compute Engine manages your SSH keys for you whenever you connect to an instance from the browser or connect to an instance with the gcloud command-line tool, creating and applying public SSH keys when necessary. However, in some situations, you might want to create and manage your own public SSH keys for your project members. If you connect to Linux instances using third party tools, you must manage the SSH keys yourself.

An SSH key consists of the following files:

  • A public SSH key file that is applied to instance-level metadata or project-wide metadata.
  • A private SSH key file that the user stores on their local devices.

Users can connect to an instance through third-party tools if their public SSH key is available to the instance through the metadata server and if they have the matching private SSH key. Any user who connects to an instance is automatically an administrator of the instance with permissions to run commands with sudo. SSH access to instances as the root user is disabled even if you specify an SSH key in project or instance metadata for root.

Before you begin

Permissions required for this task

To perform this task, you must have the following permissions.

  • compute.instances.setMetadata on the instance if setting metadata on the instance
  • compute.projects.setCommonInstanceMetadata on the project if setting project-wide metadata

Risks of manual key management

If you create and manage public SSH keys yourself through the GCP Console, the gcloud command-line tool, or the API, you must keep track of the used keys and delete the public SSH keys for users who should not have access. For example, if a team member leaves your project, remove their public SSH keys from metadata so they cannot continue to access your instances.

Additionally, specifying your gcloud tool or API calls incorrectly can potentially wipe out all of the public SSH keys in your project or on your instances, which disrupts connections for your project members.

If you are not sure that you want to manage your own keys, use Compute Engine tools to connect to your instances instead.

Overview

By creating and managing SSH keys, you can allow users to access a Linux instance through third-party tools.

An SSH key consists of the following files:

  • A public SSH key file that is applied to instance-level metadata or project-wide metadata.
  • A private SSH key file that the user stores on their local devices.

If a user presents their private SSH key, they can use a third-party tool to connect to any instance that is configured with the matching public SSH key file, even if they are not a member of your Cloud Platform project. Therefore, you can control which instances a user can access by changing the public SSH key metadata for one or more instances.

To edit public SSH key metadata:

  1. Decide which tool you will use to edit metadata:

  2. If you need to add users to a Linux instance, prepare their public SSH keys with the following processes:

  3. Edit public SSH key metadata to add or remove users from a Linux instance.

  4. Connect to your Linux instance through a third-party tool to ensure that each public SSH key is added or removed correctly. A user can only connect to an instance if their public SSH key is available to the instance through the metadata server and if they have the matching private SSH key.

Creating a new SSH key

If you do not have an existing private SSH key file and a matching public SSH key file that you can use, generate a new SSH key. If you want to use an existing SSH key, locate the public SSH key file.

Linux and macOS

On Linux or macOS workstations, you can generate a key with the ssh-keygen tool.

  1. Open a terminal on your workstation and use the ssh-keygen command to generate a new key. Specify the -C flag to add a comment with your username.

    ssh-keygen -t rsa -f ~/.ssh/[KEY_FILENAME] -C [USERNAME]
    

    where:

    • [KEY_FILENAME] is the name that you want to use for your SSH key files. For example, a filename of my-ssh-key generates a private key file named my-ssh-key and a public key file named my-ssh-key.pub.
    • [USERNAME] is the user for whom you will apply this SSH key.

    This command generates a private SSH key file and a matching public SSH key with the following structure:

    ssh-rsa [KEY_VALUE] [USERNAME]
    

    where:

    • [KEY_VALUE] is the key value that you generated.
    • [USERNAME] is the user that this key applies to.
  2. Restrict access to your private key so that only you can read it and nobody can write to it.

    chmod 400 ~/.ssh/[KEY_FILENAME]
    

    where [KEY_FILENAME] is the name that you used for your SSH key files.

Repeat this process for every user for who needs a new key. Then, locate the public SSH keys that you made as well as any existing public SSH keys that you want to add to a project or instance.

Windows

Windows does not have a built-in tool for generating SSH keys, so you must use a third-party tool to generate SSH keys if you are on a Windows workstation. Here, we describe how to generate SSH keys with the PuTTYgen tool.

  1. Download puttygen.exe.

  2. Run PuTTYgen. For this example, simply run the puttygen.exe file that you downloaded. A window opens where you can configure your key-generation settings.

  3. Click Generate and follow the on-screen instructions to generate a new key. For most cases, the default parameters are fine, but you must generate keys with at least 2048 bits. When you are done generating the key, the tool displays your public key value.

  4. In the Key comment section, replace the existing text with the username of the user for whom you will apply the key.

  5. Optionally, you can enter a Key passphrase to protect your key.

  6. Click Save private key to write your private key to a file with a .ppk extension.

  7. Click Save public key to write your public key to a file for later use. Keep the PuTTYgen window open for now.

    The correctly formatted public key is available at the top of the PuTTYgen screen:

    Screenshot of PuTTYgen public key

    This public key has the following structure:

    ssh-rsa [KEY_VALUE] [USERNAME]
    

    where:

    • [KEY_VALUE] is the key value that you generated.
    • [USERNAME] is the user that this key applies to.

Repeat this process for every user that you need to create a key for. Then, if you have other public SSH keys for users that you want to add to a project or instance, you should locate their public SSH keys now. Otherwise, format the public SSH keys that you created.

Locating an SSH key

There are multiple reasons why you might need to locate an SSH key. For example, if you want to add a user's public SSH key to a project or instance, you will need access to the public key file for their key. Alternatively, you might need to locate your private SSH key file in order to connect to a Linux instance.

When an SSH key is created, it is saved to a default location. The default locations and names of your public and private SSH key files depend on the tools that were used to create that key.

Linux and macOS

If you created a key on a Linux or macOS workstation by using the ssh-keygen tool, your key was saved to the following locations:

  • Public key file: ~/.ssh/[KEY_FILENAME].pub
  • Private key file: ~/.ssh/[KEY_FILENAME]

where [KEY_FILENAME] is the filename of the SSH key, which was set when the key was created.

If you need to add or remove the public SSH key from project or instance metadata, format the public SSH key file.

Windows

If you created a key on a Windows workstation by using the PuTTYgen tool, your public key file and private key file were saved to the locations that you designated in the following formats:

  • Public key: [PUBLIC_KEY_FILENAME]
  • Private key: [PRIVATE_KEY_FILENAME].ppk

where [PUBLIC_KEY_FILENAME] and [PRIVATE_KEY_FILENAME] are the filenames of public and private SSH keys, which were set when the key was first saved.

A default, public SSH key made with PuTTYgen should have the following format:

ssh-rsa [KEY_VALUE] [USERNAME]

where:

  • [KEY_VALUE] is the public SSH key value.
  • [USERNAME] is the user on the instance for whom you applied the key.

To view your PuTTYgen public SSH key with the correct formatting:

  1. Run PuTTYgen. If you do not have PuTTYgen, download and run puttygen.exe.

  2. Click Load to select and open your public SSH key file.

  3. After the public key file loads, the properly formatted public SSH key value is available at the top of the PuTTYgen screen:

    Screenshot of PuTTYgen public key

If you need to add or remove the public SSH key from project or instance metadata, format the public SSH key file.

gcloud

If you have already connected to an instance through the gcloud tool, your keys are already generated and applied to your project or instance. The key files are available in the following locations:

  • Linux and macOS
    • Public key: $HOME/.ssh/google_compute_engine.pub
    • Private key: $HOME/.ssh/google_compute_engine
  • Windows:
    • Public key: C:\Users\[USERNAME]\.ssh\google_compute_engine.pub
    • Private key: C:\Users\[USERNAME]\.ssh\google_compute_engine

where [USERNAME] is your username on your local workstation.

To see where your public SSH keys were applied, look for the public key in your project metadata and instance metadata. If you need to add or remove the public SSH key from project or instance metadata, first format the public SSH key file.

Formatting your public SSH key files

Before you can upload your public SSH keys to your project or instance metadata, you must check the format of each public SSH key file that you plan to add.

Depending on which tool you will use to edit metadata, format your keys to work with the GCP Console, the gcloud command-line tool, or API methods. Optionally, you can also change your public SSH keys to add, edit, or remove an expiration time.

Console

To check the format of a public SSH key:

  1. Locate and open the public SSH key file.

  2. Check the format of the public SSH key file.

    • If a public SSH key has an expiration time, then it must have the following format:

      ssh-rsa [KEY_VALUE] google-ssh {"userName":"[USERNAME]","expireOn":"[EXPIRE_TIME]"}

      where:

      • [KEY_VALUE] is the public SSH key value.
      • [USERNAME] is the user for this SSH key, which was specified when the key was created.
      • [EXPIRE_TIME] is a value in RFC3339 format. For example: 2018-12-04T20:12:00+0000.
    • Otherwise, the public SSH key must have the following format:

      ssh-rsa [KEY_VALUE] [USERNAME]

      where:

      • [KEY_VALUE] is the public SSH key value.
      • [USERNAME] is the user for this SSH key, which was specified when the key was created.
  3. If your key does not match one of the above formats or if you want to add, edit, or remove an expiration time, then follow the instructions below to format your public SSH key. Otherwise, leave the file open and add the public SSH key to project or instance metadata.

To format a public SSH key for the console:

  1. Make a copy of your public key file. Use the copy with Compute Engine and keep the original file to use with your other SSH configurations.

  2. Open the copy of your public key file.

  3. Modify the public key file so that it has the following format:

    ssh-rsa [KEY_VALUE] [USERNAME]

    where:

    • [KEY_VALUE] is the public SSH key value.
    • [USERNAME] is the user for this SSH key, which was specified when the key was created.

    Alternatively, if you want the public SSH key to have an expiration time, then modify the file to match the following format:

    ssh-rsa [KEY_VALUE] google-ssh {"userName":"[USERNAME]","expireOn":"[EXPIRE_TIME]"}

    where:

    • [KEY_VALUE] is the public SSH key value.
    • [USERNAME] is the user for this SSH key, which was specified when the key was created.
    • [EXPIRE_TIME] is a value in RFC3339 format. For example: 2018-12-04T20:12:00+0000.
  4. Save the changes that you have made, and leave the file open.

You are now ready to add the public SSH key to project or instance metadata.

gcloud or API

To check the format of a public SSH key:

  1. Locate and open the public SSH key file.

  2. Check the format of the public SSH key file.

    • If a public SSH key has an expiration time, then it must have the following format:

      [USERNAME]:ssh-rsa [KEY_VALUE] google-ssh {"userName":"[USERNAME]","expireOn":"[EXPIRE_TIME]"}

      where:

      • [USERNAME] is the user for this SSH key, which was specified when the key was created.
      • [KEY_VALUE] is the public SSH key value.
      • [EXPIRE_TIME] is a value in RFC3339 format. For example: 2018-12-04T20:12:00+0000.
    • Otherwise, the public SSH key must have the following format:

      [USERNAME]:ssh-rsa [KEY_VALUE] [USERNAME]

      where:

      • [USERNAME] is the user for this SSH key, which was specified when the key was created.
      • [KEY_VALUE] is the public SSH key value.
  3. If your key does not match one of the above formats or if you want to add, edit, or remove an expiration time, then follow the instructions below to format your public SSH key. Otherwise, leave the file open and add the public SSH key to project or instance metadata.

To format a public SSH key for the gcloud tool or the API:

  1. Make a copy of your public key file. Use the copy with Compute Engine and keep the original file to use with your other SSH configurations.

  2. Open the copy of your public key file. By default, this file should have the following format:

    ssh-rsa [KEY_VALUE] [USERNAME]

    where:

    • [KEY_VALUE] is the public SSH key value.
    • [USERNAME] is the user for this SSH key, which was specified when the key was created.
  3. Copy the username, which is found at the end of the file, and paste it to the beginning of the file followed by a colon. This public SSH key file should now have the following format:

    [USERNAME]:ssh-rsa [KEY_VALUE] [USERNAME]

    where:

    • [USERNAME] is the user for this SSH key, which was specified when the key was created.
    • [KEY_VALUE] is the public SSH key value.
  4. Optionally, you can set the expiration time for the key by deleting the second [USERNAME] and appending google-ssh to the end of the key file followed by the userName and expireOn fields in JSON.

    [USERNAME]:ssh-rsa [KEY_VALUE] google-ssh {"userName":"[USERNAME]","expireOn":"[EXPIRE_TIME]"}

    where:

    • [USERNAME] is the user for this SSH key, which was specified when the key was created.
    • [KEY_VALUE] is the public SSH key value.
    • [EXPIRE_TIME] is a value in RFC3339 format. For example: 2018-12-04T20:12:00+0000
  5. Save the changes that you have made, and leave the file open.

You are now ready to add the public SSH key to project or instance metadata.

Editing public SSH key metadata

User access to a Linux instance through third-party tools is determined by which public SSH keys are available to the instance. You can control the public SSH keys that are available to a Linux instance by editing metadata, which is where your public SSH keys and related information are stored. There are three types of metadata for your public SSH keys:

  • Project-wide public SSH keys: Use this metadata to give users general access: the ability to connect to most instances in your project.
  • Allow or Block project-wide public SSH keys: Use this metadata value to block or allow project-wide public SSH keys on a specific instance. By default, an instance accepts all project-wide public SSH keys. Block project-wide public SSH keys if you want to restrict the instance to only users with instance-level public SSH keys.
  • Instance-level public SSH keys: Use this metadata to give users special access: the ability to connect to a specific instance in your project, even if it blocks project-wide public SSH keys.

Adding or removing project-wide public SSH keys

Use project-wide public SSH keys to give users general access to a Linux instance. Project-wide public SSH keys give users access to all of the Linux instances in a project that allow project-wide public SSH keys. If an instance blocks project-wide public SSH keys, a user cannot use their project-wide public SSH key to connect to the instance unless the same public SSH key is also added to instance metadata.

Console

To add or remove project-wide public SSH keys from the GCP Console:

  1. In the Google Cloud Platform Console, go to the metadata page for your project.

    Go to the Metadata page

  2. Under SSH Keys, click Edit.

  3. Modify the project-wide public SSH keys:

    • To add a public SSH key, click Add item at the bottom of the page. This will produce a text box. Copy the contents of your public SSH key file and paste them in to the text box. Repeat this process for each public SSH key that you want to add.
    • To remove a public SSH key, click the removal button next to it:

      Screenshot of PuTTYgen public key

      Repeat this process for each public SSH key that you want to remove.

  4. When you are done, click Save at the bottom of the page.

gcloud

To add or remove project-wide public SSH keys with the gcloud tool:

  1. If your project already has project-wide public SSH keys, obtain those public SSH keys from metadata:

    1. Obtain the existing metadata for the project:

      gcloud compute project-info describe

    2. From the output, find the ssh-keys metadata value:

      ...
      metadata:
        fingerprint: QCofVTHlggs=
        items:
        - key: ssh-keys
          value: |-
            [USERNAME_1]:ssh-rsa [EXISTING_KEY_VALUE_1] [USERNAME_1]
            [USERNAME_2]:ssh-rsa [EXISTING_KEY_VALUE_2] [USERNAME_2]
      ...

      where:

      • [USERNAME_1] and [USERNAME_2] are the usernames for your existing keys.
      • [EXISTING_KEY_VALUE_1] and [EXISTING_KEY_VALUE_2] are public key values that are already applied to your project.
    3. Copy the public SSH keys.

  2. Create and open a new text file on your local workstation.

  3. In the file, create a list of all of the public SSH keys that you want to add or keep in project metadata. If you have existing project-wide keys, any keys that you do not include in your list will be removed.

    For example, the sample list below will remove the key for [USERNAME_1] because their SSH key has been omitted. It will also keep the SSH key for [USERNAME_2] and add the SSH key for [USERNAME_3] because their SSH keys are included in the list.

    [USERNAME_2]:ssh-rsa [EXISTING_KEY_VALUE_2] [USERNAME_2]
    [USERNAME_3]:ssh-rsa [NEW_KEY_VALUE] [USERNAME_3]
    

    where:

    • [USERNAME_1],[USERNAME_2], and [USERNAME_3] are the usernames of the public SSH keys.
    • [EXISTING_KEY_VALUE_1] is a public key value for an SSH key that you want to remove.
    • [EXISTING_KEY_VALUE_2] is a public key value for an SSH key that you want to keep.
    • [NEW_KEY_VALUE] is a public key value for an SSH key that you want to add.
  4. Save and close the file.

  5. In the command prompt, use the compute project-info add-metadata command to set the project-wide ssh-keys value. Include the --metadata-from-file flag and specify the path to your list file.

    gcloud compute project-info add-metadata --metadata-from-file ssh-keys=[LIST_PATH]
    

    where [LIST_PATH] is the path to your list of public SSH keys.

API

Add or remove project-wide public keys using the instances.setMetadata method.

  1. Use the projects.get method to obtain the metadata fingerprint value. If you want to keep your existing project-wide keys, obtain the existing ssh-keys values.

    GET https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]
    
    ...
    "fingerprint": "[FINGERPRINT]",
    "items": [
     {
      "key": "ssh-keys",
      "value": "[USERNAME_1]:ssh-rsa [EXISTING_KEY_VALUE_1] [USERNAME_1]\n[USERNAME_2]:ssh-rsa [EXISTING_KEY_VALUE_2] [USERNAME_2]"
     }
    ]
    ...

    where:

    • [PROJECT_ID] is your unique project ID.
    • [FINGERPRINT] is the unique ID for this specific metadata configuration, which prevents you from accidentally overwriting concurrent changes.
    • [USERNAME_1] and [USERNAME_2] are the usernames for your existing keys.
    • [EXISTING_KEY_VALUE_1] and [EXISTING_KEY_VALUE_2] are public key values that are already applied to your project.
  2. Create a list of all of the public SSH keys that you want to add or keep in project-wide metadata. If you currently have public SSH keys in project-wide metadata, any keys that you do not include in your list will be removed.

    For this example, the file contains a new [KEY_VALUE] followed by one of the existing key values that you obtained in the previous step. The [EXISTING_KEY_VALUE_1] is left out, so it will be removed from the instance in the next step. Use \n characters to separate each key value.

    [USERNAME_3]:ssh-rsa [NEW_KEY_VALUE] [USERNAME_3]\n[USERNAME_2]:ssh-rsa [EXISTING_KEY_VALUE_2] [USERNAME_2]
    

    where:

    • [USERNAME_1], [USERNAME_2], and [USERNAME_3] are the username for your keys.
    • [EXISTING_KEY_VALUE_1] is a public key value for an SSH key that you want to remove.
    • [EXISTING_KEY_VALUE_2] is a public key value for an SSH key that you want to keep.
    • [NEW_KEY_VALUE] is a public key value for an SSH key that you want to add.
  3. Use the projects.setcommoninstancemetadata method to set the project-wide ssh-keys value. Include the fingerprint value, which ensures that you do not overwrite any concurrent changes to this metadata value.

    POST https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/setCommonInstanceMetadata
    
    {
     "items": [
      {
       "key": "ssh-keys",
       "value": "[USERNAME_3]:ssh-rsa [NEW_KEY_VALUE] [USERNAME_3]\n[USERNAME_2]:ssh-rsa [EXISTING_KEY_VALUE_2] [USERNAME_2]"
      }
     ]
     "fingerprint": "[FINGERPRINT]"
    }
    

    where:

    • [PROJECT_ID] is your unique project ID.
    • [USERNAME_1], [USERNAME_2], and [USERNAME_3] are the usernames for your keys.
    • [EXISTING_KEY_VALUE_1] is a public key value for an SSH key that you want to remove.
    • [EXISTING_KEY_VALUE_2] is a public key value for an SSH key that you want to keep.
    • [NEW_KEY_VALUE] is a public key value for an SSH key that you want to add.
    • [FINGERPRINT] is the fingerprint that you obtained earlier with the projects.get method.

When you have finished, test your changes by trying to connect to your Linux instance through third-party tools.

If you encounter issues, check the metadata of the instance that you are trying to connect to. If instance-level metadata is set to block project-wide SSH keys or has a deprecated instance-only sshKeys value, the instance will ignore all project-wide SSH keys. To apply project-wide keys to an instance, make sure the instance allows project-wide public SSH keys and, if present, remove the deprecated instance-only sshKeys value from instance metadata.

Allowing or blocking project-wide public SSH keys from a Linux instance

If you need your instance to ignore project-wide public SSH keys and use only the instance-level keys, you can block project-wide public SSH keys from the instance. This will only allow users whose public SSH key is stored in instance-level metadata to access the instance. If you want your instance to use both project-wide and instance-level public SSH keys, set the instance metadata to allow project-wide SSH keys. This will allow any user whose public SSH key is stored in project-wide or instance-level metadata to access the instance.

Console

To allow or block project-wide public SSH keys from the GCP Console:

  1. In the Google Cloud Platform Console, go to the VM instances page.

    Go to the Instances page

  2. Click on the name of the instance that you want to modify.

  3. Click Edit in the toolbar.

  4. Under SSH Keys, go to the Block project-wide SSH keys checkbox.

    • To block users with project-wide SSH keys from connecting to this instance, select Block project-wide SSH keys.
    • To allow users with project-wide SSH keys to connect to this instance, deselect Block project-wide SSH keys.
  5. When you are done, click Save at the bottom of the page.

gcloud

To allow or block project-wide public SSH keys from a Linux instance, add the block-project-ssh-keys metadata value to your instance:

  • To block project-wide public SSH keys, set the metadata value to TRUE:

    gcloud compute instances add-metadata [INSTANCE_NAME] --metadata block-project-ssh-keys=TRUE
    

    where [INSTANCE_NAME] is the name of the instance that you want to block project-wide public SSH keys.

  • To allow project-wide public SSH keys, set the metadata value to FALSE:

    gcloud compute instances add-metadata [INSTANCE_NAME] --metadata block-project-ssh-keys=FALSE
    

    where [INSTANCE_NAME] is the name of the instance that you want to allow project-wide public SSH keys.

API

To block or allow project-wide public SSH keys from a Linux instance:

  • To block project-wide public SSH keys, add the block-project-ssh-keys metadata value to your instance and set it to TRUE. This metadata value blocks all project-wide keys from functioning on this instance so that only instance-level keys will work.

     POST https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/zones/[ZONE]/instances/[INSTANCE_NAME]/setMetadata
    
     {
      "items": [
       {
        "key": "block-project-ssh-keys",
        "value": TRUE
       }
      ]
      "fingerprint": "[FINGERPRINT]"
     }
    

    where:

    • [PROJECT_ID] is your unique project ID.
    • [ZONE] is the zone where your instance is located.
    • [INSTANCE_NAME] is the instance where you want to block project-wide keys.
    • [FINGERPRINT] is the unique ID for this specific metadata configuration, which prevents you from accidentally overwriting concurrent changes.
  • To allow project-wide public SSH keys, add the block-project-ssh-keys metadata value to your instance and set it to FALSE. This metadata value allows all project-wide keys (as well as instance-level keys) to function on this instance.

     POST https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/zones/[ZONE]/instances/[INSTANCE_NAME]/setMetadata
    
     {
      "items": [
       {
        "key": "block-project-ssh-keys",
        "value": FALSE
       }
      ]
      "fingerprint": "[FINGERPRINT]"
     }
    

    where:

    • [PROJECT_ID] is your unique project ID.
    • [ZONE] is the zone where your instance is located.
    • [INSTANCE_NAME] is the instance where you want to allow project-wide keys.
    • [FINGERPRINT] is the unique ID for this specific metadata configuration, which prevents you from accidentally overwriting concurrent changes.

When you have finished, test your changes by trying to connect to your Linux instance through third-party tools.

Adding or removing instance-level public SSH keys

Instance-level public SSH keys give users access to a specific Linux instance. Users with instance-level public SSH keys can access a Linux instance even if it blocks project-wide public SSH keys.

Console

To add or remove instance-level public SSH keys from the GCP Console:

  1. In the Google Cloud Platform Console, go to the VM instances page.

    Go to the Instances page

  2. Click on the name of the instance that you want to modify.

  3. Click Edit in the toolbar.

  4. Under SSH Keys, click Show and edit. The section expands to show all of the instance-level public SSH keys.

  5. Modify the instance-level public SSH keys:

    • To add a public SSH key, click Add item. This will produce a text box. Copy the contents of your public SSH key file and paste them in to the text box. Repeat this process for each public SSH key that you want to add.
    • To remove a public SSH key, click the removal button next to it:

      Screenshot of PuTTYgen public key

      Repeat this process for each public SSH key that you want to remove.

  6. When you are done, click Save at the bottom of the page.

gcloud

To add or remove instance-level public SSH keys with the gcloud tool:

  1. If your instance already has instance-level public SSH keys, obtain those public SSH keys from metadata:

    1. Obtain the existing metadata for the instance:

      gcloud compute instances describe [INSTANCE_NAME]

      where [INSTANCE_NAME] is the name of the instance where you need to add or remove public SSH keys.

    2. From the output, find the ssh-keys metadata value:

      ...
      metadata:
        fingerprint: QCofVTHlggs=
        items:
        ...
        - key: ssh-keys
          value: |-
            [USERNAME_1]:ssh-rsa [EXISTING_KEY_VALUE_1] [USERNAME_1]
            [USERNAME_2]:ssh-rsa [EXISTING_KEY_VALUE_2] [USERNAME_2]
      ...

      where:

      • [USERNAME_1] and [USERNAME_2] are the usernames for your existing keys.
      • [EXISTING_KEY_VALUE_1] and [EXISTING_KEY_VALUE_2] are public key values that are already applied to your instance.
    3. Copy the public SSH keys under the ssh-keys metadata value.

  2. Create and open a new text file on your local workstation.

  3. In the file, create a list of all of the public SSH keys that you want to add or keep in instance-level metadata. If you currently have public SSH keys in instance-level metadata, any keys that you do not include in your list will be removed.

    For example, the sample list below will remove the key for [USERNAME_1] because their SSH key has been omitted. It will also keep the SSH key for [USERNAME_2] and add the SSH key for [USERNAME_3] because their SSH keys are included in the list.

    [USERNAME_2]:ssh-rsa [EXISTING_KEY_VALUE_2] [USERNAME_2]
    [USERNAME_3]:ssh-rsa [NEW_KEY_VALUE] [USERNAME_3]
    

    where:

    • [USERNAME_1],[USERNAME_2], and [USERNAME_3] are the usernames of the public SSH keys.
    • [EXISTING_KEY_VALUE_1] is a public key value for an SSH key that you want to remove.
    • [EXISTING_KEY_VALUE_2] is a public key value for an SSH key that you want to keep.
    • [NEW_KEY_VALUE] is a public key value for an SSH key that you want to add.
  4. Save and close the file.

  5. In the command prompt, use the compute instances add-metadata command to set the instance-only ssh-key value. Include the --metadata-from-file flag and specify the path to the public key file list that you made.

    gcloud compute instances add-metadata [INSTANCE_NAME] --metadata-from-file ssh-keys=[LIST_PATH]
    

    where:

    • [INSTANCE_NAME] is the name of the instance where you want to apply the public SSH key file.
    • [LIST_PATH] is the path to your list of public SSH keys.

API

Add an instance-only ssh-keys value in metadata using the instances.setMetadata method.

  1. Use the instances.get method to obtain the metadata fingerprint value to use for the request. If you want to keep your existing instance-level keys, obtain the existing ssh-keys values.

    GET https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/zones/[ZONE]/instances/[INSTANCE_NAME]
    
    ...
    "fingerprint": "[FINGERPRINT]",
    "items": [
     {
      "key": "ssh-keys",
      "value": "[USERNAME_1]:ssh-rsa [EXISTING_KEY_VALUE_1] [USERNAME_1]\n[USERNAME_2]:ssh-rsa [EXISTING_KEY_VALUE_2] [USERNAME_2]"
     }
    ]
    ...

    where:

    • [PROJECT_ID] is your unique project ID.
    • [ZONE] is the zone where your instance is located.
    • [INSTANCE_NAME] is the instance where you want to edit instance-level public SSH keys.
    • [FINGERPRINT] is the unique ID for this specific metadata configuration, which prevents you from accidentally overwriting concurrent changes.
    • [USERNAME_1] and [USERNAME_2] are the usernames for your existing keys.
    • [EXISTING_KEY_VALUE_1] and [EXISTING_KEY_VALUE_2] are public key values that are already applied to your instance.
  2. Create a list of all of the public SSH keys that you want to add or keep in instance-level metadata. If you currently have public SSH keys in instance-level metadata, any keys that you do not include in your list will be removed.

    For this example, the file contains a new [KEY_VALUE] followed by one of the existing key values that you obtained in the previous step. The [EXISTING_KEY_VALUE_1] is left out, so it will be removed from the instance in the next step. Use \n characters to separate each key value.

    [USERNAME_3]:ssh-rsa [NEW_KEY_VALUE] [USERNAME_3]\n[USERNAME_2]:ssh-rsa [EXISTING_KEY_VALUE_2] [USERNAME_2]
    

    where:

    • [USERNAME_1], [USERNAME_2], and [USERNAME_3] are the usernames for your keys.
    • [EXISTING_KEY_VALUE_1] is a public key value for an SSH key that you want to remove.
    • [EXISTING_KEY_VALUE_2] is a public key value for an SSH key that you want to keep.
    • [NEW_KEY_VALUE] is a public key value for an SSH key that you want to add.
  3. Use the instances.setMetadata method to set the instance-only ssh-keys value. Include the fingerprint value, which ensures that you do not overwrite any concurrent changes to this metadata value.

    POST https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/zones/[ZONE]/instances/[INSTANCE_NAME]/setMetadata
    
    {
     "items": [
      {
       "key": "ssh-keys",
       "value": "[USERNAME_3]:ssh-rsa [NEW_KEY_VALUE] [USERNAME_3]\n[USERNAME_2]:ssh-rsa [EXISTING_KEY_VALUE_2] [USERNAME_2]"
      }
     ]
     "fingerprint": "[FINGERPRINT]"
    }
    

    where:

    • [PROJECT_ID] is your unique project ID.
    • [ZONE] is the zone where your instance is located.
    • [INSTANCE_NAME] is the instance where you want to edit instance-level public SSH keys.
    • [USERNAME_1], [USERNAME_2], and [USERNAME_3] are the usernames for your keys.
    • [EXISTING_KEY_VALUE_1] is a public key value for an SSH key that you want to remove.
    • [EXISTING_KEY_VALUE_2] is a public key value for an SSH key that you want to keep.
    • [NEW_KEY_VALUE] is a public key value for an SSH key that you want to add.
    • [FINGERPRINT] is the unique ID for this specific metadata configuration, which prevents you from accidentally overwriting concurrent changes.

When you have finished, test your changes by trying to connect to your Linux instance through third-party tools.

Managing SSH keys using the OS Login API

As an alternative to managing your public SSH keys in project or instance metadata, you can associate your public SSH keys with your user accounts. Compute Engine instances can obtain these public keys to use for authentication and authorization when you connect to an instance using SSH.

You can associate public keys with the following user account types:

You can use the public keys associated with your account to connect to Compute Engine instances only when you meet the following requirements:

  • Your user account must have one or more associated public SSH keys. These keys are generated for you when you connect to an instance using the browser or the gcloud command-line tool, but you can also manually add your own public keys if necessary.
  • You possess the private SSH keys that match the public SSH keys associated with your account.
  • Your project or organization grants your account one of the necessary OS Login roles. These roles determine if you have access to any of the instances in the project or organization, and also determine whether you have sudo privileges.
  • The instance that you want to connect to is configured to use OS Login.
  • You are connecting to an instance within your scope:
    • If you are an organization member, you can connect only to instances in projects that are part of your same organization. You cannot connect to instances in other organizations or to projects that are owned by consumer accounts.
    • If you are not an organization member, you are using a consumer account and can connect only to instances in projects of which you are a member.

To grant SSH access to users outside of your project or organization, you must manually add users and their public keys directly to your instances. Public SSH keys in instance or project metadata do not function on instances enabled for OS Login.

Associating your public SSH keys with your user accounts provides the following benefits:

  • Public keys are associated with user accounts rather than project or instance metadata values, which are easier to maintain and track.
  • Public keys are never stored on your instances, and are always obtained directly from your user account.
  • You authorize users for SSH access and sudo privileges through IAM roles rather than manually configuring instances or applying metadata values.
  • You can restrict your project members so that they can access your instances but are unable to add their own arbitrary keys to metadata, which allows you to more easily audit who has access to your instances.
  • You can revoke SSH access from individual accounts by revoking IAM roles rather than by manually removing public SSH keys from metadata and the instance.

After you enable OS Login on your instances, you can connect to your instances as normal. OS Login works when you connect through the browser or the gcloud command-line tool. Compute Engine creates and manages your SSH keys for you and stores your public keys as part of your user account.

Optionally, you can manually generate and manage your own SSH keys and associate the public keys with user accounts. Then, connect to instances using third-party tools and provide your private key.

Enabling OS Login on instances

Before you can manage your keys with OS Login, you must enable the feature by setting the enable-oslogin metadata value to TRUE in either project or instance metadata. You can apply this metadata value on your instances with one of the following methods:

For example, you might add the enable-oslogin metadata value to a single instance using the following command:

gcloud compute instances add-metadata [INSTANCE_NAME] \
  --metadata enable-oslogin=TRUE

In addition to the required metadata values, your instance must have the latest version of the Linux Guest Environment installed. The following public image families include the required packages:

  • CentOS image families:
    • centos-7
    • centos-6
  • Debian image families:
    • debian-9
    • debian-8
  • RHEL image families:
    • rhel-7
    • rhel-6
  • SLES image families:
    • sles-12
  • SLES for SAP image families:
    • sles-12-sp2-sap
    • sles-12-sp1-sap
  • Ubuntu image families:
    • ubuntu-1604-lts
    • ubuntu-1404-lts
    • ubuntu-1710
    • ubuntu-1704

If you have instances that run custom images that you imported, install the Linux Guest Environment on those instances to enable OS Login capability.

After you enable OS Login on the instances in your project, grant users permission to connect to those instances.

Configuring user access through OS Login

Instances enabled for OS Login accept connections only from user accounts that have the following roles in your project or organization:

  • The iam.serviceAccountUser role.
  • One of the OS Login roles:
    • The compute.osLogin role, which does not grant sudo permission
    • The compute.osAdminLogin role, which grants sudo permission

Grant an OS Login role to the project member that requires access to the instances. If you cannot grant this role to yourself or another project member, ask a project admin to grant the role for you. To revoke user access to instances managed using OS Login, remove the user roles. The user still has public SSH keys associated with their account, but those keys no longer function on instances managed using OS Login.

After you configure the necessary roles, connect to an instance from the browser or connect to an instance using the gcloud command-line tool. Both of these options automatically generate SSH keys and associate them with your user account.

Alternatively, if you create your own SSH keys and add those keys to your user account, you can connect to instances using third-party tools.

Adding SSH keys to your user account

You can use the gcloud command-line tool, or the OS Login API to add SSH keys to your own account. Alternatively, if you are a domain admin for an organization, you can use the Directory API, to add SSH keys to the user account in your organization.

gcloud

The gcloud beta compute os-login commands are available only on Google Cloud SDK version 176 and later.

Use the gcloud beta command-line tool to associate public SSH keys with an account.

gcloud beta compute os-login ssh-keys add \
    --key-file [KEY_FILE_PATH] \
    --ttl [EXPIRE_TIME]

where:

  • [KEY_FILE_PATH] is the path to the public SSH key on your local workstation.
  • [EXPIRE_TIME] is an optional flag to set an expiration time for the public SSH key. For example, you can specify 30m and the SSH key will expire after 30 minutes. Valid units for this flag are s for seconds, m for minutes, h for hours, or d for days. You can set the value to 0 to indicate no expiration time.

OS Login API

Use the OS Login API to associate public SSH keys with an account.

POST https://oslogin.googleapis.com/v1beta/users/[ACCOUNT_EMAIL]:importSshPublicKey

{
 "key": "[SSH_KEY]",
 "expirationTimeUsec": "[EXPIRATION_TIMESTAMP]"
}

where:

  • [ACCOUNT_EMAIL] is the email address that represents your managed user account.
  • [SSH_KEY] is the public key that you want to apply to the account.
  • [EXPIRATION_TIMESTAMP] is the expiration time for the key in microseconds since epoch.

Directory API

If you are a domain admin for an organization, you can use the Directory API, to add SSH keys to the account of another user in your organization. For example, create a PUT request to update a user profile with one or more SSH sshPublicKeys entries.

PUT https://www.googleapis.com/admin/directory/v1/users/[USER_ID_KEY]

{
 "sshPublicKeys": [
  {
   "key": "[SSH_KEY]",
   "expirationTimeUsec": "[EXPIRATION_TIMESTAMP]"
  },
  {
   "key": "[SSH_KEY]",
   "expirationTimeUsec": "[EXPIRATION_TIMESTAMP]"
  }
 ]
}

where:

  • [USER_ID_KEY] is an immutable ID for the user.
  • [SSH_KEY] is a public key that you want to apply to the account.
  • [EXPIRATION_TIMESTAMP] is the expiration time for a key in microseconds since epoch.

To remove all keys from an account, specify "sshPublicKeys": null as the body:

PUT https://www.googleapis.com/admin/directory/v1/users/[USER_ID_KEY]

{
  "sshPublicKeys": null
}

where [USER_ID_KEY] is an immutable ID for the user.

After you add your keys to your account, you can connect to instances using third-party tools and the username associated with your account. Your organization admin can change this username. You can find the username for your account by running the gcloud beta compute os-login describe-profile command:

gcloud beta compute os-login describe-profile

name: [ACCOUNT_EMAIL]
posixAccounts:
⋮
  username: [USER_NAME]
⋮

where:

  • [ACCOUNT_EMAIL] is the email address that represents your managed user account.
  • [USER_NAME] is the username for establishing SSH connections. By default, this is generated from your [ACCOUNT_EMAIL].

Disabling OS Login

Disabling OS Login restores SSH keys that you have configured in project or instance metadata.

To disable OS Login for a specific instance in your project, you can set enable-oslogin=FALSE in instance metadata. This metadata value overrides the project-wide enable-oslogin=TRUE metadata value.

To disable OS Login for all of the instances in your project, set enable-oslogin=FALSE in project-wide metadata. This project-wide setting does not override instance-level metadata, so any instances with enable-oslogin=TRUE set in their metadata continue to use OS Login for authentication and authorization.

What's next

Send feedback about...

Compute Engine Documentation