变量的另一个用途是将一条命令的运行结果保存到变量中,供后面的playbook使用。下面是一个简单的示例:
- hosts: web_servers
  tasks:
     - shell: /usr/bin/foo
       register: foo_result
       ignore_errors: True
     - shell: /usr/bin/bar
       when: foo_result.rc == 5
上述示例注册了一个foo_result变量,变量值为shell:/usr/bin/foo的运行结果,ignore_errors:True为忽略错误。变量注册完成后,
就可以在后面playbook中使用了,当条件语句when:foo_result.rc==5成立时,shell:/usr/bin/bar命令才会运行,其中
foo_result.rc为返回/usr/bin/foo的resultcode(返回码)。图9-8返回“rc=0”的返回码。

tasks:
  - name: "shutdown Debian flavored systems"
    command: /sbin/shutdown -t now
    when: ansible_os_family == "Debian"  结果将返回BOOL类型值,为True执行command
 - command: /bin/something
    when: result|failed
 - command: /bin/something_else
    when: result|success
  - command: /bin/still/something_else
    when: result|skipped
“when:result|success”的意思为当变量result执行结果为成功状态时,将执行/bin/something_else命令,其他同理,其中
success为Ansible内部过滤器方法,返回Ture代表命令运行成功。

循环
- name:Install package
  yum: name={{ item }} state=installed
  with_items:
     - pkg1
     - pkg2
循环的次数为with_items的元素个数,这里有2个元素,分别为pkg1、pkg2,会分别替换{{item}}项

results matching ""

    No results matching ""