用roles部署nginx

本文详细介绍了如何使用Ansible配置Web服务器角色,包括初始化角色、配置变量、任务、处理器及模板,以及如何将角色整合到playbook中并执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、初始化一个role

[root@bogon ~]# ansible-galaxy init /etc/ansible/roles/websrvs

查看已经创建的role
[root@bogon ~]# ls /etc/ansible/roles/
webservs



2、配置role

把初始化后 role里面没用的删除,只留下面四个目录

[root@bogon ~]# cd /etc/ansible/roles/webservs/
[root@bogon webservs]# ls
handlers  README.md  tasks  templates  vars
[root@bogon webservs]# ls templates/
index.html.j2  nginx.conf.j2


配置变量vars

[root@bogon webservs]# cat vars/main.yml 
---
# vars file for /etc/ansible/roles/webservs
worker_processes: 4
worker_connections: 768
max_open_files: 65506


tasks 文件内容

[root@bogon webservs]# cat tasks/main.yml 
---
# tasks file for /etc/ansible/roles/webservs
- name: install nginx
  command: yum install nginx -y

- name: copy nginx config file
  template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
  notify: restart nginx

- name: copy index.html
  template:
    src: index.html.j2
    dest: /usr/share/nginx/www/index.html
    mode: 0644
  notify: restart nginx

- name: see file
  command: ls /root
  notify: restart nginx


handlers 文件内容:

[root@bogon webservs]# cat handlers/main.yml 
---
# handlers file for /etc/ansible/roles/webservs
- name: restart nginx
  service: name=nginx state=restarted


模板文化内容:

[root@bogon webservs]# cat templates/nginx.conf.j2 
worker_processes {{ worker_processes }};
worker_rlimit_nofile {{ max_open_files }};

events {
    worker_connections {{ worker_connections }};
}

http {
    server {
        listen       80;
        root  /usr/share/nginx/www;
        index index.html index.htm default.html index.php;
        server_name loclhost;
        location / {
            try_files  / =404;
        }
    }
    
}


[root@bogon webservs]# cat templates/index.html.j2 
<html>
  <head>
    <title>welcome to american</title>
  </head>
  <body>
  <h1>nginx, confitured by ansible</h1>
  <p>if you can see this, ansible successfully installed nginx.</p>
  
  <p>{{ ansible_hostname }}</p>
  </body>
</html>


3、配置playbook,把role添加进来

[root@bogon ~]# cat nginx_role.yaml 
---
- hosts: webservers
  become: yes
  become_method: sudo
  roles:
    - role: webservs

4、开始执行Playbook

[root@bogon ~]# ansible-playbook nginx_role.yaml

 

转载于:https://www.cnblogs.com/effortsing/p/10284361.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值