Search code examples
jenkinsenvironment-variablesredhatjenkins-groovyamazon-linux-2

How can I add a variable to jenkins during the install on Amazon Linux


I have a variable that I need to add as Jenkins Environment Variable so that the $jenkins_home/init.d groovy scripts can use them. I have this variable set in the host machine(where iam installing jenkins) - Amazon linux EC2 via a .sh file in /etc/profile.d and sourceing the /etc/profile . This did not help as I am not able to access the variable from jenkins. Can anybody please help on how I can achieve this.


Solution

  • In Jenkins, you can setup the global variables using the below given groovy script. You will have to use this in a shell script that you use to provision a jenkins server. This should be executed right after install so that, jenkins can use then while running jobs.

    The below given groovy script creates the environment variables one by one, createGlobalEnvironmentVariables('Var1','DummyValue')

    This adds a global variable with name as Var1 and value as DummyValue

    If you have multiple values, you can use the ones given below. envVars.put("Key1", "Value1) envVars.put("Key2", "Value2)

    before calling instance.save(). We have a shell script file that has this and many other functions to install and configure jenkins in a single shot.

    import hudson.EnvVars;
    import hudson.slaves.EnvironmentVariablesNodeProperty;
    import hudson.slaves.NodeProperty;
    import hudson.slaves.NodePropertyDescriptor;
    import hudson.util.DescribableList;
    import jenkins.model.Jenkins;
    
    public createGlobalEnvironmentVariables(String key, String value){
    
            Jenkins instance = Jenkins.getInstance();
    
            DescribableList<NodeProperty<?>, NodePropertyDescriptor> globalNodeProperties = instance.getGlobalNodeProperties();
            List<EnvironmentVariablesNodeProperty> envVarsNodePropertyList = globalNodeProperties.getAll(EnvironmentVariablesNodeProperty.class);
    
            EnvironmentVariablesNodeProperty newEnvVarsNodeProperty = null;
            EnvVars envVars = null;
    
            if ( envVarsNodePropertyList == null || envVarsNodePropertyList.size() == 0 ) {
                newEnvVarsNodeProperty = new hudson.slaves.EnvironmentVariablesNodeProperty();
                globalNodeProperties.add(newEnvVarsNodeProperty);
                envVars = newEnvVarsNodeProperty.getEnvVars();
            } else {
                envVars = envVarsNodePropertyList.get(0).getEnvVars();
            }
            envVars.put(key, value)
            instance.save()
    }
    createGlobalEnvironmentVariables('Var1','DummyValue')