Python สำหรับ DevOps นั้นเป็นเครื่องมือที่ช่วยให้เราสามารถเขียน Script จัดการ Server อัตโนมัติ เพื่อให้การทำงาน DevOps นั้นสะดวก และรวดเร็วขึ้น บทความนี้จะบอกวิธีการเขียน Python Script สำหรับ DevOps
Python สำหรับ DevOps คืออะไร?
Python สำหรับ DevOps นั้นเป็นการใช้ Python ในการเขียน Script เพื่อจัดการ Server อัตโนมัติ เช่น การติดตั้ง Software, การ Configure Server, การ Monitoring Server เป็นต้น
ทำไมต้องใช้ Python สำหรับ DevOps?
เหตุผลที่ต้องใช้ Python สำหรับ DevOps นั้นมีดังต่อไปนี้
- Python ใช้งานง่ายและเข้าใจง่าย
- Python มีไลบรารี่มากมายสำหรับ DevOps
- Python สามารถใช้ได้หลายๆ Platform
- Python มีชุมชนผู้ใช้งานที่ใหญ่
- Python ช่วยลดเวลาในการพัฒนา
ไลบรารี่ Python สำหรับ DevOps
ไลบรารี่ Python สำหรับ DevOps มีหลายตัว เช่น
- Paramiko – สำหรับเชื่อมต่อ SSH
- Fabric – สำหรับการ Deploy และ Automation
- Ansible – สำหรับ Infrastructure Automation
- Requests – สำหรับการสร้าง HTTP Request
- Docker-py – สำหรับ Docker API
- Kubernetes Python Client – สำหรับ Kubernetes API
- Click – สำหรับสร้าง Command Line Interface
- Pandas – สำหรับ Data Analysis
- Boto3 – สำหรับ AWS API
- Flask – สำหรับสร้าง Web Server
ตัวอย่างการเขียน Python Script สำหรับ DevOps
1. Script สำหรับ Monitor Server
import psutil
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_alert(subject, message):
sender = "[email protected]"
recipient = "[email protected]"
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = recipient
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
server = smtplib.SMTP('localhost')
server.send_message(msg)
server.quit()
def monitor_cpu():
cpu_percent = psutil.cpu_percent(interval=1)
if cpu_percent > 80:
send_alert("High CPU Usage", f"CPU usage: {cpu_percent}%")
return cpu_percent
def monitor_memory():
memory = psutil.virtual_memory()
memory_percent = memory.percent
if memory_percent > 80:
send_alert("High Memory Usage", f"Memory usage: {memory_percent}%")
return memory_percent
def monitor_disk():
disk = psutil.disk_usage('/')
disk_percent = disk.percent
if disk_percent > 80:
send_alert("High Disk Usage", f"Disk usage: {disk_percent}%")
return disk_percent
if __name__ == "__main__":
while True:
print(f"CPU: {monitor_cpu()}%")
print(f"Memory: {monitor_memory()}%")
print(f"Disk: {monitor_disk()}%")
time.sleep(60)
2. Script สำหรับเชื่อมต่อ SSH
import paramiko
def ssh_connect(host, username, password):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=username, password=password)
return ssh
def execute_command(ssh, command):
stdin, stdout, stderr = ssh.exec_command(command)
return stdout.read().decode()
if __name__ == "__main__":
host = "192.168.1.100"
username = "root"
password = "password"
ssh = ssh_connect(host, username, password)
result = execute_command(ssh, "ls -la /home")
print(result)
ssh.close()
3. Script สำหรับ Backup Database
import subprocess
import datetime
import os
def backup_mysql(db_host, db_user, db_password, db_name, backup_dir):
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
backup_file = f"{backup_dir}/{db_name}_{timestamp}.sql"
command = f"mysqldump -h {db_host} -u {db_user} -p{db_password} {db_name} > {backup_file}"
subprocess.run(command, shell=True)
return backup_file
def upload_to_s3(file_path, bucket_name, object_name):
import boto3
s3_client = boto3.client('s3')
s3_client.upload_file(file_path, bucket_name, object_name)
return True
if __name__ == "__main__":
db_host = "localhost"
db_user = "root"
db_password = "password"
db_name = "myapp"
backup_dir = "/backups"
bucket_name = "my-backup-bucket"
backup_file = backup_mysql(db_host, db_user, db_password, db_name, backup_dir)
print(f"Backup created: {backup_file}")
object_name = os.path.basename(backup_file)
upload_to_s3(backup_file, bucket_name, object_name)
print(f"Backup uploaded to S3")
Best Practices สำหรับ Python DevOps
Best Practices สำหรับการเขียน Python Script สำหรับ DevOps มีดังต่อไปนี้
- ใช้ Version Control (Git) สำหรับจัดการ Code
- ใช้ Environment Variables สำหรับจัดการ Configuration
- ใช้ Logging สำหรับ Debug และ Monitoring
- ใช้ Exception Handling สำหรับจัดการ Error
- ใช้ Unit Testing สำหรับทดสอบ Script
- ใช้ Documentation สำหรับให้ข้อมูลเพิ่มเติม
- ใช้ Virtual Environment สำหรับจัดการ Dependencies
- ใช้ Continuous Integration (CI) สำหรับ Automation Test
สรุป
Python สำหรับ DevOps นั้นเป็นเครื่องมือที่มีประโยชน์สำหรับการจัดการ Server อัตโนมัติ และช่วยให้การทำงาน DevOps นั้นสะดวก และรวดเร็วขึ้น ด้วยไลบรารี่ที่มากมาย และชุมชนผู้ใช้งานที่ใหญ่ ทำให้ Python เป็นตัวเลือกที่ดีสำหรับการพัฒนา DevOps
