ansible-playbook剧本基础(一)

ansible的剧本是使用yaml语言进行编写的,基本语法如下:

基本语法:
1、大小写
2、同级别要对齐,缩进表示层级
3、缩进不允许使用Tab键
4、缩进空格数不规定,相同元素区分即可


支持的数据结构:
1、对象:键值对集合,又称映射/哈希/字典
例如:name:example 键:值
2、数组:一组按次序排列的值,又称序列/列表/
例如:-apple
3、纯量:单个的、不再分的值
例如:number:12.30
sure:true


play-book剧本
通过tasks调用ansible的模板将多个play组织在一个playbook中运行。
palybook构成部分:
(1)tasks:任务,相当于执行事务
(2)variables:变量(定义场景:hosts文件;剧本中;命令中)
(3)templates:模板
(4)handlers:处理器,满足条件,触发执行操作
(5)roles:角色


一个简单的playbook小示例:
实验环境:两台centos7,一台ansible服务器,一台测试机。
ansible服务器地址:192.168.71.128
测试机服务器地址:192.168.71.129

vim /opt/book.yml      #首先创建一个以.yml为结尾的文件
- hosts: webserver           #hosts定义了配置文件中的组名
  remote_user: root          #剧本中的演员:root用户,也可以是你推送秘钥的任意用户
  tasks:                              #任务,以下是执行什么任务
   - name: download apache          #自行定义的名称
     yum: name=httpd                        #指定模块,模块后跟相对应的操作
   - name: stopped firewalld
     service: name=firewalld state=stopped
   - name: stopped selinux
     command: '/usr/sbin/setenforce 0'
   - name: copy index.html
     template: src=/opt/index.html dest=/var/www/html/index.html          #这里的模板要注意,需要创建推送的文件并写入你指定的内容。
   - name: started apache
     service: name=httpd state=started
检查yml文件中语法的正确性

ansible-playbook book.yml --syntax-check #检查yaml语法
ansible-playbook book.yml --list-tasks #检查tasks任务
ansible-playbook book.yml --syntax-hosts #检查生效的主机
ansible-playbook book.yml --start-at-task='Copy Nginx.conf

执行过程如下:
ansible-playbook剧本基础(一)

效果图如下:
ansible-playbook剧本基础(一)


playbook剧本一些常用的操作

1、触发器调用

- hosts: webserver            #定义主机组
  vars:                       #定义变量
    http_port: 80            
    max_clients: 200
  users:root
  tasks:                      #执行的任务
    - name: write the apache config file
    template: src=/srv/httpd,j2 dest=/etc/httpd.conf
    notify:                    #调用触发以下操作
    - restart apache
  - name: ensure apache is running
    service: name=httpd state=started
  handlers:                    #处理器,给notify调用的命令,不调用不进行任何操作。
    - name: restart apache 
      service: name=httpd state=restarted

2、执行错误,跳过改操作继续执行

- hosts: webserver
  remote_user: root
  tasks:
  - name: create mysql
    user:                      #这里不添加任何的实质性操作,会报错
    ignore_errors: true       #添加该行后出错跳过,继续执行
  - name: apache status
    command: 'systemctl status httpd'

ansible-playbook剧本基础(一)

猜你喜欢

转载自blog.51cto.com/13760226/2307643