How to Install and Setup Jenkins on Ubuntu Linux

How to Install and Setup Jenkins on Ubuntu Linux

Are you tired of manually building, testing, and deploying your software? Wish there was a way to automate those tedious tasks and accelerate your development workflow? Enter Jenkins, your new CI/CD superhero! Jenkins is an open-source automation server that empowers you to build, test, and deploy your code with ease, freeing up your time for more creative and strategic work.

In this comprehensive guide, we’ll walk you through the process of installing and setting up Jenkins on your Ubuntu Linux machine, step by step. Whether you’re a seasoned developer looking to streamline your workflow or a DevOps enthusiast eager to explore the world of continuous integration and continuous delivery (CI/CD), this tutorial has got you covered. Get ready to unleash the power of automation and take your software development to the next level!

Jenkins offers a multitude of benefits for development teams of all sizes:

  • Automation: Say goodbye to repetitive manual tasks. Jenkins can automate your entire build, test, and deployment pipeline.
  • Flexibility: With a vast ecosystem of plugins, Jenkins can integrate with virtually any tool in your development stack.
  • Scalability: From small projects to enterprise-level applications, Jenkins scales to meet your needs.
  • Community Support: Benefit from a large, active community and extensive documentation.
  • Cost-Effective: As an open-source solution, Jenkins helps you implement robust CI/CD practices without breaking the bank.

By the end of this guide, you’ll have a fully functional Jenkins installation on your Ubuntu system, ready to revolutionize your development process. Let’s dive in and get started with Jenkins!

Prerequisites

Before we begin the Jenkins installation process, let’s ensure you have everything you need:

  1. Ubuntu Linux: This guide assumes you’re using a recent version of Ubuntu (18.04 LTS or newer). The commands and procedures should work on most Debian-based distributions, but you may need to adjust them slightly for other systems.
  2. System Requirements: Jenkins is relatively lightweight, but for optimal performance, ensure your system meets these minimum requirements:
  • 256 MB of RAM (1 GB+ recommended for better performance)
  • 1 GB of disk space (10 GB+ recommended if running many jobs)
  • A modern processor (multi-core is beneficial for running multiple jobs simultaneously)

3. Java Runtime Environment (JRE): Jenkins requires Java to run. OpenJDK 11 is recommended and can be installed with the following command:

   sudo apt update
   sudo apt install openjdk-11-jre

Verify the installation by running:

   java -version
  1. Web Browser: You’ll need a modern web browser to access the Jenkins web interface. Firefox, Chrome, or Safari are all excellent choices.
  2. System Access: Ensure you have sudo privileges on your Ubuntu system to install packages and make system-wide changes.
  3. Network Access: Jenkins will need to communicate over the network. Make sure your firewall allows incoming connections on port 8080 (Jenkins’ default port).

With these prerequisites in place, you’re ready to begin the Jenkins installation process. Let’s move on to the next section, where we’ll walk through the steps to get Jenkins up and running on your Ubuntu system.

Installing Jenkins

Now that we have our prerequisites sorted, let’s dive into the Jenkins installation process. We’ll be using the official Jenkins repository to ensure we get the latest stable version. Follow these steps carefully:

  1. Add the Jenkins Repository:
    First, we need to add the Jenkins repository to our system’s package manager. This ensures we can easily install and update Jenkins using apt.
   curl -fsSL https://pkg.jenkins.io/debian-stable/jenkins.io-2023.key | sudo tee \
     /usr/share/keyrings/jenkins-keyring.asc > /dev/null

   echo deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc] \
     https://pkg.jenkins.io/debian-stable binary/ | sudo tee \
     /etc/apt/sources.list.d/jenkins.list > /dev/null

These commands add the Jenkins GPG key and repository to your system.

  1. Update Package Lists:
    Before installing Jenkins, let’s make sure our package lists are up to date:
   sudo apt update
  1. Install Jenkins:
    Now, we can install Jenkins using the apt package manager:
   sudo apt install jenkins

This command will download and install Jenkins and its dependencies. The process may take a few minutes, depending on your internet connection speed.

  1. Start Jenkins Service:
    Once the installation is complete, Jenkins should start automatically. You can verify its status with:
   sudo systemctl status jenkins

You should see output indicating that Jenkins is active and running. If it’s not running for some reason, you can start it manually:

   sudo systemctl start jenkins
  1. Enable Jenkins to Start on Boot:
    To ensure Jenkins starts automatically when your system boots up, enable the Jenkins service:
   sudo systemctl enable jenkins
  1. Open Firewall Port:
    If you have a firewall enabled on your Ubuntu system (which is recommended for security), you’ll need to open port 8080 to access Jenkins:
   sudo ufw allow 8080

If you’re using a different firewall, consult its documentation for the equivalent command.

  1. Verify Installation:
    Open a web browser and navigate to http://localhost:8080 (or replace localhost with your server’s IP address if you’re accessing it remotely). You should see the Jenkins setup wizard.

Congratulations! You’ve successfully installed Jenkins on your Ubuntu system. In the next section, we’ll guide you through the initial setup process to get Jenkins fully configured and ready for use.

Initial Setup

Now that Jenkins is installed, it’s time to complete the initial setup process. This involves unlocking Jenkins, installing essential plugins, and creating your first admin user. Let’s walk through these steps:

  1. Unlock Jenkins:
    When you first access Jenkins in your web browser, you’ll be presented with an “Unlock Jenkins” screen. To unlock Jenkins, you need to provide an initial admin password. This password is automatically generated during the installation process and stored on your server. To retrieve the password, run the following command in your terminal:
   sudo cat /var/lib/jenkins/secrets/initialAdminPassword

Copy the alphanumeric string that’s displayed. This is your initial admin password.

Paste this password into the “Administrator password” field on the Jenkins setup wizard and click “Continue”.

  1. Customize Jenkins: On the next screen, you’ll be asked to customize Jenkins. You have two options:
    • Install suggested plugins: This option installs a set of commonly used plugins that are suitable for most users. It’s recommended for beginners.
    • Select plugins to install: This allows you to handpick the plugins you want to install. It’s more suitable for advanced users who know exactly what they need.
    For this guide, we’ll choose “Install suggested plugins”. Click on this option to proceed.
  2. Plugin Installation: Jenkins will now download and install the selected plugins. This process may take several minutes, depending on your internet connection speed. You’ll see a progress bar indicating the status of each plugin installation.
  3. Create First Admin User: After the plugins are installed, you’ll be prompted to create your first admin user. Fill in the following details:
    • Username
    • Password
    • Confirm password
    • Full name
    • Email address
    Make sure to use a strong, unique password for your admin account. This account will have full access to Jenkins, so it’s crucial to keep it secure. After filling in all the fields, click “Save and Continue”.
  4. Instance Configuration: On the next screen, you’ll be asked to confirm the Jenkins URL. This is the address you’ll use to access Jenkins. By default, it will be set to your server’s IP address or domain name. If you’re running Jenkins locally, the default http://localhost:8080 is fine. If you’re setting up Jenkins on a remote server, make sure the URL is correct and accessible. Click “Save and Finish” to complete the setup.
  5. Jenkins is Ready: You’ll see a “Jenkins is ready!” message. Click on “Start using Jenkins” to access your new Jenkins dashboard.

Congratulations! You’ve successfully completed the initial setup of Jenkins. You now have a fully functional Jenkins installation with a set of commonly used plugins and an admin user account.

In the next sections, we’ll dive deeper into configuring Jenkins, creating jobs, and exploring some advanced features to help you get the most out of your new CI/CD tool.

Configuring Jenkins

Now that Jenkins is up and running, let’s configure some essential settings to enhance its functionality and security. We’ll cover security settings, tool configurations, and important plugins.

Security Configuration

Securing your Jenkins installation is crucial, especially if it’s accessible over the internet. Let’s configure some basic security settings:

  1. Access the Security Settings:
  • From the Jenkins dashboard, click on “Manage Jenkins” in the left sidebar.
  • Find and click on “Configure Global Security”.

2. Enable Security:

  • Ensure the “Enable security” checkbox is ticked (it should be by default).

3. Security Realm:

  • Under “Security Realm”, select “Jenkins’ own user database”.
  • Check “Allow users to sign up” if you want to allow new user registrations. For tighter control, leave this unchecked and manually create user accounts.

4. Authorization:

  • For “Authorization”, select “Matrix-based security” for fine-grained access control.
  • In the matrix, give your admin user (the one you created during setup) full permissions by checking all boxes in its row.
  • For the “Anonymous” user, you might want to give “Read” access to allow users to view the Jenkins dashboard without logging in. Adjust this based on your security requirements.

5. CSRF Protection:

  • Ensure “Prevent Cross Site Request Forgery exploits” is checked.

6. Agent-to-Controller Security:

  • Under “Agents”, select “Random” for the “TCP port for inbound agents” option. This enhances security for distributed builds.

Remember to click “Save” at the bottom of the page to apply these security settings.

Configuring Tools

Jenkins uses various tools to build and test your projects. Let’s configure some essential tools:

  1. Access Global Tool Configuration:
    • From “Manage Jenkins”, click on “Global Tool Configuration”.
  2. JDK Configuration:
    • Scroll to the “JDK” section and click “Add JDK”.
    • Give it a name (e.g., “OpenJDK 11”).
    • Uncheck “Install automatically” if you’ve already installed Java on your system.
    • Set the JAVA_HOME path (e.g., /usr/lib/jvm/java-11-openjdk-amd64).
  3. Git Configuration:
    • Scroll to the “Git” section.
    • If Git is already installed on your system, Jenkins should auto-detect it. If not, you can specify the path to the Git executable.
  4. Maven Configuration (if needed):
    • If you’ll be building Java projects with Maven, scroll to the “Maven” section and click “Add Maven”.
    • Give it a name (e.g., “Maven 3”).
    • Check “Install automatically” to let Jenkins download and install Maven, or specify the path if it’s already installed.

Remember to click “Save” to apply these tool configurations.

Essential Plugins

Jenkins’ power comes from its extensive plugin ecosystem. Let’s install and configure some essential plugins:

  1. Access Plugin Manager:
    • From “Manage Jenkins”, click on “Manage Plugins”.
  2. Install Recommended Plugins:
    • Go to the “Available” tab.
    • Search for and install the following plugins (if not already installed):
      • Git Plugin (for source code management)
      • Pipeline Plugin (for creating advanced build pipelines)
      • Blue Ocean (for a modern, visual pipeline editor)
      • Docker Plugin (if you’re working with Docker containers)
  3. Configure Git Plugin:
    • After installation, go back to “Manage Jenkins” > “Configure System”.
    • Scroll to the “Git plugin” section.
    • Set the “Global Config user.name Value” and “Global Config user.email Value” for Git operations.
  4. Configure Pipeline Plugin:
    • The Pipeline plugin doesn’t require much configuration out of the box, but you can customize its behavior in “Manage Jenkins” > “Configure System” > “Pipeline: Shared Groovy Libraries” if needed.
  5. Configure Blue Ocean:
    • Blue Ocean adds a new UI to Jenkins. Access it by clicking “Open Blue Ocean” in the left sidebar of the Jenkins dashboard.
    • Follow the on-screen prompts to set up your first pipeline or explore the new interface.

With these configurations in place, your Jenkins installation is now more secure, equipped with essential tools, and enhanced with powerful plugins. In the next section, we’ll explore how to create and configure jobs in Jenkins to start automating your build and deployment processes.

Creating Jobs

Now that Jenkins is configured, it’s time to put it to work! In this section, we’ll explore how to create different types of jobs in Jenkins, focusing on Freestyle and Pipeline jobs. We’ll also cover key job configuration options to help you get the most out of your automation.

Freestyle Jobs

Freestyle jobs are the simplest type of job in Jenkins, suitable for straightforward build and test processes. Let’s create a basic Freestyle job:

  1. Create a New Job:
    • From the Jenkins dashboard, click “New Item” in the left sidebar.
    • Enter a name for your job (e.g., “My First Freestyle Job”).
    • Select “Freestyle project” and click “OK”.
  2. Configure Source Code Management:
    • In the job configuration page, scroll to the “Source Code Management” section.
    • Select “Git” and enter your repository URL.
    • If your repository is private, you’ll need to add credentials. Click “Add” > “Jenkins” and enter your Git credentials.
  3. Set Build Triggers:
    • In the “Build Triggers” section, you can specify when the job should run.
    • For example, select “Poll SCM” and enter H/15 * * * * in the schedule to check for changes every 15 minutes.
  4. Add Build Steps:
    • In the “Build” section, click “Add build step” and choose an appropriate action.
    • For a simple example, select “Execute shell” and enter a command like echo "Hello, Jenkins!".
  5. Configure Post-Build Actions:
    • In the “Post-build Actions” section, you can specify actions to take after the build.
    • For example, add “Archive the artifacts” to save build outputs.
  6. Save the Job:
    • Click “Save” at the bottom of the page to create your job.

You can now run your job manually by clicking “Build Now” on the job’s page, or wait for it to be triggered based on your configuration.

Pipeline Jobs

Pipeline jobs offer more flexibility and power, allowing you to define your entire build/test/deploy process as code. Let’s create a basic Pipeline job:

  1. Create a New Pipeline Job:
    • Click “New Item”, enter a name, select “Pipeline”, and click “OK”.
  2. Define the Pipeline:
    • In the job configuration page, scroll to the “Pipeline” section.
    • You can either write your pipeline script directly in the “Script” text area or select “Pipeline script from SCM” to load the script from your repository.
  3. Write a Basic Pipeline: Here’s a simple example pipeline:
   pipeline {
       agent any
       stages {
           stage('Build') {
               steps {
                   echo 'Building the project...'
               }
           }
           stage('Test') {
               steps {
                   echo 'Running tests...'
               }
           }
           stage('Deploy') {
               steps {
                   echo 'Deploying the project...'
               }
           }
       }
   }
  1. Save the Pipeline:
  • Click “Save” to create your Pipeline job.

You can now run your Pipeline job and see it progress through each stage visually in the Jenkins interface.

Key Job Configuration Options

Whether you’re creating Freestyle or Pipeline jobs, there are several important configuration options to consider:

  1. Source Code Management:
    • Jenkins supports various version control systems. Git is the most popular, but you can also use Subversion, Mercurial, and others.
    • For Git, you can specify branches to build, credentials for private repositories, and even set up multiple repositories.
  2. Build Triggers:
    • SCM polling: Regularly check for changes in your repository.
    • Webhooks: Trigger builds immediately when changes are pushed to your repository.
    • Scheduled builds: Run builds at specific times using cron syntax.
    • Upstream/downstream jobs: Trigger builds based on the completion of other jobs.
  3. Build Environment:
    • Set environment variables for your build.
    • Use secret text, files, or credentials for sensitive information.
    • Clean up the workspace before or after builds.
  4. Build Steps:
    • Execute shell commands or Windows batch commands.
    • Invoke build tools like Maven, Gradle, or Ant.
    • Run tests and generate reports.
  5. Post-build Actions:
    • Archive artifacts for later use.
    • Publish test results and code coverage reports.
    • Send notifications (email, Slack, etc.) based on build results.
    • Trigger downstream jobs.
  6. Pipeline-specific Options:
    • Use parameters to make your pipeline configurable.
    • Implement input steps for manual approvals.
    • Utilize parallel stages for faster execution.
    • Implement error handling and recovery steps.

Remember, the power of Jenkins lies in its flexibility. Start with simple jobs and gradually add complexity as you become more comfortable with the system.

Advanced Topics

As you become more proficient with Jenkins, you might want to explore some advanced features to further enhance your CI/CD pipeline. Let’s briefly touch on a few advanced topics:

Distributed Builds

Jenkins can distribute build jobs across multiple agent nodes, allowing for parallel execution and improved performance:

  1. Set up Agent Nodes:
    • Go to “Manage Jenkins” > “Manage Nodes and Clouds”.
    • Click “New Node” to add a new agent.
    • Configure the agent’s launch method, number of executors, and labels.
  2. Use Agents in Jobs:
    • In Freestyle jobs, use the “Restrict where this project can be run” option to specify agent labels.
    • In Pipeline jobs, use the agent directive to specify where stages should run.

Credentials Management

Jenkins provides a secure way to store and use credentials:

  1. Add Credentials:
    • Go to “Manage Jenkins” > “Manage Credentials”.
    • Click on the appropriate domain and “Add Credentials”.
    • Choose the credential type (username/password, SSH key, secret text, etc.) and enter the details.
  2. Use Credentials in Jobs:
    • In job configurations, you can select credentials from dropdown menus for SCM, build steps, etc.
    • In Pipeline jobs, use the credentials() function to securely access credentials.

Backups and Restoration

Regularly backing up your Jenkins configuration is crucial:

  1. Backup Jenkins Home:
    • The Jenkins home directory (usually /var/lib/jenkins) contains all configuration, job details, and build history.
    • Set up a cron job to regularly backup this directory.
  2. Use Backup Plugins:
    • Install the “ThinBackup” or “Backup” plugin for more granular control over backups.
    • Configure backup frequency, retention policy, and backup location.
  3. Restoration:
    • To restore Jenkins, stop the Jenkins service, replace the Jenkins home directory with your backup, and restart the service.
    • For plugin-based backups, follow the plugin’s restoration procedure.

Conclusion

Congratulations! You’ve successfully installed, configured, and started using Jenkins on your Ubuntu Linux system. Let’s recap the key steps we’ve covered:

  1. We installed Jenkins and its prerequisites on Ubuntu.
  2. We completed the initial setup, including unlocking Jenkins and creating an admin user.
  3. We configured essential security settings and tool integrations.
  4. We explored creating both Freestyle and Pipeline jobs, covering key configuration options.
  5. We touched on advanced topics like distributed builds, credentials management, and backups.

Jenkins is an incredibly powerful tool for automating your software development processes. Its flexibility and extensive plugin ecosystem make it suitable for a wide range of projects and workflows. As you continue to use Jenkins, you’ll discover new ways to optimize your CI/CD pipeline and improve your development efficiency.

Remember, this guide is just the beginning of your Jenkins journey. Here are some next steps to consider:

  • Explore more advanced Pipeline features like shared libraries and declarative syntax.
  • Integrate Jenkins with your issue tracking system (e.g., Jira) and code review tools.
  • Implement automated deployment strategies like blue-green deployments or canary releases.
  • Dive deeper into Jenkins’ security features and best practices.
  • Contribute to the Jenkins community by reporting bugs, suggesting features, or even developing plugins.

The world of CI/CD is constantly evolving, and Jenkins is evolving with it. Stay curious, keep learning, and don’t hesitate to experiment with new features and plugins. Happy automating!

Disclaimer: While every effort has been made to ensure the accuracy of the information in this blog post, we cannot guarantee its completeness or suitability for all situations. Jenkins configurations and plugin options may evolve over time. Please refer to the official Jenkins documentation for the latest information. Report any inaccuracies so we can correct them promptly.

Leave a Reply

Your email address will not be published. Required fields are marked *


Translate ยป