Ansible 或SaltStack 编写自动化运维脚本时,目标是通过模块化、参数化、可复用的方式来实现自动化运维任务。以下是编写自动化脚本的详细流程和示例。
Ansible
Ansible 使用 YAML 格式编写任务,称为Playbooks。它基于无代理架构,通过 SSH 与目标机器通信。
示例:安装 Nginx 并启动服务
- name: Install and configure Nginx
hosts: webservers
become: yes
tasks:
- name: Install Nginx
yum:
name: nginx
state: present
- name: Start and enable Nginx service
service:
name: nginx
state: started
enabled: yes
- name: Deploy Nginx configuration
template:
src: templates/nginx.conf.j2
dest: /etc/nginx/nginx.conf
owner: root
group: root
mode: '0644'
notify: restart nginx
handlers:
- name: restart nginx
service:
name: nginx
state: restarted
目录结构:
playbooks/ nginx_setup.yml templates/ nginx.conf.j2执行命令
ansible-playbook -i inventory nginx_setup.ymlSaltStack
SaltStack 使用state 文件(SLS 文件)来定义任务。它基于主从架构或无主模式。
示例:安装 Nginx 并启动服务
State 文件 (nginx.sls):
nginx:
pkg.installed:
- name: nginx
service.running:
- 
name: nginx 
- 
enable: True 
- 
require: 
- 
pkg: nginx 
nginx_config:
file.managed:
- 
name: /etc/nginx/nginx.conf 
- 
source: salt://nginx/nginx.conf 
- 
user: root 
- 
group: root 
- 
mode: 0644 
- 
require: 
- 
pkg: nginx 
目录结构:
salt/ nginx/nginx.sls files/ nginx.conf执行命令
salt'*' state.apply nginx设计高效脚本的关键点
- 
模块化和可重用性 :Ansible 中使用角色(roles),SaltStack 中使用模块化的 - SLS文件。
 
- 
参数化 :使用vars或 - pillar变量以提高脚本的灵活性。
 
- 
错误处理 : - 确保任务中包含适当的错误处理机制,如ignore_errors(Ansible)或onfail(SaltStack)。
 
- 确保任务中包含适当的错误处理机制,如
- 
Idempotence:脚本应支持幂等性,多次运行不会影响结果。 
选择 Ansible 或 SaltStack 的场景
- 
Ansible :适用于无代理、任务较轻量的场景(如快速配置和部署)。 
- 
SaltStack :适用于复杂的、需要实时通信的场景(如大规模管理和定时任务)。 
如果你有特定的需求或复杂的场景,可以进一步讨论适合的实现方式。