如何在 10 分钟内使用 Ansible 部署 Web 应用
发布: (2025年12月3日 GMT+8 00:47)
3 min read
原文: Dev.to
Source: Dev.to
什么是 Ansible?
Ansible 是一款功能强大的自动化工具,用于服务器配置。它通过 SSH 工作,无需代理,并使用 YAML 剧本(playbooks)来自动化任务。
在本指南中,您将学习
- 如何安装 Ansible
- 如何搭建项目结构
- 如何添加 SSH 密钥
- 如何测试 SSH 连接
- 如何创建静态内容文件
- 如何编写示例 playbook
- 如何配置清单文件
- 如何运行 playbook
- 如何验证部署
步骤 1 – 在 Ubuntu 上安装 Ansible
sudo apt update
sudo apt install ansible -y
ansible --version
步骤 2 – 创建 Ansible 项目结构
# 创建项目文件夹
mkdir ansible_demo
cd ansible_demo
# 创建 inventory 与 playbooks 目录
mkdir inventory playbooks
清单文件
cd inventory
touch hosts.ini
Playbook 文件
cd ../playbooks
touch web_prac.yml
步骤 3 – 向项目添加 SSH 密钥
cd ..
mkdir ssh
cd ssh
touch nagios.pem
将您的 PEM 密钥内容粘贴到 nagios.pem 中,然后设置正确的权限:
chmod 600 nagios.pem
步骤 4 – 使用 PEM 测试 SSH 连接
ssh -i ssh/nagios.pem ubuntu@
如果您成功登录,说明连接正常。
步骤 5 – 为静态内容创建 files 文件夹
cd ../playbooks
mkdir files
cd files
touch index.html
在 index.html 中添加您的 HTML 内容。
步骤 6 – 示例 Playbook (web_prac.yml)
---
- name: Setup Web Server
hosts: webserver
become: yes
tasks:
- name: Install NGINX
apt:
name: nginx
state: present
update_cache: yes
- name: Copy index.html to web server
copy:
src: files/index.html
dest: /var/www/html/index.html
owner: www-data
group: www-data
mode: '0644'
- name: Start and enable NGINX
service:
name: nginx
state: started
enabled: yes
步骤 7 – 清单文件 (hosts.ini)
[webserver]
13.201.29.244
ansible_user=ubuntu
ansible_ssh_private_key_file=../ssh/nagios.pem
步骤 8 – 运行 Ansible Playbook
在 ansible_demo 目录下执行:
ansible-playbook -i inventory/hosts.ini playbooks/web_prac.yml
如果运行完成且没有错误,说明部署成功。
步骤 9 – 在浏览器中验证
打开浏览器并访问:
http://
您应该能看到由 NGINX 提供的 index.html 内容。
最终结果
通过本指南,您将完成:
- 安装 Ansible
- 创建专业的项目结构
- 创建清单文件
- 编写 YAML Playbook
- 添加用于身份验证的 SSH 密钥
- 使用 Ansible 自动化部署网页