下面给你一个用 Ansible 部署 Web 服务的完整思路和示例,以 Nginx + 静态/动态站点 为例,适合入门到中等复杂度场景。
假设环境如下:
# Ubuntu / Debian
sudo apt update
sudo apt install ansible -y
# CentOS
sudo yum install epel-release -y
sudo yum install ansible -y
验证:
ansible --version
hosts.ini
[web]
192.168.1.10
192.168.1.11
[web:vars]
ansible_user=root
ansible_ssh_private_key_file=~/.ssh/id_rsa
测试连通性:
ansible web -i hosts.ini -m ping
deploy_web.yml
---
- name: Deploy Nginx Web Service
hosts: web
become: yes
tasks:
- name: Install Nginx
apt:
name: nginx
state: latest
when: ansible_os_family == "Debian"
- name: Install Nginx (CentOS)
yum:
name: nginx
state: latest
when: ansible_os_family == "RedHat"
- name: Start and enable Nginx
service:
name: nginx
state: started
enabled: yes
- name: Copy website files
copy:
src: ./site/
dest: /var/www/html/
mode: '0644'
- name: Configure Nginx site
template:
src: nginx.conf.j2
dest: /etc/nginx/sites-available/default
notify: Restart Nginx
handlers:
- name: Restart Nginx
service:
name: nginx
state: restarted
nginx.conf.j2
server {
listen 80;
server_name {{ ansible_hostname }};
root /var/www/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
.
├── hosts.ini
├── deploy_web.yml
├── nginx.conf.j2
└── site/
└── index.html
ansible-playbook -i hosts.ini deploy_web.yml
访问:
http://目标服务器IP
systemd 模块管理服务pip / git 模块拉代码uwsgi / gunicorn + Nginx[web:prod]
192.168.1.10
[web:test]
192.168.2.10
ansible-galaxy init nginx
ansible web -m setup # 查看主机变量
ansible-playbook xxx.yml --check
ansible-playbook xxx.yml -vvv
如果你愿意,我可以:
你现在的 Web 服务是哪种?
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。