关于ansible的常规用法

常规用法

每个tab必须相同,每个tab是2个空格必须是全文都是2个空格

[student@workstation ~]$ vim test.yml
---
- hosts: serverb.lab.example.com
tasks:
- name: install command
yum:
name:
- tree
- net-tools
state: present
[student@workstation ~]$ ansible-playbook test.yml

block块

block除了能和when结合起来使用,还有一个很重要的功能,就是"错误处理"功能
常用语法:
- block:定义块
rescue:当出现异常时,执行的语句
always:无论结果如何都要执行的语句
[student@workstation inventory-variables]$ cat test.yml
---
- hosts: serverb.lab.example.com
tasks:
- name: xxxx
block:
- shell: 'cat /etc/redhat-elease'
- shell: 'ls /testdir' ==> testdir目录在目标主机上并没有
- shell: 'ls /opt'
rescue:
- debug:
msg: '报错了...'
always:
- debug:
msg: "不管怎么样我都执行..."
如上所示,定义了一个block,这个block中有3个任务,即在目标主机中执行了3个shell命令
除了block关键字,还有另外一个关键字rescue,rescue关键字与block关键字对齐,rescue的字面意思为"救援",
表示当block中只要有一个任务执行失败,就会执行rescue中的任务进行补救,当然在rescue中定义什么任务,是由你决定的。
也就是说当block中的任务出错时,会执行rescue中的任务,当block中的任务顺利执行时,则不会执行rescue中的任务。
block里的任意一个任务失败,都会去执行rescue的任务,rescue中又有任意任务执行失败,就会去执行always

官方示例

tasks:
- name: Install, configure, and start Apache
block:
- name: Install httpd and memcached
ansible.builtin.yum:
name:
- httpd
- memcached
state: present
- name: Apply the foo config template
ansible.builtin.template:
src: templates/src.j2
dest: /etc/foo.conf
- name: Start service bar and enable it
ansible.builtin.service:
name: bar
state: started
enabled: True
when: ansible_facts['distribution'] == 'CentOS'
become: true
become_user: root
ignore_errors: yes
posted @   Linux大魔王  阅读(197)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示