# How to set up jenkins with gitea

In the process of developing and releasing software, one of the most useful tools at a developer's disposal is a solution that performs **continuous integration** and **continuous deployment**, or **CI/CD**.

Continuous integration (CI) refers to the practice of multiple developers merging their changes to a codebase back into the main branch often, perhaps daily or even more frequently, relying on smaller chunks of work that are more easily reviewed to and tested during the process of development. In order to ensure that these changes don't leave the main branch in a broken state, a tool that helps with continuous integration will often include functionality that runs test suites within the software package. When a developer proposes a merge of their work back into the main branch, the tests will run automatically and report back whether or not they pass, which may mean that the code is not ready to land.

Continuous deployment or continuous delivery (CD) refers to the idea that changes to code --- whether they're security patches, bug fixes, or new features --- be released quickly and seamlessly to the end users of the application. In the case of applications that the user runs, this will mean a frequent release schedule, offering incremental improvements to the software they are using. In the case of a service such as a website, this will mean frequent deployments of the new features in the code to the site so that the user's experience is continuously improving.

There are several tools that can help with CI/CD. These run as their own web services, which work with many source code management (SCM) systems to perform these tasks automatically. [Jenkins](https://jenkins.io) is one such solution, that provides a way of executing **pipelines** --- sets of steps that the service will run through such as building the software and running tests --- that are described in the code itself. Jenkins is a full-featured CI/CD tool with a flexible, declarative pipeline syntax that allows you to accomplish many tasks.

This tutorial aims to show how Jenkins can integrate with the source code management tool Gitea in order to offer fully self-hosted solutions for SCM and CI/CD. You will be connecting Jenkins with Gitea, and creating a sample project for Jenkins to run tests on in order to see how the two services work together.

### Prerequisites

For this tutorial, you will need the following:

* A server set up running an installation of Gitea. For more information on how to run Gitea on your own server, see this tutorial on [How To Install Gitea on Ubuntu Using Docker](https://www.digitalocean.com/community/tutorials/how-to-install-gitea-on-ubuntu-using-docker), which will walk you through the steps of [setting up your own Ubuntu server](https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-20-04), [Installing Docker](https://www.digitalocean.com/community/tutorials/how-to-install-and-use-docker-on-ubuntu-20-04), [Installing Docker Compose](https://www.digitalocean.com/community/tutorials/how-to-install-and-use-docker-compose-on-ubuntu-20-04#step-1-installing-docker-compose), and then installing Gitea [on your own domain](https://docs.digitalocean.com/products/networking/dns/).
* A server set up running an installation of Jenkins. For more information on how to set up your own instance of Jenkins, This tutorial on [How to Install Jenkins on Ubuntu 20.04](https://www.digitalocean.com/community/tutorials/how-to-install-jenkins-on-ubuntu-20-04) will get you going.

## Step 1 — Prepare Gitea for Integration

Jenkins communicates to Gitea via a user that you create on your Gitea instance. In order to create this user, log into an account on your Gitea instance with administrative access. Click on your user icon in the upper right corner of the page and go to **Site Administration**, and then the **User Accounts** tab. Click **Create User Account** and make a new account named `jenkins`. Enter an email and secure password, then uncheck **Require user to change password**; this user will not be used to log into Gitea except to manage its connection to Jenkins, and that will be by the system administrators.

Once you have created the user, you will need to add a team to the organization that contains your source code's repository. On the organization's page, there will be a **Teams** section. Click **New Team** and create a team named `ci`. You can give this team access to all repositories or just the ones you specify. You may leave the permissions as is unless other work will be undertaken by the `ci` team members, in which case change them to meet your needs; you will always be able to update this later. Add your `jenkins` user to this team once it has been created by clicking the **Add Team Member** button on the team's page.

Now that you have the user set up for Jenkins to access, you will need to create an application token. To do this, log out of your current account and then log in as the `jenkins` user you just created. Click on your user icon in the upper right corner of the page, and click on **Settings**. In the tabs at the top of the page, click **Applications** where you will be able to generate a new access token. In the **Manage Access Tokens** section of the page, fill in the **Token Name** field with `jenkins` and click **Generate Token**. You will be provided with a token at the top of the page, a series of hexadecimal letters and numbers. Copy this token and paste it somewhere safe, as you will need it in future steps, and it will not be shown again.

## Step 2 — Install the Gitea Plugin

The first step to integrate Jenkins with Gitea is to install the Gitea plugin in Jenkins. In order to do so, from the main dashboard, click **Manage Jenkins**. Once you're there, you will find a link titled **Manage Plugins**. Once you click that, in the tabs beneath the title of the page, select **Available**. This will allow you to search the Jenkins repository for all available plugins. Filter for "Gitea" and the plugin will appear in the list. Tick the checkbox next to the plugin and click **Install without restart**.

When the plugin is installed, you will be able to configure Jenkins to use your Gitea server. This is done through the **Manage Jenkins** page again, available via a link on the menu. There, you will see a link to **Configure System**. Scrolling down the page, you will find a **Gitea Servers** section. Click **Add** beneath to add a Gitea server. In that section, enter a name for the Gitea server, and then its full URL.

This section will also have a checkbox labeled **Manage hooks**. By default, Jenkins will only build Gitea branches and pull requests on demand. For each repository configured with Jenkins, you can opt to let Jenkins manage the webhooks that are called when a pull requests is created which will start the Jenkins pipeline. However, checking the **Manage hooks** checkbox while configuring the server will do this by default for all repositories. It acts as an "opt out" setting, rather than the default "opt in". If you do decide to check this box, you will be prompted to enter credentials. Add a new set of credentials, and on the modal pop-up that is shown, set the kind of credentials to "Gitea Personal Access Token" and the scope to "System". This will ensure that the Gitea owner of the access token will only have access to Jenkins and its nodes.

[![Jenkins Gitea server screen](TODO)](TODO)

Name your credential something like `jenkins-gitea` and paste your token from **Step 1** into the token field. This will give Jenkins application access to Gitea via the token created for the `jenkins` user. Leave the **ID** and **Description** fields blank and click **Add**. When you are returned to the server configuration, click **Save** to create the Gitea server in Jenkins.

## Step 3 — Map Gitea to Jenkins

Now that both Gitea and Jenkins are prepared, you can map them to each other. On the Jenkins dashboard, click **+ New Item**. This will provide you with a list of various types of items that you can create. For the purposes of CI with Gitea, you will need to create an organization. Type the name of you organization in the field provided, click **Organization Folder**, and then click **OK** to create the organization. This will provide you with the ability to set up your organisation. Set the name of the organization and provide a short description, then, under **Projects**, add a Gitea organization via the **Add** drop down provided. This will pre-fill with some of the information you added in the previous step, but you will need to associate credentials with the project. If you created the credentials in the previous step, those will appear in the list when you click **Add** in the credentials section, otherwise you will need to create them as above, using the access token you created in **Step 1**. Follow the instructions in **Step 2** for creating the credentials, making sure to set the kind to "Gitea Personal Access Token". In the **Owner** field, enter `jenkins`, the user you created in **Step 1**.

In the **Behaviors** section, you will be able to set how Jenkins discovers code to run its CI pipeline against. For instance, you can set it so that Jenkins discovers all branches whether or not they have filed pull requests, or what types of pull requests to discover. For now, the default behaviors are fine, so you do not need to change them. The rest of the page contains various other ways that you can tune Jenkins's interaction with Gitea, all of which have sensible defaults, so you do not need to change them, but if you would like to learn more, clicking on the question marks within each section will provide you with more information about how each field works.

When you are done creating the organization folder, click **Save** and you will be shown the results of Jenkins scanning the Gitea organization for repositories and branches that meet its criteria. For now, the criteria is simply whether or not a repository contains a file named `Jenkinsfile`, which describes the pipeline used to test or deploy the project. We will create the pipeline in the next step

## Step 5 — Create the Jenkins CI Pipeline

Let's create a sample project in order to test this interaction. In Gitea, create a new repository, and then clone it on your local machine. Since Jenkins works with pull requests, switch to a new branch named `jenkins`:

```command
git checkout -b jenkins
```

Using your favorite code editor, create a new file named `jenkins_test.py` and enter the following into it:

```python
[label jenkins_test.py]
assert 1 == 1
```

This simple Python script ensure that 1 really is equal to 1, which is a very important fact to have at hand. Save and close the file in your code editor.

Now, open up a new file in your project named `Jenkinsfile` (including the capital `J`), and enter the following:

```jenkinsfile
[label Jenkinsfile]
pipeline {
    agent none
    stages {
        stage('test') {
            agent {
                docker {
                    image "python"
                }
            }
            steps {
                script {
                    sh """
                    python jenkins_test.py
                    """
                }
            }
        }
    }
}
```

Let's go over what this pipeline is saying.

* We set `agent none` at the beginning as we will be using a docker agent specifically within the `test` stage.
* Jenkins pipelines are made up of various different stages, which can be tasks such as testing, linting, and deploying your code. In this case, we created a `test` stage to run tests against our Python.
* The agent declaration says that this stage should use a Docker container running the `python` image from the public Docker registry.
* The `steps` section is where the real work occurs. Each step required for testing is provided in order. In our case, we only have one step, which is to run a script in the shell, which calls `python jenkins_test.py`.

Add both of these files to your Git working tree and commit your changes:

```command
git add .
git commit -m "Added test and Jenkinsfile"
```

Now, push your branch up to Gitea:

```command
git push origin jenkins
```

On the repository page in Gitea, create a new pull request in order to merge your `jenkins` branch into your main branch (often named `main` or `master`). Since Jenkins is watching the repository and now sees that there is a `Jenkinsfile` in the branch you are trying to merge in, it recognizes that this is a repository that it should track and will begin running the pipeline for that pull request.

<$>[note]
**Note:** Jenkins may not pick up on this change right away depending on whether or not the webhooks are configured for the project. If that's the case, on the Jenkins page for your organization, click **Scan Gitea Organization Now** and it should pick up on the ranch and repository.
<$>

On the Jenkins page for your organization, you should see your repository in the list. When you click on it, you will be provided with a list of pipelines that are running; there should be one in the **Pull Requests** section for "PR-1". When you click on that, you should see the status of the current pipeline. If it is running, you can click on **Console Output** on the left menu to view the steps that it is taking such as creating the Docker container, pulling the Python image, and then running the script specified in the Jenkinsfile. If 1 is indeed equal to 1, then this build should be successful.

When you look back at your pull request on Gitea, you will see that there is a new section above the comment box where it is running checks via Jenkins. This can be **in progress** where the indicator is yellow, or **checks passed** if it's green or **checks failed** if it's red. This provides an indicator as to the branch's status within Gitea itself, so that you need not open up Jenkins just to check for a pass or fail.

## Conclusion

In this tutorial, you learned how to set up Jenkins and Gitea so that you can run continuous integration pipelines against your source code repositories. Continuous integration ensures that the quality of your code remains high and that the chances of breaking changes being introduced into your main branch of your code. Just as Gitea provides an excellent self-hosted source code management solution, Jenkins provides an excellent continuous integration solution, and together, they can help keep your project moving quickly and cleanly.
