Build Your Own RPM Package With a Sample Go Program
Tags: fedora, rhel, rpm, package
Published: 2022-11-17 09:54:23

---
title: Build Your Own RPM Package With a Sample Go Program
published: true
date: 2022-11-16 08:06:55 UTC
tags: #fedora #rhel #rpm #package
canonical_url: https://developers.redhat.com/articles/2021/05/21/build-your-own-rpm-package-sample-go-program
---

> This post was originally published on Red Hat Developer. To read the original post, visit [Build your own RPM package with a sample Go program](https://developers.redhat.com/articles/2021/05/21/build-your-own-rpm-package-sample-go-program).

A deployment usually involves multiple steps that can be tricky. These days, we have a wide variety of tools to help us create reproducible deployments. In this article, I will show you how easy it is to build a basic RPM package.

We have had package managers for a while. [RPM](https://rpm.org) and [YUM](http://yum.baseurl.org) simplify installing, updating, or removing a piece of software. However, many companies use package managers only to install software from the operating system vendor and don’t use them for deployments. Creating a package can be daunting at first, but usually, it’s a rewarding exercise that can simplify your pipeline. As a test case, I will show you how to package a simple program written in [Go](https://go.dev).

## Creating the package

Many sites rely on configuration managers for deployment. For instance, a typical [Ansible](https://developers.redhat.com/products/ansible/overview) playbook might be:

```yaml
 tasks:
    - name: 'Copy the artifact'
      copy:
        src: 'my_app'
        dest: '/usr/bin/my_app'
      
    - name: 'Copy configuration files'
      template:
        src: config.json
        dest: /etc/my_app/config.json
```

Of course, a real-life playbook will include more steps, like checking the previous installation or handling services. But why not use something like this?

```yaml
  tasks:
    - name: 'Install my_app'
      yum:
        name: 'my_app'
```

Now, let’s see our Go application that serves up a webpage. Here's the `main.go` file:

```go
package main

import (
    "encoding/json"
    "flag"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

type config struct {
    Text string `json:"string"`
}

func main() {

    var filename = flag.String("config", "config.json", "")
    flag.Parse()

    data, err := ioutil.ReadFile(*filename)
    if err != nil {
        log.Fatalln(err)
    }

    var config config
    err = json.Unmarshal(data, &config)

    if err != nil {
        log.Fatalln(err)
    }

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, config.Text)
    })

    log.Fatal(http.ListenAndServe(":8081", nil))

}
```

And our `config.json`:

```json
{
    "string": "Hello world :)"
}
```

If we run this program, we should see a web page with the config.json text in port 8081. It's far from production-ready, but it will serve as an example.

## Adding services

What about a service? Adding services is an excellent way to unify the management of an application, so let’s create our `my_app.service`:

```bash
[Unit]
Description=My App

[Service]
Type=simple
ExecStart=/usr/bin/my_app -config /etc/my_app/config.json

[Install]
WantedBy=multi-user.target
```

Every time we want to deploy our application, we need to:

1. Compile the project.
2. Copy it to `/usr/bin/my_app`.
3. Copy the `config.json` file to `/etc/my_app/config.json`.
4. Copy `my_app.service` to `/etc/systemd/system/`.
5. Start the service.

## Creating the spec file

Like Ansible, an RPM package needs a definition file where we specify the installation steps, the dependencies, and other things that we might need to install our application on a server:

```bash
$ sudo dnf install git
$ sudo dnf module install go-toolset
$ sudo dnf groupinstall "RPM Development Tools"
```

With all of this installed, we are ready to create the package definition file, also known as the spec file:

```bash
$ rpmdev-newspec my_app.spec
```

A spec file can be tricky, but we will keep this simple to appreciate the power of the tool:

```yaml
Name:           my_app
Version:        1.0
Release:        1%{?dist}
Summary:        A simple web app

License:        GPLv3
Source0:        %{name}-%{version}.tar.gz

BuildRequires:  golang
BuildRequires:  systemd-rpm-macros

Provides:       %{name} = %{version}

%description
A simple web app

%global debug_package %{nil}

%prep
%autosetup


%build
go build -v -o %{name}


%install
install -Dpm 0755 %{name} %{buildroot}%{_bindir}/%{name}
install -Dpm 0755 config.json %{buildroot}%{_sysconfdir}/%{name}/config.json
install -Dpm 644 %{name}.service %{buildroot}%{_unitdir}/%{name}.service

%check
# go test should be here... :)

%post
%systemd_post %{name}.service

%preun
%systemd_preun %{name}.service

%files
%dir %{_sysconfdir}/%{name}
%{_bindir}/%{name}
%{_unitdir}/%{name}.service
%config(noreplace) %{_sysconfdir}/%{name}/config.json


%changelog
* Wed May 19 2021 John Doe - 1.0-1
- First release%changelog
```

A few notes:

* The `Source0` entry can be the source code repository, something like this: `https://github.com/user/my_app/archive/v%version.tar.gz`.
* If you use a URL in `Source0`, you can issue `spectool -g my_app.spec` to download your source code.
* Git allows you to quickly set up a tarball without creating a remote repository:

```bash
$ git archive --format=tar.gz --prefix=my_app-1.0/ -o my_app-1.0.tar.gz HEAD
```

* The tarball content should look like this:

```bash
$ tar tf my_app-1.0.tar.gz 
my_app-1.0/
my_app-1.0/config.json
my_app-1.0/main.go
my_app-1.0/my_app.service
```

## Building the RPM

First, we need to create the rpmbuild structure and place our tarball inside the source's directory:

```bash
$ rpmdev-setuptree
$ mv my_app-1.0.tar.gz ~/rpmbuild/SOURCES
```

Now, let’s build the RPM for [Red Hat Enterprise Linux](https://developers.redhat.com/products/rhel/overview) 8:

```bash
$ rpmbuild -ba my_app.spec
```

And that's it!

You should be able to install the RPM now and start the service:

```bash
$ sudo dnf install ~/rpmbuild/RPMS/x86_64/my_app-1.0-1.el8.x86_64.rpm
$ sudo systemctl start my_app
$ curl -L http://localhost:8081
```

You should see the content of our `config.json` (which, by the way, is under `/etc/my_app`).

But what if we have a new version of our application? We only need to increase the spec file version and build it again. DNF will see that there is a new update available.

And if you are using a package repository, you only need to run `dnf update my_app`.

## Conclusion

If you want to delve more into the idea of incorporating RPM files in your deployments, I suggest looking at the [RPM Packaging Guide](https://rpm-packaging-guide.github.io) and the [Fedora Packaging Guidelines](https://docs.fedoraproject.org/en-US/packaging-guidelines).

Also, a variety of exciting tools are available to help with the build process or even create repositories for you to use, such as [mock](https://github.com/rpm-software-management/mock), [fedpkg](https://pagure.io/fedpkg), [COPR](https://pagure.io/copr/copr), and [Koji](https://pagure.io/koji/). These tools can help you in complex scenarios with multiple dependencies, complex steps, or multiple architectures.

Note that the workflow demonstrated in this article is also applicable to Fedora and to CentOS Stream.