02 . Ansible高级用法(运维开发篇) (4)

playbook里的变量

1. playbook的yaml文件中定义变量赋值 > 2. --exxtra-vars执行参数赋给变量 > 3. 在文件中定义变量 > 4. 注册变量 # register关键字可以存储指定命令的输出结果到一个自定义的变量中. --- - hosts: database remote_user: root vars: touch_file: youmen_file tasks: - name: get date command: date register: date_output - name: touch shell: "touch /tmp/{{touch_file}}" - name: echo date_output shell: "echo {{date_output.stdout}}>/tmp/{{touch_file}}" 数据结构

yaml支持的数据结构
字典

{name:jeson}

列表

- Apple - Mango - Orange

纯量: 数字,布尔,字符串

条件判断 循环 循环类型 关键字
标准循环   with_items    
嵌套循环   with_nested    
遍历字典   with_dict    
并行遍历列表   with_together    
遍历列表和索引   with_indexed_items    
遍历文件列表的内容   with_file    
遍历目录文件   with_fileglog    
重试循环   until    
查找第一个匹配文件   with_first_found    
随机选择   with_random_choice    
在序列中循环   with_sequence    

条件循环语句复用

种类一, 标准循环

--- - hosts: nginx tasks: - name: add serveral users user: name=http://www.likecs.com/{{ item.name }} state=present groups=http://www.likecs.com/{{ item.groups }} with_items: - { name: 'testuser1',groups: 'wheel' } - { name: 'testuser2',groups: 'root' }

种类二, 遍历字典

--- - hosts: nginx remote_user: root tasks: - name: add serveral users user: name=http://www.likecs.com/{{ item.key }} state=present groups=http://www.likecs.com/{{ item.value }} with_dict: { 'testuser3':'wheel','testuser4':'root' }

种类三, 遍历目录中内容

--- - hosts: nginx remote_user: root tasks: - file: dest=http://www.likecs.com/tmp/aa state=directory - copy: src=http://www.likecs.com/{{ item }} dest=http://www.likecs.com/tmp/bb owner=root mode=600 with_fileglob: - aa/*n 条件语句结合循环语句使用场景 --- - hosts: nginx remote_user: root tasks: - debug: msg="{{ item.key }} is the winner" with_dict: {'jeson':{'english':60,'chinese':30},'tom':{'english':20,'chinese':30}} when: item.value.english >= 10 异常

异常处理和相关操作

异常处理

1.忽略错误

默认会检查命令和模块的返回状态,遇到错误就中断playbook的执行
加入参数: ignore_errors: yes
Example

- hosts: nginx remote_user: root tasks: - name: ignore false command: /bin/false ignore_errors: yes - name: touch a file file: path=http://www.likecs.com/tmp/test22 state=touch mode=0700 owner=root group=root

2. tags标签处理

--- - hosts: nginx remote_user: root tasks: - name: get process shell: touch /tmp/change_test2 changed_when: false

打标签

意义: 通过tags和任务对象进行捆绑,控制部分或者指定的task执行

# 打标签 # 对一个对象打一个标签 # 对一个对象打多个标签 # 打标签的对象包括: 单个task任务,include对象,roles对象等.

标签使用

-t : 执行指定的tag标签任务 --skip-tags: 执行 --skip-tags之外的标签任务

自定义change状态

--- - hosts: nginx remote_user: root tasks: - name: get process shell: ps -ef |wc -l register: process_count failed_when: process_count > 3 - name: touch a file file: path=http://www.likecs.com/tmp/test1 state=touch mode=0700 owner=root group=root roles角色和场景演练

使用roles角色
include的用法

include_tasks/include: 动态的包含tasks任务列表执行

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpjydf.html