Ansible第五章 ansible中的任务执行控制

本文详细介绍了Ansible中任务执行的控制机制,包括如何使用循环迭代任务,如简单循环和循环散列,以及条件判断如`when`语句的多种组合。还讲解了触发器、处理失败任务的策略,如`ignore_errors`、`force_handlers`等,并给出了相关的练习案例,帮助读者深入理解Ansible的控制流程。
摘要由CSDN通过智能技术生成

一.循环

循环迭代任务

1.简单循环

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

实例:
---
- name: create file
hosts: 172.25.0.254
tasks:
  - name: file module
    file:
      name: /mnt/{ {item}}
      state: present
    loop:
      - westos_file1
      - westos_file2

 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

练习:

http://172.25.254.250/RHCE_EXAM/files/hwreport.empty
创建一个名为/home/devops/.ansible/hwreport.yaml 的playbook 它将在所在所有受管节点上含有以下信息的输出文件 /mnt/hwreport.txt 清单主机名称
以MB表示总内存大小
BIOS 版本
磁盘设备 vda 的大小
磁盘设备vdb的大小
输出文件中的每一行含有一个 key=value 对
将它保存到/mnt/hwreport.txt
使用正确的值改为 /mnt/hwreport.txt
如果硬件不存在,相关的值设为NONE

[devops@ansible .ansible]$ cat hwreport.yaml 
- name: hwreport
  hosts: westos
  tasks:
    - name: download
      get_url:
        url: http://172.25.254.250/RHCE_EXAM/files/hwreport.empty
        dest: /mnt/hwreport.txt
        force: yes

    - name: check device
      lineinfile:
        path: /mnt/hwreport.txt
        regexp: "{
  {item.start}}"
        line: "{
  {item.start}}={
  {item.reline}}"
      loop:
        - name: HOST
          reline: "HOST={
  {ansible_facts['fqdn']}}"
        - name: MEMERY
          reline: "{
  {ansible_facts['memtotal_mb']}}"
        - name: BIOS
          reline: "{
  {ansible_facts['bios_version']}}"
        - name: DISK_SIZE_VDA
          reline: "{
  {ansible_facts['devices']['vda']['size'] | default ('NONE')}}"
        - name: DISK_SIZE_VDB
          reline: "{
  {ansible_facts['devices']['vdb']['size'] | default ('NONE')}}"
            
[devops@ansible .ansible]$ ansible-playbook hwreport.yaml

 

在受控主机中查看:

[root@node1 mnt]# cat hwreport
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值