在ansible playbook中管理任务控制 处理程序 任务错误
最近简单的写法(没有循环)
- name: start httpd
service:
name: httpd
state: started
- name: start firewlld
service:
name: firewalld
state: started
Ansible 使用 loop 关键字对一组项目进行迭代,简单的循环 service: name: "{{ item }}" --->item 循环变量 state: started loop: - httpd - firewalld
方法二:
--- - name: Deploy and start Apache HTTPD service hosts: webserver vars: services: 变量名 - httpd - firewalld tasks: - name: install package yum: name: - "{{ web_pkg }}" - "{{ firewall_pkg }}" state: latest - name: start service httpd service: name: "{{ item }}" state: started loop: "{{ services }}" - name: the firewall port for http is open firewalld: service: "{{ rule }}" permanent: yes state: enabled immediate: true
早期: 循环关键字: With_items --->行为 loop 关键字相同 Ansible 版本不同,循环关键字不同
循环散列或字典列表:
--- - name: Create user group hosts: servera.lab.example.com become: true tasks: - name: create user user: name: "{{ item.name }}" state: present groups: "{{ item.groups }}" loop: - name: natasha - groups: wheel
ansible 可以使用 conditionals 在符合特定条件时执行任务或play(when语句)
如:在执行前先判断主机内存 是否 >= 384G
条件任务语法
when 语句用于有条件的运行任务,他取要测试的条件作为值,如果条件满足则运行,否则就跳过任务
--- - name: simple boolean task demo hosts: all vars: run_my_task: true tasks: - name: httpd package is installed yum: name: httpd when: run_my_task
例如:测试my_service 变量是否有值,若有值,将 my_service 的值用作要安装的软件包的名称,如果未定义 my_service 变量,则跳过任务且不显示错误
--- - name: test variable is defind demo hosts: all vars: my_service: httpd tasks: - name: "{{ my_service }} package is installed " yum: name: "{{ my_service }}" when: my_service is defind
示例:
第一个变量的值存在,作为第二个变量的列表的值
--- - name : demo hosts: all vars: supported_distros: - Red Hat - CentOS tasks: - name: install httpd yum: name: httpd state: latest when: ansible_distribution in supported_distros
~ 注意点: When 语句的缩进,when 语法不是模块变量,它必须通过缩进到任务的最高级别,放置在 模块的外面
例子:组合使用 注册变量= register 和条件 when 任务详情:只有在postfix服务处于运行状态时才会重启httpd服务
- name: Restart HTTPD if Postfix is Running hosts: all become: true tasks: - name: Get Postfix server status command: /usr/bin/systemctl is-active postfix ----查看 postfix 是否运行 ignore_errors: yes 如果 command 这个模块的命令失败,则不停止运行 register: cloudshelledu (名字自定义) 将 command 模块的结果信息临时存储到 cloudshelledu 该变量中
- name: print debug
debug:
var: cloudshelledu (注册变量的名字)
- name: Restart Apache HTTPD based on Postfx status service: name: httpd state: restarted when: cloudshelledu.rc == 0 如果 systemctl is-active postfix 命令代码为 0, 说明 postfix 服务是启动的,那么条件满足,重启 httpd 服务
小结:在写playbook时会经常用到 register注册变量 和 when 判断语句,为了判断上一段代码有没有执行成功,当用到when语句时多用到debug模块,将信息打印出来用于判断
注:archive (了解下这个模块)
原文:https://www.cnblogs.com/leading-net/p/13023166.html