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

...

相关推荐
likeyou~coucou14 小时前
自动化之ansible(二)
运维·自动化·ansible
明阳mark15 小时前
Ansible 学习笔记
笔记·学习·ansible
DC_BLOG15 小时前
Linux-Ansible模块进阶
linux·运维·服务器·ansible
DC_BLOG1 天前
Linux-Ansible命令
linux·运维·服务器·ansible
李匠20244 天前
云计算架构学习之Ansible-playbook实战、Ansible-流程控制、Ansible-字典循环-roles角色
学习·云计算·ansible
fenglei20207 天前
Ansible批量配置服务器免密登录步骤详解
运维·git·github·ansible
敖光 SRE7 天前
自动化运维之ansible快速入门
运维·自动化·ansible
大新新大浩浩7 天前
ceph部署-14版本(nautilus)-使用ceph-ansible部署实验记录
ceph·ansible
罗狮粉 9910 天前
AlmaLinux使用Ansible自动部署k8s集群
容器·kubernetes·ansible
Lz__Heng10 天前
Ansible 主机清单语法
ansible