用roles部署nginx

Posted effortsing

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用roles部署nginx相关的知识,希望对你有一定的参考价值。

1、初始化一个role

[[email protected] ~]# ansible-galaxy init /etc/ansible/roles/websrvs

查看已经创建的role
[[email protected] ~]# ls /etc/ansible/roles/
webservs



2、配置role

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

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


vars文件内容

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


tasks 文件内容

[[email protected] 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=/home/lmx/test_ansible/nginx.conf.j2 dest=/etc/nginx/nginx.conf
  notify: restart nginx

- name: copy index.html
  template:
    src: /home/lmx/test_ansible/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 文件内容:

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


模板文化内容:

[[email protected] 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;
        }
    }
    
}


[[email protected] 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添加进来

[[email protected] ~]# cat nginx_role.yaml 
---
- hosts: webservers
  become: yes
  become_method: sudo
  roles:
    - role: webservs

4、开始执行Playbook

[[email protected] ~]# ansible-playbook nginx_role.yaml

 

以上是关于用roles部署nginx的主要内容,如果未能解决你的问题,请参考以下文章

06Ansible角色

Ansible自动化部署之ROLES

Ansible 部署源码nginx

Ansible 部署源码nginx

ansible批量部署nginx

nginx.conf 忽略了 nginx-ingress 配置映射片段