How to export Jenkins build variable programatically

279 Views Asked by At

I’m trying to do a slight modification to this plugin https://github.com/bitbar/testdroid-run-in-cloud-plugin.

I want to export the test results URL that are provided by the Testdroid API as a job environment variable something like TEST_CLOUD_LINK. I found the variable that holds this information in the CloudLink class but I’m not sure on how I could export it as a env variable to use in the build.

Anyone can help with an example?

1

There are 1 best solutions below

0
On BEST ANSWER

I managed to get it working.

Fist I defined an Action class implementing EnvironmentContributingAction interface.

public class RunInCloudEnvInject implements EnvironmentContributingAction {

    private String key;

    private String value;

    public RunInCloudEnvInject(String key, String value) {
        this.key = key;
        this.value = value;
    }

    @Override public void buildEnvVars(AbstractBuild<?, ?> abstractBuild, EnvVars envVars) {
        if (envVars != null && key != null && value != null) {
            envVars.put(key, value);
        }
    }

    @Override public String getIconFileName() {
        return null;
    }

    @Override public String getDisplayName() {
        return "RunInCloudBuilderEnvInjectionAction";
    }

    @Override public String getUrlName() {
        return null;
    }
}

After that I modified this snippet bellow inside the @Override perform() method of the class that implements the abstract builder.

        String cloudLink = String.format("%s/#service/testrun/%s/%s", cloudLinkPrefix, testRun.getProjectId(),
                testRun.getId());
        build.getActions().add(new CloudLink(build, cloudLink));

        RunInCloudEnvInject variable = new RunInCloudEnvInject("CLOUD_LINK", cloudLink);
        build.addAction(variable);

Now I can use my CLOUD_LINK environment variable inside the Jenkins build to post the results url in a Slack notification for example.

Here is the pull request https://github.com/jenkinsci/testdroid-run-in-cloud-plugin/pull/4