温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何用Ansible部署Web服务器

发布时间:2026-10-11 20:58:05 来源:亿速云 阅读:102 作者:小樊 栏目:系统运维

下面给你一个从零到可用的思路,用 Ansible 部署 Web 服务器(以 Nginx 为例),适合初学者也能直接落地。


一、整体架构示例

假设环境:

  • 控制机(你跑 Ansible 的机器)
  • 受控机(Web 服务器,Linux,如 Ubuntu / CentOS)

目标:

  • 安装 Nginx
  • 启动并设置开机自启
  • 部署一个简单网页

二、准备工作

1. 控制机安装 Ansible

# Ubuntu / Debian
sudo apt update
sudo apt install ansible -y

# CentOS
sudo yum install epel-release -y
sudo yum install ansible -y

2. 配置 SSH 免密登录

ssh-keygen
ssh-copy-id user@web-server-ip

三、Inventory 主机清单

inventory.ini

[web]
192.168.1.10 ansible_user=ubuntu

测试连通性:

ansible web -i inventory.ini -m ping

四、编写 Playbook(核心)

示例:部署 Nginx(Ubuntu)

deploy_web.yml

---
- name: Deploy Nginx Web Server
  hosts: web
  become: true

  tasks:
    - name: Install Nginx
      apt:
        name: nginx
        state: present
        update_cache: yes

    - name: Start and enable Nginx
      service:
        name: nginx
        state: started
        enabled: true

    - name: Deploy index.html
      copy:
        src: files/index.html
        dest: /var/www/html/index.html
        mode: '0644'

五、网页文件

files/index.html

<!DOCTYPE html>
<html>
<head>
  <title>Ansible Web</title>
</head>
<body>
  <h1>Hello from Ansible!</h1>
</body>
</html>

六、执行部署

ansible-playbook -i inventory.ini deploy_web.yml

浏览器访问:

http://web-server-ip

七、常见扩展(进阶)

1. 使用变量

vars:
  web_root: /var/www/html

2. 多服务器

[web]
web1 ansible_host=192.168.1.10
web2 ansible_host=192.168.1.11

3. 使用 Role(推荐)

ansible-galaxy init nginx

目录结构:

roles/
└── nginx/
    ├── tasks/
    ├── templates/
    └── handlers/

八、排查建议

  • 权限问题 → 加 become: true
  • 服务没启动 → 看 systemctl status nginx
  • Playbook 报错 → 加 -v 或 -vvv

如果你愿意,我可以:

  • 给你 CentOS 版本
  • 用 Apache / Docker / HTTPS
  • 或写一个 生产级 Role

你现在的系统是 Ubuntu 还是 CentOS?

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手