Tuesday, 29 September 2020

Java: HashiCorp Vault: Hello World Application

 Step 1: Create new maven project ‘hashiCorp’. 

Step 2: Update pom.xml with maven dependencies.

pom.xml

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sample.app</groupId>
    <artifactId>hashicorp</artifactId>
    <version>1</version>

    <dependencies>
        <dependency>
            <groupId>com.bettercloud</groupId>
            <artifactId>vault-java-driver</artifactId>
            <version>5.1.0</version>
        </dependency>
    </dependencies>
</project>

 

Step 3: Create new package ‘com.sample.app’ and define App.java like below.

App.java
package com.sample.app;

import java.util.HashMap;
import java.util.Map;

import com.bettercloud.vault.Vault;
import com.bettercloud.vault.VaultConfig;
import com.bettercloud.vault.VaultException;
import com.bettercloud.vault.response.LogicalResponse;

public class App {
    private static final String VAULT_SERVER_PATH = "http://127.0.0.1:9999";
    private static final String TOKEN = "s.E3BRk50CvwMf7nWA0of9qsQB";

    public static void main(String args[]) throws VaultException {
        final VaultConfig vaultConfig = new VaultConfig().address(VAULT_SERVER_PATH).token(TOKEN).build();
        final Vault vault = new Vault(vaultConfig);

        final Map<String, Object> secrets = new HashMap<>();
        secrets.put("user_name", "krishna");
        secrets.put("password", "password123");

        // Write operation
        final LogicalResponse writeResponse = vault.logical().write("secret/my-app", secrets);

        // Read Data
        final String userName = vault.logical().read("secret/my-app").getData().get("user_name");
        final String password = vault.logical().read("secret/my-app").getData().get("password");

        System.out.println("user name : " + userName);
        System.out.println("password: " + password);

    }
}

 

Output

user name : krishna
password: password123

 

Note

Update VAULT_SERVER_PATH and TOKEN accordingly.

 

 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment