ansible的脚本:playbook剧本

playbook组成部分:

1、tasks任务  包含要在目标主机上需要执行的操作,使用模块定义这些操作

2、variables变量  存储和传递数据。变量可以自定义,可以在playbook当中定义为全局变量,也可以外部传参

3、Templates模板  用于生成配置文件。模板是包含占位符的文件。占位符由ansible在执行时转化成变量值

4、handlers处理器  当需要有变更的时候,可以执行触发器

5、Roles角色  是一种组织和封装playbook的,允许把相关的任务、变量、模板、处理器组织成一个可复用的单元

示例模板一:

#this is playbook-1

- name: first play

#一个name就是一个任务名,可以不写

  gather_facts: false

#是否收集目标主机的系统信息,false就是不收集,否则默认就是收集

  hosts: 192.168.233.20

#执行的目标主机

  remote_root: root

#指定执行的用户

  tasks:

   - name: ping test

     ping:

   - name: close selinux

     command: '/sbin/setenforce 0'

     ignore_errors: True

   - name: close firewalld

     service: name=firewalld state=stopped

   - name: install httpd

     yum: name=httpd

   - name: start httpd

     service: enabled=true name=httpd state=started

   - name: editon index.html

     shell: echo "this httpd" > /var/www/html/index.html

     notify: restart httpd

  handlers:

   - name: restart httpd

     service: name=httpd state=restarted

检查语法是否正确

ansible-playbook test1.yaml --syntax-check

检查生效的任务

ansible-playbook test1.yaml --list-task

检查生效的目标主机

ansible-playbook test1.yaml --list-hosts

[root@10 opt]# ansible-playbook test1.yaml

vars:

    groupname: wxy

    username: yc

- 开头就是一个列表

playbook的条件判断

when 是一个比较常见的应用场景,实现满足条件即执行,不满足条件即跳过的任务

when满足条件即执行,不满足条件即跳过

playbook中的循环

ansible有多种循环格式

with_items 循环遍历

with_items 最常用的

with_list 列别分组循环

with_together 列表对应的列,数据结合的方式循环

with_nested 相当与双重循环,第一层定义了循环的次数,第二层表式第一层的每个元素会循环几次

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