ansible Playbook案例 安装nginx
时间: 2025-06-17 08:49:42 浏览: 19
### 使用 Ansible Playbook 安装 Nginx 的案例
以下是基于多个引用内容整理的一个完整的 Ansible Playbook 示例,用于安装和配置 Nginx:
#### 1. 准备工作
确保已经正确配置了 Ansible 环境,并且目标主机已添加到 `hosts` 文件中。
```yaml
---
- name: Install and Configure Nginx
hosts: web
become: true
tasks:
- name: Ensure required packages are installed
yum:
name: "{{ item }}"
state: present
loop:
- gcc
- make
- openssl-devel
- pcre-devel
- zlib-devel
- wget
tags: preparation
- name: Download Nginx source package
shell: |
cd /tmp/
wget https://nginx.org/download/nginx-1.21.6.tar.gz
register: download_result
failed_when: "'404 Not Found' in download_result.stdout"
changed_when: "'saved' in download_result.stderr or 'already exists' not in download_result.stderr"
tags: download
- name: Extract the downloaded archive
unarchive:
src: /tmp/nginx-1.21.6.tar.gz
dest: /tmp/
remote_src: yes
tags: extraction
- name: Compile and install Nginx from source
shell: |
cd /tmp/nginx-1.21.6
./configure --prefix=/usr/share/nginx \
--conf-path=/etc/nginx/nginx.conf \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log \
--pid-path=/run/nginx.pid \
--with-http_ssl_module
make && make install
args:
creates: /usr/share/nginx/sbin/nginx
tags: compilation
- name: Create necessary directories for logs
file:
path: "/var/log/nginx/{{ item }}"
state: directory
mode: '0755'
with_items:
- access.log
- error.log
notify: restart nginx
tags: log_directories
- name: Copy custom configuration files to target host
copy:
src: /path/to/local/nginx.conf
dest: /etc/nginx/nginx.conf
owner: root
group: root
mode: '0644'
notify: reload nginx
tags: config_copy
- name: Start and enable Nginx service
systemd:
name: nginx
state: started
enabled: yes
tags: service_management
handlers:
- name: Restart Nginx
systemd:
name: nginx
state: restarted
- name: Reload Nginx Configuration
systemd:
name: nginx
state: reloaded
```
此脚本涵盖了从依赖包安装、源码下载编译到最终服务启动的全过程[^3]。如果只需要通过 Yum 或 Apt 包管理器快速安装,则可以简化为以下版本[^4]:
```yaml
---
- name: Quick Installation of Nginx via Package Manager
hosts: web
become: true
tasks:
- name: Install Nginx using YUM (for CentOS/RHEL)
yum:
name: nginx
state: present
- name: Start and Enable Nginx Service
service:
name: nginx
state: started
enabled: yes
```
以上两种方法均可实现 Nginx 的安装与运行,具体选择取决于实际需求以及环境条件。
---
###
阅读全文
相关推荐


















