Anisble中的任务执行控制

一、循环

1、简单循环

使用loop赋值列表的格式:

loop:  ##赋值列表
- value1
- value2
- ...
{{item}}  ##迭代变量名称

2、循环散列或字典列表

  • 可以赋予不同的服务不同的状态
- name: create file
 hosts: 172.25.0.254
 tasks:
 - name: file module
 service:
 name: "{{ item.name}}"
 state: "{{ item.state }}"
 loop:
 - name: httpd
 state: started
 - name: vsftpd
 state: stopped

二、条件判定

1、when条件语句

此条件代表两者都满足时

when:
- 条件1
- 条件2

此条件代表两者满足一个即可

when:
- 条件1 
  or 
  条件2

2、条件判断

= value == "字符串“,value == 数字
< value < 数字
> value > 数字
<= value <= 数字
>= value >= 数字
!= value != 数字
is defined value is defined(变量存在)
is not defined value is not defined(变量不存在)
in value is in value(变量为)
not in value is not in value(变量不为)
bool变量为true value(value的值为true)
bool变量false not value(value的值为false)
value in value2(value的值在value2列表中)

上述的应用实例:

使用loop when 创建用户

vim user.yml

- name: create user
  hosts: all
  vars:
    userlist:
    - name: user1
      id: 6666
      comment: user1 comment
    - name: user2
      id: 7777
  tasks:
  - name: create user2
    user:
      name: "{{item.name}}"
      uid: "{{item.id}}"
      comment: "{{item.comment}}"
      state: present
    when:
      item.comment is defined
    loop:
      "{{userlist}}"
  - name: create user
    user:
      name: "{{item.name}}"
      uid: "{{item.id}}"
      state: present
    when:
      item.comment is not defined
    loop:
      "{{userlist}}"

ansible-playbook user.yml  -C

Anisble中的任务执行控制_第1张图片

三、触发器

notify:触发器当遇到更改时触发handlers
handlers:触发器触发后执行的动作

 示例:

使用触发器 j2 loop 安装httpd服务并运行虚拟主机

vim web.yml

webs:
- doc: /var/www/html
  index: "www.westos.org's page"

- name: bbs.westos.org
  doc: /var/www/virtual/westos.org/bbs/html
  index: "bbs.westos.org's page"

- name: login.westos.org
  doc: /var/www/virtual/westos.org/login/html
  index: "login.westos.org's page"

Anisble中的任务执行控制_第2张图片

vim vhosts.conf.j2

{% for web in webs %}
{% if web.name is defined %}

  ServerName {{web.name}}
{% endif %}
{% if web.name is not defined %}

{% endif %}
  DocumentRoot {{web.doc}}

{% endfor %}

Anisble中的任务执行控制_第3张图片

vim httpd.yml

- name: create virtualhost
  hosts: all
  vars_files: ./web.yml
  tasks:
  - name: yum
    yum:
      name: httpd
      state: present

  - name: service
    service:
      name: httpd
      state: started
      enabled: yes

  - name: create doc
    lineinfile:
      path: "{{item.doc}}/index.html"
      line: "{{item.index}}"
      create: yes
    loop: "{{webs}}"

  - name: create vhosts.conf
    template:
      src: ./vhosts.conf.j2
      dest: /etc/httpd/conf.d/vhost.conf
    notify: restart httpd

  handlers:
  - name: restart httpd
    service:
      name: httpd
      state: restarted

触发器工作 

Anisble中的任务执行控制_第4张图片

 Anisble中的任务执行控制_第5张图片

因为没有文件修改触发器没有触发所以不进行重启服务Anisble中的任务执行控制_第6张图片

你可能感兴趣的:(ansible,服务器,apache,运维)