Correct usage of stash\unstash into a different directory

mindparse picture mindparse · Mar 27, 2017 · Viewed 60.8k times · Source

In one of my stages I need to copy the contents of two folders after a build is completed and copy to a different directory.

I am actually converting a freestyle job to pipeline, and have been using the artifact deployer plugin. Reading around, it looks like stash and unstash commands should help with what I want to achieve.

Can someone verify if this is the correct approach below please?

stage('Build') {
      steps {
        sh '''
          gulp set-staging-node-env
          gulp prepare-staging-files
          gulp webpack
        '''
        stash includes: '/dist/**/*', name: 'builtSources'
        stash includes: '/config/**/*', name: 'appConfig'
        dir('/some-dir') {
          unstash 'builtSources'
          unstash 'appConfig'
        }
      }
    }

If I change dir in one stage, does that mean all other stages thereafter will try to execute commands from that directory, or do they do back to using the workspace default location?

Thanks

EDIT

I have realised what I actually want to do is to copy built sources to a different node (running a different OS). So in my snippet I have shared, where I am switching directories, that directory is actually to be on a different machine (node) that I have setup.

Would I need to wrap the dir() block with a node('my-node-name') block? Im struggling to find examples.

Thanks

Answer

rusia.inc picture rusia.inc · Mar 27, 2017

I hope it is meant to be this:

stash includes: 'dist/**/*', name: 'builtSources'

stash includes: 'config/**/*', name: 'appConfig'

where dist and config are the directories in the workspace path, so it should be a relative path like above.

Rest seems alright, only to mention that path "/some-dir" should be writable by jenkins user (user used to run jenkins daemon).

And yes it falls back to its then enclosing workspace path (in this case default) when it exits dir block.

EDIT

So when you stash a path, it is available to be unstashed at any step later in the pipeline. So yes, you could put dir block under a node('<nodename>') block.

You could add something like this :

stage('Move the Build'){
  node('datahouse'){
    dir('/opt/jenkins_artifacts'){
      unstash 'builtSources'
      unstash 'appConfig'
    }
  }
}