Linux Essentials for Cloud — Part 3
Inside this issue, Automation and Scripting, System Services and Daemons, and Security Basics.
Hi—this is Kisan from The Cloud Handbook. Each week I share about Cloud, DevOps, System Design deep dives and technologies around it. If you have not subscribed yet, you can subscribe here. It’s free.
In case you missed the previous parts:
In today’s issue, we are going to talk about Automation and Scripting, System Services and Daemons, and Security Basics.
Before we get started, if you have not subscribed yet, please feel free to subscribe using button below.
1. Automation and Scripting
Automation and Scripting is one of the most have skill while working in cloud. Either you are a DevOps engineer, Infra engineer, you must have basics knowledge of automating things and scripting.
So, let’s start with basic shell scripting.
Shell Scripting Basics
Creating a Basic Script:
#!/bin/bash
# This is a comment
# Variables
NAME="World"
DATE=$(date)
# Output
echo "Hello, $NAME!"
echo "Current date: $DATE"
# Make script executable
chmod +x script.sh
Variables and Data Types:
#!/bin/bash
# String variables
NAME="John"
MESSAGE='Hello World'
# Numeric variables
COUNT=10
PRICE=19.99
# Arrays
FRUITS=("apple" "banana" "orange")
echo ${FRUITS[0]} # First element
echo ${FRUITS[@]} # All elements
echo ${#FRUITS[@]} # Array length
Conditional Statements:
#!/bin/bash
# If-else statement
if [ $COUNT -gt 5 ]; then
echo "Count is greater than 5"
elif [ $COUNT -eq 5 ]; then
echo "Count is exactly 5"
else
echo "Count is less than 5"
fi
# String comparison
if [ "$NAME" = "John" ]; then
echo "Hello John!"
fi
# File tests
if [ -f "/etc/passwd" ]; then
echo "Password file exists"
fi
if [ -d "/var/log" ]; then
echo "Log directory exists"
fi
Loops:
#!/bin/bash
# For loop with range
for i in {1..5}; do
echo "Number: $i"
done
# For loop with array
for fruit in ${FRUITS[@]}; do
echo "Fruit: $fruit"
done
# While loop
counter=1
while [ $counter -le 5 ]; do
echo "Counter: $counter"
((counter++))
done
# For loop with files
for file in /var/log/*.log; do
echo "Processing: $file"
done
Functions:
#!/bin/bash
# Define function
backup_file() {
local file=$1
local backup_dir=$2
if [ -f "$file" ]; then
cp "$file" "$backup_dir/$(basename $file).backup"
echo "Backed up $file"
else
echo "File $file not found"
return 1
fi
}
# Call function
backup_file "/etc/nginx/nginx.conf" "/backup"
To learn more about bash scripting, this beginner friendly videos will teach you everything to get started.
2. System Services and Daemons
Using systemctl to Manage Services
systemctl
What it is:
A command-line utility to interact with systemd.
Used to control and inspect services and units managed by
systemd
.
Role: It doesn’t do the work itself—it just sends instructions to
systemd
.Examples:
# Start a service
systemctl start nginx
# Enable a service at boot
systemctl enable nginx
# Check status of a service
systemctl status nginx
# Reboot system
systemctl reboot
Think of it as:
The "remote control" for thesystemd
engine.
Basic Service Management:
# Start a service
sudo systemctl start nginx
sudo systemctl start ssh
# Stop a service
sudo systemctl stop nginx
sudo systemctl stop ssh
# Restart a service
sudo systemctl restart nginx
sudo systemctl restart ssh
# Reload service configuration (without stopping)
sudo systemctl reload nginx
# Check service status
systemctl status nginx
systemctl status ssh
# Enable service to start at boot
sudo systemctl enable nginx
sudo systemctl enable ssh
# Disable service from starting at boot
sudo systemctl disable nginx
# Check if service is enabled
systemctl is-enabled nginx
# Check if service is active
systemctl is-active nginx
Advanced systemctl Commands:
# List all services
systemctl list-units --type=service
# List all enabled services
systemctl list-unit-files --type=service --state=enabled
# List failed services
systemctl --failed
# Show service dependencies
systemctl list-dependencies nginx
# Mask a service (prevent it from being started)
sudo systemctl mask nginx
# Unmask a service
sudo systemctl unmask nginx
# Edit service configuration
sudo systemctl edit nginx
# Show service properties
systemctl show nginx
# Reload systemd configuration
sudo systemctl daemon-reload
Understanding Init Systems
Systemd (Modern Linux Distributions):
Default init system for most modern Linux distributions
Uses unit files to define services
Supports parallel service startup
Provides dependency management
Integrated logging with journald
Key Systemd Concepts:
Units: Resources that systemd manages (services, sockets, devices, etc.)
Targets: Groups of units, similar to runlevels
Dependencies: Relationships between units
Unit Files: Configuration files defining units
Common Systemd Targets:
# Check current target
systemctl get-default
# List available targets
systemctl list-units --type=target
# Change to different target
sudo systemctl isolate multi-user.target
sudo systemctl isolate graphical.target
# Set default target
sudo systemctl set-default multi-user.target
Common Services in the Cloud
SSH Service (sshd):
# Check SSH service status
systemctl status ssh # Ubuntu/Debian
systemctl status sshd # RHEL/CentOS
# SSH configuration
sudo vim /etc/ssh/sshd_config
# Common SSH hardening settings
Port 2222 # Change default port
PermitRootLogin no # Disable root login
PasswordAuthentication no # Use key-based auth only
MaxAuthTries 3 # Limit login attempts
# Restart SSH after configuration changes
sudo systemctl restart ssh
Nginx Web Server:
# Install and start Nginx
sudo apt install nginx # Ubuntu/Debian
sudo yum install nginx # RHEL/CentOS
sudo systemctl start nginx
sudo systemctl enable nginx
# Nginx configuration files
/etc/nginx/nginx.conf # Main configuration
/etc/nginx/sites-available/ # Available sites (Ubuntu/Debian)
/etc/nginx/sites-enabled/ # Enabled sites (Ubuntu/Debian)
/etc/nginx/conf.d/ # Configuration directory (RHEL/CentOS)
# Test configuration
sudo nginx -t
# Reload configuration
sudo systemctl reload nginx
Docker Service:
# Install Docker
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
# Start and enable Docker
sudo systemctl start docker
sudo systemctl enable docker
# Add user to docker group
sudo usermod -aG docker $USER
# Check Docker status
systemctl status docker
# Docker service configuration
/etc/docker/daemon.json # Docker daemon configuration
/lib/systemd/system/docker.service # Systemd service file
3. Security Basics
SSH Hardening
Key-Based Authentication Setup:
# Generate SSH key pair (on client)
ssh-keygen -t rsa -b 4096 -C "your-email@example.com"
ssh-keygen -t ed25519 -C "your-email@example.com" # More secure
# Copy public key to server
ssh-copy-id username@server-ip
# Or manually:
cat ~/.ssh/id_rsa.pub | ssh username@server-ip "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
SSH Server Configuration (/etc/ssh/sshd_config):
# Change default port
Port 2222
# Disable root login
PermitRootLogin no
# Disable password authentication
PasswordAuthentication no
ChallengeResponseAuthentication no
UsePAM no
# Allow only specific users
AllowUsers username1 username2
# Allow only specific groups
AllowGroups sshusers
# Limit authentication attempts
MaxAuthTries 3
MaxStartups 3:30:10
# Set idle timeout
ClientAliveInterval 300
ClientAliveCountMax 2
# Disable X11 forwarding (if not needed)
X11Forwarding no
# Enable key-based authentication
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
# Restart SSH service after changes
sudo systemctl restart ssh
SSH Client Configuration (~/.ssh/config):
# Global settings
Host *
ServerAliveInterval 60
ServerAliveCountMax 3
HashKnownHosts yes
# Specific server configuration
Host webserver
HostName 192.168.1.100
User ubuntu
Port 2222
IdentityFile ~/.ssh/webserver-key.pem
IdentitiesOnly yes
Firewall Basics
UFW (Uncomplicated Firewall):
# Check firewall status
sudo ufw status verbose
# Enable firewall
sudo ufw enable
# Default policies
sudo ufw default deny incoming
sudo ufw default allow outgoing
# Allow specific ports
sudo ufw allow 22/tcp # SSH
sudo ufw allow 80/tcp # HTTP
sudo ufw allow 443/tcp # HTTPS
sudo ufw allow 3306/tcp # MySQL
# Allow specific services
sudo ufw allow 'Nginx Full'
sudo ufw allow 'OpenSSH'
# Allow from specific IP
sudo ufw allow from 192.168.1.100
# Allow from specific subnet
sudo ufw allow from 192.168.1.0/24
# Deny specific port
sudo ufw deny 23/tcp # Telnet
# Delete rules
sudo ufw delete allow 80/tcp
sudo ufw --force reset # Reset all rules
# Show numbered rules
sudo ufw status numbered
# Delete rule by number
sudo ufw delete 2
iptables (Advanced Firewall):
# List current rules
sudo iptables -L -n -v
# Basic input policy (be careful!)
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT
# Allow loopback traffic
sudo iptables -A INPUT -i lo -j ACCEPT
# Allow established connections
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# Allow SSH
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# Allow HTTP and HTTPS
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Save rules (Ubuntu/Debian)
sudo iptables-save > /etc/iptables/rules.v4
# Save rules (RHEL/CentOS)
sudo service iptables save
Keeping Systems Up to Date
Automated Updates (Ubuntu):
# Install unattended-upgrades
sudo apt install unattended-upgrades
# Configure automatic updates
sudo dpkg-reconfigure -plow unattended-upgrades
# Configuration file
sudo vim /etc/apt/apt.conf.d/50unattended-upgrades
# Example configuration
Unattended-Upgrade::Allowed-Origins {
"${distro_id}:${distro_codename}";
"${distro_id}:${distro_codename}-security";
"${distro_id}ESMApps:${distro_codename}-apps-security";
"${distro_id}ESM:${distro_codename}-infra-security";
};
Unattended-Upgrade::AutoFixInterruptedDpkg "true";
Unattended-Upgrade::MinimalSteps "true";
Unattended-Upgrade::Remove-Unused-Dependencies "true";
Unattended-Upgrade::Automatic-Reboot "false";
Automated Updates (RHEL/CentOS):
# Install yum-cron
sudo yum install yum-cron
# Enable and start service
sudo systemctl enable yum-cron
sudo systemctl start yum-cron
# Configure yum-cron
sudo vim /etc/yum/yum-cron.conf
# Key settings
update_cmd = security # Only security updates
apply_updates = yes # Automatically apply updates
Security Best Practices:
Use principle of least privilege
Regularly review file permissions on critical files
Monitor changes to system files
Keep systems updated with security patches
Use configuration management tools for consistency
Get in touch
Found something worth sharing? Reply to this email or tag me Kisan Tamang— I might feature it next week.
Liked this article? Feel free to drop ❤️ and Restack with your friends.
If you have any feedbacks or questions 💬, comment below. See you in the next one.
You can find me on Twitter, Linkedin.
If you want to work with me or want to sponsor The Cloud Handbook Newsletter, please email me at kisan.codes@gmail.com.
See you in the next one! Until then, keep learning and building.