目標:用一個腳本,在多台 Web 伺服器(CentOS + Ubuntu)上完成自動化部署,實現 跨作業系統、批量管理。
建立一個檔案,存放所有目標伺服器 IP 或 hostname
# remote_hosts
web01
web02
Script box 會從這個檔案讀取主機,執行遠端命令
for host in $(cat remote_hosts)
do
ssh devops@$host "hostname"
done
ssh devops@$host "free -m"
ssh devops@$host "uptime"


yum,Ubuntu 用 apt#!/bin/bash
# Variable Declaration
#PACKAGE="httpd wget unzip"
#SVC="httpd"
URL='<https://www.tooplate.com/zip-templates/2098_health.zip>'
ART_NAME='2098_health'
TEMPDIR="/tmp/webfiles"
yum --help &> /dev/null
if [ $? -eq 0 ]
then
# Set Variables for CentOS
PACKAGE="httpd wget unzip"
SVC="httpd"
echo "Running Setup on CentOS"
# Installing Dependencies
echo "########################################"
echo "Installing packages."
echo "########################################"
sudo yum install $PACKAGE -y > /dev/null
echo
# Start & Enable Service
echo "########################################"
echo "Start & Enable HTTPD Service"
echo "########################################"
sudo systemctl start $SVC
sudo systemctl enable $SVC
echo
# Creating Temp Directory
echo "########################################"
echo "Starting Artifact Deployment"
echo "########################################"
mkdir -p $TEMPDIR
cd $TEMPDIR
echo
wget $URL > /dev/null
unzip $ART_NAME.zip > /dev/null
sudo cp -r $ART_NAME/* /var/www/html/
echo
# Bounce Service
echo "########################################"
echo "Restarting HTTPD service"
echo "########################################"
systemctl restart $SVC
echo
# Clean Up
echo "########################################"
echo "Removing Temporary Files"
echo "########################################"
rm -rf $TEMPDIR
echo
sudo systemctl status $SVC
ls /var/www/html/
else
# Set Variables for Ubuntu
PACKAGE="apache2 wget unzip"
SVC="apache2"
echo "Running Setup on CentOS"
# Installing Dependencies
echo "########################################"
echo "Installing packages."
echo "########################################"
sudo apt update
sudo apt install $PACKAGE -y > /dev/null
echo
# Start & Enable Service
echo "########################################"
echo "Start & Enable HTTPD Service"
echo "########################################"
sudo systemctl start $SVC
sudo systemctl enable $SVC
echo
# Creating Temp Directory
echo "########################################"
echo "Starting Artifact Deployment"
echo "########################################"
mkdir -p $TEMPDIR
cd $TEMPDIR
echo
wget $URL > /dev/null
unzip $ART_NAME.zip > /dev/null
sudo cp -r $ART_NAME/* /var/www/html/
echo
# Bounce Service
echo "########################################"
echo "Restarting HTTPD service"
echo "########################################"
systemctl restart $SVC
echo
# Clean Up
echo "########################################"
echo "Removing Temporary Files"
echo "########################################"
rm -rf $TEMPDIR
echo
sudo systemctl status $SVC
ls /var/www/html/
fi