Update example code links, remove unneeded comments (#13491)

This commit is contained in:
VAL
2021-12-22 09:33:12 -08:00
committed by GitHub
parent 15ada63e47
commit c1495da531
9 changed files with 50 additions and 127 deletions

View File

@@ -59,7 +59,7 @@ check out our [Getting Started guides](https://learn.hashicorp.com/collections/v
on HashiCorp's learning platform. There are also [additional guides](https://learn.hashicorp.com/vault)
to continue your learning.
For examples of how to interact with Vault from inside your application in different programming languages, see the [vault-examples](https://github.com/hashicorp/vault-examples) repo.
For examples of how to interact with Vault from inside your application in different programming languages, see the [vault-examples](https://github.com/hashicorp/vault-examples) repo. An out-of-the-box [sample application](https://github.com/hashicorp/hello-vault-go) is also available.
Show off your Vault knowledge by passing a certification exam. Visit the
[certification page](https://www.hashicorp.com/certification/#hashicorp-certified-vault-associate)

View File

@@ -3,6 +3,6 @@ Vault API
This provides the `github.com/hashicorp/vault/api` package which contains code useful for interacting with a Vault server.
For examples of how to use this module, see the [vault-examples](https://github.com/hashicorp/vault-examples/tree/main/go) repo.
For examples of how to use this module, see the [vault-examples](https://github.com/hashicorp/vault-examples) repo.
[![GoDoc](https://godoc.org/github.com/hashicorp/vault/api?status.png)](https://godoc.org/github.com/hashicorp/vault/api)

View File

@@ -25,7 +25,7 @@ These libraries are officially maintained by HashiCorp.
$ go get github.com/hashicorp/vault/api
```
[Code samples](https://github.com/hashicorp/vault-examples/tree/main/go)
[Example application](https://github.com/hashicorp/hello-vault-go)
### Ruby
@@ -56,8 +56,6 @@ $ pip install ansible-modules-hashivault
$ Install-Package VaultSharp
```
[Code samples](https://github.com/hashicorp/vault-examples/tree/main/dotnet/Examples)
- [Vault.NET](https://github.com/Chatham/Vault.NET)
```shell-session

View File

@@ -264,9 +264,7 @@ import (
auth "github.com/hashicorp/vault/api/auth/approle"
)
// Fetches a key-value secret (kv-v2) after authenticating via AppRole,
// an auth method used by machines that are unable to use platform-based
// authentication mechanisms like AWS Auth, Kubernetes Auth, etc.
// Fetches a key-value secret (kv-v2) after authenticating via AppRole.
func getSecretWithAppRole() (string, error) {
config := vault.DefaultConfig() // modify for more granular configuration
@@ -343,12 +341,12 @@ using VaultSharp.V1.AuthMethods.AppRole;
using VaultSharp.V1.AuthMethods.Token;
using VaultSharp.V1.Commons;
namespace Examples
namespace Examples
{
public class ApproleAuthExample
{
const string DefaultTokenPath = "../../../path/to/wrapping-token";
/// <summary>
/// Fetches a key-value secret (kv-v2) after authenticating to Vault via AppRole authentication
/// </summary>
@@ -358,7 +356,7 @@ namespace Examples
// The Secret ID is a value that needs to be protected, so instead of the app having knowledge of the secret ID directly,
// we have a trusted orchestrator (https://learn.hashicorp.com/tutorials/vault/secure-introduction?in=vault/app-integration#trusted-orchestrator)
// give the app access to a short-lived response-wrapping token (https://www.vaultproject.io/docs/concepts/response-wrapping).
// Read more at: https://learn.hashicorp.com/tutorials/vault/approle-best-practices?in=vault/auth-methods#secretid-delivery-best-practices
// Read more at: https://learn.hashicorp.com/tutorials/vault/approle-best-practices?in=vault/auth-methods#secretid-delivery-best-practices
var vaultAddr = Environment.GetEnvironmentVariable("VAULT_ADDR");
if(String.IsNullOrEmpty(vaultAddr))
{
@@ -384,9 +382,9 @@ namespace Examples
// We pass null here instead of the wrapping token to avoid depleting its single usage
// given that we already initialized our client with the wrapping token
Secret<Dictionary<string, object>> secretIdData = vaultClientForUnwrapping.V1.System
.UnwrapWrappedResponseDataAsync<Dictionary<string, object>>(null).Result;
.UnwrapWrappedResponseDataAsync<Dictionary<string, object>>(null).Result;
var secretId = secretIdData.Data["secret_id"]; // Grab the secret_id
var secretId = secretIdData.Data["secret_id"]; // Grab the secret_id
// We create a second VaultClient and initialize it with the AppRole auth method and our new credentials.
IAuthMethodInfo authMethod = new AppRoleAuthMethodInfo(roleId, secretId.ToString());
@@ -397,9 +395,9 @@ namespace Examples
// We can retrieve the secret from VaultClient
Secret<SecretData> kv2Secret = null;
kv2Secret = vaultClient.V1.Secrets.KeyValue.V2.ReadSecretAsync(path: "/creds").Result;
var password = kv2Secret.Data.Data["password"];
return password.ToString();
}
}

View File

@@ -765,13 +765,6 @@ import (
// Fetches a key-value secret (kv-v2) after authenticating to Vault via AWS IAM,
// one of two auth methods used to authenticate with AWS (the other is EC2 auth).
// A role must first be created in Vault bound to the IAM ARN you wish to
// authenticate with, like so:
// vault write auth/aws/role/dev-role-iam \
// auth_type=iam \
// bound_iam_principal_arn="arn:aws:iam::AWS-ACCOUNT-NUMBER:role/AWS-IAM-ROLE-NAME" \
// ttl=24h
// Learn more about the available parameters at https://www.vaultproject.io/api/auth/aws#parameters-10
func getSecretWithAWSAuthIAM() (string, error) {
config := vault.DefaultConfig() // modify for more granular configuration
@@ -840,17 +833,11 @@ using VaultSharp.V1.SecretsEngines.AWS;
namespace Examples
{
public class AwsAuthExample
public class AwsAuthExample
{
/// <summary>
/// <summary>
/// Fetches a key-value secret (kv-v2) after authenticating to Vault via AWS IAM,
/// one of two auth methods used to authenticate with AWS (the other is EC2 auth).
/// A role must first be created in Vault bound to the IAM ARN you wish to authenticate with, like so:
/// vault write auth/aws/role/dev-role-iam \
/// auth_type=iam \
/// bound_iam_principal_arn="arn:aws:iam::AWS-ACCOUNT-NUMBER:role/AWS-IAM-ROLE-NAME" \
/// ttl=24h
/// Learn more about the available parameters at https://www.vaultproject.io/api/auth/aws#parameters-10
/// </summary>
public string GetSecretAWSAuthIAM()
{
@@ -860,21 +847,21 @@ namespace Examples
throw new System.ArgumentNullException("Vault Address");
}
var roleName = Environment.GetEnvironmentVariable("AWS_ROLE_NAME");
var roleName = Environment.GetEnvironmentVariable("VAULT_ROLE");
if(String.IsNullOrEmpty(roleName))
{
throw new System.ArgumentNullException("AWS Role Name");
throw new System.ArgumentNullException("Vault Role Name");
}
var amazonSecurityTokenServiceConfig = new AmazonSecurityTokenServiceConfig();
// Initialize BasicAWS Credentials w/ an accessKey and secretKey
Amazon.Runtime.AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey: Environment.GetEnvironmentVariable("AWS_ACCESS_KEY_ID"),
Amazon.Runtime.AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey: Environment.GetEnvironmentVariable("AWS_ACCESS_KEY_ID"),
secretKey: Environment.GetEnvironmentVariable("AWS_SECRET_ACCESS_KEY"));
// Construct the IAM Request and add necessary headers
var iamRequest = GetCallerIdentityRequestMarshaller.Instance.Marshall(new GetCallerIdentityRequest());
iamRequest.Endpoint = new Uri(amazonSecurityTokenServiceConfig.DetermineServiceURL());
iamRequest.ResourcePath = "/";
@@ -896,9 +883,9 @@ namespace Examples
// We can retrieve the secret from the VaultClient object
Secret<SecretData> kv2Secret = null;
kv2Secret = vaultClient.V1.Secrets.KeyValue.V2.ReadSecretAsync(path: "/creds").Result;
var password = kv2Secret.Data.Data["password"];
return password.ToString();
}
}

View File

@@ -230,14 +230,6 @@ import (
// Fetches a key-value secret (kv-v2) after authenticating to Vault via Azure authentication.
// This example assumes you have a configured Azure AD Application.
// Learn more about Azure authentication prerequisites: https://www.vaultproject.io/docs/auth/azure
//
// A role must first be created in Vault bound to the resource groups and subscription ids:
// vault write auth/azure/role/dev-role \
// policies="dev-policy"
// bound_subscription_ids=$AZURE_SUBSCRIPTION_ID \
// bound_resource_groups=test-rg \
// ttl=24h
func getSecretWithAzureAuth() (string, error) {
config := vault.DefaultConfig() // modify for more granular configuration
@@ -282,6 +274,7 @@ func getSecretWithAzureAuth() (string, error) {
return value, nil
}
```
</CodeBlockConfig>
@@ -302,7 +295,7 @@ using VaultSharp.V1.Commons;
namespace Examples
{
public class AzureAuthExample
public class AzureAuthExample
{
public class InstanceMetadata
{
@@ -314,17 +307,9 @@ namespace Examples
const string MetadataEndPoint = "http://169.254.169.254/metadata/instance?api-version=2017-08-01";
const string AccessTokenEndPoint = "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/";
/// <summary>
/// <summary>
/// Fetches a key-value secret (kv-v2) after authenticating to Vault via Azure authentication.
/// This example assumes you have a configured Azure AD Application.
/// Learn more about Azure authentication prerequisites: https://www.vaultproject.io/docs/auth/azure
///
/// A role must first be created in Vault bound to the resource groups and subscription ids:
/// vault write auth/azure/role/dev-role \
/// policies="dev-policy"
/// bound_subscription_ids=$AZURE_SUBSCRIPTION_ID \
/// bound_resource_groups=test-rg \
/// ttl=24h
/// </summary>
public string GetSecretWithAzureAuth()
{
@@ -338,7 +323,7 @@ namespace Examples
if(String.IsNullOrEmpty(roleName))
{
throw new System.ArgumentNullException("Vault Role Name");
}
}
string jwt = GetJWT();
InstanceMetadata metadata = GetMetadata();
@@ -347,16 +332,16 @@ namespace Examples
var vaultClientSettings = new VaultClientSettings(vaultAddr, authMethod);
IVaultClient vaultClient = new VaultClient(vaultClientSettings);
// We can retrieve the secret from the VaultClient object
Secret<SecretData> kv2Secret = null;
kv2Secret = vaultClient.V1.Secrets.KeyValue.V2.ReadSecretAsync(path: "/creds").Result;
var password = kv2Secret.Data.Data["password"];
return password.ToString();
}
/// <summary>
/// Query Azure Resource Manage for metadata about the Azure instance
/// </summary>
@@ -371,7 +356,7 @@ namespace Examples
StreamReader streamResponse = new StreamReader(metadataResponse.GetResponseStream());
string stringResponse = streamResponse.ReadToEnd();
var resultsDict = JsonConvert.DeserializeObject<Dictionary<string, InstanceMetadata>>(stringResponse);
return resultsDict["compute"];
}
@@ -387,7 +372,7 @@ namespace Examples
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Pipe response Stream to a StreamReader and extract access token
StreamReader streamResponse = new StreamReader(response.GetResponseStream());
StreamReader streamResponse = new StreamReader(response.GetResponseStream());
string stringResponse = streamResponse.ReadToEnd();
var resultsDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(stringResponse);

View File

@@ -388,17 +388,6 @@ import (
// Fetches a key-value secret (kv-v2) after authenticating to Vault
// via GCP IAM, one of two auth methods used to authenticate with
// GCP (the other is GCE auth).
//
// A role must first be created in Vault bound to the IAM user's service
// account you wish to authenticate with, like so:
// vault write auth/gcp/role/dev-role-iam \
// type="iam" \
// policies="dev-policy" \
// bound_service_accounts="my-service@my-project.iam.gserviceaccount.com"
// Your Vault instance must also be configured with GCP credentials to
// perform API calls to IAM, like so:
// vault write auth/gcp/config credentials=@path/to/server/creds.json
// Learn more at https://www.vaultproject.io/docs/auth/gcp
func getSecretWithGCPAuthIAM() (string, error) {
config := vault.DefaultConfig() // modify for more granular configuration
@@ -457,6 +446,7 @@ func getSecretWithGCPAuthIAM() (string, error) {
return value, nil
}
```
</CodeBlockConfig>
@@ -481,19 +471,11 @@ using Data = Google.Apis.Iam.v1.Data;
namespace Examples
{
public class GCPAuthExample
public class GCPAuthExample
{
/// <summary>
/// Fetches a key-value secret (kv-v2) after authenticating to Vault via GCP IAM,
/// one of two auth methods used to authenticate with GCP (the other is GCE auth).
///
/// A role must first be created in Vault bound to the IAM user's service account you wish to authenticate with, like so:
/// type="iam" \
/// policies="dev-policy" \
/// bound_service_accounts="my-service@my-project.iam.gserviceaccount.com"
/// Your Vault instance must also be configured with GCP credentials to perform API calls to IAM, like so:
/// vault write auth/gcp/config credentials=@path/to/server/creds.json
/// Learn more at https://www.vaultproject.io/docs/auth/gcp
/// </summary>
public string GetSecretGcp()
{
@@ -503,10 +485,10 @@ namespace Examples
throw new System.ArgumentNullException("Vault Address");
}
var roleName = Environment.GetEnvironmentVariable("GCP_ROLE");
var roleName = Environment.GetEnvironmentVariable("VAULT_ROLE");
if(String.IsNullOrEmpty(roleName))
{
throw new System.ArgumentNullException("GCP Role Name");
throw new System.ArgumentNullException("Vault Role Name");
}
// Learn about authenticating to GCS with service account credentials at https://cloud.google.com/docs/authentication/production
@@ -516,18 +498,18 @@ namespace Examples
}
var jwt = SignJWT();
IAuthMethodInfo authMethod = new GoogleCloudAuthMethodInfo(roleName, jwt);
var vaultClientSettings = new VaultClientSettings(vaultAddr, authMethod);
IVaultClient vaultClient = new VaultClient(vaultClientSettings);
IVaultClient vaultClient = new VaultClient(vaultClientSettings);
// We can retrieve the secret after creating our VaultClient object
Secret<SecretData> kv2Secret = null;
kv2Secret = vaultClient.V1.Secrets.KeyValue.V2.ReadSecretAsync(path: "/creds").Result;
var password = kv2Secret.Data.Data["password"];
return password.ToString();
}
@@ -547,7 +529,7 @@ namespace Examples
});
string svcEmail = $"{svcAcctName}@{gcpProjName}.iam.gserviceaccount.com";
string name = $"projects/-/serviceAccounts/{svcEmail}";
string name = $"projects/-/serviceAccounts/{svcEmail}";
TimeSpan currentTime = (DateTime.UtcNow - new DateTime(1970, 1, 1));
int expiration = (int)(currentTime.TotalSeconds) + 900;
@@ -563,7 +545,7 @@ namespace Examples
ProjectsResource.ServiceAccountsResource.SignJwtRequest request = iamService.Projects.ServiceAccounts.SignJwt(requestBody, name);
Data.SignJwtResponse response = request.Execute();
return JsonConvert.SerializeObject(response.SignedJwt).Replace("\"", "");
}

View File

@@ -322,10 +322,7 @@ import (
)
// Fetches a key-value secret (kv-v2) after authenticating to Vault with a Kubernetes service account.
//
// As the client, all we need to do is pass along the JWT token representing our application's Kubernetes Service Account in our login request to Vault.
//
// For a more in-depth setup explanation, please see the full version of this code in the hashicorp/vault-examples repo.
// For a more in-depth setup explanation, please see the relevant readme in the hashicorp/vault-examples repo.
func getSecretWithKubernetesAuth() (string, error) {
// If set, the VAULT_ADDR environment variable will be the address that
// your pod uses to communicate with Vault.
@@ -394,37 +391,12 @@ using VaultSharp.V1.Commons;
namespace Examples
{
public class KubernetesAuthExample
public class KubernetesAuthExample
{
const string DefaultTokenPath = "path/to/service-account-token";
// Fetches a key-value secret (kv-v2) after authenticating to Vault with a Kubernetes service account.
//
// As the client, all we need to do is pass along the JWT token representing our application's Kubernetes Service Account in our login request to Vault.
// This token is automatically mounted to your application's container by Kubernetes. Read more at https://www.vaultproject.io/docs/auth/kubernetes
//
// SETUP NOTES: If an operator has not already set up Kubernetes auth in Vault for you, then you must also first configure the Vault server with its own Service Account token to be able to communicate with the Kubernetes API
// so it can verify that the client's service-account token is valid. The service account that will be performing that verification needs the ClusterRole system:auth-delegator.
//
// export TOKEN_REVIEW_JWT=$(kubectl get secret $TOKEN_REVIEWER_SECRET --output='go-template={{ .data.token }}' | base64 --decode)
// export KUBE_HOST=$(kubectl config view --raw --minify --flatten --output='jsonpath={.clusters[].cluster.server}')
// kubectl config view --raw --minify --flatten --output='jsonpath={.clusters[].cluster.certificate-authority-data}' | base64 --decode > path/to/kube_ca_cert
//
// vault write auth/kubernetes/config \
// token_reviewer_jwt=${TOKEN_REVIEW_JWT} \
// kubernetes_host=${KUBE_HOST} \
// kubernetes_ca_cert=@path/to/kube_ca_cert \
// issuer="kubernetes/serviceaccount"
//
// The "issuer" field is normally only required when running Kubernetes 1.21 or above, and may differ from the default value above:
// https://www.vaultproject.io/docs/auth/kubernetes#discovering-the-service-account-issuer.
//
// Finally, make sure to create a role in Vault bound to your pod's service account:
//
// vault write auth/kubernetes/role/dev-role-k8s \
// policies="dev-policy" \
// bound_service_account_names="my-app" \
// bound_service_account_namespaces="default"
// For a more in-depth setup explanation, please see the relevant readme in the hashicorp/vault-examples repo.
public string GetSecretWithK8s()
{
var vaultAddr = Environment.GetEnvironmentVariable("VAULT_ADDR");
@@ -441,19 +413,19 @@ namespace Examples
// Get the path to service account token or fall back on default path
string pathToToken = String.IsNullOrEmpty(Environment.GetEnvironmentVariable("SA_TOKEN_PATH")) ? DefaultTokenPath : Environment.GetEnvironmentVariable("SA_TOKEN_PATH");
string jwt = File.ReadAllText(pathToToken);
string jwt = File.ReadAllText(pathToToken);
IAuthMethodInfo authMethod = new KubernetesAuthMethodInfo(roleName, jwt);
var vaultClientSettings = new VaultClientSettings(vaultAddr, authMethod);
IVaultClient vaultClient = new VaultClient(vaultClientSettings);
IVaultClient vaultClient = new VaultClient(vaultClientSettings);
// We can retrieve the secret after creating our VaultClient object
Secret<SecretData> kv2Secret = null;
kv2Secret = vaultClient.V1.Secrets.KeyValue.V2.ReadSecretAsync(path: "/creds").Result;
var password = kv2Secret.Data.Data["password"];
return password.ToString();
}
}

View File

@@ -115,7 +115,7 @@ leased token associated with your identity to renew it.
The following code snippet demonstrates how to renew auth tokens.
<CodeTabs heading="gcp auth example">
<CodeTabs heading="token renewal example">
<CodeBlockConfig lineNumbers>
@@ -188,6 +188,7 @@ func manageTokenLifecycle(client *vault.Client, token *vault.Secret) error {
log.Printf("Failed to renew token: %v. Re-attempting login.", err)
return nil
}
// This occurs once the token has reached max TTL.
log.Printf("Token can no longer be renewed. Re-attempting login.")
return nil
@@ -200,7 +201,7 @@ func manageTokenLifecycle(client *vault.Client, token *vault.Secret) error {
func login(client *vault.Client) (*vault.Secret, error) {
// WARNING: A plaintext password like this is obviously insecure.
// See the files starting in auth-* for full examples of how to securely
// See the hashicorp/vault-examples repo for full examples of how to securely
// log in to Vault using various auth methods. This function is just
// demonstrating the basic idea that a *vault.Secret is returned by
// the login call.