Search code examples
jenkinsgroovyjenkins-pipelinekey-valuehashicorp-vault

Extract key-pair value in Jenkinsfile


I have this jenkinsfile in which I am getting the value from Hashicorp vault. The secrets are in key-value pair. I have stored that in secret_key variable. How do I extract the value from it

node {
    withCredentials([[$class: 'VaultTokenCredentialBinding', 
                      addrVariable: 'VAULT_ADDR', 
                      credentialsId: 'token', 
                      tokenVariable: 'VAULT_TOKEN', 
                      vaultAddr: 'http://ip:8200']]) {
        script{
            secret_key = sh (
                        script: 'vault kv get -format json -field=data kv/secret', 
                        returnStdout: true
                        )
        }
    }
}

Output:

+ vault kv get -format json -field=data kv/secret
{
  "password": "admin",
  "username": "admin"
}

Solution

  • The Vault CLI returns a JSON String to stdout, so you can parse it in your pipeline accordingly with the readJSON step method:

    secretKeyMap = readJSON(text: secret_key)
    

    Afterwards, the readJSON method returns a Map type converted from the JSON String, so you can also parse that accordingly with the proper syntax:

    secretKeyMap['password'] // admin
    secretKeyMap['username'] // admin
    secretKeyMap.password // admin
    secretKeyMap.username // admin