All posts by Kipkoech Sang

I am a technology enthusiast who loves to share gained knowledge through offering daily tips as a way of empowering others. I am fan of Linux and all other things open source.

How to install SaltStack on Fedora 36

In this guide, we will walk you through the installation of SaltStack on Fedora 36.

SaltStack is a Python-based, open-source for event-driven It automation, remote task execution, and configuration management. Salt was designed to be highly modular and easily extensible, to make it easy to mold to diverse IT enterprise use cases.

Salt is capable of maintaining remote nodes in defined states that is it can ensure specific packages are installed and that specific services are running. Salt can query and execute commands either on individual nodes or by using arbitrary selection criteria.

The core functions of Salt

  • Salt enables commands on the remote systems to be called in parallel rather than serially.
  • Salt provides a simple programming interface.
  • It uses the smallest and fastest network payload possible
  • Use a secure and encrypted protocol.

Salt Architecture

Salt uses the master client model. Master issues command to the client and the client executes the commands. Salt master is the server that is running the salt-master service. Salt minions are the servers running the salt-minion services.

A target is a group of minions across one or many masters that a job’s salt command applies to.

Grains interface derives information about the underlying system. Grains are collected for the operating system, domain name, IP addresses, kernel os, etc.

Installing salt on Fedora 36

1. Update system repositories

Before we begin, we need to update our system repositories in order to make them up to date.

sudo dnf update 

2. Install Salt on Fedora 36

Salt is readily available on Fedora repositories and the EPEL. So it is easy to run and install Salt using the dnf or the yum package.

To install both Salt master and minion on your system, use the following command and remember that you need to install a master on the control machine and minions on the servers you want the salt to run on.

Install Salt master

$ sudo dnf install salt-master

The following is the output from the above command.

Package                    Arch        Version              Repository    Size
================================================================================
Installing:
 salt-master                noarch      3004.2-1.fc36        updates      3.1 M
Installing dependencies:
 dnf-utils                  noarch      4.2.1-1.fc36         updates       37 k
 libtomcrypt                x86_64      1.18.2-14.fc36       fedora       389 k
 libtommath                 x86_64      1.2.0-7.fc36         fedora        63 k
 libunwind                  x86_64      1.6.2-2.fc36         fedora        67 k
 openpgm                    x86_64      5.2.122-28.fc36      fedora       177 k
 python3-msgpack            x86_64      1.0.3-2.fc36         fedora        86 k
 python3-pycryptodomex      x86_64      3.15.0-1.fc36        updates      1.1 M
 python3-pycurl             x86_64      7.45.1-1.fc36        fedora       186 k
 python3-zmq                x86_64      22.3.0-2.fc36        fedora       403 k
 salt                       noarch      3004.2-1.fc36        updates      9.3 M
 zeromq                     x86_64      4.3.4-3.fc36         fedora       440 k

Transaction Summary
================================================================================
Install  12 Packages

Total download size: 15 M
Installed size: 58 M
Is this ok [y/N]: y

To install Salt minion we use the following command.

sudo dnf install salt-minion

Whenever you want to connect to minions, you need to have proper permission and for this we need to have Salt ssh.

sudo dnf install salt-ssh

In order to install Salt API we use the following command.

sudo dnf install salt-api

3. Post installation tasks

After the installation is complete, you can run post installations tasks on both master and minions.

To enable Salt master start automatically on boot use the following command.

sudo systemctl enable salt-master

To start Salt master, we use the following command

sudo systemctl start salt-master

To enable Salt minion start automatically on boot we use the this command.

sudo systemctl enable salt-minion

To start Salt minion, we use the following command.

sudo systemctl start salt-minion

To check the status of both Salt master and Salt minion, we use the following command.

$ sudo systemctl status salt-master // for salt master
$ sudo systemctl status salt-minion // for salt minion
● salt-master.service - The Salt Master Server
     Loaded: loaded (/usr/lib/systemd/system/salt-master.service; enabled; ven>
     Active: active (running) since Sat 2022-08-13 06:36:03 UTC; 11s ago
       Docs: man:salt-master(1)
             file:///usr/share/doc/salt/html/contents.html
             https://docs.saltproject.io/en/latest/contents.html
   Main PID: 10739 (salt-master)
      Tasks: 32 (limit: 1113)
     Memory: 199.1M
        CPU: 6.621s
     CGroup: /system.slice/salt-master.service
             ├─ 10739 /usr/bin/python3 /usr/bin/salt-master
             ├─ 10743 /usr/bin/python3 /usr/bin/salt-master
             ├─ 10746 /usr/bin/python3 /usr/bin/salt-master
             ├─ 10747 /usr/bin/python3 /usr/bin/salt-master
             ├─ 10750 /usr/bin/python3 /usr/bin/salt-master
             ├─ 10751 /usr/bin/python3 /usr/bin/salt-master
             ├─ 10752 /usr/bin/python3 /usr/bin/salt-master
             ├─ 10759 /usr/bin/python3 /usr/bin/salt-master
             ├─ 10760 /usr/bin/python3 /usr/bin/salt-master
             ├─ 10762 /usr/bin/python3 /usr/bin/salt-master
             ├─ 10766 /usr/bin/python3 /usr/bin/salt-master
             ├─ 10768 /usr/bin/python3 /usr/bin/salt-master

4. Configuration of the Saltstack

To start off, we need to configure the master so that it will know of the existence of the minions. All the configuration files are found on /etc/salt/.The minions or the master must be findable for it to establish the communication.

To configure Salt master go to /etc/salt/master and add your master IP address with Salt-master IP address.

$ sudo vi /etc/salt/master

Uncomment interface and add the salt-master IP address.

Restart Salt-master for the changes to take effect.

sudo systemctl restart salt-master

Next we need to configure Salt-minion, go to /etc/salt/minion and replace master: salt with a master IP address.

sudo /etc/salt/minion

Uncomment master: salt and remove salt and replace with your master IP address.

We need to restart the server again for the changes to take effect.

sudo systemctl restart salt-minion 

5. Test configuration

To see the configuration use the following commands:

sudo salt-key -L

From the above command you be in a position to see the following:

Accepted Keys:
Denied Keys:
Unaccepted Keys:
Rejected Keys:

To accept all keys use the following command.

$ salt-key -A

Conclusion

Congratulations we have installed Salt-master and Salt-Minion on Fedora 36.

How to install PostgreSQL 15 Beta on Ubuntu 22.04

In this guide, we are going to walk through installing PostgreSQL 15 Beta on Ubuntu 22.04.

PostgreSQL is a powerful, open-source object-relational database system that uses and extends the SQL language combined with many features that safely store and scale the most complicated data workloads. It was designed to handle a range of workloads from single machines to data warehousing.

Every single database must conform to ACID properties i.e Atomicity, Consistency, Isolation, and Durability. This is true for PostgreSQL as well, it must conform to those features for transactions to pass the tests.

1. Update the Ubuntu repository

The first thing to do is to update the ubuntu repository in order to make them up to date.

$ sudo apt update && apt upgrade -y

2. Install PostgreSQL 15 on Ubuntu 22.04

In order to run PostgreSQL 15 on Ubuntu 22.04, we are supposed to add 15 component to /etc/apt/sources.list.d/pgdg.list entry so that version 15 will be available for installation.

In order to add 15 to sources.list file, use the following command.

sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main 15" > /etc/apt/sources.list.d/pgdg.list'

Next, we need to import the repository signing key.

wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -

The next thing is to update the system again for the changes to take effect.

sudo apt update 

Lastly, install PostgreSQL with the following command.

apt-get install postgresql-15

You will get the following as the output

The following additional packages will be installed:
  libcommon-sense-perl libjson-perl libjson-xs-perl libllvm14 libpq5
  libtypes-serialiser-perl pgdg-keyring postgresql-client-15
  postgresql-client-common postgresql-common ssl-cert
Suggested packages:
  postgresql-doc-15
The following NEW packages will be installed:
  libcommon-sense-perl libjson-perl libjson-xs-perl libllvm14 libpq5
  libtypes-serialiser-perl pgdg-keyring postgresql-15 postgresql-client-15
  postgresql-client-common postgresql-common ssl-cert
0 upgraded, 12 newly installed, 0 to remove and 9 not upgraded.
Need to get 44.1 MB of archives.
After this operation, 176 MB of additional disk space will be used.
Do you want to continue? [Y/n] 

3. Setting up password for Postgres role

Local connections on Posgtresql use peer to check the authenticated users. That is Postgresql instead of asking for the user password, it only checks on the logged-in user to ascertain if the user has credentials to get access to the resources.

Let’s change the way we log in and use a more strong password instead. Let’s set the password for the Postgres user first.

Open psql as the Postgres user with this command sudo -u postgres psql

$ sudo -u postgres psql

You will get output like this.

could not change directory to "/root": Permission denied
psql (15beta3 (Ubuntu 15~beta3-1.pgdg22.04+1))
Type "help" for help.

postgres=# 

The reason we are getting could not change directory to "/root": Permission denied psql is because of the Postgres authentication, we need to set the password first.

To change the Postgres password use the following command inside of the Postgres interface.

postgres=# ALTER USER POSTGRES WITH ENCRYPTED PASSWORD 'strgpasswd';

After we have set the password, we now need to tell Postgres to use this password. To do that we need to change pg_hba.conf file. I am using vim as my text editor here, you are free to use your preferred editor as well.

Look for this line of code and change peer to md5

local  all  postgres  peer
local  all  postgres  md5

To edit the configuration file use the following command.

sudo vi /etc/postgresql/15/main/pg_hba.conf

Restart PostgreSQL for the changes to take effect.

sudo systemctl restart postgresql

We can also ascertain whether PostgreSQL is running on our system with the following command.

sudo systemctl status postgresql

If you get the status active then we are good to go.

 ● postgresql.service - PostgreSQL RDBMS
     Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor pr>
     Active: active (exited) since Fri 2022-08-12 06:48:04 UTC; 1min 57s ago
    Process: 25558 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
   Main PID: 25558 (code=exited, status=0/SUCCESS)
        CPU: 2ms

Aug 12 06:48:04 localhost systemd[1]: Starting PostgreSQL RDBMS...
Aug 12 06:48:04 localhost systemd[1]: Finished PostgreSQL RDBMS.
lines 1-9/9 (END)

After this, we can log in again to the Postgres

psql -U postgres
psql (15beta3 (Ubuntu 15~beta3-1.pgdg22.04+1))
Type "help" for help.

postgres=# 

We have successfully changed Postgres to use password authentication.

Conclusion

Congratulations, we have successfully installed PostgreSQL 15 on Ubuntu 22.04 and also set the password for the default user Postgres. For more information get the latest from PostgreSQL documentation.

For user disclaimer, this is the beta version so it’s not suitable to use in production because it’s still very unstable.

How to install Monit 5 on Fedora 36

In this tutorial, we are going to learn how to install Monit 5 on Fedora 36.

Monit is a small open source utility for monitoring and managing Unix systems. It performs automatic maintenance whenever there is downtime in your system.

Uses of Monit.

Monit can have many use cases because of its versatility. Let’s look at the following:

  • Monit can be used to monitor files and directories, Monit monitor this system for any changes such as file timestamp, security changes or file size changes, etc.
  • Monit acts proactively, whereby in case of an error in the system functionality, Monit can send an alert to inform that such a process wasn’t complete.
  • Monit can be used to test programs and scripts such as cron jobs do. You can monitor and check the scripts you want to use in any scenario.
  • We use Monit to monitor any daemon processes or any other process running on the localhost such as sshd, Nginx, or MySQL processes.
  • Monit can be used to monitor general system functionality such as CPU and RAM usage.
  • It can be used to monitor network connections on various servers because Monit has built-in tests for Internet protocols such as SMTP, and HTTP.

How to Install Monit 5 on Fedora 36

1. Update system repositories.

Before you begin any installation, make sure you update all the system packages in order to make them up to date. To update Fedora use sudo dnf update.

$ sudo dnf update

Follow the prompts in order to complete updates successfully.

2. Install Monit 5 on Fedora 36

Monit is readily available on the Fedora packages, so to install you use the following command sudo dnf install monit.

$ sudo dnf install monit 

You should be in a position to see the following output.

Fedora Modular 36 - x86_64 - Updates             12 kB/s |  15 kB     00:01    
Dependencies resolved.
================================================================================
 Package        Architecture    Version                  Repository        Size
================================================================================
Installing:
 monit          x86_64          5.32.0-1.fc36            updates          391 k

Transaction Summary
================================================================================
Install  1 Package

Total download size: 391 k
Installed size: 990 k
Is this ok [y/N]: y
Downloading Packages:
monit-5.32.0-1.fc36.x86_64.rpm                  949 kB/s | 391 kB     00:00    
--------------------------------------------------------------------------------
Total                                           619 kB/s | 391 kB     00:00     
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                        1/1 
  Installing       : monit-5.32.0-1.fc36.x86_64                             1/1 
  Running scriptlet: monit-5.32.0-1.fc36.x86_64                             1/1 
  Verifying        : monit-5.32.0-1.fc36.x86_64                             1/1 

Installed:
  monit-5.32.0-1.fc36.x86_64                                                    

Complete!

3. Configure Monit service

To configure Monit to start on boot we use the following command sudo systemctl enable monit

$ sudo systemctl enable monit

To start Monit immediately we use the following command.

$ sudo systemctl start monit 

To check the status of Monit we use the following command.

$ sudo systemctl status monit 
● monit.service - Pro-active monitoring utility for unix systems
     Loaded: loaded (/usr/lib/systemd/system/monit.service; enabled; vendor pre>
     Active: active (running) since Thu 2022-08-11 08:00:10 UTC; 12s ago
       Docs: man:monit(1)
             https://mmonit.com/wiki/Monit/HowTo
   Main PID: 15788 (monit)
      Tasks: 2 (limit: 1113)
     Memory: 2.0M
        CPU: 29ms
     CGroup: /system.slice/monit.service
             └─ 15788 /usr/bin/monit -I

Aug 11 08:00:10 localhost.localdomain systemd[1]: Started monit.service - Pro-a>
Aug 11 08:00:10 localhost.localdomain monit[15788]:  New Monit id: d45a290ce0d6>
                                                     Stored in '/root/.monit.id'
Aug 11 08:00:10 localhost.localdomain monit[15788]: Starting Monit 5.32.0 daemo>
Aug 11 08:00:10 localhost.localdomain monit[15788]: 'localhost.localdomain' Mon>

There are packages installed with Monit automatically. To check those files you can use the following command rpm -ql monit.

$ sudo rpm -ql monit
/etc/monit.d
/etc/monitrc
/usr/bin/monit
/usr/lib/.build-id
/usr/lib/.build-id/9a
/usr/lib/.build-id/9a/670fe3396cb159ea1c384f1f673a420b3691ed
/usr/lib/systemd/system/monit.service
/usr/share/doc/monit
/usr/share/doc/monit/CHANGES
/usr/share/doc/monit/COPYING
/usr/share/man/man1/monit.1.gz

NB: Prefix sudo whenever you are working as a regular user.

Conclusion

We have successfully installed and configured Monit on Ubuntu 22.04. For further reference check the Monit documentation.

How to install Monit 5 on Ubuntu 22.04

Monit is a small open source utility for monitoring and managing Unix systems. It performs automatic maintenance whenever there is downtime in your system. From this tutorial, you are going to learn how to install Monit on Ubuntu 22.04.

Uses of Monit.

Monit can have many use cases because of its versatility. Let’s look at the following:

  • Monit can be used to monitor files and directories, Monit monitor this system for any changes such as file timestamp, security changes or file size changes, etc.
  • Monit acts proactively, whereby in case of an error in the system functionality, Monit can send an alert to inform that such a process wasn’t complete.
  • Monit can be used to test programs and scripts such as cron jobs do. You can monitor and check the scripts you want to use in any scenario.
  • We use Monit to monitor any daemon processes or any other process running on the localhost such as sshd, Nginx, or MySQL processes.
  • Monit can be used to monitor general system functionality such as CPU and RAM usage.
  • It can be used to monitor network connections on various servers because Monit has built-in tests for Internet protocols such as SMTP, and HTTP.

How to install Monit on Ubuntu 22.04

1. Run system updates.

Before we begin the installation, let’s start by updating our system repositories to make them up to date.

sudo apt update && apt upgrade -y

2. Install Monit from the packages.

Because Monit is available on the Ubuntu package repository, we are only going to use the following command to do the install apt install monit.

$ sudo apt install monit

You should be in a position to see the following output.

Suggested packages:
  default-mta | postfix | mail-transport-agent sysvinit-core
The following NEW packages will be installed:
  monit
0 upgraded, 1 newly installed, 0 to remove and 304 not upgraded.
Need to get 399 kB of archives.
After this operation, 1,100 kB of additional disk space will be used.
Get:1 http://ke.archive.ubuntu.com/ubuntu jammy/universe amd64 monit amd64 1:5.31.0-1 [399 kB]
Fetched 399 kB in 1s (497 kB/s)
Selecting previously unselected package monit.
(Reading database ... 330871 files and directories currently installed.)
Preparing to unpack .../monit_1%3a5.31.0-1_amd64.deb ...
Unpacking monit (1:5.31.0-1) ...
Setting up monit (1:5.31.0-1) ...
Processing triggers for man-db (2.10.2-1) ...

After the installation is complete, we can check the version with the following command monit --version.

$ monit --version
This is Monit version 5.31.0
Built with ssl, with ipv6, with compression, with pam and with large files
Copyright (C) 2001-2022 Tildeslash Ltd. All Rights Reserved.

3. Configure Monit service

To configure Monit to start on boot we use the following command sudo systemctl enable monit

$ systemctl enable monit

To start Monit immediately we use the following command.

$ sudo systemctl start monit 

To check the status of Monit we use the following command.

$ sudo systemctl status monit 
● monit.service - LSB: service and resource monitoring daemon
     Loaded: loaded (/etc/init.d/monit; generated)
     Active: active (running) since Thu 2022-08-11 08:47:50 EAT; 15min ago
       Docs: man:systemd-sysv-generator(8)
      Tasks: 1 (limit: 9355)
     Memory: 2.6M
        CPU: 141ms
     CGroup: /system.slice/monit.service
             └─16979 /usr/bin/monit -c /etc/monit/monitrc

Ago 11 08:47:50 zx-pc systemd[1]: Starting LSB: service and resource monitoring>
Ago 11 08:47:50 zx-pc monit[16966]:  * Starting daemon monitor monit
Ago 11 08:47:50 zx-pc monit[16966]:    ...done.
Ago 11 08:47:50 zx-pc systemd[1]: Started LSB: service and resource monitoring >
lines 1-14/14 (END)

Conclusion

We have successfully installed and configured Monit on Ubuntu 22.04. For further reference check the Monit documentation.

How to install Redis on Ubuntu 22.04

Welcome to this tutorial where we will learn how to install the Redis server o Ubuntu 22.04.

Redis server is an open source in-memory data store used by many developers as a database, cache, streaming engine, and message broker.

Redis as a real-time data store means Redis’ versatile in-memory data structures let you build data infrastructure for real-time applications requiring low latency and high throughput

Caching and session storage. Redis speed is ideal for caching database queries, complex computations, API calls, and session states.

Streaming and messaging. Streamed data type enables high-speed data ingestion, messaging, event sourcing, and notifications.

Install Redis on Ubuntu 22.04

1. Update system repositories

Before we begin the installation, we need to update our system repositories in order to make system repositories up to date.

$ sudo apt update && apt upgrade -y

2. Add Redis to the apt repository

To install the stable version of Redis we need to install it from the official Redis packages and to do so we need to add an apt repository .

$ curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg

Add the downloaded package to the repository by using echo.

$ echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list

What follows is to update the system repositories once more for the changes to take effect.

sudo apt update

Lastly is to install Redis with the following command.

sudo apt install redis 

You should get the output something like this.

The following additional packages will be installed:
  redis-server redis-tools
Suggested packages:
  ruby-redis
The following NEW packages will be installed:
  redis redis-server redis-tools
0 upgraded, 3 newly installed, 0 to remove and 0 not upgraded.
Need to get 1642 kB of archives.
After this operation, 9437 kB of additional disk space will be used.
Do you want to continue? [Y/n] 

3. Testing Redis

If your installation was successful, you can test Redis with the following command.

sudo systemctl status redis-server 

You must see the following output.

● redis-server.service - Advanced key-value store
     Loaded: loaded (/lib/systemd/system/redis-server.service; disabled; vendor>
     Active: active (running) since Tue 2022-07-26 07:41:00 UTC; 7min ago
       Docs: http://redis.io/documentation,
             man:redis-server(1)
   Main PID: 24426 (redis-server)
     Status: "Ready to accept connections"
      Tasks: 5 (limit: 1033)
     Memory: 2.8M
        CPU: 385ms
     CGroup: /system.slice/redis-server.service
             └─24426 "/usr/bin/redis-server 127.0.0.1:6379" "" "" "" "" "" "" ""

Jul 26 07:41:00 localhost systemd[1]: Starting Advanced key-value store...
Jul 26 07:41:00 localhost systemd[1]: Started Advanced key-value store.
lines 1-15/15 (END)

We can also leverage Redis-cli whenever we want to test whether Redis is working correctly. To use Redis-cli use the following command to ping the connection.

$ redis-cli

root@localhost:~# redis-cli
127.0.0.1:6379> ping
PONG
127.0.0.1:6379> ping
PONG
127.0.0.1:6379> 

To know that Redis is establishing communication, you will get an output as pong

4. Configuring Redis

By default Redis is accessible from the localhost. it doesn’t allow remote connections. So to enable Redis to accept remote connections, we need to edit the following configuration file.

$ sudo vi /etc/redis/redis.conf

Check the line that begins with bind 127.0.0.1 : : 1 and uncomment it.

bind 127.0.0.1 ::1

Save and exit and make sure you restart the Redis server again for the changes to take effect.

sudo systemctl restart redis-server

To check that the service has actually taken effect, let’s test it with the netstat command

$ sudo netstat -lnp | grep redis

If you find an error that netstat is not installed you can do an install with the following command.

sudo apt install net-tools 

You will see the output like this.

tcp        0      0 127.0.0.1:6379          0.0.0.0:*               LISTEN      24735/redis-server  
tcp6       0      0 ::1:6379                :::*                    LISTEN      24735/redis-server 

5. Securing Redis

By default, Redis binds to all interfaces and has no authentication systems in place. To make Redis more secure, use the following steps to harden your Redis.

  • Make sure the port Redis uses to listen for connections (by default 6379 and additionally 16379 if you run Redis in cluster mode, plus 26379 for Sentinel) is firewalled so that it is not possible to contact Redis from the outside world.
  • Use the requirepass option in order to add an additional layer of security so that clients will require to authenticate using the AUTH command.
  • Use a configuration file where the bind directive is set in order to guarantee that Redis listens on only the network interfaces you are using.

In Redis password is configured directly by changing the following configuration file.

$ sudo vi /etc/redis/redis.conf

Scroll down to the security section and change the following and uncomment it and place a very strong password

# requirepass foobared

Save the file and exit and make sure you restart the Redis server again.

sudo systemctl restart redis-server

Conclusion

Congratulations, you have installed and configured the Redis server accordingly. For more information, check its rich documentation.

How to install and setup SFTP server on Ubuntu 22.04

SFTP (Secure File Transfer Protocol) is a file transfer protocol that provides secure access to a remote computer. Think of it as a tunnel provider, whenever you want to connect remotely, you use SFTP protocol to ensure your connection is secure from eavesdropping, we use Secure Shell (SSH) for that.

FTP protocol is a client/server protocol that transfers files over the internet. FTP clients are used to sending and retrieving files to and from servers storing files and also responding to the clients’ needs.

To get started with the installation, make sure ssh is installed, then set up sftp user group, configure ssh service, and lastly connect via sftp service.

1. Update system repositories.

To start off, update your system repositories in order to make them up to date.

sudo apt update && apt upgrade -y

2. Install ssh server

SFTP depends on ssh protocol for communication, we have to install it if not already installed on your system.

sudo apt install ssh 

The following will be the sample output.

Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following NEW packages will be installed:
  ssh
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 4834 B of archives.
After this operation, 133 kB of additional disk space will be used.
Get:1 http://mirrors.linode.com/ubuntu jammy/main amd64 ssh all 1:8.9p1-3 [4834 B]
Fetched 4834 B in 0s (199 kB/s)
Selecting previously unselected package ssh.
(Reading database ... 108902 files and directories currently installed.)
Preparing to unpack .../ssh_1%3a8.9p1-3_all.deb ...
Unpacking ssh (1:8.9p1-3) ...
Setting up ssh (1:8.9p1-3) ...
Scanning processes...                                                           
Scanning candidates...                                                          
Scanning linux images...                                                        

Restarting services...
Service restarts being deferred:
 /etc/needrestart/restart.d/dbus.service
 systemctl restart networkd-dispatcher.service
 systemctl restart systemd-logind.service
 systemctl restart unattended-upgrades.service
 systemctl restart user@0.service

If you want to install FTP over OpenSSH, you need to edit the sshd configuration file.

sudo vim /etc/ssh/sshd_config

You will need to add this below the file.

Match group sftp
ChrootDirectory /home
X11Forwarding no
AllowTcpForwarding no
ForceCommand internal-sftp

Restart the ssh server for the changes to take effect.

sudo systemctl restart ssh

3. Create SFTP user account.

Set up STTP user and group which will log in here.

To set the group use the following command.

$ sudo addgroup sftpgroup
Adding group `sftpgroup' (GID 1000) ...
Done.

Then we need to create sftpuser and you need to assign it to sftp group

sudo useradd -m sftpuser -g sftpgroup

Set the password for sftpuser.

$ sudo passwd sftpuser
New password: 
Retype new password: 
passwd: password updated successfully

Lastly, grant the new user access home directory.

sudo chmod 700 /home/sftpuser/

4. Connect to sftp

To connect to sftp we use the command

$ sftp sftpuser@localhost

For instance, to login to the sftp I have created, I need to type sftp sftpuser@127.0.0.1

$ sftp sftpuser@127.0.0.1
The authenticity of host '127.0.0.1 (127.0.0.1)' can't be established.
ED25519 key fingerprint is 
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '127.0.0.1' (ED25519) to the list of known hosts.
sftpuser@127.0.0.1's password: 
Connected to 127.0.0.1.
sftp> 
sftp> 

5. Useful SFTP commands

Whenever you need help with any command using the following command.

sftp> help

If you want to navigate through your SFTP, use pwd

sftp> pwd
Remote working directory: /home/sftpuser

To download files with sftp command.

sftp> get filename.zip

Conclusion

We have successfully installed sftp on Ubuntu 22.04, happy learning.

How to perform CRUD functionalities in Django Rest Framework

Django Rest framework is a powerful toolkit for building web APIs.

What is an API?

An API (Application Programming Interface) is a set of rules shared by a particular service. These rules determine in which format and with which command set your application can access the service, as well as what data this service can return in the response. It acts as a layer between your application and external service.

REST API (Representational state transfer) is an API that uses HTTPS requests for communication with web services. From the python site, the REST API can be viewed as a data source located on an internet address that can be accessed in a certain way through certain libraries.

Types of Requests:

GET: retrieve information like a search result

POST: adds new data to the server

PUT: changes existing information

DELETE: deletes existing information

Status Codes

200-OK. The request was successful.

204-No content. The server successfully processed the request and did not return any content.

301-Moved permanently. The server responds that the requested page(endpoint) has been moved to another address and redirects to this address.

400-Bad request. The server cannot process the request because of the client-side errors (incorrect request format).

401-Unauthorized. Occurs when authentication failed due to incorrect credentials or even their absence.

403-Forbidden. Access to the specified resource is denied.

404-Not found. The requested resource was not found on the server.

500-Internal Server Error. Occurs when an unknown error has occurred on the server.

Enough with the theory part. Let’s see how we can create CRUD functionalities in the Django Rest framework.

I will create a small to-do list application to guide us through the process.

Steps to follow.

  1. Create a project and set up a virtual environment.
  2. Activate virtual environment
  3. Install Django using pip
  4. Create a project and an app

Create a Django Project and set up a virtual environment.

The first thing to do whenever you are creating Django projects is to set up your virtual environment where you can work in isolation. Let’s start. Install venv package to allow you to create a virtual environment. On your terminal use the following command to create virtual environment.

$ python3 -m venv env 

If you ls you will see your environment created. For my case, I created env as my environment.

To activate your environment, use the following command.

source env/bin/activate

After the environment is activated, let’s install Django using the pip command.

pip install django

Create a requirements.txt file to store all your installations so that the next time someone is using your applications, it will be easy to start off. An easy way to create requirements is to use the freeze command.

pip freeze > requirements.txt

And to do an installation from the requiremets.txt file, use the following command.

pip install -r requiremets.txt

Create a Django Project

To create a Django project, we use the following command.

django-admin startproject myapi .

Take note of the period in the end, it will help create a project from the current directory.

After this is done, create an app.

python manage.py startapp todoapi

The last thing before we can start our server is to go to settings.py and add your created app to the installed apps section. From here the best thing is to open your project using Visual Studio or Pycharm. For me, I will be using Pycharm.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    
    'todoapi',# our app
]

From here you can test if the server is running

python manage.py runserver

if you see the following as output, then we are good to continue.

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
July 13, 2022 - 07:03:07
Django version 4.0.6, using settings 'myapi.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Go to the given IP address to see the outcome.

Let’s render something rather than the default Django output by adding our app to the projects urls.py section.

#myapi.urls
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('todoapi.urls')), # add this todoapi.urls 
]

Also to keep our URLs neat and tidy, go to todoapi and create a urls.py

#todoapi urls.py
from django.urls import path
from . import views 

urlpatterns = [
    path('', views.home, name='home'),
]

Go to todoapi views.py and create the first view of our rest API.

#todoapi/views.py
from django.shortcuts import render
from django.http import HttpResponse


def home(request):
    return HttpResponse("My first api")

You are supposed to see “my first API from the browser”. This means we are good to create our API now.

Create Django Rest API

To start creating a rest API, you need to install djangorestframework and add it to your installed apps in the settings.py

pip install djangorestframework

Then you need to add it to your installed apps

INSTALLED_APPS = [
    ...
    'rest_framework',
]

Also you can add it to your requirements.txt file

pip freeze > requirements.txt 

To begin with, we are going to use function based views therefore we need decorators. For function based views, we use @api_view.

Go to models.py and add the following

#todoapi models.py
from django.db import models


class Todo(models.Model):
    title = models.CharField(max_length=150)
    completed = models.BooleanField(blank=True, null=True, default=False)

    def __str__(self):
        return self.title

To begin, lets create a serializers.py file in our todoapi app first.

#todoapi serializers.py
from rest_framework import serializers

from todoapi.models import Todo


class TodoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Todo
        fields = '__all__'

You need to make migrations for the serializer tables to be created.

$ python manage.py makemigrations
$ python manage.py migrate 

From here you can create admin account so that you can insert the test data. to create admin panel use the following command.

$ python manage.py createsuperuser
Username (leave blank to use 'nextgen'): admin
Email address: 
Password: 
Password (again): 
Superuser created successfully.

The next thing is to register admin in the admin dashboard. use the following.

from django.contrib import admin

# Register your models here.
from todoapi.models import Todo

admin.site.register(Todo)

Running CRUD operations

List Request

To start performing CRUD operations, lets start with the List Operations, this will show all the todos we have in our database. List is a GET operations, so make sure to add that

Go to views.py and add the following.

@api_view(['GET'])
def list_view(request):
    todos = Todo.objects.all()
    serializer = TodoSerializer(todos, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)

Create a url corresponding to the above view.

path('todo-list/', views.list_view, name='todo-list')

Detail Request

The next thing is to create a detail view, also we are going to use GET to retrieve data.

@api_view(['GET'])
def detail_view(request, pk):
    todo = Todo.objects.get(id=pk)
    serializer = TodoSerializer(todo, many=False)
    return Response(serializer.data)

Note we are using primary key to retrieve specific item.

Create corresponding url for detail view set.

path('detail-view/<int:pk>/', views.detail_view, name='detail-view')

Create Request

Here we are using POST to post data into the database. Use the following code

@api_view(['POST'])
def create_view(request):
    serializer = TodoSerializer(data=request.data)

    if serializer.is_valid():
        serializer.save()
    return Response(serializer.data, status=status.HTTP_201_CREATED)

Add corresponding url path

 path('create-todo/', views.create_view, name='create-todo'),

For testing purposes you can use Insomnia or postman or you can stick to the one provided once you access the API on your browser.

Update request

To update a given request we use POST method. use the following code.

@api_view(['POST'])
def update_view(request, pk):
    todo = Todo.objects.get(id=pk)
    serializer = TodoSerializer(instance=todo, data=request.data)

    if serializer.is_valid():
        serializer.save()
    return Response(serializer.data, status=status.HTTP_202_ACCEPTED)

Add corresponding url path

path('update-todo/<int:pk>/', views.update_view, name='update-todo'),

Delete request

To use delete request, DELETE options is called. Use the following code.

@api_view(['DELETE'])
def delete_view(request, pk):
    todo = Todo.objects.get(id=pk)
    todo.delete()
    return Response("Todo deleted successfully", status=status.HTTP_204_NO_CONTENT)

Add corresponding url path accordingly.

path('delete-todo/<int:pk>/', views.delete_view, name='delete-todo'),

Conclusion

We have successfully performed CRUD operations on Django Rest API. To take it further you can use swaggerUI to visualize your API or you can connect to any frontend libraries such React, Vue, Svelte or use Vanilla Javascript.

How to install Prometheus Server on Ubuntu 22.04

In this guide, we will learn how to install the Prometheus server on Ubuntu 22.04. Prometheus is an open-source system monitoring and alerting toolkit. Prometheus collects and stores its metrics as time-series data. Metrics information is stored with the timestamp at which it was recorded, alongside optional key-value pairs called labels.

And now you are wondering what are metrics? Metrics are numeric measurements and time-series mean that the changes are recorded over time.

Install Prometheus on Ubuntu 22.04

1. Update the system repositories.

Let us update the system first in order to make the repositories up to date.

$ sudo apt update && apt upgrade -y

2. Download and install Prometheus

Download the latest release of Prometheus into your system from the Prometheus download page.

$ wget https://github.com/prometheus/prometheus/releases/download/v2.37.0-rc.0/prometheus-2.37.0-rc.0.linux-amd64.tar.gz

After the download is complete, the next step is to extract the archive:

$ tar xvfz prometheus-*.tar.gz

For convenience, we can change the directory for the extracted archive

$ cd prometheus-*

From there we can create a configuration file directory

$ sudo mkdir -p /etc/prometheus

Then we can create the data directory

$ sudo mkdir -p /var/lib/prometheus

Let’s now move the binary files Prometheus and promtool to /usr/local/bin/

Use the following code snippet

$ sudo mv prometheus promtool /usr/local/bin/

Let’s use a Prometheus.yaml file that we can use as an example to see how Prometheus monitors your infrastructure. This file will only monitor itself for now.

$ sudo vi prometheus.yml

you will see the following contents from prometheus.yaml file

global:
  scrape_interval:     15s
  external_labels:
    monitor: 'codelab-monitor'
scrape_configs:
   scraped from this config.
  - job_name: 'prometheus'
    scrape_interval: 5s

    static_configs:
      - targets: ['localhost:9090']

Move the template configuration file prometheus.yml to /etc/prometheus/ directory

$ sudo mv prometheus.yml /etc/prometheus/prometheus.yml

We have installed Prometheus. Let’s verify the version

$ prometheus --version
prometheus, version 2.37.0-rc.0 (branch: HEAD, revision: 2479fb42f0a9bb45c2e82f11efc73c0a75fc492c)
  build user:       root@b82e7804c2b2
  build date:       20220705-13:33:30
  go version:       go1.18.3
  platform:         linux/amd64

3. Create Prometheus System Group

The following code can help create the Prometheus system group.

$ sudo groupadd --system prometheus

We can then create a Prometheus system user and assign the primary group created

$ sudo useradd -s /sbin/nologin --system -g prometheus prometheus

Set the ownership of Prometheus files and data directories to the Prometheus group and user.

$ sudo chown -R prometheus:prometheus /etc/prometheus/  /var/lib/prometheus/

$ sudo chmod -R 775 /etc/prometheus/ /var/lib/prometheus/

Lastly, we can create a systemd service to run at boot time

$ sudo nano /etc/systemd/system/prometheus.service

Add the following content to prometheus.service

[Unit]
Description=Prometheus
Wants=network-online.target
After=network-online.target

[Service]
User=prometheus
Group=prometheus
Restart=always
Type=simple
ExecStart=/usr/local/bin/prometheus \
    --config.file=/etc/prometheus/prometheus.yml \
    --storage.tsdb.path=/var/lib/prometheus/ \
    --web.console.templates=/etc/prometheus/consoles \
    --web.console.libraries=/etc/prometheus/console_libraries \
    --web.listen-address=0.0.0.0:9090

[Install]
WantedBy=multi-user.target

Start the Prometheus service

$ sudo systemctl start prometheus

Now we can check if our Prometheus is up and running

$ sudo systemctl status prometheus
● prometheus.service - Prometheus
     Loaded: loaded (/etc/systemd/system/prometheus.service; disabled; vendor p>
     Active: active (running) since Sat 2022-07-09 06:36:04 UTC; 32s ago
   Main PID: 13447 (prometheus)
      Tasks: 6 (limit: 1033)
     Memory: 17.9M
        CPU: 86ms
     CGroup: /system.slice/prometheus.service
             └─13447 /usr/local/bin/prometheus --config.file=/etc/prometheus/pr>

Jul 09 06:36:04 localhost prometheus[13447]: ts=2022-07-09T06:36:04.386Z caller>
Jul 09 06:36:04 localhost prometheus[13447]: ts=2022-07-09T06:36:04.389Z caller>
Jul 09 06:36:04 localhost prometheus[13447]: ts=2022-07-09T06:36:04.390Z caller>
Jul 09 06:36:04 localhost prometheus[13447]: ts=2022-07-09T06:36:04.390Z caller>
Jul 09 06:36:04 localhost prometheus[13447]: ts=2022-07-09T06:36:04.392Z caller>
Jul 09 06:36:04 localhost prometheus[13447]: ts=2022-07-09T06:36:04.392Z caller>
Jul 09 06:36:04 localhost prometheus[13447]: ts=2022-07-09T06:36:04.393Z caller>
Jul 09 06:36:04 localhost prometheus[13447]: ts=2022-07-09T06:36:04.394Z caller>
Jul 09 06:36:04 localhost prometheus[13447]: ts=2022-07-09T06:36:04.394Z caller>
Jul 09 06:36:04 localhost prometheus[13447]: ts=2022-07-09T06:36:04.395Z caller>
lines 1-20/20 (END)

Add firewall rules to allow Prometheus to run on TCP port 9090

$ ufw allow 9090/tcp

Access your server from the browser.

http://<ip address>or<hostname>:9090
nextgentips: Prometheus dashboard

Conclusion

Congratulations! you have successfully installed Prometheus on Ubuntu 22.04. To read more consult Prometheus documentation.

How to install Python Pip on Ubuntu 22.04

In this tutorial, you will learn how to install Python pip on Ubuntu 22.04.

Pip is a package management system written in Python and is used to install and manage software packages. It connects to an online repository of public packages called the Python Package Index. It can also be configured to connect to other package repositories.

Usually, Pip is automatically installed while working in a virtual environment, and also if you are using Python that has not been modified by the redistributor to remove ensure pip.

Pip is recommended tool for installing Python packages. For you to start using pip, you need to have python3 installed on your system.

Installing Python pip on Ubuntu 22.04

You can install pip either through a virtual environment or while installing Python. It depends on which one you prefer. I will be using a virtual environment to install pip on Ubuntu 22.04.

1. Run system updates

First, we need to update our repositories to make them up to date by issuing update and upgrade commands on our terminal.

$ sudo apt update && apt upgrade -y

2. Create a virtual environment

A virtual environment is used to manage Python packages for different projects. It creates an isolated environment for pip packages.

Begin by creating a directory where your virtual environment will be located.

$ sudo mkdir nextgen
$ cd nextgen

Next, create a virtual environment

$ python3 -m venv env

env is the name given to a virtual environment.

In case you encounter the following error, follow the instruction in order to make necessary changes.

The virtual environment was not created successfully because ensurepip is not
available.  On Debian/Ubuntu systems, you need to install the python3-venv
package using the following command.

    apt install python3.10-venv

You may need to use sudo with that command.  After installing the python3-venv
package, recreate your virtual environment.

Failing command: ['/root/nextgen/env/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']

Correct this error by running

sudo apt install python3.10-venv

From the above, you will see the following output.

The following additional packages will be installed:
  python3-pip-whl python3-setuptools-whl
The following NEW packages will be installed:
  python3-pip-whl python3-setuptools-whl python3.10-venv
0 upgraded, 3 newly installed, 0 to remove and 0 not upgraded.
Need to get 2473 kB of archives.
After this operation, 2882 kB of additional disk space will be used.
Do you want to continue? [Y/n] 

The next thing is to run python3 -m venv env again.

sudo python3 -m venv env

You need to activate the virtual environment to start using it.

$ source env/bin/activate 
(env) root@localhost:~/nextgen# 

Now that we have activated the virtual environment, you can now check if pip has been installed, because pip is installed while creating the virtual environment.

pip --version
pip 22.0.2 from /root/nextgen/env/lib/python3.10/site-packages/pip (python 3.10)

Conclusion

We have learned how to install pip on Ubuntu 22.04 because this is the starting point for any python programming. I am glad you have enjoyed the tutorial. Feel free to comment in case you are faced with a challenge.

How to install PHP 8.1 on Ubuntu 22.04

In this tutorial, we will learn how to install the current stable release version of PHP 8.1 on Ubuntu 22.04.

PHP is a general-purpose scripting language suitable for web development. Most websites out there are programmed using PHP language because it is:

  • Fast – PHP is fast because it runs on its own memory space. Also, PHP has a Zend engine that parses PHP code and turns it into opcodes which are then interpreted.
  • Flexible – PHP is flexible because it allows for almost all databases. MySQL is the de-facto database to connect to because it is open source.
  • Free and open source
  • PHP is forgiving – Why do we say PHP is forgiving? It is forgiving, meaning learning is not so hard and therefore suitable to almost all programmers starting out.
  • PHP supports major communication protocols i.e LDAP, IMAP, POP3.

Features of PHP 8.1

PHP 8.1 is a major update release version. It contains many new features and optimizations such as:

  • It introduced the Enumerations feature. Enumerations or Enum feature allow a developer to define a custom type that is limited to one of the discrete numbers of possible values. This is helpful while defining the domain model.
  • Improvement of RFC read-only property version 2. This prevents modification of the property after initialization.
  • The introduction of RFC fibers calls for action. This seeks to eliminate synchronous and asynchronous function calls by allowing functions to become interruptible without affecting the entire function.
  • Introduction of a non-return type. This indicates that a function either exits throws an exception or doesn’t terminate.
  • Introduction of first-class callable actions.
  • Introduction of fsync and fdatasync functions
  • Introduction of array_is_list functions
  • Introduction of explicit octal numeral notation

Installing PHP 8.1 on Ubuntu 22.04

1. Run system updates

The first thing to do in a new system is to update our repositories in order to make them up to date. Run upgrade command also.

$ sudo apt update && apt upgrade -y

2. Add Ondrej Sury PPA repository

To run PHP 8.1 on Ubuntu 22.04, we need to add Ondrej Sury PPA into our system. This is the maintainer of the PHP repository at the moment. This PPA is not currently checked so installing from it will not guarantee 100% results.

To add this PPA use the following command on our terminal.

$ sudo add-apt-repository ppa:ondrej/php

You will see the following as the output.

PPA publishes dbgsym, you may need to include 'main/debug' component
Repository: 'deb https://ppa.launchpadcontent.net/ondrej/php/ubuntu/ jammy main'
Description:
Co-installable PHP versions: PHP 5.6, PHP 7.x and most requested extensions are included. Only Supported Versions of PHP (http://php.net/supported-versions.php) for Supported Ubuntu Releases (https://wiki.ubuntu.com/Releases) are provided. Don't ask for end-of-life PHP versions or Ubuntu release, they won't be provided.

Debian oldstable and stable packages are provided as well: https://deb.sury.org/#debian-dpa

You can get more information about the packages at https://deb.sury.org

IMPORTANT: The <foo>-backports is now required on older Ubuntu releases.

BUGS&FEATURES: This PPA now has a issue tracker:
https://deb.sury.org/#bug-reporting

CAVEATS:
1. If you are using php-gearman, you need to add ppa:ondrej/pkg-gearman
2. If you are using apache2, you are advised to add ppa:ondrej/apache2
3. If you are using nginx, you are advised to add ppa:ondrej/nginx-mainline
   or ppa:ondrej/nginx

PLEASE READ: If you like my work and want to give me a little motivation, please consider donating regularly: https://donate.sury.org/

WARNING: add-apt-repository is broken with non-UTF-8 locales, see
https://github.com/oerdnj/deb.sury.org/issues/56 for workaround:

# LC_ALL=C.UTF-8 add-apt-repository ppa:ondrej/php
More info: https://launchpad.net/~ondrej/+archive/ubuntu/php
Adding repository.
Press [ENTER] to continue or Ctrl-c to cancel.
Adding deb entry to /etc/apt/sources.list.d/ondrej-ubuntu-php-jammy.list
Adding disabled deb-src entry to /etc/apt/sources.list.d/ondrej-ubuntu-php-jammy.list
Adding key to /etc/apt/trusted.gpg.d/ondrej-ubuntu-php.gpg with fingerprint 14AA40EC0831756756D7F66C4F4EA0AAE5267A6C
Hit:1 http://mirrors.linode.com/ubuntu jammy InRelease
Hit:2 http://mirrors.linode.com/ubuntu jammy-updates InRelease                 
Hit:3 http://mirrors.linode.com/ubuntu jammy-backports InRelease               
Hit:4 http://security.ubuntu.com/ubuntu jammy-security InRelease               
Get:5 https://ppa.launchpadcontent.net/ondrej/php/ubuntu jammy InRelease [23.9 kB]
Get:6 https://ppa.launchpadcontent.net/ondrej/php/ubuntu jammy/main amd64 Packages [92.9 kB]
Get:7 https://ppa.launchpadcontent.net/ondrej/php/ubuntu jammy/main Translation-en [29.1 kB]
Fetched 146 kB in 2s (68.5 kB/s)                                 
Reading package lists... Done

You need to update your system repositories again for the changes to take effect.

sudo apt update 

Install PHP 8.1 on Ubuntu 22.04

After you have updated your system, it’s now time to run the installation, with the following command.

sudo apt install php8.1 -y

You will be in a position to see the following as output.

The following additional packages will be installed:
  apache2 apache2-bin apache2-data apache2-utils libapache2-mod-php8.1 libapr1
  libaprutil1 libaprutil1-dbd-sqlite3 libaprutil1-ldap liblua5.3-0 php-common
  php8.1-cli php8.1-common php8.1-opcache php8.1-readline ssl-cert
Suggested packages:
  apache2-doc apache2-suexec-pristine | apache2-suexec-custom www-browser
  php-pear
The following NEW packages will be installed:
  apache2 apache2-bin apache2-data apache2-utils libapache2-mod-php8.1 libapr1
  libaprutil1 libaprutil1-dbd-sqlite3 libaprutil1-ldap liblua5.3-0 php-common
  php8.1 php8.1-cli php8.1-common php8.1-opcache php8.1-readline ssl-cert
0 upgraded, 17 newly installed, 0 to remove and 1 not upgraded.
Need to get 7227 kB of archives.
After this operation, 29.6 MB of additional disk space will be used.
Do you want to continue? [Y/n] y

Now we can check to see the version of PHP installed

php --version
PHP 8.1.7 (cli) (built: Jun 25 2022 08:13:46) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.7, Copyright (c) Zend Technologies
    with Zend OPcache v8.1.7, Copyright (c), by Zend Technologies

Conclusion

We have learned how to install PHP 8.1 on Ubuntu 22.04, now you can proceed to write your programs using this awesome language. Consult PHP documentation in case you experience any difficulty. Happy coding!