When it comes to automatically managing Linux updates and system reboots, two common approaches are:
Cron job + Shell script
Apache Airflow + Shell script
Both have merits depending on your use case, infrastructure complexity, and operational needs.
✅ 1. Cron + Shell Script
🔧 How it works:
You schedule a shell script using crontab that handles updates (apt update && apt upgrade or yum update, etc.) and reboots (reboot if needed).
✅ Pros:
Feature
Cron + Script
Simple
Easy to implement, no third-party dependencies
Lightweight
Minimal overhead compared to running Airflow
Reliable
Very mature, stable, well-tested in Unix environments
Suitable for single servers
Good for small scale or individual machines
❌ Cons:
Limitation
Description
Limited Logic
Harder to manage complex workflows or dependencies
No GUI / Tracking
Lacks monitoring, logging is basic unless manually configured
No Built-in Retry
Need additional scripting for retries and failure handling
Harder Failure Notification
Setting up email or alerting adds overhead
✅ 2. Airflow + Shell Script
🔧 How it works:
Use Apache Airflow DAGs (Directed Acyclic Graphs) to define a workflow that runs update and reboot scripts on one or more machines (typically via SSH).
✅ Pros:
Feature
Airflow + Script
Workflow Management
Ideal for complex workflows with dependencies (e.g., staggered updates)
Rich Logging
Logs all outputs in its web UI, making debugging easier
Retries / Alerting
Automatic retries, failure alerts via email, Slack, etc.
Task Scheduling
Built-in scheduling with advanced features
Scalability
Can manage updates on hundreds of nodes via orchestration (e.g., remote execution)
❌ Cons:
Limitation
Description
Heavy
Requires Airflow web server, scheduler, DB, workers — resource-hungry
Complex Setup
Steep learning curve for initial configuration
Overkill for Simple Use
Too complex if just updating one or two servers periodically
Security
Needs care around handling SSH keys or sudo scripts in DAGs
🚀 When to Use What
Scenario
Best Choice
Single server or minimal setup
Cron + Shell Script
Lightweight, fast configuration
Cron + Shell Script
No external dependencies
Cron + Shell Script
Many servers or need workflow orchestration
Airflow + Script
Need dashboards, alerting, retry-on-failure
Airflow + Script
DevOps toolchain already includes Airflow
Airflow + Script
🎯 My Recommendation
💡 Choice: Cron + Shell Script (for simple or medium use cases)
Why?
It's simple, efficient, well-supported, and there's no overhead unless your update process needs workflow logic or you're orchestrating a multi-node update policy.
🎁 Optional: Hybrid / Alternative Suggestion
If you like the logging and monitoring aspects of Airflow but want something simple:
Use Bash + Cron, and:
Log to a central location (e.g., logger, remote files)
Set up health checks (e.g., via cron + curl to a webhook)
Would you like a production-ready sample shell script and crontab line for this use case?
User
give me both scripts
Assistant
Sure! Here's a production-ready shell script and crontab entry for managing Linux updates and reboots. You'll also get a sample Airflow DAG using a shell script, if you want to go the Airflow route.
✅ OPTION 1: Cron + Shell Script
🔧 Shell Script: auto_update.sh
bash
#!/bin/bash
# --------------------------
# Production Linux update script
# Logs updates, handles errors, reboots if necessary
# Author: YourName
# --------------------------
# Settings
LOGFILE="/var/log/auto_update.log"
REBOOT_FLAG="/var/run/reboot-required" # Used in Debian/Ubuntu
DATE=$(date "+%Y-%m-%d %H:%M:%S")
# Log start
echo "[$DATE] Starting system update..." | tee -a "$LOGFILE"
# Update & Upgrade
{
apt update -y && apt upgrade -y
apt autoremove -y
} >> "$LOGFILE" 2>&1
# Check for reboot
if [ -f "$REBOOT_FLAG" ]; then
echo "[$DATE] Reboot required. Rebooting system..." | tee -a "$LOGFILE"
shutdown -r +5 "System will reboot in 5 minutes to complete updates." >> "$LOGFILE" 2>&1
else
echo "[$DATE] No reboot needed." | tee -a "$LOGFILE"
fi
echo "[$DATE] Update process finished." | tee -a "$LOGFILE"
echo "----------------------------------------" | tee -a "$LOGFILE"
🛠️ Make executable:
bash
chmod +x /usr/local/bin/auto_update.sh
🕑 Crontab Entry
Edit crontab:
bash
sudo crontab -e
Add the following line to run it at 2:00 AM every Sunday:
cron
0 2 * * 0 /usr/local/bin/auto_update.sh
✅ OPTION 2: Airflow + Shell Script
User
perfect, now add the *.sh script
Assistant
Great! Below is the full contents of the production-ready auto_update.sh script for Linux system updates and reboots. This script is designed to:
Run unattended updates (Debian/Ubuntu-based systems by default)
Log all activity
Conditionally reboot the system if required
Be scheduled via cron or used with Airflow
📜 auto_update.sh
bash
#!/bin/bash
# -----------------------------------------------------------------------------
# Auto Update Script for Linux Systems (Debian/Ubuntu compatible)
# Performs system update, logs output, restarts if necessary.
# Author: YourName
# Version: 1.0
# -----------------------------------------------------------------------------
# CONFIGURATION
LOGFILE="/var/log/auto_update.log"
REBOOT_FLAG="/var/run/reboot-required"
FORMAT_DATE=$(date "+%Y-%m-%d %H:%M:%S")
MARK="[$FORMAT_DATE]"
# Ensure only root executes the script
if [[ $EUID -ne 0 ]]; then
echo "$MARK This script must be run as root!" | tee -a "$LOGFILE"
exit 1
fi
echo "$MARK Starting system update..." | tee -a "$LOGFILE"
# Update and upgrade system packages
{
echo "$MARK Running apt update..."
apt update -y
echo "$MARK Running apt upgrade..."
apt upgrade -y
echo "$MARK Running apt autoremove..."
apt autoremove -y
} >> "$LOGFILE" 2>&1
# Check if reboot is required
if [ -f "$REBOOT_FLAG" ]; then
echo "$MARK Reboot required. Scheduling reboot..." | tee -a "$LOGFILE"
shutdown -r +5 "System will reboot in 5 minutes to complete updates." >> "$LOGFILE" 2>&1
else
echo "$MARK No reboot required." | tee -a "$LOGFILE"
fi
echo "$MARK Update complete." | tee -a "$LOGFILE"
echo "------------------------------------------------" | tee -a "$LOGFILE"
🛠️ Installation Steps
Save the script:
bash
sudo nano /usr/local/bin/auto_update.sh
Paste the script above, then save and exit (Ctrl + O, Enter, Ctrl + X).
Make it executable:
bash
sudo chmod +x /usr/local/bin/auto_update.sh
Schedule with cron (Optional):
bash
sudo crontab -e
Add the job (runs at 2 AM every Sunday):
cron
0 2 * * 0 /usr/local/bin/auto_update.sh
🔄 Reboot Customization Notes:
If you're using RedHat/CentOS, switch out the package commands:
bash
yum update -y
And comment/remove the apt lines.
To send Slack/email notifications or log to a remote service (like Splunk, ELK, CloudWatch), this script can be extended easily.
Would you like a version for RedHat-based distributions as well?
User
perfect, we use gitlab to, The same Process in gitlab ? Show me
Assistant
Great! If you're using GitLab, you can fully integrate your Linux update & reboot automation with GitLab CI/CD, just like with Airflow or Cron. GitLab is powerful for:
Centralizing task automation
Logging and version-controlling scripts
Running actions on runners (GitLab CI agents installed on your servers)
Triggering updates via manual pipelines or on schedule
✅ Overview: Update System via GitLab CI/CD
🎯 Goal:
Use .gitlab-ci.yml file to:
Run the auto_update.sh script
Schedule updates
Use a GitLab Runner (can be local or remote)
Optional: Schedule or manually trigger pipeline
🗂️ Project Structure:
bash
your-repo/
├── .gitlab-ci.yml
└── auto_update.sh
You store the script (auto_update.sh) inside the repo
CI runs it on GitLab Runner (which must be able to run sudo apt update)
📜 auto_update.sh (same from above)
Already created — place this in your GitLab repo.
If needed, wrap it to avoid rebooting in GitLab CI test runs (optional):
bash
#!/bin/bash
if [[ "$CI" == "true" ]]; then
echo "[CI MODE] Skipping reboot for test mode."
export SKIP_REBOOT=true
fi
⚙️ .gitlab-ci.yml
yaml
stages:
- update
linux_update:
stage: update
script:
- echo "Starting system update from GitLab CI..."
- chmod +x ./auto_update.sh
- sudo ./auto_update.sh
tags:
- linux-update-runner # Ensure your GitLab Runner is labeled correctly
when: manual # 💡 Change to 'always' or schedule below
only:
- main # Or 'master', or a protected branch
🎯 Key Points:
1️⃣ Shell Script: auto_update.sh
Same script as above — keep it on the server or remote hosts you want to update.
2️⃣ Airflow DAG: linux_update_dag.py
Here's a simple DAG that uses BashOperator or SSHOperator to run the update script.
Option A: On local host with BashOperator
python
from airflow import DAG
from airflow.operators.bash import BashOperator
from datetime import datetime, timedelta
default_args = {
'owner': 'devops',
'depends_on_past': False,
'start_date': datetime(2024, 1, 1),
'retries': 1,
'retry_delay': timedelta(minutes=10),
}
dag = DAG(
'linux_update_dag',
default_args=default_args,
description='Run Linux updates and reboot if needed',
schedule_interval='0 2 * * 0', # Sunday at 2AM
catchup=False,
)
update_system = BashOperator(
task_id='run_linux_update',
bash_command='/usr/local/bin/auto_update.sh',
dag=dag,
)
💡 Use this if Airflow is on the same server or has NFS-mounted scripts.
Option B: Remote host with SSHOperator (Airflow Connections required)
python
from airflow import DAG
from airflow.providers.ssh.operators.ssh import SSHOperator
from datetime import datetime, timedelta
default_args = {
'owner': 'devops',
'depends_on_past': False,
'start_date': datetime(2024, 1, 1),
'retries': 1,
'retry_delay': timedelta(minutes=10),
}
dag = DAG(
'linux_remote_update',
default_args=default_args,
description='Remote Linux update and reboot',
schedule_interval='0 2 * * 0', # Weekly
catchup=False,
)
# Assumes Airflow SSH connection called "linux_host"
remote_update = SSHOperator(
task_id='remote_update_script',
ssh_conn_id='linux_host', # Airflow connection ID
command='/usr/local/bin/auto_update.sh',
dag=dag,
)
🛡️ Make sure you set up the SSH connection (Admin → Connections) and the user has sudo permissions.
🔚 Summary Table
Option
Setup Required
Best For
Pros
Cron + Script
Simple
1-10 servers
Lightweight, quick to set up
Airflow + Script
Complex
10+ nodes or orchestration
Workflow tracking, retries, alerting
Would you like to include remote execution to multiple servers from one script via SSH too? (useful for cluster-wide updates.)
sudo is required unless your script uses root-less commands.
Make sure your GitLab Runner has sudo access.
Use runner tags to control on which server this runs.
🕑 Option A: GitLab Scheduled Pipeline
To auto-run updates weekly (like cron):
Go to your GitLab repo ➝ CI / CD ➝ Schedules
Click New Schedule
Set:
Description: Weekly System Update
Interval: 0 2 * * 0 (Sunday at 2 AM)
Target branch: main
Save
Your job will now run like a cron job, but fully monitored via GitLab UI.
🛠️ Option B: Manual Trigger
Run directly via GitLab UI ("Run pipeline" → select job linux_update).
🛡️ Requirements for GitLab Runner
Your GitLab Runner must:
Be registered with your GitLab instance
Have root or sudo privileges
Be tagged appropriately (e.g., linux-update-runner)
Have access to /usr/local/bin/ or script paths
It could be self-hosted on the same server you want to update.
🔒 Security Considerations
Concern
Solution
Reboot via CI
Tag CI job for manual execution only (when: manual) or restrict to schedules
Sudo
Ensure the CI runner user has passwordless sudo for safety
Concurrent CI jobs
Limit CI concurrency if you use runners in production envs