This page describes how to create a regional secret. A secret contains one or more secret versions, along
with metadata such as labels and annotations. The actual contents of a secret are stored
in a [secret version](https://docs.cloud.google.com/secret-manager/regional-secrets/add-secret-version-rs.md.txt).

## Before you begin

1. [Enable the Secret Manager API](https://docs.cloud.google.com/secret-manager/regional-secrets/config-sm-rs.md.txt).

2. [Configure Secret Manager to use a regional endpoint](https://docs.cloud.google.com/secret-manager/regional-secrets/config-sm-rs.md.txt#identify_endpoints).

3. Set up authentication.


   Select the tab for how you plan to use the samples on this page:

   ### Console


   When you use the Google Cloud console to access Google Cloud services and
   APIs, you don't need to set up authentication.

   ### gcloud

   In the Google Cloud console, activate Cloud Shell.

   [Activate Cloud Shell](https://console.cloud.google.com/?cloudshell=true)


   At the bottom of the Google Cloud console, a
   [Cloud Shell](https://docs.cloud.google.com/shell/docs/how-cloud-shell-works.md.txt)
   session starts and displays a command-line prompt. Cloud Shell is a shell environment
   with the Google Cloud CLI
   already installed and with values already set for
   your current project. It can take a few seconds for the session to initialize.

   ### REST


   To use the REST API samples on this page in a local development environment, you use the
   credentials you provide to the gcloud CLI.
   1. [Install](https://docs.cloud.google.com/sdk/docs/install) the Google Cloud CLI.
   2. If you're using an external identity provider (IdP), you must first [sign in to the gcloud CLI with your federated identity](https://docs.cloud.google.com/iam/docs/workforce-log-in-gcloud.md.txt).


   For more information, see
   [Authenticate for using REST](https://docs.cloud.google.com/docs/authentication/rest.md.txt)
   in the Google Cloud authentication documentation.

   <br />

## Required roles


To get the permissions that
you need to create a secret,

ask your administrator to grant you the
[Secret Manager Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/secretmanager.md.txt#secretmanager.admin) (`roles/secretmanager.admin`) IAM role on the project, folder, or organization.


For more information about granting roles, see [Manage access to projects, folders, and organizations](https://docs.cloud.google.com/iam/docs/granting-changing-revoking-access.md.txt).


You might also be able to get
the required permissions through [custom
roles](https://docs.cloud.google.com/iam/docs/creating-custom-roles) or other [predefined
roles](https://docs.cloud.google.com/iam/docs/roles-overview#predefined).

## Create a regional secret

You can create secrets using the Google Cloud console, the Google Cloud CLI, the Secret Manager API, or the
Secret Manager client libraries.

### Console

1. In the Google Cloud console, go to the **Secret Manager** page.


   [Go to Secret Manager](https://console.cloud.google.com/security/secret-manager)
2. On the **Secret Manager** page, click the **Regional secrets** tab, and then
   click **Create regional secret**.

3. On the **Create regional secret** page, enter a name for the secret in the **Name** field.
   A secret name can contain uppercase and lowercase letters, numerals, hyphens, and underscores. The maximum allowed length for a name is 255 characters.

4. (Optional) ([Preview](https://cloud.google.com/products/#product-launch-stages)) Select the **Secret type**. You can use secret types to
   categorize your secrets.

   The available regional secret types are:
   - **Cloud SQL DB credentials**: Used for the managed rotation feature for Cloud SQL.
   - **Other DB credentials**: For secrets that contain database credentials.
   - **Access key**: For secrets that contain an access key.
   - **Certificate**: For secrets that contain a certificate.
   - **Other**: For secrets that do not fit into other categories.

   > [!NOTE]
   > **Note:** You can only select a secret type when you create a secret. You can't add or update the secret type of an existing secret.

5. Enter a value for the secret (for example, `abcd1234`). The secret value can be in any format
   but must not be larger than 64 KiB. You can also upload a text file that contain the secret value using
   the **Upload file** option. This action automatically creates the secret version.

6. Choose the location where you want to store your regional secret.
   Select one of the following options:

   - **Region**: Stores the secret in a single region for minimal latency.
   - **Multi-region** : Replicates secrets across multiple locations for high availability. For more information, see [Available
     multi-regions](https://docs.cloud.google.com/secret-manager/docs/locations#location-mr).
7. Click **Create secret**.

### gcloud


Before using any of the command data below,
make the following replacements:

- <var translate="no">SECRET_ID</var>: the ID of the secret.
- <var translate="no">LOCATION</var>: the Google Cloud [location](https://docs.cloud.google.com/secret-manager/docs/locations.md.txt) of the secret.


Execute the

following

command:

#### Linux, macOS, or Cloud Shell

> [!NOTE]
> **Note:** Ensure you have initialized the Google Cloud CLI with authentication and a project by running either [gcloud init](https://docs.cloud.google.com/sdk/gcloud/reference/init); or [gcloud auth login](https://docs.cloud.google.com/sdk/gcloud/reference/auth/login.md.txt) and [gcloud config set project](https://docs.cloud.google.com/sdk/gcloud/reference/config/set.md.txt).

```bash
gcloud secrets create SECRET_ID \
    --location=LOCATION
```

#### Windows (PowerShell)

> [!NOTE]
> **Note:** Ensure you have initialized the Google Cloud CLI with authentication and a project by running either [gcloud init](https://docs.cloud.google.com/sdk/gcloud/reference/init); or [gcloud auth login](https://docs.cloud.google.com/sdk/gcloud/reference/auth/login.md.txt) and [gcloud config set project](https://docs.cloud.google.com/sdk/gcloud/reference/config/set.md.txt).

```bash
gcloud secrets create SECRET_ID `
    --location=LOCATION
```

#### Windows (cmd.exe)

> [!NOTE]
> **Note:** Ensure you have initialized the Google Cloud CLI with authentication and a project by running either [gcloud init](https://docs.cloud.google.com/sdk/gcloud/reference/init); or [gcloud auth login](https://docs.cloud.google.com/sdk/gcloud/reference/auth/login.md.txt) and [gcloud config set project](https://docs.cloud.google.com/sdk/gcloud/reference/config/set.md.txt).

```bash
gcloud secrets create SECRET_ID ^
    --location=LOCATION
```

### REST


Before using any of the request data,
make the following replacements:

- <var translate="no">LOCATION</var>: the Google Cloud [location](https://docs.cloud.google.com/secret-manager/docs/locations.md.txt) of the secret.
- <var translate="no">PROJECT_ID</var>: the Google Cloud project ID.
- <var translate="no">SECRET_ID</var>: the ID of the secret.


HTTP method and URL:

```
POST https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets?secretId=SECRET_ID
```


Request JSON body:

```
{}
```

To send your request, choose one of these options:

#### curl

> [!NOTE]
> **Note:** The following command assumes that you have logged in to the `gcloud` CLI with your user account by running [`gcloud init`](https://docs.cloud.google.com/sdk/gcloud/reference/init) or [`gcloud auth login`](https://docs.cloud.google.com/sdk/gcloud/reference/auth/login.md.txt) , or by using [Cloud Shell](https://docs.cloud.google.com/shell/docs.md.txt), which automatically logs you into the `gcloud` CLI . You can check the currently active account by running [`gcloud auth list`](https://docs.cloud.google.com/sdk/gcloud/reference/auth/list.md.txt).


Save the request body in a file named `request.json`,
and execute the following command:

```
curl -X POST \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     -d @request.json \
     "https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets?secretId=SECRET_ID"
```

#### PowerShell

> [!NOTE]
> **Note:** The following command assumes that you have logged in to the `gcloud` CLI with your user account by running [`gcloud init`](https://docs.cloud.google.com/sdk/gcloud/reference/init) or [`gcloud auth login`](https://docs.cloud.google.com/sdk/gcloud/reference/auth/login.md.txt) . You can check the currently active account by running [`gcloud auth list`](https://docs.cloud.google.com/sdk/gcloud/reference/auth/list.md.txt).


Save the request body in a file named `request.json`,
and execute the following command:

```
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets?secretId=SECRET_ID" | Select-Object -Expand Content
```

You should receive a JSON response similar to the following:

```
{
  "name": "projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID",
  "createTime": "2024-03-25T08:24:13.153705Z",
  "etag": "\"161477e6071da9\""
}
```

### Go

To run this code, first [set up a Go development environment](https://docs.cloud.google.com/go/docs/setup.md.txt) and
[install the Secret Manager Go SDK](https://docs.cloud.google.com/secret-manager/docs/reference/libraries.md.txt#client-libraries-install-go).
On Compute Engine or GKE, you must
[authenticate with the cloud-platform scope](https://docs.cloud.google.com/secret-manager/docs/accessing-the-api.md.txt#oauth-scopes).

```go
import (
	"context"
	"fmt"
	"io"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
	"google.golang.org/api/option"
)

// createSecret creates a new secret with the given name. A secret is a logical
// wrapper around a collection of secret versions. Secret versions hold the
// actual secret material.
func CreateRegionalSecret(w io.Writer, projectId, locationId, id string) error {
	// parent := "projects/my-project/locations/my-location"
	// id := "my-secret"

	// Create the client.
	ctx := context.Background()

	//Endpoint to send the request to regional server
	endpoint := fmt.Sprintf("secretmanager.%s.rep.googleapis.com:443", locationId)
	client, err := secretmanager.NewClient(ctx, option.WithEndpoint(endpoint))
	if err != nil {
		return fmt.Errorf("failed to create secretmanager client: %w", err)
	}
	defer client.Close()

	parent := fmt.Sprintf("projects/%s/locations/%s", projectId, locationId)

	// Build the request.
	req := &secretmanagerpb.CreateSecretRequest{
		Parent:   parent,
		SecretId: id,
	}

	// Call the API.
	result, err := client.CreateSecret(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create regional secret: %w", err)
	}
	fmt.Fprintf(w, "Created regional secret: %s\n", result.Name)
	return nil
}
```

### Java

To run this code, first [set up a Java development environment](https://docs.cloud.google.com/java/docs/setup.md.txt) and
[install the Secret Manager Java SDK](https://docs.cloud.google.com/secret-manager/docs/reference/libraries.md.txt#client-libraries-install-java).
On Compute Engine or GKE, you must
[authenticate with the cloud-platform scope](https://docs.cloud.google.com/secret-manager/docs/accessing-the-api.md.txt#oauth-scopes).

```java
import com.google.cloud.secretmanager.v1.LocationName;
import com.google.cloud.secretmanager.v1.Secret;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretManagerServiceSettings;
import java.io.IOException;

public class CreateRegionalSecret {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // Your GCP project ID.
    String projectId = "your-project-id";
    // Location of the secret.
    String locationId = "your-location-id";
    // Resource ID of the secret to create.
    String secretId = "your-secret-id";
    createRegionalSecret(projectId, locationId, secretId);
  }

  // Create a new regional secret 
  public static Secret createRegionalSecret(
      String projectId, String locationId, String secretId) 
      throws IOException {

    // Endpoint to call the regional secret manager sever
    String apiEndpoint = String.format("secretmanager.%s.rep.googleapis.com:443", locationId);
    SecretManagerServiceSettings secretManagerServiceSettings =
        SecretManagerServiceSettings.newBuilder().setEndpoint(apiEndpoint).build();

    // Initialize the client that will be used to send requests. This client only needs to be
    // created once, and can be reused for multiple requests.
    try (SecretManagerServiceClient client = 
        SecretManagerServiceClient.create(secretManagerServiceSettings)) {
      // Build the parent name from the project.
      LocationName location = LocationName.of(projectId, locationId);

      // Build the regional secret to create.
      Secret secret =
          Secret.newBuilder().build();

      // Create the regional secret.
      Secret createdSecret = client.createSecret(location.toString(), secretId, secret);
      System.out.printf("Created regional secret %s\n", createdSecret.getName());

      return createdSecret;
    }
  }
}
```

### Node.js

To run this code, first [set up a Node.js development environment](https://docs.cloud.google.com/nodejs/docs/setup.md.txt) and
[install the Secret Manager Node.js SDK](https://docs.cloud.google.com/secret-manager/docs/reference/libraries.md.txt#client-libraries-install-nodejs).
On Compute Engine or GKE, you must
[authenticate with the cloud-platform scope](https://docs.cloud.google.com/secret-manager/docs/accessing-the-api.md.txt#oauth-scopes).

```javascript
/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project'
// const locationId = 'locationId';
// const secretId = 'my-secret';
const parent = `projects/${projectId}/locations/${locationId}`;

// Imports the Secret Manager libray

const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

// Adding the endpoint to call the regional secret manager sever
const options = {};
options.apiEndpoint = `secretmanager.${locationId}.rep.googleapis.com`;
// Instantiates a client
const client = new SecretManagerServiceClient(options);

async function createRegionalSecret() {
  const [secret] = await client.createSecret({
    parent: parent,
    secretId: secretId,
  });

  console.log(`Created regional secret ${secret.name}`);
}

createRegionalSecret();
```

### Python

To run this code, first [set up a Python development environment](https://docs.cloud.google.com/python/docs/setup.md.txt) and
[install the Secret Manager Python SDK](https://docs.cloud.google.com/secret-manager/docs/reference/libraries.md.txt#client-libraries-install-python).
On Compute Engine or GKE, you must
[authenticate with the cloud-platform scope](https://docs.cloud.google.com/secret-manager/docs/accessing-the-api.md.txt#oauth-scopes).

```python
from google.cloud import secretmanager_v1


def create_regional_secret(
    project_id: str,
    location_id: str,
    secret_id: str,
    ttl: Optional[str] = None,
) -> secretmanager_v1.Secret:
    """
    Creates a new regional secret with the given name.
    """

    # Endpoint to call the regional secret manager sever
    api_endpoint = f"secretmanager.{location_id}.rep.googleapis.com"

    # Create the Secret Manager client.
    client = secretmanager_v1.SecretManagerServiceClient(
        client_options={"api_endpoint": api_endpoint},
    )

    # Build the resource name of the parent project.
    parent = f"projects/{project_id}/locations/{location_id}"

    # Create the secret.
    response = client.create_secret(
        request={
            "parent": parent,
            "secret_id": secret_id,
            "secret": {"ttl": ttl},
        }
    )

    # Print the new secret name.
    print(f"Created secret: {response.name}")

    return response

```

> [!NOTE]
> **Note:** Replication policies don't apply to regional secrets. Regional secrets can only be stored in the location that you choose when you create the secret.

## Add a secret version

Secret Manager automatically versions secret data using secret versions. Key operations, such
as access, destroy, disable, and enable, are applied to specific secret versions. With Secret Manager, you
can associate secrets with specific versions such as `42` or with dynamic aliases
such as `latest`. To learn more, see [Add a secret version](https://docs.cloud.google.com/secret-manager/regional-secrets/add-secret-version-rs.md.txt).

## Access a secret version

To access the secret data from a particular secret version for successful authentication, see
[Access a regional secret version](https://docs.cloud.google.com/secret-manager/regional-secrets/access-secret-version-rs.md.txt).

## What's next

- [Check the quotas and rate limits](https://docs.cloud.google.com/secret-manager/quotas.md.txt) for different types of API requests (access, read, and write) per project.
- [Add CMEK encryption to regional secrets](https://docs.cloud.google.com/secret-manager/regional-secrets/create-secret-cmek-encryption.md.txt)
- [Add a regional secret version](https://docs.cloud.google.com/secret-manager/regional-secrets/add-secret-version-rs.md.txt)