How to assign BUILD_USER_ID to another env variable?

Hi, I want to use environment variable BUILD_USER_ID to build a path, for use as a global variable, environment variable or parameter in a declarative pipeline.

I understand how to access BUILD_USER_ID within a stage:

    steps {
        wrap([$class: 'BuildUser']) {
            script {
                echo "Jenkins_${BUILD_USER_ID}"
            }
        }   
    }

but how can I assign that value to an environment variable, parameter or global variable?

This fails:

wrap([$class: 'BuildUser']) {
    environment {
        USER_DIR = "Jenkins_${BUILD_USER_ID}"
}

I’m having a very similar head scratcher. I want a post build step to email the person that requested the pipeline, unless it was automated and BUILD_USER_ID is not accessible in a post pipeline section.

We got that somewhat working by using a jenkins library where all the code was under a single vars/foo.groovy and ‘caching’ the user id. But as our library code has grown over time we are trying to split the logic into smaller files and now we cannot get a reliable way to persist information accross different places in the declarative pipelines.

Between groovy and the lack of clear documentation as to how the code is evaluated we are quite stuck.