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

 

版权声明:本文为effortsing原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/effortsing/p/10284361.html