2019-08-27 ansible剧本

2019-08-27  本文已影响0人  麟之趾a

剧本编写扩展功能

1.剧本变量的设置
2.剧本变量注册功能
register注册变量

[root@m01 /etc/ansible]# cat test01.yml 
- hosts: web01
  tasks:
    - name: vars register
      shell: df -h
      register: oldboy
    - name: play
      debug: msg={{ oldboy.stdout_lines  }}

3.剧本编写判断功能

[root@m01 /etc/ansible]# cat test01.yml 
- hosts: oldboy
  tasks:
    - name: vars register
      shell: hostname
      register: oldboy
    - name: play
      debug: msg={{ oldboy.stdout_lines  }}
      when: (ansible_nodename == 'nfs01')
============================================================================================
when 语句判断   and  是并且关系    or 是或者关系

4.剧本编写循环功能

[root@m01 /etc/ansible]# cat test01.yml 
- hosts: oldboy
  tasks:
    - name: create directory
      file: path={{ item }} state=directory
      with_items:
        - oldboy01
        - oldboy2
============================================================================
[root@m01 /etc/ansible]# cat test01.yml 
- hosts: oldboy
  tasks:
    - name: create user
      user: name={{ item.name  }} shell={{ item.shell }}
      with_items:
        - {name: 'olg01', shell: '/sbin/nologin'}
        - {name: 'olg02', shell: '/sbin/bash'}

5.编写忽略错误功能
ignor_errors: yes

[root@m01 /etc/ansible]# cat test01.yml
- hosts: oldboy
  tasks:
    - name: test shell
      shell: ddd
      ignore_errors: yes

6.剧本编写标签功能
-t 指定标签,--skip-tags 跳过标签,tags: 使用标签

[root@m01 /etc/ansible]# cat test01.yml
- hosts: oldboy
  tasks:
    - name: test shell
      shell: df -h
    - name: create file
      file: path=/tmp/1 state=touch
      tags: oldboy

7 .剧本提高执行效率,取消剧本信息收集功能
gather_facts: no

[root@m01 /etc/ansible]# cat test01.yml 
- hosts: oldboy
  gather_facts: no
  tasks:
    - name: test shell
      shell: df -h

PS:取消信息收集功能,判断也不能执行了
总结:剧本执行慢的原因

1 .ssh远程连接优化没有配置,关闭认证功能,关闭DNS反向解析功能
2 .yum 下载软件慢,使用本地的yum库
3 .剧本执行收集信息慢
4 .剧本执行过程必须完整(即不能随便使用ctrl+c中断,特别是使用yum模块安装东西时)

8.触发器
notify,handlers

[root@m01 /etc/ansible]# cat test01.yml 
- hosts: backup
  tasks:
    - name: copy config
      copy: src=/file/rsyncd.conf dest=/etc
      notify: restart rsyncd
    - name: boot server
      service: name=rsyncd state=started
  handlers:
    - name: restart rsyncd
      service: name=rsyncd state=restarted
=============================================================================
触发器实是在所有任务执行完毕后执行

9.批量添加剧本

方式一: include_tasks: f1.yml
- hosts: all
      remote_user: root
      tasks:
        - include_tasks: f1.yml
        - include_tasks: f2.yml
方式二: include f1.yml
 - include:f1.yml   
 - include:f2.yml
方式三: import_playbook 推荐
[root@m01 ansible-playbook]# cat main.yml 
    - import_playbook: base.yml     
    - import_playbook: rsync.yml    
    - import_playbook: nfs.yml 

上一篇 下一篇

猜你喜欢

热点阅读