I have a snippet of code that is obtaining an environment variable as follows:
You can achieve that by installing EnvInject plugin.
1) After installing check the Prepare an environment for the job option in the job configuration screen. This option will display several field for you to fill.
2) Fill the Script Content area with a command
touch env.properties to create the file.
3) Fill the Properties Contentt field with the variables you want to inject inside your recently created env.properties file by doing so. Place one variable per line ex:
4) Reference env.properties file you've just created in the file path area.
5) At runtime Jenkins will inject those variables and they will be available to your program.