Accessing Java Code Level Variables in Jenkins Post-Build Actions for Slack Notifications
In this article, we will discuss how to access Java code level variables in Jenkins post-build actions, specifically for sending custom messages to Slack channels. This can be useful for monitoring Java application builds, viewing variable values, and sending notifications after successful or failed builds.
Prerequisites
To get started, make sure you have the following:
- Jenkins installed and running
- Slack webhook URL for a channel
- A Java project set up in Jenkins
Setting up Slack Notifications in Jenkins
First, we need to configure Jenkins to send Slack notifications. In Jenkins, navigate to Manage Jenkins > Configure System > Slack Notification.
Enter your Slack webhook URL in the Slack Webhook URLs field and click the Add button. Optionally, you can configure additional settings such as channel, username, or emoji for the notifications.
Note: You need the appropriate permissions to install and configure the Slack plugin in your Jenkins instance.
Sending Custom Messages with Java Code Level Variables
To send custom messages using Java code level variables, we'll create a Jenkins Post-build Action called Execute a custom script in the job configuration.
Below is a sample Java code snippet that demonstrates how to access a Java code level variable and send it as part of a custom message to Slack using Jenkins post-build actions. Note that the variable name is jenkinsVariable and its value is set to "helloWorld".
import hudson.model.Result;
import hudson.model.AbstractBuild;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Builder;
import jenkins.tasks.SimpleBuildStep;
import edu.umd.cs.findbugs.BAUReport;
import edu.umd.cs.findbugs.FindBugsBundledReporter;
import edu.umd.cs.findbugs.FindBugsReportFormat;
import edu.umd.cs.findbugs.FindBugs2;
import edu.umd.cs.findbugs.FindBugsException;
import java.io.File;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import jenkins.model.BuildListener;
public class SlackNotifier extends Builder {
private String jenkinsVariable = "helloWorld";
@DataBoundConstructor
public SlackNotifier() {}
@DataBoundSetter
public void setJenkinsVariable(String jenkinsVariable) {
this.jenkinsVariable = jenkinsVariable;
}
@Override
public boolean perform(AbstractBuild build, BuildListener listener) {
String status = (build.getResult() == Result.SUCCESS) ? "Build succeeded!" : "Build failed!";
String message = String.format("Build status: %s
Variable value: %s", status, jenkinsVariable);
// Slack Notification Logic
// You can customize the method below to suit your needs
sendSlackNotification(message, listener);
return true;
}
/**
* Sends a Slack notification with a given message
* @param message - The message to send to the Slack channel in Markdown format
* @param listener - The listener for Jenkins log output
*/
private void sendSlackNotification(String message, BuildListener listener) {
// Custom Slack notification code here
String slackUrl = "YOUR_SLACK_WEBHOOK_URL";
String payload = "{\"text\": \"" + message + "\"}";
// Sending the POST request
try {
URL url = new URL(slackUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestMethod("POST");
OutputStream out = con.getOutputStream();
out.write(payload.getBytes("UTF-8"));
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
out.flush();
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This SlackNotifier class can be added to your project's build steps and Jenkinsfile as needed. When a build runs, the post-build action executes the perform method.
The perform method retrieves the Jenkins build result, constructs a custom message using the Java string variable jenkinsVariable, and sends it as a Slack notification.
You can customize the sendSlackNotification method to suit your needs, such as adding additional variables, custom formatting, or customizing the Slack message payload.
- Install and configure the Slack plugin and webhook in Jenkins
- Create a custom post-build action called Execute a custom script in the Jenkins job configuration
- Write a Java class in your project that extends
Builderand implementsperformandsendSlackNotificationmethods - Configure your project's Jenkinsfile and build steps to include the custom
SlackNotifierclass