Skip to content

Instantly share code, notes, and snippets.

@bootswithdefer
Created November 7, 2018 22:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bootswithdefer/2a18f54816691b91f1ade5fe30d0614a to your computer and use it in GitHub Desktop.
Save bootswithdefer/2a18f54816691b91f1ade5fe30d0614a to your computer and use it in GitHub Desktop.
Using Hashicorp Vault AppRoles in a Jenkinsfile in pure groovy.
stage('pure-groovy-vault') {
agent none
environment {
VAULT_TOKEN_GEN_CRED = credentials('jenkins-vault-approle')
}
steps {
script {
println("Vault: Authenticate as Jenkins")
def body = """{"role_id": "${VAULT_TOKEN_GEN_CRED_USR}", "secret_id": "${VAULT_TOKEN_GEN_CRED_PSW}"}"""
def url = 'https://vault-url/v1/auth/approle/login'
def res = httpRequest contentType: 'APPLICATION_JSON', httpMode: 'POST', requestBody: body, url: url, quiet: true
def json = readJSON text: "${res.content}"
def vault_token = json.auth.client_token
def role_name = "msnet-test"
println("Vault: Get ${role_name} role-id")
url = "https://vault-url/v1/auth/approle/role/${role_name}/role-id"
res = httpRequest contentType: 'APPLICATION_JSON', httpMode: 'GET', requestBody: body, url: url, quiet: true,
customHeaders: [[maskValue: true, name: 'X-Vault-Token', value: "${vault_token}"]]
json = readJSON text: "${res.content}"
def role_id = json.data.role_id
println("Vault: Generate ${role_name} secret-id")
url = "https://vault-url/v1/auth/approle/role/${role_name}/secret-id"
res = httpRequest contentType: 'APPLICATION_JSON', httpMode: 'POST', requestBody: body, url: url, quiet: true,
customHeaders: [[maskValue: true, name: 'X-Vault-Token', value: "${vault_token}"]]
json = readJSON text: "${res.content}"
def secret_id = json.data.secret_id
println("Vault: Authenticate as ${role_name}")
body = """{"role_id": "${role_id}", "secret_id": "${secret_id}"}"""
url = 'https://vault-url/v1/auth/approle/login'
res = httpRequest contentType: 'APPLICATION_JSON', httpMode: 'POST', requestBody: body, url: url, quiet: true
json = readJSON text: "${res.content}"
vault_token = json.auth.client_token
def secret_path = "secret/apps/msnet/test"
println("Vault: Get secrets from ${secret_path}")
url = "https://vault-url/v1/${secret_path}"
res = httpRequest contentType: 'APPLICATION_JSON', httpMode: 'GET', requestBody: body, url: url, quiet: true,
customHeaders: [[maskValue: true, name: 'X-Vault-Token', value: "${vault_token}"]]
json = readJSON text: "${res.content}"
println(json.data.username)
println(json.data.password)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment