playbooks是一个不同于使用Ansible命令行执行方式的模式,其功能更强大灵活。简单来说,playbook是一个非常简单的配置管理和多主机部署系统,不同于任何已经存在的模式,可作为一个适合部署复杂应用程序的基础
核心元素
Tasks:任务,由模板定义的操作列表
Variables:变量
Templates:模板,即使用模板语法的文件
Handlers:处理器 ,当某条件满足时,触发执行的操作
Roles:角色
#示例一:测试连接性 ping.yml - hosts: test remote_user: root #执行:ansible-playbook ping.yml #示例二:执行命令 selinux.yml - hosts: test remote_user: root tasks: - name: selinux command : "setenforce 0" ignore_errors: True - name: check command : "getenforce" #这里需要加入ignore_errors,因为所有的任务如果有返回值的时候下,都会报错后停止 #执行:ansible-playbook selinux.yml #示例三:将本地文件复制到目标,并且演示如何使用通知执行一个处理器handlers cpcat.yml - hosts: test remote_user: root tasks: - name: cp data copy: src=~ /playbook/data dest= /tmp notify: - cats handlers: - name: cats command : 'cp /tmp/data /tmp/data.3' #执行:ansible-playbook cpcat.yml #这里的handlers的格式如以上,当notify后,它会自动执行,但只会执行一次。 #示例四:变量的使用 vars.yml - hosts: test remote_user: root vars: - ip: 192.168.42.73 - times : 4 tasks: - name: ping vars shell: 'ping {{ip}} -c {{times}} >> /tmp/vars.log' ignore_errors: True - name: ping items shell: 'ping {{item}} -c 1 >> /tmp/vars.log' ignore_errors: True with_items: - 192.168.42.1 - 192.168.42.74 #执行:ansible-playbook vars.yml #第一个任务演示使用单个变量,with_items演示的是使用一个变量组,用法如上。 示例五:条件判断 when.yml - hosts: test remote_user: root tasks: - name: test os shell: 'echo "this is centos" > /tmp/os' when: - ansible_distribution == "CentOS" #执行:ansible-playbook when.yml #示例六:标签的使用 tags.yml - hosts: test remote_user: root tasks: - name: output file copy: dest= /tmp/tags content= 'write one line' tags: - one - name: netstat shell: 'netstat -lnp | grep tcp > /tmp/tcp' tags: #- always - two #执行:ansible-playbook tags.yml --tags=one #这里使用--tags参数来选择一个或者一组任务来执行 #如果tags为always,那么无论有没有指定tag,这个任务都会执行。 |