Nathan
Nathan

Reputation: 167

Jenkins - set env var to output of a command?

I've inherited a Jenkins file and need to insert an environment variable. The variable is the output of the command:

openssl rand -base64 32

I've added it to the file like this:

sh('env.TF_VAR_sql_secret=$(openssl rand -base64 32)')

This outputs as I'd expect in the console:

env.SECRET=secretstuffhere

but running 'env' later on shows that this isn't actually set. So the command is working but I am messing up on the actual setting of the variable. I've also tried adding an 'environment' block as follows:

    environment {
        SECRET = """${sh(
            returnStdout: true,
            script: 'openssl rand -base64 32'
            )}""" 
    }

which returns an error:

env.SECRET=secretstuffhere: not found. 

I really don't know what I'm doing with this but I feel I'm really close. It may have something to do with they way the jenkins file is structured?

Upvotes: 0

Views: 1659

Answers (1)

vijay v
vijay v

Reputation: 2076

The second block doesn't look correct. Like as you said, you were close to it.

    environment {
      SECRET = sh(script: 'openssl rand -base64 32', returnStdout: true) 
    }

Doing a println SECRET would give you the expected result as well W41NW9ly0kLsUgASJY7bpmSnqx5UYL6e2hefrMkrdIs=.

Pipeline-Snippet

Upvotes: 2

Related Questions