As per the official Jenkins wiki info, a Jenkins freestyle mission is a typical construct job or activity. This can be so simple as constructing or packaging an software, working assessments, constructing or sending a report, and even merely working just a few instructions.
Collating knowledge for assessments may also be accomplished by Jenkins. For example, a real-world situation may contain Jenkins permitting you to submit stories to log administration at any specified stage regarding administration, which can embrace particulars about artifacts or delivery software logs. On this Jenkins tutorial, we’ll dive deeper into learn how to create a job in Jenkins and finally, a Jenkins freestyle mission. Let’s discover out extra about Jenkins Construct Job earlier than we start making a Freestyle Challenge.
What Is a Construct Job?
The construct jobs are on the coronary heart of any Jenkins construct course of. To place it plainly, think about a Jenkins construct job as a specific activity or step in your whole construct course of. The duty or step may contain merely compiling the supply code and working your unit assessments over. Or you’ll be able to configure a construct job to do different co-related duties, resembling:
- Measuring code protection or code high quality metrics
- Working your integration assessments
- Producing technical documentation
- And even deploying the appliance to an online server
Usually, an actual mission requires many separate, however associated construct jobs in a CI or DevOps cycle. Allow us to first perceive what the Jenkins Freestyle Challenge is and the way we are able to create it.
What Is Jenkins Freestyle Challenge?
Jenkins helps various kinds of construct jobs. The 2 mostly used Jenkins construct jobs are:
- Freestyle builds
- Maven 2/3 builds
One of the best half in regards to the Jenkins Freestyle Challenge is that it lets you configure nearly any construct job, thus making them extremely versatile and configurable. The Maven 2/3 builds, alternatively, perceive the Maven mission construction and allow you to arrange Maven construct jobs shortly with added options. In a Freestyle construct job, you’ll be able to break down your construct job into a number of smaller construct steps, making it simpler to prepare builds in separate levels. For instance, in a single step, a construct may run a collection of practical assessments after which tag the construct in a second step if all practical assessments are profitable.
It might be acceptable to invoke an Ant activity or a Maven goal or run a shell script in a technical phrases construct part. Varied different Jenkins plugins additionally allow you to use further varieties of construct steps. These contain Grails, Gant, Rake, Gradle, Ruby, MSBuild, and many others. However what highlights a Jenkins Freestyle mission is that it allows you to create general-purpose construct jobs with most flexibility. So the underside line is that the Freestyle tasks help you configure nearly any construct job.
A Jenkins mission entails steps and post-build actions and is a repeatable construct job. There are limitations within the varieties of actions you’ll be able to carry out in a construct step or post-build motion. Inside a Jenkins freestyle mission, there are a number of customary plugins accessible that can assist you overcome this downside. These plugins help you configure construct triggers and provide project-based safety for the Jenkins mission.
When To Use a Jenkins Freestyle Challenge
Any entry to the shell or a batch surroundings propagates a excessive stage of safety entry for the Jenkins Freestyle mission. In Freestyle Challenge environments, it is handy to create a script that instructs a Jenkins freestyle job to FTP a file from one server to a different, compile a listing of Java code, and even run a SonarQube take a look at.
A Jenkins freestyle job may be as highly effective and sophisticated as any construct job constructed with a Jenkins pipeline or a Groovy DSL. Nevertheless, the one disadvantage to freestyle tasks is that the person should know learn how to script all of those actions, and builders have to learn to handle these scripts. Plugins resembling Git, Maven, and SonarQube are the popular option to entry assets. Technologically, each developer can write a script to entry these assets inside a Jenkins freestyle mission.
Nevertheless, it is suggested that each developer within the growth group ought to observe the guided safety finest practices and inhibit from adapting a scripted strategy.
Making a Freestyle Construct Job
To arrange freestyle tasks utilizing Jenkins, we have to be sure that now we have Jenkins put in and up and working. Additionally, it’s necessary to be authenticated because the “Admin.”
After getting Jenkins up and prepared, allow us to create a Jenkins freestyle job.
Step 1
- Get logged on to your Jenkins dashboard by way of the Jenkins set up path.
- Except you have got outlined a personal host, it is going to be hosted on the localhost at http://localhost:8080.
- In case your Jenkins is put in in one other path, be sure that to make use of the suitable URL to entry the dashboard.
Step 2
Go to the “New Item” possibility on the high left-hand facet of your major dashboard.
Step 3
- Right here, enter the identify of the merchandise you wish to create. Allow us to use “Hi there World.”
- Choose Freestyle mission as the choice for this new merchandise.
- Click on OK.
Once we hit Okay, Jenkins robotically takes us to the mission configuration view, the place we have to configure our mission particulars. Moreover, we are able to present intricate particulars by way of tab choices. The primary tab is the overall particulars of the mission. So the following step is to enter mission particulars.
Step 4
Enter the mission particulars within the Basic tab, together with the identify and outline of the mission that must be examined.
Subsequent, let’s perceive what the Supply Code Administration tab does. It checks out code from model management hosts, which means that in case your code is hosted on GitHub or some other repositories, you need to add the repository particulars.
Jenkins will clone the repository.
The blue query mark icons current on the right-hand backside facet serve us with fast suggestions, and they are often very resourceful and supply extra clarification at occasions.
Step 5
Underneath the Supply Code Administration(SCM) tab:
- Choose Git as a repository supply and enter your Git Repository URL.
- In case you have got your repository created regionally, it’s permissible to make use of a neighborhood repository.
- Suppose the GitHub repository you might be utilizing is personal. In that case, Jenkins will validate the login credentials with GitHub, and upon profitable validation, it’s going to then pull the supply code out of your GitHub repository.
After you have got offered all of the mission and repo particulars, the following half is to construct the code. You possibly can handle the settings beneath the Construct part to construct the code at your required time. You possibly can even schedule the construct to run periodically if wanted.
Step 6
Go to the Construct part and click on on the Add construct step.
Underneath the construct part, click on on the “Add build step.”
Then, “Execute Windows batch command” and add the instructions you wish to execute throughout the construct course of.
For instance, Java compile batch instructions:
Step 7
When you have got entered all the info:
- Click on Apply.
- Save the mission.
Step 8
On the left-hand facet panel, click on the Construct Now button to construct the supply code.
Step 9
We are able to see the standing of the construct beneath Construct Historical past.
Step 10
We are able to confirm the historical past of the executed construct beneath the Construct Historical past by clicking the construct quantity. By clicking on the Construct Quantity –> Console Output, it ought to present you successful or failure message relying on how the job ran.
To sum up, we ran a “Hello World” program on GitHub. Jenkins pulled up the supply code from the distant repository and constantly constructed it at a frequency you outline.
Jenkins Freestyle Challenge for Docker Container Photographs
The under demonstration is about making a Jenkins Freestyle mission that first builds a Docker picture after which scans it for any vulnerabilities and compliance points as a testover.
- Go to the Jenkins high web page.
- Create a brand new mission.
- Click on on ‘New Item.’
- Enter a reputation to your mission in ‘Enter an item name.’
- Choose ‘Freestyle project.’
- Then click on, OK.
- Subsequent, add a construct step.
- Within the Construct part → Add construct step → choose Execute shell→ Command.
- Enter the under command within the Command textual content field.
echo "Creating Dockerfile..." echo "FROM imiell/bad-dockerfile:latest" > Dockerfile docker construct --no-cache -t take a look at/test-image:0.1 .
- Embrace a construct step that can scan for vulnerabilities within the container picture(s).
- Choose Scan Prisma Cloud Photographs within the Add Create Part drop-down listing.
- Choose the picture to be scanned within the Picture area by specifying the repository and tag.
- In case the picture you wish to scan is generated past this construct, or if you wish to scan for a picture for every construct, even when a brand new picture just isn’t generated by the construct, then press Superior and choose Ignore Picture Improvement Time.
- To instantly publish the scan leads to Jenkins, add a post-build motion. This post-build step is dependent upon a file created by the earlier scan-build step, which incorporates the scan outcomes. Within the Jenkins construct software, this step explicitly makes the outcomes accessible for evaluate. Word that the outcomes have already been printed within the Console over the past scan part, and they’re prepared for evaluation there.
- Choose Publish Prisma Cloud Evaluation Outcomes from the drop-down menu beneath Add Publish-Construct Motion.
- Settle for the default within the Scan End result Folders.
- The publishing stage doesn’t take away the outcome information from the scan. Within the workspace, they continue to be.
- Click on Save, then Construct Now.
- Study the outcomes after the construct completes. Within the following locations, scan stories can be found:
- Prisma Cloud Console: Log into Console, go to Monitor –> Vulnerabilities –> Photographs –>CI.
- Jenkins: Scroll down into the construct job –> then click on Picture Vulnerabilities to see an in depth report.
Jenkins Freestyle Challenge for Serverless Features
It’s just like the process for container photos to arrange Jenkins to scan serverless features, besides that you need to use the Scan Prisma Cloud Features assemble step.
- Operate Path: Path to the perform’s ZIP archive to scan
- Operate Identify: (That is non-compulsory) Identifier string to align coverage guidelines within the Console with scanned features; If you construct coverage guidelines within the Console, the perform identify will goal particular guidelines to particular features. If this area is left undefined, the plugin matches the primary rule perform, the place the identify of the perform is a wildcard.
- AWS CloudFormation template file: (That is non-compulsory) Path to a template file in both JSON or YAML format with CloudFormation; Prisma Cloud checks the supply code of the perform for the AWS service APIs which can be used, compares the APIs used with the permissions of the perform, and stories when the features have permissions for APIs they don’t want.
Changing a Challenge From Jenkins Freestyle Challenge to a Declarative Pipeline
In Jenkins, managing freestyle jobs is cumbersome. Declarative Pipelines provide a extra fashionable and urged resolution. It’s time-consuming and error-prone, nevertheless, to attempt to convert Freestyle jobs to Declarative Pipelines manually. You need to use the Migration Assistant Declarative Pipeline plugin to streamline this operation.
Throughout the conversion, the Declarative Pipeline Migration Assistant makes use of a best-effort strategy: supported configurations are transformed robotically in Freestyle tasks, and placeholder levels are generated for plugins that aren’t but supported. The Declarative Pipeline Migration Assistant’s benefits embrace:
- Producing a Jenkinsfile from a mission for Freestyle
- A Jenkinsfile customizatio.
- Making a Jenkins pipeline mission and inserting a Jenkins file
Producing a Jenkinsfile From a Challenge for Freestyle
A centralized configuration file, known as a Jenkinsfile, is the idea for pipeline or multi-branch pipeline tasks. Within the textual content editor or GUI, a Jenkinsfile may be generated. The file is maintained both with the mission code or, for instance, a software program configuration administration (SCM) software like Git in a separate repository.
Utilizing an SCM to retailer the file provides the configuration file a centralized location, permits code evaluate, and supplies an audit path for the pipeline. To construct an preliminary Jenkinsfile, the Declarative Pipeline Migration Assistant makes use of info from a Freestyle mission. The Declarative Pipeline Migration Assistant is just accessible from the Jenkins UI and never from the Jenkins CLI. See Defining Pipeline for extra details about pipelines.
Conditions
Two plugins, specifically:
- The Pipeline plugins
- The Declarative Pipeline Migration Assistant plugin
Steps to generate a Jenkinsfile from a Freestyle mission:
- Go to the –> Freestyle mission.
- From the Freestyle mission tab, select To Declarative from the left navigation menu.
- The plugin just isn’t suitable with pipelines. It is best to evaluate the documentation of the plugin to see whether it is Pipeline-compatible. Use the shell step as a substitute possibility if the plugin just isn’t suitable with the pipeline.
- The plugin is suitable with Pipeline and seems within the Snippet Generator. (See desk under for a listing of suitable plugins.) To assemble the proper syntax, use the Snippet Generator.
- The plugin is suitable with the pipeline and won’t seem within the Snippet Generator. For extra particulars on implementing the plugin, discuss with the Pipeline documentation; see Customizing a Jenkinsfile.
- You possibly can write plugins for the Declarative Pipeline Migration Assistant for reusability; see Extending the plugin for Declarative Pipeline Migration Assistant.
The desk under displays a listing of the supported plugins.
Sort | Step |
---|---|
scm |
git |
step |
shell step |
step |
batch step |
step |
Maven construct step |
construct wrapper |
|
construct wrapper |
secret (convert to credentials binding) |
construct wrapper |
Construct a timeout plugin |
job property |
|
job property |
construct parameters |
job property |
construct discarder configuration |
construct set off |
upstream tasks set off |
construct set off |
SCM pooling |
construct set off |
timer set off |
construct surroundings |
present configuration information |
construct surroundings |
use secret textual content(s) or file(s) |
post-build motion |
|
post-build motion |
|
post-build motion |
set off one other mission |
post-build motion |
mail notification |
post-build motion |
Don’t fail the construct if archiving returns nothing |
post-build motion |
archive artifacts provided that the construct is profitable |
post-build motion |
fingerprint all archived tasks |
Jenkinsfile Customization
After making a Jenkinsfile from a Freestyle mission, you have got just a few choices.
- You possibly can both copy-paste the Jenkinsfile right into a textual content file.
- Or, you’ll be able to obtain the offered textual content file and open it within the textual content editor.
- Then, to carry out the identical duties carried out by the Freestyle mission, evaluate the Jenkinsfile and edit as required for the brand new Pipeline mission.
Making a Pipeline Challenge in Jenkins and Including a Jenkinsfile
The subsequent transfer is so as to add the Jenkinsfile because the configuration file to a Pipeline or Multibranch Pipeline mission after making a Jenkinsfile from a Freestyle mission and modifying the Jenkinsfile. Creating the Jenkins pipeline mission first. Then, by copying and pasting the Jenkinsfile into the Pipeline editor or storing it in an SCM like GitHub and linking the repository to the Pipeline mission, add the Jenkinsfile to your mission. Steps to create a Pipeline mission and including the Jenkinsfile:
Step 1
In Jenkins, create a pipeline mission and duplicate and paste the Jenkinsfile textual content into the editor of the pipeline.
Step 2
Retailer the Jenkinsfile in a repository for SCM resembling GitHub and:
Extending the Declarative Pipeline Migration Assistant Plugin
A small variety of plugins are presently supported by the Declarative Pipeline Migration Assistant plugin. For a listing of plugins supported, see the desk above. Past this listing, if you wish to add assist for a specific plugin that’s presently not supported, it entails attaching the API dependency to the converter and creating the extension.
Including the API Dependence of the Converter
The next code snippet illustrates learn how to add a dependency on the converter API:
org.jenkins-ci.plugins.to-declarative declarative-pipeline-migration-assistant-api
Creating the Extension
The next code snippet is an illustration of learn how to create the extension:
``` @Extension public class ShellConverter extends SingleTypedConverter @Override public boolean convert( ConverterRequest request, ConverterResult outcome, Object goal ) { Shell shell = (Shell) goal; /* Do some work to generate a brand new stage . . . */ ModelASTStage stage = new ModelASTStage( this ); // use a utility methodology so as to add the stage to the pipeline mannequin ModelASTUtils.addStage( request.getModelASTPipelineDef(), stage); // true for fulfillment, false for failure return true; } ```
Instance Conversions
The summary class SingleTypedConverter
defines the extension of the conversion.
Instance Construct Step Conversion
The next code snippet is an illustration of learn how to convert a Shell script Freestyle step utilizing the API:
``` @Extension public class ShellConverter extends SingleTypedConverter { @Override public boolean convert (ConerterRequest request, ConverterRequest outcome, Object goal ) { Shell shell = (Shell) goal; ModelASTStage stage = new ModelASTStage( this ); int stageNumber = request.getAndIncrement( SHELL_NUMBER_KEY ); stage.setName( "Shell script " + stageNumber ); ModelASTBranch department = new ModelASTBranch( this ); stage.setBranches( Arrays.asList( department ) ); ModelASTStep step = new ModelASTStep( this ); step.setName( "sh" ); ModelASTSingleArgument singleArgument = new ModelASTSingleArgument( this ); singleArgument.setValue( ModelASTValue.fromConstant( shell.getCommand(), this ) ); step.setArgs( singleArgument ); ModelASTUtils.wrapBranch(outcome, step, department); ModelASTUtils.addStage(outcome.getModelASTPipelineDef(), stage); return true; } } ```
Instance Construct Wrapper Conversion
The next instance converts the Config File Freestyle wrapper construct utilizing the API. This conversion makes use of a helper methodology so as to add a wrapper round all future construct step conversions.
``` // This was to not have the config-file-provider plugin as a required dependency // However you need to use (as you employ your plugin) @OptionalExtension(requirePlugins = { "config-file-provider" }) public class ConfigFileBuildWrapperConverter extends SingleTypedConverter { personal Logger LOGGER = LoggerFactory.getLogger( ConfigFileBuildWrapperConverter.class ); @Override public boolean convert(ConverterRequest request, ConverterResult outcome, Object goal) { ConfigFileBuildWrapper configFileBuildWrapper = (ConfigFileBuildWrapper) goal; if(configFileBuildWrapper.getManagedFiles() == null || configFileBuildWrapper.getManagedFiles().isEmpty() ) { return true; } outcome.addWrappingTreeStep( () -> construct( configFileBuildWrapper) ); return true; } personal ModelASTTreeStep construct(ConfigFileBuildWrapper configFileBuildWrapper) { ModelASTTreeStep configFileProvider = new ModelASTTreeStep( this ); configFileProvider.setName( "configFileProvider" ); ModelASTSingleArgument singleArgument = new ModelASTSingleArgument( null ); configFileProvider.setArgs( singleArgument ); ManagedFile managedFile = configFileBuildWrapper.getManagedFiles().get( 0 ); StringBuilder gstring = new StringBuilder( "[configFile(fileId:'" ); gstring.append( managedFile.getFileId()); gstring.append( "', targetLocation: '" ); gstring.append( managedFile.getTargetLocation() ); gstring.append( "')]" ); singleArgument.setValue( ModelASTValue.fromGString( gstring.toString(), this ) ); return configFileProvider; } } ```
Instance Writer Conversion
The next instance converts the ArtifactArchiver
Freestyle post-build step utilizing the API. This conversion modifies the mannequin so as to add some construct situations.
``` @Extension public class ArtifactArchiverConverter extends SingleTypedConverter { @Override public boolean convert(ConverterRequest request, ConverterResult outcome, Object goal) { ArtifactArchiver artifactArchiver = (ArtifactArchiver) goal; ModelASTBuildCondition buildCondition; if(artifactArchiver.isOnlyIfSuccessful()) { buildCondition = ModelASTUtils.buildOrFindBuildCondition( outcome.getModelASTPipelineDef(), "success" ); } else { buildCondition = ModelASTUtils.buildOrFindBuildCondition( outcome.getModelASTPipelineDef(), "always" ); } ModelASTStep archiveArtifacts = ModelASTUtils.buildGenericStep(artifactArchiver, this); ModelASTUtils.addStep(buildCondition, archiveArtifacts); return true; } } ```
Relying on which situation the artifact must be executed, we add the step to the construct situation.
Instance SCM Conversion
The next instance converts the Git SCM Freestyle stage utilizing the API. This conversion provides a stage to the Pipeline mannequin.
``` @OptionalExtension(requirePlugins = { "git"}) public class GitScmConverter extends SingleTypedConverter { @Override public boolean convert(ConverterRequest request, ConverterResult outcome, Object goal) { Listing repoList = ( (GitSCM) goal ).getUserRemoteConfigs(); if(repoList.isEmpty()){ return true; } ModelASTStage stage = new ModelASTStage( this ); stage.setName( "Checkout Scm" ); Listing steps = new ArrayList(); // a step shall be created per distant repository for( UserRemoteConfig userRemoteConfig : repoList) { ModelASTStep git = new ModelASTStep( null ); git.setName( "git" ); Map args = new HashMap(); { ModelASTKey url = new ModelASTKey( this ); url.setKey( "url" ); ModelASTValue urlValue = ModelASTValue.fromConstant( userRemoteConfig.getUrl(), this ); args.put( url, urlValue ); } ... ModelASTNamedArgumentList stepArgs = new ModelASTNamedArgumentList( null); stepArgs.setArguments( args ); git.setArgs( stepArgs ); steps.add( git ); } ModelASTBranch department = new ModelASTBranch( this ); department.setSteps(steps); stage.setBranches( Arrays.asList( department ) ); ModelASTUtils.addStage(outcome.getModelASTPipelineDef(), stage ); return true; } } ```
- Create a brand new stage.
- Steps shall be generated as:
- git url: ""
,department: ''
,changelog: ''
,credentialsId: ''
,pool: ''
- A step is created primarily based on every distant repository.
- Create the Git step.
- Add parameters – URL.
- Within the authentic code, add extra parameters.
- Configure args of the step.
- Create a department for the stage.
- Use a utility methodology so as to add the stage to the Pipeline mannequin.
Instance Construct Set off Conversion
Utilizing the API, the next instance transforms the cron
set off. The pipeline mode is modified by this conversion so as to add a set off property by way of a utility course of.
@Extension public class TimerTriggerConverter extends SingleTypedConverter { @Override public boolean convert(ConverterRequest request, ConverterResult outcome, Object goal) { TimerTrigger timerTrigger = (TimerTrigger) goal; String cronValue = timerTrigger.getSpec(); ModelASTTrigger modelASTTrigger = new ModelASTTrigger( this ); modelASTTrigger.setName( "cron" ); modelASTTrigger.setArgs( Arrays.asList(ModelASTValue.fromConstant( cronValue, this )) ); ModelASTUtils.addTrigger( outcome.getModelASTPipelineDef(), modelASTTrigger ); return true; } }
That’s how one can create your very personal pipeline tasks!
Wrapping Up!
On this weblog, we noticed the central characteristic of Jenkins studying learn how to create a job in Jenkins, Jenkins construct jobs, and creating pipeline tasks. By way of the Jenkins Freestyle Challenge, you’ll be able to construct your mission, and mix any SCM with any construct system. We additionally noticed just a few extensions of Freestyle tasks just like the Docker container photos.
The conversion of freestyle tasks into Declarative Pipelines presents a extra fashionable and urged resolution. Tell us what you’re feeling about this weblog within the feedback under. Attempt reproducing the steps for Jenkins to create and construct a job to be taught on the go.
Completely satisfied testing!