Ansible角色:Linux巡检

Ansible角色:Linux巡检

Ansible基于脚本进行linux巡检:CPU、内存、磁盘。并写入日志


一、版本要求

被控节点:Linux
控制节点:Ansible2.9


二、如何使用

1、进入Ansible默认角色目录

cd /etc/ansible/roles

如果在ansible.cfg中更改了默认的角色目录,根据你自己角色目录进行更改


2、创建一个角色

ansible-galaxy init linux_check

3、下载

linux_check.tar.gz


4、解压

tar zxvf linux_check.tar.gz

5、主机清单

vim /etc/ansible/hosts

ansible_ssh_host 填写被控主机地址
ansible_ssh_user 填写被控主机用户
ansible_ssh_pass 填写被控主机登录密码

[CentOS]
host_A ansible_ssh_host= 

[CentOS:vars]
ansible_ssh_user= 
ansible_ssh_pass= 
ansible_ssh_port= 22

三、实例剧本

1、主剧本

---
- hosts: CentOS
  remote_user: root
  roles:
    - linux_check

四、角色详解

1、角色目录

defaults
  └─main.yml  
files
  └─check_resources.sh
handlers
meta
tasks
  ├─main.yml
  ├─sh.yml
  └─write_in_log.yml
templates
tests
  └─test.yml
vars


2、任务

主任务
main.yml

---
# tasks file for linux-check
#剧本执行顺序
- include: sh.yml
- include: write_in_log.yml

巡检任务
sh.yml

---
  #执行巡检脚本
  - name: run sh
    script: check_resources.sh
    register: check_result
    
  #ansible中输出执行结果
  - name: debug
    debug:
      msg: "{{ check_result.stdout_lines}}"

写入日志任务
weite_in_log.yml

---
  #创建日志文件目录任务
  - name: create logfolder
    file:
      path: /etc/log
      state: directory

  #以时间和日期为日志名,创建日志文件
  - name: create logfile
    file:
      path: /etc/log/checkfile-{{ ansible_date_time.date }}_{{ ansible_date_time.time }}.log
      state: touch
      
  #将巡检结果写入日志
  - name: write result in logfile
    copy:
      content: "{{ check_result.stdout }}"
      dest: /etc/log/checkfile-{{ ansible_date_time.date }}_{{ ansible_date_time.time }}.log

3、脚本

巡检脚本
check_resources.sh

#!/bin/bash
free -m | awk 'NR==2{printf "Memory Usage: %s/%sMB (%.2f%%)\n", $3,$2,$3*100/$2 }';

df -h -t ext2 -t ext4 | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print "Disk Usage:"" " $1 " " $3"/"$2" ""("$5")"}';

top -bn1 | grep load | awk '{printf "CPU Load: %.2f\n", $(NF-2)}';
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值