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
...

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT大白鼠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值