Ansible角色:Linux巡检
Ansible基于脚本进行linux巡检:CPU、内存、磁盘。并写入日志
一、版本要求
被控节点:Linux
控制节点:Ansible2.9
二、如何使用
1、进入Ansible默认角色目录
cd /etc/ansible/roles
如果在ansible.cfg中更改了默认的角色目录,根据你自己角色目录进行更改
2、创建一个角色
ansible-galaxy init linux_check
3、下载
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)}';