Ansible 或SaltStack 编写自动化运维脚本时,目标是通过模块化、参数化、可复用的方式来实现自动化运维任务。以下是编写自动化脚本的详细流程和示例。
Ansible 使用 YAML 格式编写任务,称为Playbooks。它基于无代理架构,通过 SSH 与目标机器通信。
---
- 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.yml
SaltStack 使用state
文件(SLS 文件)来定义任务。它基于主从架构或无主模式。
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
:适用于无代理、任务较轻量的场景(如快速配置和部署)。
:适用于复杂的、需要实时通信的场景(如大规模管理和定时任务)。
如果你有特定的需求或复杂的场景,可以进一步讨论适合的实现方式。