ansible Role介绍
# ansilbe自1.2版本引入的新特性,用于层次性、结构化地组织playbook。 # roles能够根据层次型结构自动装载变量文件、tasks以及handlers等。 # 要使用roles只需要在playbook中使用include指令即可。 #简单来讲,roles就是通过分别将变量、文件、任务、模块及处理器放置于单独的目录中, # 并可以便捷地include它们的一种机制。 # 角色一般用于基于主机构建服务的场景中,但也可以是用于构建守护进程等场景中。 ############## 创建role的步骤 (1) 创建以roles命名的目录; (2) 在roles目录中分别创建以各角色名称命名的目录,如webservers等。注意:在 roles 必须包括 site.yml文件,可以为空; (3) 在每个角色命名的目录中分别创建files、handlers、meta、tasks、templates和vars目录; 用不到的目录可以创建为空目录,也可以不创建; (4) 在playbook文件中,调用各角色; ############### role内各目录中可用的文件 tasks目录:至少应该包含一个名为main.yml的文件,其定义了此角色的任务列表; 此文件可以使用include包含其它的位于此目录中的task文件; files目录:存放由copy或script等模块调用的文件; templates目录:template模块会自动在此目录中寻找Jinja2模板文件; handlers目录:此目录中应当包含一个main.yml文件,用于定义此角色用到的各handler; 在handler中使用include包含的其它的handler文件也应该位于此目录中; vars目录:应当包含一个main.yml文件,用于定义此角色用到的变量; meta目录:应当包含一个main.yml文件,用于定义此角色的特殊设定及其依赖关系; ansible 1.3及其以后的版本才支持; default目录:为当前角色设定默认变量时使用此目录;应当包含一个main.yml文件。
一、zabbix_client_install
1.创建playbook的目录结构
[root@ansible ~]# cd /etc/ansible/roles/ [root@ansible roles]# mkdir zabbix_client_install [root@ansible roles]# mkdir zabbix_client_install/{files,handlers,meta,tasks,template,vars} [root@ansible roles]# tree zabbix_client_install/ zabbix_client_install/ ├── files #存放需要使用的文件目录 ├── handlers #用来定义要用到的handler的目录 ├── meta #定义依赖关系的目录 ├── tasks #用来存放任务列表的目录 ├── template #存放模板的目录 └── vars #定义变量的目录
2.定义变量
[root@ansible roles]# cat /etc/ansible/roles/zabbix_client_install/vars/main.yml zabbix_dir: /usr/local #客户端的安装路径 zabbix_version: 2.4.5 #要安装的版本 zabbix_user: zabbix zabbix_port: 10050 zabbix_server_ip: 192.168.3.21
3.定义安装zabbix客户端的playbook配置文件
[root@ansible roles]# cat /etc/ansible/zabbix_client_install.yml - hosts: web remote_user: root gather_facts: True roles: - zabbix_client_install
4.定义galaxy_info的配置文件
[root@ansible roles]# cat /etc/ansible/roles/zabbix_client_install/meta/main.yml galaxy_info: author: lyao description: Install Zabbix Client license: MIT min_ansible_version: 1.6 platforms: - name: CentOS versions: - 6 categories: - Monitor dependencies: []
5.task里的copy.yml信息
[root@ansible ansible]# cat /etc/ansible/roles/zabbix_client_install/tasks/copy.yml - name: Stop Exist Zabbix Client Service In Redhat Client shell: ps -ef|grep zabbix|grep -v grep|awk '{print $2}'|xargs kill -9 >>/dev/null 2>&1 ignore_errors: yes when: ansible_os_family == "RedHat" and ansible_distribution_major_version|int == 6 - name: Delete Exist Zabbix Client Dir In Redhat Client shell: rm -rf {{zabbix_dir}}/zabbix ignore_errors: yes when: ansible_os_family == "RedHat" and ansible_distribution_major_version|int == 6 - name: Install Base Require Software In Redhat Client yum: name={{item}} state=latest with_items: - telnet - dmidecode - tar - name: Create Zabbix User In Redhat Client user: name={{zabbix_user}} state=present createhome=no shell=/sbin/nologin when: ansible_os_family == "RedHat" and ansible_distribution_major_version|int == 6 - name: Copy Zabbix Client Software To Redhat Client copy: src=zabbix-{{zabbix_version}}.tar.gz dest=/tmp/zabbix-{{zabbix_version}}.tar.gz owner=root group=root when: ansible_os_family == "RedHat" and ansible_distribution_major_version|int == 6 - name: Uncompression Zabbix Client Software To Redhat Client shell: tar xf /tmp/zabbix-{{zabbix_version}}.tar.gz -C {{zabbix_dir}}/ when: ansible_os_family == "RedHat" and nsible_distribution_major_version|int == 6 - name: Copy Zabbix Start Script To Redhat Client template: src=zabbix_agentd dest=/etc/init.d/zabbix_agentd owner=root group=root mode=755 when: ansible_os_family == "RedHat" and ansible_distribution_major_version|int == 6 - name: Copy Zabbix Config To Redhat Client template: src=zabbix_agentd.conf dest={{zabbix_dir}}/zabbix/conf/zabbix_agentd.conf owner={{zabbix_user}} group={{zabbix_user}} mode=0644 when: ansible_os_family == "RedHat" and ansible_distribution_major_version|int == 6
6.task里的install.yml信息
[root@ansible ansible]# cat /etc/ansible/roles/zabbix_client_install/tasks/install.yml - name: Modify Zabbix Dir Permisson In Redhat Client file: path={{zabbix_dir}}/zabbix owner={{zabbix_user}} group={{zabbix_user}} mode=0755 when: ansible_os_family == "RedHat" and ansible_distribution_major_version|int == 6 - name: Check Zabbix User Sudo Permisson In Redhat Client shell: grep "{{zabbix_user}}" /etc/sudoers |wc -l register: zabbix_sudoer ignore_errors: True when: ansible_os_family == "RedHat" and ansible_distribution_major_version|int == 6 - name: Give sudo pression to zabbix user in redhat client shell: echo "{{zabbix_user}} ALL=(root) NOPASSWD:/bin/netstat,/usr/bin/omreport" >>/etc/sudoers when: ansible_os_family == "RedHat" and ansible_distribution_major_version|int == 6 and zabbix_sudoer|int == 0 - name: start zabbix service in redhat client shell: /etc/init.d/zabbix_agentd start when: ansible_os_family == "RedHat" and ansible_distribution_major_version|int == 6 - name: add boot start zabbix service in redhat client shell: chkconfig zabbix_agentd on when: ansible_os_family == "RedHat" and ansible_distribution_major_version|int == 6
7.task的delete.yml信息
[root@ansible ansible]# cat /etc/ansible/roles/zabbix_client_install/tasks/delete.yml - name: delete zabbix commpression software in redhat client shell: rm -rf /tmp/zabbix-{{zabbix_version}}.tar.gz when: ansible_os_family == "RedHat" and ansible_distribution_major_version|int == 6
8.task的mail.yml,此文件时允许运行哪个任务
[root@ansible ansible]# cat /etc/ansible/roles/zabbix_client_install/tasks/main.yml - include: copy.yml - include: install.yml - include: delete.yml
9.template的zabbix_agentd,这个文件时客户端zabbix的服务启动脚本
[root@ansible ansible]# cat /etc/ansible/roles/zabbix_client_install/template/zabbix_agentd #!/bin/bash # # chkconfig: - 85 15 # description: Zabbix client script. # processname: Zabbix . /etc/profile SERVICE="Zabbix agent" DAEMON={{ zabbix_dir }}/zabbix/sbin/zabbix_agentd PIDFILE=/tmp/zabbix_agentd.pid CONFIG={{ zabbix_dir }}/zabbix/conf/zabbix_agentd.conf zabbix_agent_status=`ps aux|grep zabbix_agentd.conf|grep -v grep|wc -l` zabbix_agent_pid=`ps aux|grep zabbix_agentd|grep -v grep|awk 'NR==1{print $2}'` # Source function library. . /etc/rc.d/init.d/functions # Source networking configuration. . /etc/sysconfig/network function check() { if [ $? -eq 0 ];then action $"Operating is:" /bin/true else action $"Operating is:" /bin/false fi } case $1 in 'start') if [ -x ${DAEMON} ] then $DAEMON -c $CONFIG # Error checking here would be good... echo "${SERVICE} started." else echo "Can't find file ${DAEMON}." echo "${SERVICE} NOT started." fi check ;; 'stop') if [ -s ${PIDFILE} ] then if kill `cat ${PIDFILE}` >/dev/null 2>&1 then echo "${SERVICE} terminated." rm -f ${PIDFILE} fi fi check ;; 'restart') /bin/bash $0 stop sleep 5 /bin/bash $0 start ;; 'status') if [ $zabbix_agent_status -ne 0 ];then echo "Zabbix Agentd is running ($zabbix_agent_pid)" else echo "Zabbix Agentd is not running!" fi ;; *) echo "Usage: $0 {start|stop|status|restart}" ;; esac exit 0
10.template的zabbix_agentd.conf,这是zabbix服务的配置文件
[root@ansible ansible]# cat /etc/ansible/roles/zabbix_client_install/template/zabbix_agentd.conf # This is a config file for the Zabbix agent daemon (Unix) # To get more information about Zabbix, visit http://www.zabbix.com ############ GENERAL PARAMETERS ################# ### Option: PidFile # Name of PID file. # # Mandatory: no # Default: # PidFile=/tmp/zabbix_agentd.pid ### Option: LogFile # Name of log file. # If not set, syslog is used. # # Mandatory: no # Default: # LogFile= LogFile=/tmp/zabbix_agentd.log ### Option: LogFileSize # Maximum size of log file in MB. # 0 - disable automatic log rotation. # # Mandatory: no # Range: 0-1024 # Default: # LogFileSize=1 ### Option: DebugLevel # Specifies debug level # 0 - no debug # 1 - critical information # 2 - error information # 3 - warnings # 4 - for debugging (produces lots of information) # # Mandatory: no # Range: 0-4 # Default: # DebugLevel=3 ### Option: SourceIP # Source IP address for outgoing connections. # # Mandatory: no # Default: # SourceIP= ### Option: EnableRemoteCommands # Whether remote commands from Zabbix server are allowed. # 0 - not allowed # 1 - allowed # # Mandatory: no # Default: # EnableRemoteCommands=0 ### Option: LogRemoteCommands # Enable logging of executed shell commands as warnings. # 0 - disabled # 1 - enabled # # Mandatory: no # Default: # LogRemoteCommands=0 ##### Passive checks related ### Option: Server # List of comma delimited IP addresses (or hostnames) of Zabbix servers. # Incoming connections will be accepted only from the hosts listed here. # No spaces allowed. # If IPv6 support is enabled then '127.0.0.1', '::127.0.0.1', '::ffff:127.0.0.1' are treated equally. # # Mandatory: no # Default: # Server=zabbix-server-external.autoclouds.net Server={{ zabbix_server_ip }} ### Option: ListenPort # Agent will listen on this port for connections from the server. # # Mandatory: no # Range: 1024-32767 # Default: ListenPort={{ zabbix_port }} ### Option: ListenIP # List of comma delimited IP addresses that the agent should listen on. # First IP address is sent to Zabbix server if connecting to it to retrieve list of active checks. # # Mandatory: no # Default: # ListenIP=0.0.0.0 ### Option: StartAgents # Number of pre-forked instances of zabbix_agentd that process passive checks. # If set to 0, disables passive checks and the agent will not listen on any TCP port. # # Mandatory: no # Range: 0-100 # Default: # StartAgents=3 ##### Active checks related ### Option: ServerActive # List of comma delimited IP:port (or hostname:port) pairs of Zabbix servers for active checks. # If port is not specified, default port is used. # IPv6 addresses must be enclosed in square brackets if port for that host is specified. # If port is not specified, square brackets for IPv6 addresses are optional. # If this parameter is not specified, active checks are disabled. # Example: ServerActive=127.0.0.1:20051,zabbix.domain,[::1]:30051,::1,[12fc::1] # # Mandatory: no # Default: # ServerActive= ### Option: Hostname # Unique, case sensitive hostname. # Required for active checks and must match hostname as configured on the server. # Value is acquired from HostnameItem if undefined. # # Mandatory: no # Default: # Hostname= Hostname={{ ansible_hostname }} ### Option: HostnameItem # Item used for generating Hostname if it is undefined. # Ignored if Hostname is defined. # # Mandatory: no # Default: # HostnameItem=system.hostname ### Option: RefreshActiveChecks # How often list of active checks is refreshed, in seconds. # # Mandatory: no # Range: 60-3600 # Default: # RefreshActiveChecks=120 ### Option: BufferSend # Do not keep data longer than N seconds in buffer. # # Mandatory: no # Range: 1-3600 # Default: # BufferSend=5 ### Option: BufferSize # Maximum number of values in a memory buffer. The agent will send # all collected data to Zabbix Server or Proxy if the buffer is full. # # Mandatory: no # Range: 2-65535 # Default: # BufferSize=100 ### Option: MaxLinesPerSecond # Maximum number of new lines the agent will send per second to Zabbix Server # or Proxy processing 'log' and 'logrt' active checks. # The provided value will be overridden by the parameter 'maxlines', # provided in 'log' or 'logrt' item keys. # # Mandatory: no # Range: 1-1000 # Default: # MaxLinesPerSecond=100 ### Option: AllowRoot # Allow the agent to run as 'root'. If disabled and the agent is started by 'root', the agent # will try to switch to user 'zabbix' instead. Has no effect if started under a regular user. # 0 - do not allow # 1 - allow # # Mandatory: no # Default: # AllowRoot=0 ############ ADVANCED PARAMETERS ################# ### Option: Alias # Sets an alias for parameter. It can be useful to substitute long and complex parameter name with a smaller and simpler one. # # Mandatory: no # Range: # Default: ### Option: Timeout # Spend no more than Timeout seconds on processing # # Mandatory: no # Range: 1-30 # Default: Timeout=20 ### Option: Include # You may include individual files or all files in a directory in the configuration file. # Installing Zabbix will create include directory in /usr/local/etc, unless modified during the compile time. # # Mandatory: no # Default: # Include= # Include=/usr/local/etc/zabbix_agentd.userparams.conf # Include=/usr/local/etc/zabbix_agentd.conf.d/ ####### USER-DEFINED MONITORED PARAMETERS ####### ### Option: UnsafeUserParameters # Allow all characters to be passed in arguments to user-defined parameters. # 0 - do not allow # 1 - allow # # Mandatory: no # Range: 0-1 # Default: # UnsafeUserParameters=0 ### Option: UserParameter # User-defined parameter to monitor. There can be several user-defined parameters. # Format: UserParameter=<key>,<shell command> # See 'zabbix_agentd' directory for examples. # # Mandatory: no # Default: # UserParameter= UserParameter=memcached_stats[*],(echo stats; sleep 1) | telnet {{ ansible_default_ipv4.address }} $1 2>&1 | awk '/STAT $2 / {print $NF}' UserParameter=mysql[*],mysql -h {{ ansible_default_ipv4.address }} -P 3306 -uzabbix -pzabbix -e "show global status"|grep "\<$1\>"|cut -f2 UserParameter=redis_stats[*],(echo info; sleep 1) | telnet {{ ansible_default_ipv4.address }} $1 2>&1 |grep $2|cut -d : -f2 UserParameter=custom.vfs.dev.read.ops[*],cat /proc/diskstats | grep $1 | head -1 | awk '{print $$4}' UserParameter=custom.vfs.dev.read.ms[*],cat /proc/diskstats | grep $1 | head -1 | awk '{print $$7}' UserParameter=custom.vfs.dev.write.ops[*],cat /proc/diskstats | grep $1 | head -1 | awk '{print $$8}' UserParameter=custom.vfs.dev.write.ms[*],cat /proc/diskstats | grep $1 | head -1 | awk '{print $$11}' UserParameter=custom.vfs.dev.io.active[*],cat /proc/diskstats | grep $1 | head -1 | awk '{print $$12}' UserParameter=custom.vfs.dev.io.ms[*],cat /proc/diskstats | grep $1 | head -1 | awk '{print $$13}' UserParameter=custom.vfs.dev.read.sectors[*],cat /proc/diskstats | grep $1 | head -1 | awk '{print $$6}' UserParameter=custom.vfs.dev.write.sectors[*],cat /proc/diskstats | grep $1 | head -1 | awk '{print $$10}' UserParameter=MongoDB.Status[*],/bin/echo "db.serverStatus().$1" | /usr/bin/mongo admin | grep "$2"|awk -F: '{print $$2}'|awk -F, '{print $$1}' UserParameter=check_lvm[*],/usr/bin/sudo /usr/local/zabbix/bin/check_lvm.sh $1 UserParameter=TCP_ESTABLISHED,ss -s|awk 'NR==2{print $4}'|cut -d , -f1 UserParameter=TCP_CLOSED,ss -s|awk 'NR==2{print $6}'|cut -d , -f1 UserParameter=TCP_TIMEWAIT,ss -s|awk 'NR==2{print $12}'|cut -d / -f1 UserParameter=zabbix_low_discovery[*],/bin/bash /usr/local/zabbix/bin/zabbix_low_discovery.sh $1 UserParameter=mysql_stats[*],mysql -h {{ ansible_default_ipv4.address }} -P $1 -uzabbix -pzabbix -e "show global status"|grep "\<$2\>"|cut -f2 UserParameter=mysql_stats_slave[*],mysql -h {{ ansible_default_ipv4.address }} -P $1 -uzabbix -pzabbix -e "show slave status\G"|grep "\<$2\>"|awk '{if($NF=="Yes") {print 1} else {print 0}}' UserParameter=check_platform,dmidecode |grep Vendor|awk -F ' ' '{if($2=="Dell") {print 1} else {print 0}}' #follow is hardware monitor UserParameter=hardware_battery,omreport chassis batteries|awk '/^Status/{if($NF=="Ok") {print 1} else {print 0}}' UserParameter=hardware_cpu_model,awk -v hardware_cpu_crontol=`sudo omreport chassis biossetup|awk '/C State/{if($NF=="Enabled") {print 0} else {print 1}}'` -v hardware_cpu_c1=`sudo omreport chassis biossetup|awk '/C1[-|E]/{if($NF=="Enabled") {print 0} else {print 1}}'` 'BEGIN{if(hardware_cpu_crontol==0 && hardware_cpu_c1==0) {print 0} else {print 1}}' UserParameter=hardware_fan_health,awk -v hardware_fan_number=`omreport chassis fans|grep -c "^Index"` -v hardware_fan=`omreport chassis fans|awk '/^Status/{if($NF=="Ok") count+=1}END{print count}'` 'BEGIN{if(hardware_fan_number==hardware_fan) {print 1} else {print 0}}' UserParameter=hardware_memory_health,awk -v hardware_memory=`omreport chassis memory|awk '/^Health/{print $NF}'` 'BEGIN{if(hardware_memory=="Ok") {print 1} else {print 0}}' UserParameter=hardware_nic_health,awk -v hardware_nic_number=`omreport chassis nics |grep -c "Interface Name"` -v hardware_nic=`omreport chassis nics |awk '/^Connection Status/{print $NF}'|wc -l` 'BEGIN{if(hardware_nic_number==hardware_nic) {print 1} else {print 0}}' UserParameter=hardware_cpu,omreport chassis processors|awk '/^Health/{if($NF=="Ok") {print 1} else {print 0}}' UserParameter=hardware_power_health,awk -v hardware_power_number=`omreport chassis pwrsupplies|grep -c "Index"` -v hardware_power=`omreport chassis pwrsupplies|awk '/^Status/{if($NF=="Ok") count+=1}END{print count}'` 'BEGIN{if(hardware_power_number==hardware_power) {print 1} else {print 0}}' UserParameter=hardware_temp,omreport chassis temps|awk '/^Status/{if($NF=="Ok") {print 1} else {print 0}}'|head -n 1 UserParameter=hardware_physics_health,awk -v hardware_physics_disk_number=`omreport storage pdisk controller=0|grep -c "^ID"` -v hardware_physics_disk=`omreport storage pdisk controller=0|awk '/^State/{if($NF=="Online") count+=1}END{print count}'` 'BEGIN{if(hardware_physics_disk_number==hardware_physics_disk) {print 1} else {print 0}}' UserParameter=hardware_virtual_health,awk -v hardware_virtual_disk_number=`omreport storage vdisk controller=0|grep -c "^ID"` -v hardware_virtual_disk=`omreport storage vdisk controller=0|awk '/^State/{if($NF=="Ready") count+=1}END{print count}'` 'BEGIN{if(hardware_virtual_disk_number==hardware_virtual_disk) {print 1} else {print 0}}' UserParameter=pyora[*],/usr/local/zabbix/bin/pyora.py --username $1 --password $2 --address $3 --database $4 $5 $6 $7 $8