One of the key concept of Devops is Infrastructure as Code. Infrastructure as code is to write jobs as code and store it in version control. This gives us the following advantages,
- Gives history and audit trail
- Easy roll back to older versions
- Allows more control to developers
- Developers can bundle build instructions.
- Allow developers to control their own builds.
So, one of the tools to implement Infrastructure as code is Jenkins Job DSL plugin. It allows us to define jobs as code. DSL stands for Domain Specific Language. We can describe jobs using Groovy based language.
We will try to recreate the job we created in the last post.
- First thing to do is to create a github repo to host our build groovy file (Sample).
- Next we create a seed job, which essentially takes the Job DSL script and create a job/multiple jobs. Its a FreeStyle project. We will pull our latest script from the github repo by mentioning in the SCM step. Then, we will add a build step Process Job DSL. We will select Look on Filesystem to get the groovy file and mention the file name.
- Now, we will build the Seed project, which will generate our project basis our groovy script. We will get the following error, which is an inbuilt security feature of jenkins.
- We need to approve the script to be able to use the script. To do that, we will navigate to Dashboard > Manage Jenkins > In-process Script Approval. We will find our script there pending approval. We can approve the script and retrigger the Seed Job.
- Post approval, we will get success in console. We can also see the job listed in the Dashboard. We can check the configuration to check if its as per our configuration in the groovy script.
That’s it we have now created a job using groovy, which we can edit later as our needs change, roll back incase of any failures and maintain an audit of the changes as well.