How can environment variables be extracted from the Docker HOST to pass through to a Docker container-agent?

Jenkins setup:
Jenkins: 2.462.3

I have a multi-branch pipeline where the stages will be executed in a Docker agent. Because the Docker agent configuration is the same regardless of the stage I would like to specify the Docker agent at the top level/pipeline level, thus preventing repeatedly specifying it at the stage level with all the configuration that it requires.

My top-level agent looks like:

agent {
    docker {
        image "maven"
        args  "-v /var/run/docker.sock:/var/run/docker.sock --group-add 999"
    }
}

Of note is that I mount the host’s Docker socket into the container AND that I assign the additional group ‘999’ (which is the host’s docker gid) to the process in the container so it may use the host’s Docker socket.

This approach works fine however the Docker gid is hard-coded and I would like to extract it dynamically, for example the Docker-host-agent may be a $lave (Jenkins ‘community’ owners, please stop censoring non-offensive words and grow up!) with a different gid for the docker user. Because it’s the top-level agent it’s not possible to run bash script (as far as I can tell) to extract the gid. e.g. I need to execute in bash the script:

getent group docker | cut --delimiter ':' --field 3

What I need is the ability to setup some environment variables using a bash script before the pipeline Docker-agent starts and the script must execute on the Docker host where the agent will run.

Plugins such as Envinject and Environment script seem to offer the functionality I need but they don’t seem to be available for use in a multi-branch pipeline job.

My work around at the moment is to specify the docker agent at each stage but have a first stage which runs on a ‘native’ agent to extract the gid.