ansible条件示例剧本

备注:以下下示例主机组均为pxg

####系统符合就安装apache###


  • name: Install Apache on CentOS 7

hosts: pxg

remote_user: root # 使用root身份执行命令

tasks:

  • name: Install Apache

yum:

name: httpd # Apache软件包名称

state: present # 安装Apache

when: ansible_os_family == 'RedHat' # 仅对Red Hat/CentOS系统执行

  • name: Start Apache service

service:

name: httpd # Apache服务名称

state: started # 启动Apache服务

when: ansible_os_family == 'RedHat' # 仅对Red Hat/CentOS系统执行

...

###变量存在与否在回显提示###


  • name: Conditional Task Execution

hosts: pxg

remote_user: root # 使用root身份执行命令

vars:

user: peng

home: /home/peng

tasks:

  • name: Check if user is defined

debug:

msg: "user is defined"

when: user is defined

  • name: Check if home is defined

debug:

msg: "home is defined"

when: home is defined

...

####判断发行版本然后停止httpd服务###


  • name: 停止httpd服务

hosts: pxg

remote_user: root # 使用root身份执行命令

tasks:

  • name: 获取发行版信息

ansible.builtin.setup:

filter: "ansible_distribution"

register: dist_info # register 关键字用于将任务执行的结果保存到一个变量(dist_info)中,然后可以使用这个变量的值在 playbook 中的其他地方进行处理。

  • name: 停止httpd服务(如果发行版是CentOS或Fedora)

ansible.builtin.service:

name: httpd

state: stopped

when: dist_info.ansible_facts.ansible_distribution in ['CentOS', 'Fedora']

...

####判断根分区大小####


  • name: Check Root Partition Space and Stop vsftpd

hosts: pxg

remote_user: root # 使用root身份执行命令

tasks:

  • name: Get Root Partition Space

shell: df -h / | awk 'NR==2 {print $4}' # 获取根分区可用空间(以G为单位)

register: root_partition_space

  • name: Stop vsftpd Service

systemd:

name: vsftpd

state: stopped

when: root_partition_space |int < 3 # 当可用空间小于3G时停止服务

handlers:

  • name: Start vsftpd Service

systemd:

name: vsftpd

state: started

...

相关推荐
tianyuanwo20 小时前
Ansible自动化运维全解析:从设计哲学到实战演进
运维·自动化·ansible
哆啦A梦158820 小时前
在golang中如何将已安装的依赖降级处理,比如:将 go-ansible/[email protected] 更换为 go-ansible/@v1.1.7
开发语言·golang·ansible
lifeng43212 天前
在 CentOS 上将 Ansible 项目推送到 GitHub 的完整指南
centos·github·ansible
运维成长记7 天前
ansible-playbook 进阶 接上一章内容
linux·服务器·ansible
半桶水专家7 天前
Ansible 配置Playbook文件格式、关键字和语法详解
ansible
遇见火星9 天前
Ansible模块——Ansible配置文件!
linux·git·ansible
安顾里11 天前
Ansible安装
linux·运维·自动化·ansible
爱莉希雅&&&12 天前
运维Linux之Ansible详解学习(更新中)
linux·运维·ansible
筑梦之路18 天前
centos 9 Kickstart + Ansible自动化部署 —— 筑梦之路
centos·自动化·ansible
遇见火星18 天前
Ansible模块——通过 URL 下载文件
ansible