Coder Social home page Coder Social logo

jenkinsci / hashicorp-vault-plugin Goto Github PK

View Code? Open in Web Editor NEW
218.0 17.0 143.0 2.05 MB

Jenkins plugin to populate environment variables from secrets stored in HashiCorp's Vault.

Home Page: https://plugins.jenkins.io/hashicorp-vault-plugin/

License: MIT License

Java 95.10% HTML 3.74% HCL 0.29% Groovy 0.32% Shell 0.55%
jenkins jenkins-plugin secrets secret-management vault hashicorp-vault

hashicorp-vault-plugin's Introduction

Jenkins Vault Plugin

Build Status Jenkins Plugin GitHub release Jenkins Plugin Installs

This plugin adds a build wrapper to set environment variables from a HashiCorp Vault secret. Secrets are generally masked in the build log, so you can't accidentally print them.
It also has the ability to inject Vault credentials into a build pipeline or freestyle job for fine-grained vault interactions.

Vault Authentication Backends

This plugin allows authenticating against Vault using the AppRole authentication backend. Hashicorp recommends using AppRole for Servers / automated workflows (like Jenkins) and using Tokens (default mechanism, Github Token, ...) for every developer's machine. Furthermore, this plugin allows using a Github personal access token, or a Vault Token - either configured directly in Jenkins or read from an arbitrary file on the Jenkins controller.

How does AppRole work?

In short: you register an approle auth backend using a self-chosen name (e.g. Jenkins). This approle is identified by a role-id and secured with a secret_id. If you have both of those values you can ask Vault for a token that can be used to access vault. When registering the approle backend you can set a couple of different parameters:

  • How long should the secret_id live (can be indefinite)
  • how often can one use a token that is obtained via this backend
  • which IP addresses can obtain a token using role-id and secret-id?
  • many more

This is just a short introduction, please refer to Hashicorp itself to get detailed information.

Isolating policies for different jobs

It may be desirable to have jobs or folders with separate Vault policies allocated. This may be done with the optional policies configuration option combined with authentication such as the AppRole credential. The process is the following:

  • The Jenkins job attempts to retrieve a secret from Vault
  • The AppRole authentication is used to retrieve a new token (if the old one has not expired yet)
  • The Vault plugin then uses the policies configuration value with job info to come up with a list of policies
  • If this list is not empty, the AppRole token is used to retrieve a new token that only has the specified policies applied
  • This token is then used for all Vault plugin operations in the job

The policies list may be templatized with values that can come from each job in order to customize policies per job or folder. See the policies configuration help for more information on available tokens to use in the configuration. The Limit Token Policies option must also be enabled on the auth credential. Please note that the AppRole (or other authentication method) should have all policies configured as token_policies and not identity_policies, as job-specific tokens inherit all identity_policies automatically.

What about other backends?

Hashicorp explicitly recommends the AppRole Backend for machine-to-machine authentication. Token based auth is mainly supported for backward compatibility. Other backends that might make sense are the AWS EC2 backend, the Azure backend, and the Kubernetes backend. But we do not support these yet. Feel free to contribute!

Implementing additional authentication backends is actually quite easy:

Simply provide a class extending AbstractVaultTokenCredential that contains a Descriptor extending BaseStandardCredentialsDescriptor. The Descriptor needs to be annotated with @Extension. Your credential needs to know how to authenticate with Vault and provide an authenticated Vault session. See VaultAppRoleCredential.java for an example.

Plugin Usage

Configuration

You can configure the plugin on three different levels:

  • Global: in your global config
  • Folder-Level: on the folder your job is running in
  • Job-Level: either on your freestyle project job or directly in the Jenkinsfile

The lower the level the higher its priority, meaning: if you configure a URL in your global settings, but override it in your particular job, this URL will be used for communicating with Vault. In your configuration (may it be global, folder or job) you see the following screen: Global Configuration

The credential you provide determines what authentication backend will be used. Currently, there are five different Credential Types you can use:

Vault App Role Credential

App Role Credential

You enter your role-id and secret-id there. The description helps to find your credential later, the id is not mandatory (a UUID is generated by default), but it helps to set it if you want to use your credential inside the Jenkinsfile.

The path field is the approle authentication path. This is, by default, "approle" and this will also be used if no path is specified here.

Migrate current Jenkins Vault configuration to support a new version of plugin.

After update a plugin from version 2.2.0 you can note - builds failed with an exception java.lang.NullPointerException. These steps will help you fix it:

  1. If you using AppRole auth method - you need to update Jenkins Credential store (in UI) for all kinds Vault App Role Credential and set Path field for your correct path or just leave the default approle and save.
  2. Go to Configure of failed job and change Vault Engine in Advanced Settings and choose your version on KV Engine 1 or 2 from a select menu K/V Engine Version for ALL Vault Secrets and save.

Vault Github Credential

Github Credentia

You enter your github personal access token to authenticate to vault.

Vault GCP Credential

GCP Credential

You enter your Vault GCP auth role name and audience. The JWT will be automatically retrieved from GCE metdata. This requires that Jenkins master is running on a GCE instance.

Vault Kubernetes Credential

Kubernetes Credential

You enter your Vault Kubernetes auth role. The JWT will be automatically retrieved from the mounted secret volume (/var/run/secrets/kubernetes.io/serviceaccount/token). This assumes, that the jenkins is running in Kubernetes Pod with a Service Account attached.

Vault AWS IAM Credential

AWS IAM Credential

Authenticate to Vault using the aws auth method with the IAM workflow. The AWS credentials will be automatically retrieved from one of several standard locations. The typical use case would be Jenkins master running on an AWS EC2 instance with the credentials acquired from the instance metadata. Optionally enter your AWS IAM auth role name and Vault AWS auth mount path. If the role is not provided, Vault will determine it from the principal in the IAM identity. If the mount path is not provided, it defaults to aws.

Vault Token Credential

Token Credential

Directly specify a token to be used when authenticating with vault.

Vault Token File Credential

Token File Credential

Basically the same as the Vault Token Credential, just that the token is read from a file on your Jenkins Machine. You can use this in combination with a script that periodically refreshes your token.

Usage in FreeStyle Jobs

If you still use free style jobs (hint: you should consider migrating to Jenkinsfile), you can configure both configuration and the secrets you need on the job level.

Job Configuration

The secrets are available as environment variables then.

Usage via Jenkinsfile

Let the code speak for itself:

node {
    // define the secrets and the env variables
    // engine version can be defined on secret, job, folder or global.
    // the default is engine version 2 unless otherwise specified globally.
    def secrets = [
        [path: 'secret/testing', engineVersion: 1, secretValues: [
            [envVar: 'testing', vaultKey: 'value_one'],
            [envVar: 'testing_again', vaultKey: 'value_two']]],
        [path: 'secret/another_test', engineVersion: 2, secretValues: [
            [vaultKey: 'another_test']]]
    ]

    // optional configuration, if you do not provide this the next higher configuration
    // (e.g. folder or global) will be used
    def configuration = [vaultUrl: 'http://my-very-other-vault-url.com',
                         vaultCredentialId: 'my-vault-cred-id',
                         engineVersion: 1]
    // inside this block your credentials will be available as env variables
    withVault([configuration: configuration, vaultSecrets: secrets]) {
        sh 'echo $testing'
        sh 'echo $testing_again'
        sh 'echo $another_test'
    }
}

In the future we might migrate to a BuildStep instead of a BuildWrapper.

Use of dynamic credentials

You may also want to use dynamically allocated credentials:

import hudson.util.Secret
import com.cloudbees.plugins.credentials.CredentialsScope
import com.datapipe.jenkins.vault.credentials.VaultTokenCredential

VaultTokenCredential customCredential = new VaultTokenCredential(
    CredentialsScope.GLOBAL,
    'custom-credential',
    'My Custom Credential',
    Secret.fromString('This is my token. There are many like it, but this one is mine. My token is my best friend.')
)

node {
...
    def configuration = [vaultUrl: 'http://my-very-other-vault-url.com',
                         vaultCredential: customCredential]
...

Setting a vaultCredential will override any previously defined vaultCredentialId.

Works with any VaultCredential: VaultTokenCredential, VaultAppRoleCredential, etc.

Inject Vault Credentials into your Job

Pipeline Usage

withCredentials Block

Specify the variables for the vault address and token. Vault Address and Credentials are both required.
addrVariable and tokenVariable are optional. They will be set to VAULT_ADDR and VAULT_TOKEN respectively if omitted.

node {
    withCredentials([[$class: 'VaultTokenCredentialBinding', credentialsId: 'vaulttoken', vaultAddr: 'https://localhost:8200']]) {
        // values will be masked
        sh 'echo TOKEN=$VAULT_TOKEN'
        sh 'echo ADDR=$VAULT_ADDR'
    }
}

FreeStyle Job

freeStyle Credential Binding

Configuration as Code

There is an easier way to setup the global Vault configuration on your Jenkins server.
No need for messing around in the UI.

Jenkins Configuration as Code often shorten to JCasC or simplify Configuration as Code plugin allows you to configure Jenkins via a yaml file. If you are a first time user, you can learn more about JCasC ๐Ÿ‘ˆ

Hashicorp Plugin also adds an extension to JCasC by providing a Secret Source for Configuration as Code plugin to read secrets from, which you can read about here

Prerequisite:

Install Configuration as Code Plugin on your Jenkins instance.

Refer to Installing a new plugin in Jenkins.

Add configuration YAML:

There are multiple ways to load JCasC yaml file to configure Jenkins:

  • JCasC by default searches for a file with the name jenkins.yaml in $JENKINS_ROOT.

  • The JCasC looks for an environment variable CASC_JENKINS_CONFIG which contains the path for the configuration yaml file.

    • A path to a folder containing a set of config files e.g. /var/jenkins_home/casc_configs.

    • A full path to a single file e.g. /var/jenkins_home/casc_configs/jenkins.yaml.

    • A URL pointing to a file served on the web e.g. https://<your-domain>/jenkins.yaml.

  • You can also set the configuration yaml path in the UI. Go to <your-jenkins-domain>/configuration-as-code. Enter path or URL to jenkins.yaml and select Apply New Configuration.

To configure your Vault in Jenkins add the following to jenkins.yaml:

unclassified:
  hashicorpVault:
    configuration:
      vaultCredentialId: "vaultToken"
      vaultUrl: "https://vault.company.io"

credentials:
  system:
    domainCredentials:
      - credentials:
          - vaultTokenCredential:
              description: "Uber Token"
              id: "vaultToken"
              scope: GLOBAL
              token: "${MY_SECRET_TOKEN}"

See handling secrets section in JCasC documentation for better security.

You can also configure VaultGithubTokenCredential, VaultGCPCredential, VaultAppRoleCredential or VaultAwsIamCredential.

If you are unsure about how to do it from yaml. You can still use the UI to configure credentials.
After you configured Credentials and the Global Vault configuration.
you can use the export feature build into JCasC by visiting <your-jenkins-domain>/configuration-as-code/viewExport

HashiCorp Vault Plugin as a Secret Source for JCasC

We can provide these initial secrets for JCasC. The secret source for JCasC is configured via environment variables as way to get access to vault at startup and when configuring Jenkins instance.

For Security and compatibility considerations please read more here

  • The environment variable CASC_VAULT_PW must be present, if token is not used and appRole/Secret is not used. (Vault password.)
  • The environment variable CASC_VAULT_USER must be present, if token is not used and appRole/Secret is not used. (Vault username.)
  • The environment variable CASC_VAULT_APPROLE must be present, if token is not used and U/P not used. (Vault AppRole ID.)
  • The environment variable CASC_VAULT_APPROLE_SECRET must be present, if token is not used and U/P not used. (Vault AppRole Secret ID.)
  • The environment variable CASC_VAULT_KUBERNETES_ROLE must be present, if you want to use Kubernetes Service Account. (Vault Kubernetes Role.)
  • The environment variable CASC_VAULT_AWS_IAM_ROLE must be present, if you want to use AWS IAM authentiation. (Vault AWS IAM Role.)
  • The environment variable CASC_VAULT_AWS_IAM_SERVER_ID must be present when using AWS IAM authentication and the Vault auth method requires a value for the X-Vault-AWS-IAM-Server-ID header. (Vault AWS IAM Server ID.)
  • The environment variable CASC_VAULT_TOKEN must be present, if U/P is not used. (Vault token.)
  • The environment variable CASC_VAULT_PATHS must be present. (Comma separated vault key paths. For example, secret/jenkins,secret/admin.)
  • The environment variable CASC_VAULT_URL must be present. (Vault url, including port number.)
  • The environment variable CASC_VAULT_AGENT_ADDR is optional. It takes precedence over CASC_VAULT_URL and is used for connecting to a Vault Agent. See this section
  • The environment variable CASC_VAULT_MOUNT is optional. (Vault auth mount. For example, ldap or another username & password authentication type, defaults to userpass.)
  • The environment variable CASC_VAULT_NAMESPACE is optional. If used, sets the Vault namespace for Enterprise Vaults.
  • The environment variable CASC_VAULT_PREFIX_PATH is optional. If used, allows to use complex prefix paths (for example with KV secrets available at my/long/data/prefix/kv/secret1 set this to my/long/data/prefix/kv).
  • The environment variable CASC_VAULT_FILE is optional, provides a way for the other variables to be read from a file instead of environment variables.
  • The environment variable CASC_VAULT_ENGINE_VERSION is optional. If unset, your vault path is assumed to be using kv version 2. If your vault path uses engine version 1, set this variable to 1.
  • The issued token should have read access to vault path auth/token/lookup-self in order to determine its expiration time. JCasC will re-issue a token if its expiration is reached (except for CASC_VAULT_TOKEN).

If the environment variables CASC_VAULT_URL and CASC_VAULT_PATHS are present, JCasC will try to gather initial secrets from Vault. However for it to work properly there is a need for authentication by either the combination of CASC_VAULT_USER and CASC_VAULT_PW, a CASC_VAULT_TOKEN, the combination of CASC_VAULT_APPROLE and CASC_VAULT_APPROLE_SECRET, a CASC_VAULT_KUBERNETES_ROLE, or a CASC_VAULT_AWS_IAM_ROLE. The authenticated user must have at least read access.

You can also provide a CASC_VAULT_FILE environment variable where you load the secrets from a file.

File should be in a Java Properties format

CASC_VAULT_PW=PASSWORD
CASC_VAULT_USER=USER
CASC_VAULT_TOKEN=TOKEN
CASC_VAULT_PATHS=secret/jenkins/master,secret/admin
CASC_VAULT_URL=https://vault.dot.com
CASC_VAULT_MOUNT=ldap

A good use for CASC_VAULT_FILE would be together with docker secrets.

version: "3.6"

services:
  jenkins:
    environment:
      CASC_VAULT_FILE: /run/secrets/jcasc_vault
    restart: always
    build: .
    image: jenkins.master:v1.0
    ports:
      - 8080:8080
      - 50000:50000
    volumes:
      - jenkins-home:/var/jenkins_home
    secrets:
      - jcasc_vault

volumes:
  jenkins-home:

secrets:
  jcasc_vault:
    file: ./secrets/jcasc_vault

Example: HashiCorp Vault Plugin as a Secret Source for JCasC

Assume Vault has a secret at path secret/jenkins/passwords with keys secretKey1 and secretKey2. Set the value for environment variable CASC_VAULT_PATHS to secret/jenkins/passwords. The Hashicorp Vault Plugin provides two ways of accessing the secrets: using just the key within the secret and using the full path to the secret key. The full path option allows for you to reference multiple secrets with overlapping keys.

credentials:
  system:
    domainCredentials:
      - credentials:
          - string:
              description: "Secret using only secret key name"
              id: "secretUsingKey"
              scope: GLOBAL
              token: "${secretKey1}"
          - string:
              description: "Secret using full path"
              id: "secretUsingKey"
              scope: GLOBAL
              token: "${secret/jenkins/passwords/secretKey1}"

Vault Agent

For the use-case of Vault Agent read here

When CASC_VAULT_AGENT_ADDR is specified, you only need to specify CASC_VAULT_PATHS and optionally CASC_VAULT_ENGINE_VERSION
Since Vault Agent must be configured to handle auto authentication.

Here is an example of how to configure your Vault Agent with an app role. Vault Agent supports multiple auto-auth methods

pid_file = "/tmp/agent_pidfile"
auto_auth {
    method {
        type = "approle"
        config = {
            role_id_file_path = "/home/vault/role_id"
            secret_id_file_path = "/home/vault/secret_id"
        }
    }
    sink {
        type = "file"
        config = {
            path = "/tmp/file-foo"
        }
    }
}
cache {
    use_auto_auth_token = true
}
listener "tcp" {
    address = "0.0.0.0:8200"
    tls_disable = true
}

Ideally your Vault Agent should be running on the same Machine or running as a Container networked together.
You ought to block any connection to Vault Agent for anything that is not considered localhost.

For setup with Jenkins and Vault Agent running on the same host you can achieve this by using

listener "tcp" {
    address = "127.0.0.1:8200"
    tls_disable = true
}

For Containers you would need to use listener address of 0.0.0.0:8200.
You should never expose the Vault Agent port. You OUGHT to network Vault Agent container and Jenkins container together.

listener "tcp" {
    address = "0.0.0.0:8200"
    tls_disable = true
}

hashicorp-vault-plugin's People

Contributors

bablushaw23 avatar binlab avatar bluesliverx avatar cronik avatar dependabot[bot] avatar dineshba avatar ericcitaire avatar gotcha avatar jamesrobson-secondmind avatar jedidiahb avatar jetersen avatar jglick avatar karolkrawczyk avatar lukemonahan avatar marcoreni avatar markewaite avatar michaelsp avatar mtughan avatar netfalo avatar oleg-nenashev avatar ptierno avatar reamer avatar rnikoopour avatar schmitzhermes avatar seanmalloy avatar sethp-nr avatar sohamj avatar timja avatar tobilarscheid avatar vlatombe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hashicorp-vault-plugin's Issues

Skip SSL verification does not work even if it's checked from plugin configuration

Also I found a workaround; adding skipSslVerification property to pipeline configuration makes it work.

def secrets = [
[path: 'secret/windows', engineVersion: 1, secretValues: [
[envVar: 'pass', vaultKey: 'password']]],
[path: 'kvtest/user', engineVersion: 1, secretValues: [
[vaultKey: 'name']]]
]

def configuration = [vaultUrl: 'https://vault.company.com',
                     skipSslVerification: 'true',
                     vaultCredentialId: 'Vault',
                     engineVersion: 1]

withVault([configuration: configuration, vaultSecrets: secrets]) {
    sh 'echo $pass'
    sh 'echo $name'
}

support for nested json keys

Hi,

I have a json secret defined under 'secrets/mysecret'
The json looks like

{
    "mykey1": {
        "mykey2": "password"
    }
}

I tried to configure a withVault closure to get "mykey2"'s value but wasn't able to.
I was only able to get the root key "mykey1" - so this works:

def secrets = [
        [path: 'secret/mysecret', engineVersion: 2, secretValues: [
            [envVar: 'vaultpass', vaultKey: 'mykey1']
        ]]
    ]

But then I have to parse the Json to get the actual key I need.
If I replace vaultKey's value to mykey1.mykey2 it doesn't work.
I also tried json path syntax like $.mykey1.mykey2 and the likes.

The reason I have a nested json is due to different environments, but if this isn't supported I might have to switch to standard key-value pairs.

Thanks.

Kubernetes authentication not working

Hi, I have followed the documentation (even if it does not seem up to date) to use the Kubernetes authentication but I am having issues.

I have a simple job free style that is meant only to authenticate to Vault and expose one single key as env var.

I get

FATAL: could not log in into vault
com.bettercloud.vault.VaultException: Vault responded with HTTP status code: 403
Response body: error code: 1010
	at com.bettercloud.vault.api.Auth.loginByJwt(Auth.java:1045)
	at com.datapipe.jenkins.vault.credentials.VaultKubernetesCredential.getToken(VaultKubernetesCredential.java:60)
Caused: com.datapipe.jenkins.vault.exception.VaultPluginException: could not log in into vault
	at com.datapipe.jenkins.vault.credentials.VaultKubernetesCredential.getToken(VaultKubernetesCredential.java:63)
	at com.datapipe.jenkins.vault.credentials.AbstractVaultTokenCredential.authorizeWithVault(AbstractVaultTokenCredential.java:20)
	at com.datapipe.jenkins.vault.VaultAccessor.init(VaultAccessor.java:39)
	at com.datapipe.jenkins.vault.VaultBuildWrapper.provideEnvironmentVariablesFromVault(VaultBuildWrapper.java:154)
	at com.datapipe.jenkins.vault.VaultBuildWrapper.setUp(VaultBuildWrapper.java:98)
	at jenkins.tasks.SimpleBuildWrapper.setUp(SimpleBuildWrapper.java:146)
	at hudson.model.Build$BuildExecution.doRun(Build.java:157)
	at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:504)
	at hudson.model.Run.execute(Run.java:1880)
	at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
	at hudson.model.ResourceController.execute(ResourceController.java:97)
	at hudson.model.Executor.run(Executor.java:428)
Finished: FAILURE

and I have no idea what I am doing wrong.

I have a kubernetes service account named "jenkins", and I have created a policy named "jenkins" with the role "jenkins".
I use the k8s authentication for Vault, so the role has the service account "jenkins" and the namespace "jenkins" configured

  vault write auth/${CLUSTER_NAME_REGION}/role/jenkins \
    bound_service_account_names="jenkins" \
    bound_service_account_namespaces="jenkins" \
    policies="jenkins" \
    ttl="1h"

Please consider that if I test by running a pod with the "jenkins" service account inside of the "jenkins" namespace and they I try and login to Vault everything works as expected and I am able to get a token with the "jenkins" policy. This is the base setup of the entire infrastructure we have, and all of our pods are able to correctly authenticate with Vault and retrieve the secrets.

When I have created the credentials, I have put the value of CLUSTER_NAME_REGION as a "Mount Path", I think that part is correct. The role is also correct, as it's simply "jenkins".

Our Jenkins runs on Kubernetes, and both the master and any of the pods are run under the "jenkins" service account inside of the "jenkins" namespace.

Vault is version 1.2.4.

Could anyone tell me what am I doing wrong?

FolderVaultConfiguration not working

Yep

I have a problem configuring the plugin. I don't want a global configuration. In each project (cloudbees-folder) I would like to configure a credential (appRole) to access the Vault.
It doesn't seem to work

Different tests:
global configuration without url and credential (appRole)
Global configuration with url without credential (appRole)
Global configuration with url and identifier without rights

Capture dโ€™eฬcran 2020-10-09 aฬ€ 13 04 04
I would like to create the credentials for each project so that they can continue to use credential ID (to switch to vault) and / or substitute the old stored locally : no breakingchange in the pipeline which continues to use IDs
In project folder :
Capture dโ€™eฬcran 2020-10-09 aฬ€ 13 10 54

Only global configuration with url and credential (admin) works but projects inherit this configuration (which I don't want)
For all the tets, the plugin configuration is done in the project folder with the right url and the right credential
I can't find this behavior when using the plugin in a freestyle job
can you help me ?
Thank you

Unable to login using approle

I am able to use the vault cli and the rest api via curl to use a role id and secret id to get a token, I am also able to login using the token and get a secret. When I use the same role id and secret id with the vault jenkins plugin I get an error that the token is missing. I am running Jenkins 2.159, and Vault plugin version 3.3.0. Vault server version is 1.3.2

The configuration for the vault plugin contains my vault url which I can't disclose but is the same url I used successfully with the CLI. My credential is vault_tools_approle which I will detail below. The vault name space is blank. I have K/V engine version set to "2". I have fail on path unchecked, and I have skip ssl verification unchecked. My vault url is https. My time out is 60.

The vault credential contains the role id and secret id that I used during my tests with the rest api and the cli. The path is set to: v1/auth/app/prod/login
The id and and description are set to: vault_tools_approle

This is an example of the curl and CLI commands I used to get a token, login, and then get a secret which works. The role id, secret ID, and url are removed.

curl --request POST --data '{"role_id":"XXXXXX","secret_id":"XXXX"}' https://URL/v1/auth/app/prod/login

vault login TOKEN
vault kv get v1/ci/kv/maven/test

In my Jenkins file I have the following code. When I run this it will print "VAULT TEST 1", but does not print the "VAULT TEST 2" and fails. The error and stack trace are below.

   stage('Vault') {
        println("VAULT TEST 1")

        def secrets = [
          [path: 'v1/ci/kv/maven/test', secretValues: [
            [envVar: 'testUser', vaultKey: 'user'],
            [envVar: 'testPassword', vaultKey: 'password']]
          ]
        ]

        withVault([vaultSecrets: secrets]) {
          println("VAULT TEST 2")
          sh 'echo $testUser'
          sh 'echo $testPassword'
        }
    }
com.bettercloud.vault.VaultException: Vault responded with HTTP status code: 400
Response body: {"errors":["missing client token"]}

	at com.bettercloud.vault.api.Auth.loginByAppRole(Auth.java:524)
	at com.datapipe.jenkins.vault.credentials.VaultAppRoleCredential.getToken(VaultAppRoleCredential.java:54)
Caused: com.datapipe.jenkins.vault.exception.VaultPluginException: could not log in into vault
	at com.datapipe.jenkins.vault.credentials.VaultAppRoleCredential.getToken(VaultAppRoleCredential.java:57)
	at com.datapipe.jenkins.vault.credentials.AbstractVaultTokenCredential.authorizeWithVault(AbstractVaultTokenCredential.java:20)
	at com.datapipe.jenkins.vault.VaultAccessor.init(VaultAccessor.java:39)
	at com.datapipe.jenkins.vault.VaultBuildWrapper.provideEnvironmentVariablesFromVault(VaultBuildWrapper.java:148)
	at com.datapipe.jenkins.vault.VaultBuildWrapper.setUp(VaultBuildWrapper.java:95)
	at org.jenkinsci.plugins.workflow.steps.CoreWrapperStep$Execution2.doStart(CoreWrapperStep.java:97)
	at org.jenkinsci.plugins.workflow.steps.GeneralNonBlockingStepExecution.lambda$run$0(GeneralNonBlockingStepExecution.java:77)
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at java.lang.Thread.run(Thread.java:748)

Read secrets from vault path gives access denied

Hello
I am being able to read secrets from our vault using the generated vault token in vault secret api command. But jenkins throws Access denied for the same token configured through both "Vault token file credential" and "Vault token credential". I've tried using both freestyle and pipeline script to execute this and both gives the same "Access Denied" error.
The token field is empty when i try to update the credential and i always see it as empty even after i paste the token and click on save. Usually passwords in other credentials types are shown as concealed in latest version of jenkins. My jenkins version is 2.255 and vault plugin version is 3.6.1. The secret path is exactly same as what i used in my api command. (secret/).

image
image

I've also created a custom log for vault using the debugger line "com.datapipe.jenkins.vault" but that show no logs related to the execution. How can i debug this?

Secrets not masked in build logs

Using version 3.1.1 of this plugin on Jenkins version 2.204.2 I'm seeing that the secrets loaded from our vault instance are not being masked as other credential providers do and I'm lead to believe by the first paragraph of the README.md.

Here's my sample config for loading the secrets:

def secrets = [
    [$class: 'VaultSecret', path: 'secret/my/path-1', secretValues: [
        [$class: 'VaultSecretValue', envVar: 'testing', vaultKey: 'value']]],
    [$class: 'VaultSecret', path: 'secret/my/path-2', secretValues: [
        [$class: 'VaultSecretValue', envVar: 'another_test', vaultKey: 'yaml']]]
]

# Try using wrap
wrap([$class: 'VaultBuildWrapper', vaultSecrets: secrets]) {
    sh 'echo $testing'
    sh 'echo $another_test'
}

# Try using withVault
withVault([vaultSecrets: secrets]) {
    sh 'echo $testing'
    sh 'echo $another_test'
} 

In both cases I get the full secret output to the console when I would expect to see only ****.

Is this a known issue? Or I am doing it wrong?

Access denied to Vault Secrets at 'path'

Hi

Our team has been using Vault Engine Version 1 so far where the path was /generic/project/replication and that worked fine with Jenkins plugin withVault.

However, we recently enabled Version 2 for our project, so we have access to /project/replication.

vault kv put project/replication/test key=value
vault kv get project/replication/test 

key=value

The above works fine with a role_id and secret_id. But when I use the same credentials for Jenkins plugin I get Access denied to Vault Secrets at 'project/replication/test'

Here's the withVault method:

withVault(
  configuration: [timeout: 60, vaultCredentialId: 'vault-test-approle',
  vaultUrl: '<ur>',
  engineVersion: 2], 
  vaultSecrets: [[path: 'project/replication/test',
  secretValues: [[vaultKey: 'apikey']]]])

Any idea ? Is Jenkins not supposed with work with Vault Version 2 ?

Thanks.

Feature Request: Support environment+credentials syntax

As the community moves away from scripted pipelines to purely declarative solutions, I'm wondering if it would be possible to implement a method/step similar to credentials that could be used in an environment block. As I migrate pipelines referencing Jenkins credentials to use Vault secrets instead I've bumped into a few script quirks (like variable scoping) that could avoided all together with a one to one replacement of the environment+credentials experience.

Thank you!

Jenkins credentials example:

environment {
    AWS_ACCESS_KEY_ID = credentials('jenkins-aws-secret-key-id')
    AWS_SECRET_ACCESS_KEY = credentials('jenkins-aws-secret-access-key')
}

Proposal (Perhaps support global and folder defaults for VaultAddr, etc):

environment {
    SOME_ENV_VAR = vaultCredentials('secret/foo/bar/secretName/key', 'vaultCredentialId', 'https://vault.com:8200')
}

save vault secret to file

Hello,

configuration-as-code:1.44
hashicorp-vault:3.6.1

I've a 'special' case. Gerrit plugins looks for a ssh key in a file system. Is there a way to extract it from the vault and save to file when jenkins starts in jcasc mode?

Unit tests fail when trying to upgrade from Jenkin.version 2.164.3 to 2.235.5

Dear all,
the main branch of the plugin usese Jenkins.version=2.164.3 however some of the unit tests rely on features discontinued since Jenkin.version=2.220 (thanks Tobias Gruetzmaker for the hint.). This morning I therefore tried upgrading to later versions. Before reaching the latest (2.263) I tried an intermediate value: 2.235.5 (by simply changing the value of the jenkin.version in the pom.xml of the plugin) . Build goes fine, however when it goes to the unit testing many of them throw errors.
junitstdout.txt

Access denied to Vault Secrets at 'path/to/secret'

I have tried numerous things to get this working and it simply doesn't. I verified the user does have access to the secret and can list it.

I'm guessing I'm simply doing something wrong.

Failing pipeline:

def secrets = [
    [path: 'path/to/dev']
]

pipeline {
   agent any

   stages {
      stage('vault') {
         steps {
            // inside this block your credentials will be available as env variables
            withVault([vaultSecrets: secrets]) {
                sh 'env'
            }
         }
      }
   }
}

This results in Access denied to Vault Secrets at 'path/to/dev'

I tried wrapping withVault as well:

def secrets = [
    [path: 'path/to/dev']
]

pipeline {
   agent any

   stages {
      stage('vault') {
         steps {
            withCredentials([[$class: 'VaultTokenCredentialBinding', credentialsId: 'jenkins_token', vaultAddr: 'https://vault.url.here']]) {
                // values will be masked
                sh 'echo TOKEN=$VAULT_TOKEN'
                sh 'echo ADDR=$VAULT_ADDR'
                
                withVault([configuration: [vaultUrl: VAULT_ADDR, vaultCredentialId: 'jenkins_token', engineVersion: 2], vaultSecrets: secrets]) {
                    sh 'env'
                }
            }
         }
      }
   }
}

No matter what I do...it fails:

Masking supported pattern matches of $VAULT_ADDR or $VAULT_TOKEN or $VAULT_NAMESPACE
[Pipeline] {
[Pipeline] sh
+ echo 'TOKEN=****'
TOKEN=****
[Pipeline] sh
+ echo 'ADDR=****'
ADDR=****
[Pipeline] wrap
Access denied to Vault Secrets at 'path/to/dev'

com.datapipe.jenkins.vault.credentials.common.Vault Username Password Credential Impl getVaultSecret WARNING: Cannot retrieve secret becuase Jenkins.instance is not available

I want to do multi branch checkout using hashicorp vault secrets.

I have created credentials in Jenkins credentials store using the option vault username and password. Using that credentials id my checkout working fine in master nodes. But when my job running in slave it fails with below log.

com.datapipe.jenkins.vault.credentials.common.Vault Username Password Credential Impl getVaultSecret
WARNING: Cannot retrieve secret becuase Jenkins.instance is not available

I assume Jenkins.instance value only available in master node. As this value not available in slave nodes jobs are not able fetch the credentials. This bug have to be fixed.

Or else provide solutions to achieve my requirements.

Revoking LeaseId's via the Disposer

I've noticed that secrets provisioned on the dynamic engine (eg. GCP) no longer get revoked when a pipeline is finished with them (exits the withVault block), and instead the generated key within the serviceAccount remains active until its TTL expires. This is problematic, since GCP has a limit of 10 keys per svcAcc, so revoking these leases is important as soon as the requester is done with them.

Between tags hashicorp-vault-plugin-2.2.0 &hashicorp-vault-plugin-3.0.0, the VaultDisposer is no longer setup/used, and im struggling to find amongst commit comments why that was? I see some references to "auto-auth" in some comments surrounding when this happened in gitlogs, but unsure what thats referencing (possibly some auto revoking feature in kv engine V2?), since lease's no longer seem to be explicitly revoked in the plugin ....

For reference, we are still using secrets engine V1

Disposer being set in 2.2: https://github.com/jenkinsci/hashicorp-vault-plugin/blob/hashicorp-vault-plugin-2.2.0/src/main/java/com/datapipe/jenkins/vault/VaultBuildWrapper.java#L92

KV v2 credentials wrong path

Hi,

I have kv v2 credential defined with a namespace in the path which jenkins can't seem to be able to access.
Upon inspection I can see that it is trying to get the secret from wrong path. It's adding adding data in wrong place in the URL.

Secret path: my-namespace/kv/jenkins/common/github

I can see in vault logs that it tries to hit /v1/my-namespace/data/kv/jenkins/common/github where correct path should be /v1/my-namespace/kv/data/jenkins/common/github
In order to get kv v2 secrets, data should be included in the path right after kv eg.:
/v1//kv/data/<your_secret>

Accessing kv v1 secrets with namespace in the path works fine.

[QUESTION] Different Vaults in one job

Usecase: a Jenkins job requires to read secrets from different namespaces. For each Vault namespace, I setup Jenkins AppRole. The generated role_id and secret_id I store in Jenkins Credentials store. But I can only select/use one Vault credential per job. (the Vault Credential dropdown).

Is there a way/workaround to use multiple Vault Credentials per one Jenkins job?

Vault Plugin global level

I have Jenkins running on macOS for testing and on a windows server, I'm having an issue getting the hashicorp plugin on the windows server to provide the vault options under x.x.x.x/configure/Vault Plugin when I go to add the token I do not see the vault options compared to the doc and macOS device. Am I missing a setting?

mac device:
Screen Shot 2020-05-26 at 9 40 57 PM

windows device:
Screen Shot 2020-05-26 at 9 42 22 PM

Vault credentials not found for <path>

Can somebody help me plz? @Casz

=======
Versions:

- Jenkins: 2.217
- Plugin: 3.1.1
- Vault: 1.3.2

=======
Code:

    def secrets = [
    [path: 'secret/data/jenkins', secretValues: [
        [vaultKey: 'ad_pass']]]
    ]

    def vaultConfiguration = [vaultUrl: 'https://vault.some.nda.domain/',
            vaultCredentialId: 'admin-vault-token', skipSslVerification: true, engineVersion: 2]
    withVault([configuration: vaultConfiguration, vaultSecrets: secrets]){
        docker.withRegistry('https://some.docker.registry','ad_pass') {
            sh 'echo $ad_pass'
            // sh """
            //     make build-cloud
            // """
        }
    }

=======
In vault I tried different level disposition of creds (like secret/jenkins/ad_pass or jenkins/ad_pass). But in all cases I have this error:

com.datapipe.jenkins.vault.exception.VaultPluginException: Vault credentials not found for 'secret/data/jenkins'
	at com.datapipe.jenkins.vault.VaultBuildWrapper.responseHasErrors(VaultBuildWrapper.java:192)
	at com.datapipe.jenkins.vault.VaultBuildWrapper.provideEnvironmentVariablesFromVault(VaultBuildWrapper.java:154)
	at com.datapipe.jenkins.vault.VaultBuildWrapper.setUp(VaultBuildWrapper.java:95)
	at org.jenkinsci.plugins.workflow.steps.CoreWrapperStep$Execution2.doStart(CoreWrapperStep.java:97)
	at org.jenkinsci.plugins.workflow.steps.GeneralNonBlockingStepExecution.lambda$run$0(GeneralNonBlockingStepExecution.java:77)
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at java.lang.Thread.run(Thread.java:748)

Support addressing Vault keys by path

Feature Request

Support for Vault is very welcomed. One thing that we noticed early on is that we can manage all of our credentials this way, and not just stuff that Jenkins needs on startup.

The problem is that, even if you can add multiple Vault paths, you cannot have duplicate keys. This leads to the need of duplicating secrets in Vault.

Here's an example: we have many Azure accounts that require 4 values each for auth. The Vault way would be to have one path for each account: kv/azure/dev/, kv/azure/stage/ and kv/azure/prod/. Each of these paths would have the same keys: client_id, subscription, secret_key, tenant_id.

This makes sense in Vault, but can't be used in CasC.

I propose to address secrets in yaml files by the full Vault path. e.g. instead of ${client_id} you could call ${kv/azure/dev/client_id}.

Parsing the yaml files for paths and resolving secrets seems too involved. This is why this should replace the existing functionality. Vault paths should still be provided at startup. Retrieving them should change: instead of merging the arrays together, each path should be its own array. This would allow for duplicate key names, and would not radically change the current code.

Any documentation out there on using Vault AppRole with AWS ?

We can't seem to get the integration working. We're using Vault and approle on AWS. We have provisioned a roleid and secret. And we're getting errors such as:

Retrieving secret: aws-dev/creds/jenkins
Access denied to Vault Secrets at 'aws/creds/jenkins'

Wondering if someone has a working example, along with all the steps to make it work.

write secrets in vault

Dear all,
I am now able to get keys from vault, however what if I would like to write back into it using Jenkins ?
Could that be done with this plugin or shuold it be extended ?
Thanks and congrats.

java.lang.NullPointerException at com.datapipe.jenkins.vault.VaultBuildWrapper.provideEnvironmentVariablesFromVault(VaultBuildWrapper.java:139)

Earlier this week we updated our Jenkins server to 2.204.2 and the Hashicorp Vault Plugin from 2.5.0 to 3.1.1. Now triggered jobs (github push/PR, timer, triggered from other jobs) using the Vault Plugin are giving the following error,

FATAL: nulljava.lang.NullPointerException
at com.datapipe.jenkins.vault.VaultBuildWrapper.provideEnvironmentVariablesFromVault(VaultBuildWrapper.java:139)
at com.datapipe.jenkins.vault.VaultBuildWrapper.setUp(VaultBuildWrapper.java:94)
at jenkins.tasks.SimpleBuildWrapper.setUp(SimpleBuildWrapper.java:146)
at hudson.model.Build$BuildExecution.doRun(Build.java:157)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:504)
at hudson.model.Run.execute(Run.java:1853)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:427) 

We've rolledback the plugin to 2.5.0 but it still occurs. Verified the Global jenkins-plugin is set to KV Engine Version 1, and all the jobs are set to 1 as well. Vault server version is 1.0.2 and KV 2 is not enabled.

Running or re-building a job manually will not have this error. I added a comment to previous issue in the Jenkins Jira on a related bug as well.

Other information:

  • Jenkins Master OS: Ubuntu 18.04.4
  • Jenkins Version: 2.204.2
  • Vault Plugin Version: 2.5.0 and 3.1.1
  • Java version: OpenJDK Runtime Environment (build 1.8.0_242-8u242-b08-0ubuntu3~18.04-b08)
  • Vault Server version: 1.0.2
  • Jenkins jobs all run on remote jenkins agents using swarm plugin version 3.18 and Java 1.8.0-8u242 on Ubuntu 18.04.4

Does not respect No Proxy Host

It looks like the plugin is not respecting the No Proxy Host settings in the Plugin Manager. So when I try to use the plugin I always hit our proxy.

From the log

com.bettercloud.vault.VaultException: Vault responded with HTTP status code: 403
Response body: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<!-- FileName: index.html

The rest of the log is our proxy saying that the URL is blocked.

Unable to retrieve secrets on pipeline

Hi @tandibar @lucaspanjer @cris @cowboyd @vbehar ! I need to retrieve secrets from search engines such as openldap or AWS while executing a pipeline job in Jenkins, but I'm unable to do so. I can only retrieve values from a kv engine. It kind of confuses me about the purpose of this plugin if only static values are retrieved. Am I doing something wrong? Can anybody assist? It's been a few days already trying to map those paths, even with the root token and no luck

Issue with using certificate as env variable in freestyle pipeline from vault

Hi! i'm trying load certificate from vault into pipeline and faced with issue:

ERROR: Build step failed with exception
Also:   hudson.remoting.Channel$CallSiteStackTrace: Remote call to JNLP4-connect connection from 100.109.0.0/100.109.0.0:43828
		at hudson.remoting.Channel.attachCallSiteStackTrace(Channel.java:1788)
		at hudson.remoting.UserRequest$ExceptionResponse.retrieve(UserRequest.java:356)
		at hudson.remoting.Channel.call(Channel.java:998)
		at hudson.Launcher$RemoteLauncher.launch(Launcher.java:1057)
		at hudson.Launcher$ProcStarter.start(Launcher.java:454)
		at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:109)
		at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:66)
		at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
		at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:741)
		at hudson.model.Build$BuildExecution.build(Build.java:206)
		at hudson.model.Build$BuildExecution.doRun(Build.java:163)
		at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:504)
		at hudson.model.Run.execute(Run.java:1880)
		at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
		at hudson.model.ResourceController.execute(ResourceController.java:97)
		at hudson.model.Executor.run(Executor.java:428)
java.lang.IllegalArgumentException: Invalid environment variable value: "blablabla my certificate content.... 
at java.lang.ProcessEnvironment.validateValue(ProcessEnvironment.java:121)
	at java.lang.ProcessEnvironment.access$400(ProcessEnvironment.java:61)
	at java.lang.ProcessEnvironment$Value.valueOf(ProcessEnvironment.java:203)
	at java.lang.ProcessEnvironment$StringEnvironment.put(ProcessEnvironment.java:243)
	at java.lang.ProcessEnvironment$StringEnvironment.put(ProcessEnvironment.java:221)
	at hudson.Proc$LocalProc.environment(Proc.java:237)
	at hudson.Proc$LocalProc.<init>(Proc.java:222)
	at hudson.Launcher$LocalLauncher.launch(Launcher.java:936)
	at hudson.Launcher$ProcStarter.start(Launcher.java:454)
	at hudson.Launcher$RemoteLaunchCallable.call(Launcher.java:1316)
	at hudson.Launcher$RemoteLaunchCallable.call(Launcher.java:1269)
	at hudson.remoting.UserRequest.perform(UserRequest.java:211)
	at hudson.remoting.UserRequest.perform(UserRequest.java:54)
	at hudson.remoting.Request$2.run(Request.java:369)
	at hudson.remoting.InterceptingExecutorService$1.call(InterceptingExecutorService.java:72)
	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at hudson.remoting.Engine$1.lambda$newThread$0(Engine.java:117)
	at java.lang.Thread.run(Thread.java:748)

Jenkins - "2.235.2"
hashicorp-vault-plugin:3.6.0 (on lower versions the same error)
kubernetes:1.26.3
credentials:2.3.12

Would really appreciate any help
Thank you

Creating VaultAppRoleCredential with jenkins-dsl

I am trying to create a VaultAppRoleCredential and attach it to the properties of a folder during creation via jenkins-dsl. The folder, the FolderCredentialProperty and the DomainCredential all are being created just fine. When I get to actually creating the VaultAppRoleCredential to attach it I end up getting a method signature exception on type Secret secretId.

I am correctly importing hudson.util.Secret and using the fromString method to create a secret to assign to secretId, however, I am still getting: No signature of method: javaposse.jobdsl.plugin.structs.DescribableContext.secretId() is applicable for argument types: (hudson.util.Secret)

The job-dsl describable context helper is correctly finding VaultAppRoleCredential and correctly returning the constructor as: public com.datapipe.jenkins.vault.credentials.VaultAppRoleCredential(com.cloudbees.plugins.credentials.CredentialsScope,java.lang.String,java.lang.String,java.lang.String,hudson.util.Secret,java.lang.String)

This has been super confusing to me as I am handing it exactly what it expects. After logs of debugging I think I may have found the issue. Further through the context building when job-dsl tries to, I guess for a lack of a better word, resolve, the constructor types it ends up displaying this: VaultAppRoleCredential(scope: CredentialsScope[SYSTEM, GLOBAL, USER], id: String, description: String, roleId: String, secretId: org.kohsuke.stapler.NoStaplerConstructorException: There's no @DataBoundConstructor on any constructor of class hudson.util.Secret, path: String)

At this point it appears to set the value type of secretId to an ErrorType instead of a hudson.util.Secret type, resulting in the method signature error I ultimately end up receiving.

Is there any insight on how to resolve this issue with the DataBoundConstructor?

Version information:
Jenkins: 2.190.2
Folders Plugin: 6.10.1
Credentials Plugin: 2.3.0
Hashicorp Vault Plugin : 3.0.0
Jenkins Job-DSL Plugin: 1.76

secret engine "/" can't be encode if use engine version 2.

If there is a slash "/" in secret engine in engine version 2, it can not be encode correctly. we need to encode it manually in Jenkinsfile.

e.g.:

If the secret engine is secret/test. If we use secret/test/somesecret in Jenkinsfile, it will failed with "access denied."
we need to set the engine to secret%2Ftest, the the plugin can visit secret/test/somesecret.

IllegalArgumentException with version 3.x

We were using v2.5.0 together with hashicorp-vault-pipeline-plugin v1.3 in a declarative pipeline and this has worked for several months. After updating to v3.1.0 (and moving back to v3.0.0) we are getting this stacktrace:

java.lang.IllegalArgumentException: One or more variables have some issues with their values: SECRET
	at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.withEnvBlock(ModelInterpreter.groovy:436)
	at com.cloudbees.groovy.cps.CpsDefaultGroovyMethods.callClosureForMapEntry(CpsDefaultGroovyMethods:5226)
	at com.cloudbees.groovy.cps.CpsDefaultGroovyMethods.collect(CpsDefaultGroovyMethods:3446)
	at com.cloudbees.groovy.cps.CpsDefaultGroovyMethods.collect(CpsDefaultGroovyMethods:3463)
	at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.withEnvBlock(ModelInterpreter.groovy:432)
	at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.call(ModelInterpreter.groovy:81)
	at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.withCredentialsBlock(ModelInterpreter.groovy:484)
	at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.withCredentialsBlock(ModelInterpreter.groovy:483)
	at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.call(ModelInterpreter.groovy:80)
	at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.inDeclarativeAgent(ModelInterpreter.groovy:592)
	at org.jenkinsci.plugins.pipeline.modeldefinition.agent.CheckoutScript.checkoutAndRun(CheckoutScript.groovy:61)
...

The declarative pipeline looks like this:

pipeline {
    agent { ... }
    environment {
        SECRET = vault path: 'path', key: 'key', credentialsId: 'credentials', engineVersion: "1"
    }
    stages { ... }
}

Since the hashicorp-vault-pipeline-plugin hasn't changed and has been stable for a while, i guess it's this plugin what's causing the issue. Maybe there is some parameter missing that's required now?

Token file credential java.io.FileNotFoundException

Hi - when running the following pipeline on a worker node, the following exception occurs:

`node {
    def secrets = [
        [path: 'my-path/dev/searches/users/admin', engineVersion: 1, secretValues: [
            [envVar: 'PASSWORD', vaultKey: 'admin.password']]
        ]
    ]

    def configuration = [vaultUrl: 'https://my-vault.com:8200/',
                         vaultCredentialId: 'vault',
                         engineVersion: 1]

    withVault([configuration: configuration, vaultSecrets: secrets]) {
        sh 'echo $PASSWORD'
    }
}`
`java.io.FileNotFoundException: File '/home/ec2-user/.vault-token' does not exist
	at org.apache.commons.io.FileUtils.openInputStream(FileUtils.java:297)
	at org.apache.commons.io.FileUtils.readFileToS`

The "vault" token file credential has been created and exists, yet the withVault plugin can't source it.

Any ideas?

Accessing vault secret with full path

Hi,

The documentation is still up-to-date about this feature?

With hashicorp vault plugin version 2.5.0 and Jenkins 2.235.3 it seems to not be working anymore.

If I'm using this form:

credentials:
system:
domainCredentials:
- credentials:
- string:
description: "Secret using only secret key name"
id: "secretUsingKey"
scope: GLOBAL
token: "${secretKey1}"

No issues so far but with the second one:

credentials:
system:
domainCredentials:
- credentials:
- string:
description: "Secret using full path"
id: "secretUsingKey"
scope: GLOBAL
token: "${secret/jenkins/passwords/secretKey1}"

To no avail so far, is anybody is using the second form and can help me ? secret and key are valid.

If more information is needed feel free to ask me.

Regards,

service account name not authorized

I am getting the following error when using the kubernetes auth method in the plugin.
So I configured kubernetes method in vault and added role with service account. And i set the role in the vault kubernetes credentials.
I created a build pod with that specific service account.
Also, it's working when I use vault API calls instead of the plugin, with same service account token from within pod and same role. I am not sure what the problem is with the plugin.
Can someone please look at this issue.

Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] stage
[Pipeline] { (vault-test)
[Pipeline] podTemplate
[Pipeline] {
[Pipeline] node
Still waiting to schedule task
Waiting for next available executor
Created Pod: vault-k8s-test-55-qzvgb-n88hm-ds27s in namespace default
Agent vault-k8s-test-55-qzvgb-n88hm-ds27s is provisioned from template vault-k8s-test_55-qzvgb-n88hm
---
apiVersion: "v1"
kind: "Pod"
metadata:
  annotations:
    buildUrl: "http://jenkins:8080/job/vault-k8s-test/55/"
    runUrl: "job/vault-k8s-test/55/"
  labels:
    jenkins/jenkins-jenkins-slave: "true"
    jenkins/label: "vault-k8s-test_55-qzvgb"
  name: "vault-k8s-test-55-qzvgb-n88hm-ds27s"
spec:
  containers:
  - image: "alpine:3.7"
    name: "tmp"
    resources:
      limits:
        cpu: "2"
        memory: "4Gi"
      requests:
        cpu: "200m"
        memory: "256Mi"
    tty: true
    volumeMounts:
    - mountPath: "/home/jenkins/agent"
      name: "workspace-volume"
      readOnly: false
  - env:
    - name: "JENKINS_SECRET"
      value: "********"
    - name: "JENKINS_TUNNEL"
      value: "jenkins-agent:50000"
    - name: "JENKINS_AGENT_NAME"
      value: "vault-k8s-test-55-qzvgb-n88hm-ds27s"
    - name: "JENKINS_NAME"
      value: "vault-k8s-test-55-qzvgb-n88hm-ds27s"
    - name: "JENKINS_AGENT_WORKDIR"
      value: "/home/jenkins/agent"
    - name: "JENKINS_URL"
      value: "http://jenkins:8080/"
    image: "jenkins/jnlp-slave:3.35-5-alpine"
    name: "jnlp"
    volumeMounts:
    - mountPath: "/home/jenkins/agent"
      name: "workspace-volume"
      readOnly: false
  nodeSelector:
    beta.kubernetes.io/os: "linux"
  restartPolicy: "Never"
  securityContext: {}
  serviceAccountName: "vaultauth"
  volumes:
  - emptyDir:
      medium: ""
    name: "workspace-volume"

Running on vault-k8s-test-55-qzvgb-n88hm-ds27s in /home/jenkins/agent/workspace/vault-k8s-test
[Pipeline] {
[Pipeline] container
[Pipeline] {
[Pipeline] withVault
[Pipeline] // withVault
[Pipeline] }
[Pipeline] // container
[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // podTemplate
[Pipeline] }
[Pipeline] // stage
[Pipeline] End of Pipeline
com.bettercloud.vault.VaultException: Vault responded with HTTP status code: 500
Response body: {"errors":["service account name not authorized"]}

	at com.bettercloud.vault.api.Auth.loginByJwt(Auth.java:1045)
	at com.datapipe.jenkins.vault.credentials.VaultKubernetesCredential.getToken(VaultKubernetesCredential.java:59)
Caused: com.datapipe.jenkins.vault.exception.VaultPluginException: could not log in into vault
	at com.datapipe.jenkins.vault.credentials.VaultKubernetesCredential.getToken(VaultKubernetesCredential.java:62)
	at com.datapipe.jenkins.vault.credentials.AbstractVaultTokenCredential.authorizeWithVault(AbstractVaultTokenCredential.java:20)
	at com.datapipe.jenkins.vault.VaultAccessor.init(VaultAccessor.java:39)
	at com.datapipe.jenkins.vault.VaultBuildWrapper.provideEnvironmentVariablesFromVault(VaultBuildWrapper.java:147)
	at com.datapipe.jenkins.vault.VaultBuildWrapper.setUp(VaultBuildWrapper.java:95)
	at org.jenkinsci.plugins.workflow.steps.CoreWrapperStep$Execution2.doStart(CoreWrapperStep.java:97)
	at org.jenkinsci.plugins.workflow.steps.GeneralNonBlockingStepExecution.lambda$run$0(GeneralNonBlockingStepExecution.java:77)
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at java.lang.Thread.run(Thread.java:748)
Finished: FAILURE

Build continues when access is denied

Using version 3.1.1 of the plugin and a withVault block in a Jenkinsfile pipeline, the build just continues on if access is denied:

...
[Pipeline] withVault
10:14:19 Access denied to Vault Secrets at 'secret/<path>'
[Pipeline] {
[Pipeline] properties
[Pipeline] stage
...

I find it extremely difficult to think of a case where ignoring this (fatal) error is what users would expect, or a case where not having expected secrets present will allow a build to continue as expected. We had multiple builds produce broken results until we found this line in the output.

Would it be possible to either fix this so that access denied errors result in a build failure, or add a global configuration option to make that happen? We have hundreds of pipelines using this plugin (once again, thanks so much for this!!!) and would really like to make sure they all act as we'd expected.

Store the token in a field instead of getting a new one each time in VaultAppRoleCredential

Hi,

in the VaultAppRoleCredential, the getToken() method retrieves a new token each time it is called, by consuming roleId and secretId. (

)
The problem is when we use a single-use and short-lived SecretID, we have to regenerate a new SecretId each time we want to access Vault (eg: each time we call withVault() with the same VaultAppRoleCredential in jenkins pipeline, we have to create a new VaultAppRoleCredential before).
Is there any way to store the token somewhere in the VaultAppRoleCredential once it is populated so that the token can be reused, or is the current fashion to retrieve an auth token, the correct and only behavior we should have ?

Thanks

extracting id_rsa extraction problem

Hi
When i extract from vault ssh at Jcasc step i get '\n' marks instead of new line in my ssh key. This couse a problem becouse jenkins throws 'invalid format' exception. Any idea how to by pass this?

credentials:
  system:
    domainCredentials:
      - credentials:
        - basicSSHUserPrivateKey:
            scope: GLOBAL
            id: ${USER}-ssh_key
            username: ${USER}
            passphrase: ""
            description: "SSH ${USER}"
            privateKeySource:
              directEntry:
                privateKey: `"${secret/jenkins/id_rsa}"

Feature Request: Azure Secrets

Add ability to generate dynamic credentials to use in build step

node {
    def secrets = [
        [path: 'azure/creds/myazurerole', engineVersion: azure, secretValues: [
            [client_id: 'myID', client_secret: 'mySecret'],
           ]],
    ]

    def configuration = [vaultUrl: 'http://my-very-other-vault-url.com',
                         vaultCredentialId: 'my-vault-cred-id',
                         engineVersion: azure]
    // inside this block your credentials will be available as env variables
    withVault([configuration: configuration, vaultSecrets: secrets]) {
        sh 'az login --service-principal -u ${env.myID} -p ${env.mySecret} --tenant 202020200202
    }
}

UI Field missing for prefixPath in GlobalConfig

Good day,

we use a non-default secrets mount point in Vault and so need to set prefixPath. There is no problem if JCasc is used, but there seems to be no corresponding UI field in "Manage Jenkins", so my guess would be, one just need to add it to ../VaultConfiguration/config.jelly ?

Jenkins Version: 2.239
Plugin Version: 3.4.1

prefixPath : Generalization to other usages and Secret Parameter configuration

Hello,

Thanks to #67 we can (finally !) request secrets from non-at-root mounted KVs. And that's great ! ๐Ÿ‘

Now we can do this in a scripted pipeline :

def secrets = [
    [path: 'test/nonrootkv/secret', secretValues: [[envVar: 'result', vaultKey: 'secretkey']]]
]

def configuration = [
    vaultUrl: 'https://vault.example.com',
    prefixPath: 'test/nonrootkv/',
    vaultCredentialId: 'credentialID'
]

pipeline {
    agent {
        node {
            label 'default'
        }
    }
    stages {
        stage('Test get Secret'){
            steps {
                script {
                    withVault([configuration: configuration, vaultSecrets: secrets]) {
                        sh 'if [ -n "${result}" ]; then echo "variable is defined" && echo "test${result}"; else exit 1 ; fi'
                    }
                }
            }
        }
    }
}

However :

  • This isn't documented in the README.md
  • It would be nice to enable the prefixPath parameterization at many levels. On the top of my head I think about non-at-root mounted authentication endpoints. This would enable tidying of users' Vault mount points rather than requiring them to have everything mounted at the Vault root.
  • The Vault Secret UI config parameter does not enable a user to set a prefixPath for a non-root KV (and fails to read such secrets) :
    vault_secret

Kind regards

var/run/secrets/kubernetes.io/serviceaccount/token: No such file or directory

I have Jenkins set up in such a way that master runs in local and its slaves are run as pods in k8s. Vault is also running in the same k8 setup. When I try using the Kubernetes auth method in Jenkins plugin, it returns "var/run/secrets/kubernetes.io/serviceaccount/token: No such file or directory ". I printed the token using sh "cat var/run/secrets/kubernetes.io/serviceaccount/token", in Jenkins build itself to make sure the file is present. I was able to see the printed jwt token, but i am not sure why the plugin could'nt get the token.

folder-scoped approle is not utilized when retrieving folder-scoped credentials

Observed:
When a folder is configured to use a specific approle (different from the globally configured approle) the credentials which are also scoped to the folder (used for SCM checkout) are retrieved through the global approle instead of the one which the folder is configured to use.

To reproduce:

  1. Create a new folder in jenkins with approle credential inside this folder along with vault credentials (e.g. vault string credential)
  2. Configure folder property to use this new approle (and not the global approle)
  3. Create new pipeline (with bitbucket/github scm) which uses vault credentials + approle from this folder
  4. Observe error (such as: FAILED to retrieve username key: java.lang.RuntimeException: com.datapipe.jenkins.vault.exception.VaultPluginException: Key folder_specific_key could not be found in path secret/folder/credentials

This seems to prevent the ability to use per-folder approle / credentials for pipeline checkouts.

vaultAppRoleCredential is not available in the folder DSL

following the guidelines in the readme

Hashicorp recommends using AppRole for Servers / automated workflows (like Jenkins) and using Tokens (default mechanism, Github Token, ...) for every developer's machine

We wanted to have a configuration in which Jenkins has several approle tokens that are configured on the folder level such that each folder (assigned to a team) only has access to their specific token.

Unfortunately it seems that somehow the vaultAppRoleCredential is not available in the folder dsl. See image below.

However, it is possible to configure it through Jenkins UI and the corresponding xml configuration reflects that.

In order to fulfill the usecase above, we ended up configuring the xml manually to include the vaultAppRoleCrededential.

I would be happy to contribute and help out here provided there is some guidance on how to proceed since I have never modified a jenkins plugin myself.

Hope it helps

hashicorp-vault-plugin | 3.4.1

Screenshot 2020-05-15 at 11 50 26

Secret with empty values garbles logs

Hello,

We are using this plugin extensively, so first of all thank you for the great work!

We have noticed that when a referenced Vault secret key contains an empty value, the entire log is filled with ****.

For example, the SUCCESS message will be shown as ****S****U****C****C****E****S****.

We believe that the empty value is the reason and the culprit is probably around:
https://github.com/jenkinsci/hashicorp-vault-plugin/blob/master/src/main/java/com/datapipe/jenkins/vault/log/MaskingConsoleLogFilter.java#L47

This has an easy workaround, which is to not have empty values in secrets.
This can also be checked and handled.

Let me know if that makes sense and if we should attempt to fix this in a PR.

Note: We are using version 2.1/2.2 of the plugin.

Thanks again!

Cannot retrieve multiple secrets from Vault with single call anymore

Hello,

Please suggest, in version 2.2.0 I could retrieve all secret values from Vault by using following construction:
def vault_secrets = [ [$class: 'VaultSecret', path: "secret/data/app1/common", secretValues: [ [$class: 'VaultSecretValue', envVar: 'VAULT_SECRETS_COMMON', vaultKey: 'data']]], [$class: 'VaultSecret', path: "secret/data/app1/${config.ENVIRONMENT}", secretValues: [ [$class: 'VaultSecretValue', envVar: 'VAULT_SECRETS_APP', vaultKey: 'data']]] ]
As a result I had VAULT_SECRETS_COMMON and VAULT_SECRETS_APP with all secrets I needed inside those env vars then I could convert them to object and use in ECS task definition template (there is no point for me to extract each var separately by key as they can be added/removed arbitrary in Vault).

With the latest version 3.2.0 that does not work anymore, if I use:
def vault_secrets = [ [path: 'secret/app1/common', engineVersion: 2, secretValues: [ [envVar: 'VAULT_SECRETS_COMMON', vaultKey: "data"]]], [path: "secret/app1/${config.ENVIRONMENT}", engineVersion: 2, secretValues: [ [envVar: 'VAULT_SECRETS_APP', vaultKey: "data"]]] ]

I receive error "Vault Secret data at secret/app1/common is either null or empty"
Secrets are stored like this:
{ "key1": "val1", "key2": val2" ... }

One possible workaround is to add root level secret:
"ROOT_LEVEL_SECRET": { "key1": "val1", "key2": val2"" ... }

and use vaultKey: "ROOT_LEVEL_SECRET" but that breaks backward compatibility of my current pipelines...

value credentials not found - using namespaces ?

Dear all,
I am keep getting com.datapipe.jenkins.vault.exception.VaultPluginException: Vault credentials not found for 'mykey'
Could this be a namespace problem ?
if commandline I query without having set the namespace I also get an error (403).
I have seen that the plugin in principle support namespaces, however I could not find how to specify that.
Thankyou

unit tests deliver "cannot listen to UDP port ..." is this ok ?

0.015 [id=191] INFO o.jvnet.hudson.test.JenkinsRule#createWebServer: Running on http://localhost:53647/jenkins/
0.035 [id=204] INFO jenkins.InitReactorRunner$1#onAttained: Started initialization
0.037 [id=218] INFO jenkins.InitReactorRunner$1#onAttained: Listed all plugins
0.232 [id=207] INFO jenkins.InitReactorRunner$1#onAttained: Prepared all plugins
0.234 [id=205] INFO jenkins.InitReactorRunner$1#onAttained: Started all plugins
0.235 [id=206] INFO jenkins.InitReactorRunner$1#onAttained: Augmented all extensions
0.303 [id=212] INFO jenkins.InitReactorRunner$1#onAttained: Loaded all jobs
0.308 [id=210] INFO jenkins.InitReactorRunner$1#onAttained: Completed initialization
0.311 [id=232] INFO hudson.UDPBroadcastThread#run: Cannot listen to UDP port 33,848, skipping: java.net.SocketException: Can't assign requested address (local port 33848 to address 0:0:0:0:0:0:0:0, remote host unknown)
0.482 [id=220] INFO hudson.model.Run#execute: test #1 main build action completed: SUCCESS
0.492 [id=191] INFO jenkins.model.Jenkins#cleanUp: Stopping Jenkins
80.889 [id=191] INFO jenkins.model.Jenkins#cleanUp: Jenkins stopped

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.