40 ansible role

分类

​ role进行配置

​ 每个角色以特定的层级目录结构进行组织

nginx流程

  • gorup:nginx #添加用户组
  • user:nginx #添加用户
  • yum:nignx #安装包
  • template:nginx.conf.j2 #模板文件
  • service:nginx #启动服务

role目录

[root@node1 roles]# tree
`-- nginx
    |-- tasks  #放创建的任务
    |   |-- group.yml
    |   |-- main.yml
    |   |-- restart.yml
    |   |-- start.yml
    |   |-- temp.yml
    |   |-- user.yml
    |   `-- yum.yml
    `-- templates  #模板
        `-- nginx.conf.j2

配置文件:

roles]# cat nginx/tasks/*
main.yml  #定义yml的执行顺序
    - include: group.yml
    - include: user.yml
    - include: yum.yml
    - include: temp.yml
    - include: start.yml
group.yml
    - name: create group
      group: name=nginx 
restart.yml
    - name: restart service
      service: name=nginx state=restarted 
start.yml
    - name: start service
      service: name=nginx state=started enabled=yes
temp.yml
    - name: copy templeate
      template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
user.tml
    - name: create user
      user: name=nginx group=nginx system=yes shell=/sbin/nologin
yum.tml
    - name: install pkgs
      yum: name=nginx
      
roles]#cat nginx/templates/nginx.conf.j2      
	worker_processes {{ ansible_processor_vcpus**2 }};

角色调用

  • files/ : 存放copy或script模块调用的文件

  • templates/ : template模块查找所需模板文件的目录

  • tasks/:至少应该包含一个名为main.yml的文件,包含其他文件需要在此文件中通过include进行包含

  • handlers/: 至少应该包含一个名为main.yml的文件,包含其他文件需要在此文件中通过include进行包含

  • vasrs/: 至少应该包含一个名为main.yml的文件,包含其他文件需要在此文件中通过include进行包含

role的使用

[root@node1 app]# tree
|-- files
|   `-- vhosts.conf
|-- handlers
|   `-- main.yml
|-- tasks
|   |-- copyfile.yml
|   |-- group.yml
|   |-- main.yml
|   |-- start.yml
|   |-- temp.yml
|   |-- user.yml
|   `-- yum.yml
|-- templates
|   `-- httpd.conf.j2
 -- vars
    `-- main.yml
[root@node1 app]# cat handlers/*
- name: restart service  
  service: name=httpd state=restarted
  
[root@node1 app]# cat tasks/*
copy.yml  #拷贝文件
- name: copy cfg
  copy: src=vhosts.conf dest=/etc/httpd/conf.d/ owner=app
  
group.yml
- name: create group
  group: name=app system=yes 
  
main.yml
- include: group.yml
- include: user.yml
- include: yum.yml
- include: temp.yml
- include: copyfile.yml
- include: start.yml

start.yml
- name: start service
  service: name=httpd state=started enabled=yes
  
temp.yml   #配合templates和handlers 进行操作
- name: copy cfg
  template: src=httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
  notify: restart service  #通知handlers,名称必须一致
  
user.yml
- name: create user
  user: name=app system=yes group=app shell=/sbin/nologin 
  
yum.yml
- name: install pksg
  yum: name=httpd
  
[root@node1 app]# cat vars/main.yml 
username: app  #变量
groupname: app #变量

你可能感兴趣的:(linux运维,ansible-role)