Ansible简介 & playbook & roles & include


ansible概述
  1. 应用代码自动化部署
  • 系统管理配置自动化
  • 支持持续交付自动化
  • 支持云、大数据(openstack、aws、cloudstack、vmware)环境
  • 批量任务执行可以写成脚本,不必分发到远程就可以执行
  • 支持sudo
Ansible简介 & playbook & roles & include_第1张图片
Paste_Image.png
Ansible简介 & playbook & roles & include_第2张图片
Paste_Image.png

Playbook简介
-hosts: //被管理的主机组
 user:root  //远程执行操作的用户
 vars: //变量
  - motd_warning:'variable'
 tasks:  //任务
  -name:setup a MOTD
   copy:dest=/etc/motdcontent = "{{ motd_warning }}"
   notify:say something
 handlers: //由task的notify触发的处理动作
  -name:say something
  1. Target section 定义将要执行playbook的远程主机组
hosts:定义远程的主机组
user:执行该任务组的用户
remote_user:与user相同
sudo:如果设置为yes,执行该任务组的用户在执行任务的时候,获取root权限
sudo_user:如果你设置user为tom,sudo为yes,sudo_user为jerry,则tom用户则会获取jerry用户的权限
connection:通过什么方式连接到远程主机,默认为ssh
gather_facts:除非你明确说明不需要在远程主机上执行setup模块,否则默认会自动执行。如果你确实不需要setup模块所传递过来的变量,你可以启用该选项
  1. Variable section
    定义playbook运行时需要使用的变量
vars  直接在playbook中定义变量
vars_files:  #在文件中定义变量,var_files指定包含变量的文件位置
    - variables
vars_prompt:  #用于实现用户输入作为变量的值
    -name:variable_name 自定义变量名,可以在文件中使用
     prompt: please input xxx  提示信息
     private:yes  交互输入不显示
  • Task section
    定义将要在远程主机上执行的任务列表
tasks:
    #第一种方法
    - name: install apache
       action: yum name=httpd state=installed     
    #第二种方法
    - name: configure apache
       copy: src=files/httpd.conf dest=/etc/httpd/conf/httpd.conf
    #第三种方法    
    - name: restart apache                    
       service:
            name: httpd
            state: restarted                         
  • Handler section
    定义task执行完成以后需要调用的任务
tasks:
   - name: template configuration file
     template: src=template.j2 dest=/etc/foo.conf
     notify:
         - restart memcached
         - restart apache
handlers:
    - name: restart memcached
      service: name= memcached state=restarted
    - name: restart apache
      service: name=httpd state=restarted

playbook的roles和include

完成复杂任务时,通常需要把多个playbook进行组合,少量用include即可完成,如果playbook较多,引入roles对playbook进行有效组织十分必要

include包含
include.yml文件内容
- include xxx1.yml
- include xxx2.yml
- hosts:mfs_node
  vars_file:
    - vars.yml
    - vars1.yml
  tasks:
    - include: task.yml
  handlers:
    - include: handler.yml

task.yml文件内容
- name :xxx
  shell:xxx
  notify:touch a file

handler.yml文件内容

- name:touch a file
  shell: xxx
roles目录结构
group_vars/  //可定义整组角色都可用的变量文件,也可以单独定义某个角色变量文件,文件名对应hosts内的角色名称
hosts
main.yml   //入口文件
roles/
    role1/
       vars/
       tasks/
       handlers/
    role2/
    role3/
    ...
tools/

main.yml文件内容类似这样

- hosts: xxx1
  roles:
    - role:
- hosts: xxx2
  roles:
    - role: 
    - role:

你可能感兴趣的:(Ansible简介 & playbook & roles & include)