yaml语法之 条件测试,循环,tags 介绍



条件测试

when语句:在tasks中使用。


[root@ansible ~]# vim test5.yaml
- hosts: centos6-7
  remote_user: root
  tasks:
   - name: install httpd
     yum: name=httpd state=latest
   - name: start centos6 httpd
     shell: service httpd start
     when: ansible_distribution == "CentOS" and ansible_distribution_major_version == "6"  --> facts变量
   - name: start centos7 httpd
     shell: systemctl start httpd.service
     when: ansible_distribution == "CentOS" and ansible_distribution_major_version == "7"


wKioL1g-S8yTqnVQAAA7fjXKLFQ339.png-wh_50


wKioL1g-S9qxg1wRAAAS0TCRljg798.png


wKiom1g-S-Ti8vwpAACJPBrBIWI148.png-wh_50



循环:迭代,需要重复执行的任务


对迭代项的引用,固定变量名为 "item",使用with_item属性给定要迭代的元素;


[root@ansible ~]# vim test6.yaml
- hosts: centos7
  remote_user: root
  tasks:
   - name: create groups
     group: name={{ item }} state=present
     with_items:
      - groupx1
      - groupx2
   - name: create users
     user: name={{ item.name }} group={{ item.group }} state=present
     with_items:
      - {name: 'userx1', group: 'groupx1'}
      - {name: 'userx2', group: 'groupx2'}


wKioL1g-XYWg65ZoAABkpyq0NMo136.png-wh_50


wKiom1g-XZqBduJkAAHFxHh-F2o845.png-wh_50


wKiom1g-XaSB7urJAAAzZX4fVR0034.png-wh_50



tags:给指定的任务定义一个调用标识


[root@ansible ~]# vim test7.yaml
- hosts: centos7
  remote_user: root
  tasks:
   - name: install httpd
     yum: name=httpd state=latest
   - name: copy config file
     copy: src=/root/httpd.conf dest=/etc/httpd/conf/httpd.conf
     tags: httpdconf
   - name: start httpd service
     service: name=httpd state=started
   - name: print date
     shell: /usr/bin/date
     tags: showdate


wKioL1g-XcmC3Eg2AAAvM_Ge02k343.png-wh_50



wKioL1g-Xd3iVb30AABO2ct9dwQ317.png-wh_50