Skip to content

Add secretmanager samples #1948

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Jan 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ appengine-generated/
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*

# jenv
.java-version

# maven
target/
pom.xml.tag
Expand Down
32 changes: 32 additions & 0 deletions secretmanager/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Google Secret Manager

<a href="https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/java-docs-samples&page=editor&open_in_editor=secretmanager/README.md">
<img alt="Open in Cloud Shell" src ="http://gstatic.com/cloudssh/images/open-btn.png"></a>

Google [Secret Manager](https://cloud.google.com/secret-manager/) provides a
secure and convenient tool for storing API keys, passwords, certificates and
other sensitive data. These sample Java applications demonstrate how to access
the Secret Manager API using the Google Java API Client Libraries.

## Prerequisites

### Enable the API

You must [enable the Secret Manager API](https://console.cloud.google.com/flows/enableapi?apiid=secretmanager.googleapis.com) for your project in order to use these samples

### Set Environment Variables

You must set your project ID in order to run the tests

```text
$ export GOOGLE_CLOUD_PROJECT=<your-project-id-here>
```

### Grant Permissions

You must ensure that the [user account or service account](https://cloud.google.com/iam/docs/service-accounts#differences_between_a_service_account_and_a_user_account) you used to authorize your gcloud session has the proper permissions to edit Secret Manager resources for your project. In the Cloud Console under IAM, add the following roles to the project whose service account you're using to test:

* Secret Manager Admin (`roles/secretmanager.admin`)
* Secret Manager Secret Accessor (`roles/secretmanager.secretAccessor`)

More information can be found in the [Secret Manager Docs](https://cloud.google.com/secret-manager/docs/access-control)
61 changes: 61 additions & 0 deletions secretmanager/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<!--
Copyright 2020 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.google.cloud.secretmanager.samples</groupId>
<artifactId>secretmanager-samples</artifactId>
<packaging>jar</packaging>

<!--
The parent pom defines common style checks and testing strategies for our samples.
Removing or replacing it should not affect the execution of the samples in anyway.
-->
<parent>
<groupId>com.google.cloud.samples</groupId>
<artifactId>shared-configuration</artifactId>
<version>1.0.11</version>
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>

<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-secretmanager</artifactId>
<version>0.2.0</version>
</dependency>

<!-- test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
<version>1.0</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
60 changes: 60 additions & 0 deletions secretmanager/src/main/java/com/example/AccessSecretVersion.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example;

// [START secretmanager_access_secret_version]
import com.google.cloud.secretmanager.v1beta1.AccessSecretVersionRequest;
import com.google.cloud.secretmanager.v1beta1.AccessSecretVersionResponse;
import com.google.cloud.secretmanager.v1beta1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1beta1.SecretVersionName;
import java.io.IOException;

public class AccessSecretVersion {

public void accessSecretVersion() throws IOException {
// TODO(developer): Replace these variables before running the sample.
String projectId = "your-project-id";
String secretId = "your-secret-id";
String versionId = "your-version-id";
accessSecretVersion(projectId, secretId, versionId);
}

// Access the payload for the given secret version if one exists. The version
// can be a version number as a string (e.g. "5") or an alias (e.g. "latest").
public void accessSecretVersion(String projectId, String secretId, String versionId)
throws IOException {
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) {
SecretVersionName name = SecretVersionName.of(projectId, secretId, versionId);

// Access the secret version.
AccessSecretVersionRequest request =
AccessSecretVersionRequest.newBuilder().setName(name.toString()).build();
AccessSecretVersionResponse response = client.accessSecretVersion(request);

// Print the secret payload.
//
// WARNING: Do not print the secret in a production environment - this
// snippet is showing how to access the secret material.
String payload = response.getPayload().getData().toStringUtf8();
System.out.printf("Plaintext: %s\n", payload);
}
}
}
// [END secretmanager_access_secret_version]
64 changes: 64 additions & 0 deletions secretmanager/src/main/java/com/example/AddSecretVersion.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example;

// [START secretmanager_add_secret_version]
import com.google.cloud.secretmanager.v1beta1.AddSecretVersionRequest;
import com.google.cloud.secretmanager.v1beta1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1beta1.SecretName;
import com.google.cloud.secretmanager.v1beta1.SecretPayload;
import com.google.cloud.secretmanager.v1beta1.SecretVersion;
import com.google.protobuf.ByteString;
import java.io.IOException;

public class AddSecretVersion {

public void addSecretVersion() throws IOException {
// TODO(developer): Replace these variables before running the sample.
String projectId = "your-project-id";
String secretId = "your-secret-id";
addSecretVersion(projectId, secretId);
}

// Add a new version to the existing secret.
public void addSecretVersion(String projectId, String secretId) throws IOException {
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) {
SecretName name = SecretName.of(projectId, secretId);

// Create the secret payload.
SecretPayload payload =
SecretPayload.newBuilder()
.setData(ByteString.copyFromUtf8("my super secret data"))
.build();

// Create the request.
AddSecretVersionRequest request =
AddSecretVersionRequest.newBuilder()
.setParent(name.toString())
.setPayload(payload)
.build();

// Add the secret version.
SecretVersion version = client.addSecretVersion(request);
System.out.printf("Added secret version %s\n", version.getName());
}
}
}
// [END secretmanager_add_secret_version]
68 changes: 68 additions & 0 deletions secretmanager/src/main/java/com/example/CreateSecret.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example;

// [START secretmanager_create_secret]
import com.google.cloud.secretmanager.v1beta1.CreateSecretRequest;
import com.google.cloud.secretmanager.v1beta1.ProjectName;
import com.google.cloud.secretmanager.v1beta1.Replication;
import com.google.cloud.secretmanager.v1beta1.Secret;
import com.google.cloud.secretmanager.v1beta1.SecretManagerServiceClient;
import java.io.IOException;

public class CreateSecret {

public void createSecret() throws IOException {
// TODO(developer): Replace these variables before running the sample.
String projectId = "your-project-id";
String secretId = "your-secret-id";
createSecret(projectId, secretId);
}

// Add a new version to the existing secret.
public void createSecret(String projectId, String secretId) throws IOException {
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) {
// Build the parent name from the project.
ProjectName parent = ProjectName.of(projectId);

// Build the secret to create.
Secret secret =
Secret.newBuilder()
.setReplication(
Replication.newBuilder()
.setAutomatic(Replication.Automatic.newBuilder().build())
.build())
.build();

// Create the request.
CreateSecretRequest request =
CreateSecretRequest.newBuilder()
.setParent(parent.toString())
.setSecretId(secretId)
.setSecret(secret)
.build();

// Create the secret.
Secret createdSecret = client.createSecret(request);
System.out.printf("Created secret %s\n", createdSecret.getName());
}
}
}
// [END secretmanager_create_secret]
53 changes: 53 additions & 0 deletions secretmanager/src/main/java/com/example/DeleteSecret.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example;

// [START secretmanager_delete_secret]
import com.google.cloud.secretmanager.v1beta1.DeleteSecretRequest;
import com.google.cloud.secretmanager.v1beta1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1beta1.SecretName;
import java.io.IOException;

public class DeleteSecret {

public void deleteSecret() throws IOException {
// TODO(developer): Replace these variables before running the sample.
String projectId = "your-project-id";
String secretId = "your-secret-id";
deleteSecret(projectId, secretId);
}

// Delete an existing secret with the given name.
public void deleteSecret(String projectId, String secretId) throws IOException {
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) {
// Build the secret name.
SecretName name = SecretName.of(projectId, secretId);

// Create the request.
DeleteSecretRequest request =
DeleteSecretRequest.newBuilder().setName(name.toString()).build();

// Create the secret.
client.deleteSecret(request);
System.out.printf("Deleted secret %s\n", secretId);
}
}
}
// [END secretmanager_delete_secret]
Loading