├── README.md ├── 第11章 ├── ajax.js ├── flask-api.py ├── flask-celery-client.py ├── flask-celery-server.py └── key.yaml ├── 第3章 ├── host.py ├── roles │ └── nginx │ │ ├── files │ │ └── index.html │ │ ├── handers │ │ └── main.yaml │ │ ├── tasks │ │ └── main.yaml │ │ └── templates │ │ └── nginx.conf.j2 └── site.yaml ├── 第4章 ├── 4.2.1-variable.yaml ├── 4.2.6-variable.yaml ├── 4.2.7-variable.yaml ├── 4.3.1-loops-dict.yaml ├── 4.3.1-loops.yaml ├── 4.3.2-nested.yaml ├── 4.3.3-loops.yaml ├── 4.3.4-fileglob.yaml ├── 4.3.5-random.yaml ├── 4.3.6-until.yaml ├── 4.3.7-first-found.yaml ├── 4.3.8-register.yaml ├── 4.5.1.yaml ├── 4.6.1-lookup.yaml ├── 4.6.2-password.yaml ├── 4.6.3-pipe.yaml ├── 4.6.4-redis.yaml ├── 4.6.5-templates.yaml ├── 4.7-jinja-filter.yaml ├── example.yaml ├── hosts ├── lookups.j2 └── nginx.yaml ├── 第8章 ├── group_vars │ └── all ├── hosts ├── roles │ ├── base │ │ ├── files │ │ │ ├── RPM-GPG-KEY-EPEL-6 │ │ │ ├── RPM-GPG-KEY-ZABBIX │ │ │ ├── epel.repo │ │ │ └── zabbix.repo │ │ ├── tasks │ │ │ └── main.yaml │ │ └── templates │ │ │ └── hosts.j2 │ ├── zabbix-agent │ │ ├── tasks │ │ │ └── main.yaml │ │ └── templates │ │ │ └── zabbix_agentd.conf │ ├── zabbix-proxy │ │ ├── tasks │ │ │ └── main.yaml │ │ └── templates │ │ │ └── zabbix_proxy.conf │ └── zabbix-server │ │ ├── tasks │ │ └── main.yaml │ │ └── templates │ │ └── zabbix_server.conf └── site.yaml └── 第9章 ├── group_vars ├── all ├── haproxy └── mysql ├── hosts ├── roles ├── apache │ ├── tasks │ │ └── main.yaml │ └── templates │ │ └── index.php.j2 ├── base │ ├── files │ │ ├── CentOS-Base.repo │ │ └── epel.repo │ └── tasks │ │ └── main.yaml ├── haproxy │ ├── handers │ │ └── main.yaml │ ├── tasks │ │ └── main.yaml │ └── templates │ │ └── haproxy.cf.j2 └── mysql │ ├── handers │ └── main.yaml │ └── tasks │ └── main.yaml └── site.yaml /README.md: -------------------------------------------------------------------------------- 1 | # Ansible-Book-Code 2 | -------------------------------------------------------------------------------- /第11章/ajax.js: -------------------------------------------------------------------------------- 1 | 35 | -------------------------------------------------------------------------------- /第11章/flask-api.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf-8 3 | from ansible.inventory import Inventory 4 | from ansible.playbook import PlayBook 5 | from ansible import callbacks 6 | import ansible.runner 7 | from flask import Flask,request,jsonify,render_template,abort 8 | import commands,json 9 | app = Flask(__name__) 10 | 11 | hostfile='./hosts' 12 | ''' 13 | http://127.0.0.1:5000/API/Ansible/playbook?ip=2.2.2.2&palybook=test 14 | ''' 15 | @(Ansible) 16 | def Playbook(): 17 | vars={} 18 | inventory = Inventory(hostfile) 19 | stats = callbacks.AggregateStats() 20 | playbook_cb =callbacks.PlaybookCallbacks() 21 | runner_cb =callbacks.PlaybookRunnerCallbacks(stats) 22 | hosts=request.args.get('ip') 23 | task=request.args.get('playbook') 24 | vars['hosts'] = hosts 25 | play=task + '.yml' 26 | results = PlayBook(playbook=play,callbacks=playbook_cb,runner_callbacks=runner_cb,stats=stats,inventory=inventory,extra_vars=vars) 27 | res = results.run() 28 | return json.dumps(res,indent=4) 29 | 30 | ''' 31 | curl -H "Content-Type: application/json" -X POST -d '{"ip":"1.1.1.1","module":"shell","args":"ls -l"}' http://127.0.0.1:5000/API/Ansible/runner 32 | ''' 33 | @app.route('/API/Ansible/runner',methods=['POST']) 34 | def Runner(): 35 | print request.json 36 | if not request.json or not 'ip' in request.json or not 'module' in request.json or not 'args' in request.json: 37 | abort(400) 38 | hosts=request.json['ip'] 39 | module = request.json['module'] 40 | args=request.json['args'] 41 | runner = ansible.runner.Runner(module_name=module,module_args=args,pattern=hosts,forks=10,host_list=hostfile) 42 | tasks=runner.run() 43 | cpis={} 44 | cpis1={} 45 | for (hostname, result) in tasks['contacted'].items(): 46 | if not 'failed' in result: 47 | cpis[hostname] = result['stdout'] 48 | for (hostname, result) in tasks['dark'].items(): 49 | cpis1[hostname] = result['msg'] 50 | return render_template('cpis.html',cpis=cpis,cpis1=cpis1) 51 | 52 | if __name__ == "__main__": 53 | app.run(debug=True,host='0.0.0.0') 54 | -------------------------------------------------------------------------------- /第11章/flask-celery-client.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf-8 3 | import requests 4 | import json 5 | import argparse 6 | ppm={'server-1': '1.1.1.1','server-2': '2.2.2.2'} 7 | 8 | def tolist(fn): 9 | ips = [] 10 | with open(fn) as f: 11 | for ip in f: 12 | ips.append(ip.strip()) 13 | return ips 14 | 15 | def run(target,action,ips,users): 16 | p = {'ips': ips, 'users': users } 17 | r = requests.post('http://{0}:5000/{1}'.format(ppm[target],action), data = p) 18 | gto = r.json()['goto'] 19 | while 1: 20 | if requests.get("http://{0}:5000/{1}/result/{2}".format(ppm[target],action,gto)).json()['state'] == "PENDING": 21 | print "task running please wait........." 22 | time.sleep(1) 23 | continue 24 | else: 25 | print " " 26 | print "===============task running result==================" 27 | res=requests.get("http://{0}:5000/{1}/result/{2}".format(ppm[target],action,gto)).json()['status'] 28 | for i in res: 29 | print i,str(res[i]).replace("u","") 30 | break 31 | 32 | if __name__ == '__main__': 33 | parser = argparse.ArgumentParser() 34 | parser.add_argument('-i', '--ips', help='ips files') 35 | parser.add_argument('-u', '--users', help='uses files') 36 | parser.add_argument('-a', '--action', help='user manage action ex: add of del') 37 | parser.add_argument('-t', '--target', help='PPM IDC info ex: server-1 server-2 ....') 38 | args = vars(parser.parse_args()) 39 | if args['ips'] and args['users'] and args['action'] in ['add','del'] and args['target'] in ['server-1','server-2'] : 40 | ips=tolist(args['ips']) 41 | users=tolist(args['users']) 42 | run(args['target'],args['action'],ips,users) 43 | else: 44 | print parser.print_help() 45 | -------------------------------------------------------------------------------- /第11章/flask-celery-server.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf-8 3 | from celery import Celery 4 | import json 5 | from flask import Flask, abort, jsonify, request, session 6 | from ansible.inventory import Inventory 7 | from ansible.playbook import PlayBook 8 | from ansible import callbacks 9 | import jinja2 10 | from tempfile import NamedTemporaryFile 11 | 12 | app = Flask(__name__) 13 | app.config['SECRET_KEY'] = 'top-secret!' 14 | app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0' 15 | app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0' 16 | celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL']) 17 | celery.conf.update(app.config) 18 | 19 | @celery.task 20 | def adduser(ips, users): 21 | inventory =""" 22 | {% for i in hosts -%} 23 | {{ i }} 24 | {% endfor %} 25 | """ 26 | inventory_template = jinja2.Template(inventory) 27 | rendered_inventory = inventory_template.render({'hosts': ips}) 28 | hosts = NamedTemporaryFile(delete=False,suffix='tmp',dir='/tmp/ansible/') 29 | hosts.write(rendered_inventory) 30 | hosts.close() 31 | inventory = Inventory(hosts.name) 32 | stats = callbacks.AggregateStats() 33 | playbook_cb =callbacks.PlaybookCallbacks() 34 | runner_cb =callbacks.PlaybookRunnerCallbacks(stats) 35 | vars={} 36 | vars['users'] = users 37 | results = PlayBook(playbook='user.yaml',callbacks=playbook_cb,runner_callbacks=runner_cb,stats=stats,inventory=inventory,extra_vars=vars) 38 | res = results.run() 39 | logs = [] 40 | logs.append("finish playbook\n") 41 | logs.append(str(res)) 42 | return logs 43 | 44 | @app.route('/', methods=['GET', 'POST']) 45 | def index(): 46 | return render_template('index.html') 47 | 48 | @app.route("/add",methods=['POST']) 49 | def one(): 50 | ips = [ i.encode('ascii') for i in request.form.getlist('ips') ] 51 | users = [ i.encode('ascii') for i in request.form.getlist('users') ] 52 | res = adduser.apply_async((ips, users)) 53 | context = {"id": res.task_id, "ips": ips, "users": users} 54 | result = "add((ips){0}, (users){1})".format(context['ips'], context['users']) 55 | goto = "{0}".format(context['id']) 56 | return jsonify(result=result, goto=goto) 57 | 58 | @app.route("/add/result/") 59 | def show_add_result(task_id): 60 | task = adduser.AsyncResult(task_id) 61 | if task.state == 'PENDING': 62 | response = { 63 | 'state': task.state, 64 | 'status': 'Pending...' 65 | } 66 | elif task.state != 'FAILURE': 67 | response = { 68 | 'state': task.state, 69 | 'status': task.info 70 | } 71 | if 'result' in task.info: 72 | response['result'] = task.info['result'] 73 | else: 74 | response = { 75 | 'state': task.state, 76 | 'status': task.info, 77 | } 78 | return jsonify(response) 79 | 80 | 81 | if __name__ == "__main__": 82 | app.run(host='0.0.0.0', port=5000, debug=True) 83 | 84 | -------------------------------------------------------------------------------- /第11章/key.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: "{{hosts}}" 3 | gather_facts: false 4 | tasks: 5 | - name: key 6 | authorized_key: user=root key="{{ lookup('file', '/root/.ssh/id_rsa.pub') }}" 7 | -------------------------------------------------------------------------------- /第3章/host.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import argparse 4 | import sys 5 | import json 6 | def lists(): 7 | r = {} 8 | h=[ '172.17.42.10' + str(i) for i in range(1,4) ] 9 | hosts={'hosts': h} 10 | r['docker'] = hosts 11 | return json.dumps(r,indent=4) 12 | 13 | def hosts(name): 14 | r = {'ansible_ssh_pass': '123456'} 15 | cpis=dict(r.items()) 16 | return json.dumps(cpis) 17 | 18 | if __name__ == '__main__': 19 | parser = argparse.ArgumentParser() 20 | parser.add_argument('-l', '--list', help='hosts list', action='store_true') 21 | parser.add_argument('-H', '--host', help='hosts vars') 22 | args = vars(parser.parse_args()) 23 | 24 | if args['list']: 25 | print lists() 26 | elif args['host']: 27 | print hosts(args['host']) 28 | else: 29 | parser.print_help() 30 | -------------------------------------------------------------------------------- /第3章/roles/nginx/files/index.html: -------------------------------------------------------------------------------- 1 | hello kugou 2 | -------------------------------------------------------------------------------- /第3章/roles/nginx/handers/main.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: restart nginx 3 | service: name=nginx state=restarted 4 | -------------------------------------------------------------------------------- /第3章/roles/nginx/tasks/main.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Install nginx package 3 | yum: name=nginx-{{ version }} state=present 4 | - name: Copy nginx.conf Template 5 | template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf owner=root group=root backup=yes mode=0644 6 | notify: restart nginx 7 | - name: Copy index html 8 | copy: src=index.html dest=/usr/share/nginx/html/index.html owner=root group=root backup=yes mode=0644 9 | - name: make sure nginx service running 10 | service: name=nginx state=started 11 | -------------------------------------------------------------------------------- /第3章/roles/nginx/templates/nginx.conf.j2: -------------------------------------------------------------------------------- 1 | user nginx; 2 | worker_processes {{ ansible_processor_cores }}; 3 | 4 | error_log /var/log/nginx/error.log warn; 5 | pid /var/run/nginx.pid; 6 | 7 | 8 | events { 9 | worker_connections 1024; 10 | } 11 | 12 | 13 | http { 14 | include /etc/nginx/mime.types; 15 | default_type application/octet-stream; 16 | 17 | log_format main '$remote_addr - $remote_user [$time_local] "$request" ' 18 | '$status $body_bytes_sent "$http_referer" ' 19 | '"$http_user_agent" "$http_x_forwarded_for"'; 20 | 21 | access_log /var/log/nginx/access.log main; 22 | 23 | sendfile on; 24 | #tcp_nopush on; 25 | 26 | keepalive_timeout 65; 27 | 28 | gzip on; 29 | gzip_min_length 1k; 30 | gzip_buffers 16 64k; 31 | gzip_http_version 1.1; 32 | gzip_comp_level 6; 33 | gzip_types text/plain application/x-javascript text/css application/xml; 34 | gzip_vary on; 35 | 36 | include /etc/nginx/conf.d/*.conf; 37 | } 38 | -------------------------------------------------------------------------------- /第3章/site.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: 172.17.42.103 3 | roles: 4 | - { role: nginx, version: 1.0.15 } 5 | -------------------------------------------------------------------------------- /第4章/4.2.1-variable.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | gather_facts: False 4 | tasks: 5 | - name: diplay Host Variable from hostfile 6 | debug: msg="The {{ inventory_hostname }} Vaule is {{ key }}" 7 | -------------------------------------------------------------------------------- /第4章/4.2.6-variable.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | gather_facts: False 4 | tasks: 5 | - name: register variable 6 | shell: hostname 7 | register: info 8 | - name: display variable 9 | debug: msg="The varibale is {{ info }}" 10 | -------------------------------------------------------------------------------- /第4章/4.2.7-variable.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | gather_facts: False 4 | vars_prompt: 5 | - name: "one" 6 | prompt: "please input one value" 7 | private: no 8 | - name: "two" 9 | prompt: "please input two value" 10 | default: 'good' 11 | private: yes 12 | tasks: 13 | - name: display one value 14 | debug: msg="one value is {{ one }}" 15 | - name: display two value 16 | debug: msg="two value is {{ two }}" 17 | -------------------------------------------------------------------------------- /第4章/4.3.1-loops-dict.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | gather_facts: False 4 | tasks: 5 | - name: debug loops 6 | debug: msg="name ------> {{ item.key }} vaule -------> {{ item.vaule }}" 7 | with_items: 8 | - {key: "one", vaule: "VAULE1"} 9 | - {key: "two", vaule: "VAULE2"} 10 | -------------------------------------------------------------------------------- /第4章/4.3.1-loops.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | gather_facts: False 4 | tasks: 5 | - name: debug loops 6 | debug: msg="name ------> {{ item }}" 7 | with_items: 8 | - one 9 | - two 10 | -------------------------------------------------------------------------------- /第4章/4.3.2-nested.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | gather_facts: False 4 | tasks: 5 | - name: debug loops 6 | debug: msg="name ------> {{ item[0] }} vaule -------> {{ item[1] }}" 7 | with_nested: 8 | - ['A'] 9 | - ['a','b','c'] 10 | -------------------------------------------------------------------------------- /第4章/4.3.3-loops.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | gather_facts: False 4 | vars: 5 | user: 6 | shencan: 7 | name: shencan 8 | shell: bash 9 | ruifengyun: 10 | name: ruifengyun 11 | shell: zsh 12 | tasks: 13 | - name: debug loops 14 | debug: msg="name ------> {{ item.key }} vaule -------> {{ item.value.name }} shell ---------> {{ item.value.shell }}" 15 | with_dict: user 16 | -------------------------------------------------------------------------------- /第4章/4.3.4-fileglob.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | gather_facts: False 4 | tasks: 5 | - name: debug loops 6 | debug: msg="files --------> {{ item }}" 7 | with_fileglob: 8 | - /root/*.yaml 9 | -------------------------------------------------------------------------------- /第4章/4.3.5-random.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | gather_facts: False 4 | tasks: 5 | - name: debug loops 6 | debug: msg="name -----------> {{ item }}" 7 | with_random_choice: 8 | - "ansible1" 9 | - "ansible2" 10 | - "ansible3" 11 | -------------------------------------------------------------------------------- /第4章/4.3.6-until.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | gather_facts: False 4 | tasks: 5 | - name: debug loops 6 | shell: cat /root/Ansible 7 | register: host 8 | until: host.stdout.startswith("Master") 9 | retries: 5 10 | delay: 5 11 | -------------------------------------------------------------------------------- /第4章/4.3.7-first-found.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | gather_facts: True 4 | tasks: 5 | - name: debug loops 6 | debug: msg="files ------> {{ item }}" 7 | with_first_found: 8 | - "{{ ansible_distribution }}.yaml" 9 | - "default.yaml" 10 | -------------------------------------------------------------------------------- /第4章/4.3.8-register.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | gather_facts: True 4 | tasks: 5 | - name: debug loops 6 | shell: "{{ item }}" 7 | with_items: 8 | - hostname 9 | - uname 10 | register: ret 11 | - name: display loops 12 | debug: msg="{% for i in ret.results %} {{ i.stdout }} {% endfor %}" 13 | -------------------------------------------------------------------------------- /第4章/4.5.1.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | tasks: 4 | - name: Host 192.168.1.118 run this task 5 | debug: msg="{{ ansible_default_ipv4.address }}" 6 | when: ansible_default_ipv4.address == "192.168.1.118" 7 | 8 | - name: memtotal < 500M and processor_cores == 2 run this task 9 | debug: msg="{{ ansible_fqdn }}" 10 | when: ansible_memtotal_mb < 500 and ansible_processor_cores == 2 11 | 12 | - name: all host run this task 13 | shell: hostname 14 | register: info 15 | 16 | - name: Hostname is python Machie run this task 17 | debug: msg="{{ ansible_fqdn }}" 18 | when: info['stdout'] == "python" 19 | 20 | - name: Hostname is startswith M run this task 21 | debug: msg="{{ ansible_fqdn }}" 22 | when: info['stdout'].startswith('M') 23 | -------------------------------------------------------------------------------- /第4章/4.6.1-lookup.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | gather_facts: False 4 | vars: 5 | contents: "{{ lookup('file', '/etc/sysconfig/network') }}" 6 | tasks: 7 | - name: debug lookups 8 | debug: msg="The contents is {% for i in contents.split("\n") %} {{ i }} {% endfor %}" 9 | -------------------------------------------------------------------------------- /第4章/4.6.2-password.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | gather_facts: False 4 | vars: 5 | contents: "{{ lookup('password', 'ansible_book') }}" 6 | tasks: 7 | - name: debug lookups 8 | debug: msg="The contents is {{ contents }}" 9 | -------------------------------------------------------------------------------- /第4章/4.6.3-pipe.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | gather_facts: False 4 | vars: 5 | contents: "{{ lookup('pipe', 'date +%Y-%m-%d') }}" 6 | tasks: 7 | - name: debug lookups 8 | debug: msg="The contents is {% for i in contents.split("\n") %} {{ i }} {% endfor %}" 9 | -------------------------------------------------------------------------------- /第4章/4.6.4-redis.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | gather_facts: False 4 | vars: 5 | contents: "{{ lookup('redis_kv', 'redis://localhost:6379,ansible') }}" 6 | tasks: 7 | - name: debug lookups 8 | debug: msg="The contents is {% for i in contents.split("\n") %} {{ i }} {% endfor %}" 9 | -------------------------------------------------------------------------------- /第4章/4.6.5-templates.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | gather_facts: True 4 | vars: 5 | contents: "{{ lookup('template', './lookups.j2') }}" 6 | tasks: 7 | - name: debug lookups 8 | debug: msg="The contents is {% for i in contents.split("\n") %} {{ i }} {% endfor %}" 9 | -------------------------------------------------------------------------------- /第4章/4.7-jinja-filter.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | gather_facts: False 4 | vars: 5 | list: [1,2,3,4,5] 6 | one: "1" 7 | str: "string" 8 | tasks: 9 | - name: run commands 10 | shell: df -h 11 | register: info 12 | 13 | - name: debug pprint filter 14 | debug: msg="{{ info.stdout | pprint }}" 15 | 16 | - name: debug conditionals filter 17 | debug: msg="The run commands status is changed" 18 | when: info|changed 19 | 20 | - name: debug int capitalize filter 21 | debug: msg="The int value {{ one | int }} The lower value is {{ str | capitalize }}" 22 | 23 | - name: debug default filter 24 | debug: msg="The Variable value is {{ ansible | default('anible is not define') }}" 25 | 26 | - name: debug list max and min filter 27 | debug: msg="The list max value is {{ list | max }} The list min value is {{ list | min }}" 28 | 29 | - name: debug ramdom filter 30 | debug: msg="The list ramdom value is {{ list | random }} and generate a random value is {{ 1000 | random(1, 10) }}" 31 | 32 | - name: debug join filter 33 | debug: msg="The join filter value is {{ list | join("+") }}" 34 | 35 | - name: debug replace and regex_replace filter 36 | debug: msg="The replace value is {{ str | replace('t','T') }} The regex_replace vaule is {{ str | regex_replace('.*tr(.*)$', '\\1') }} " 37 | -------------------------------------------------------------------------------- /第4章/example.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: 192.168.1.117:192.168.1.118 #目标主机支持`Ad-Hoc`模式的所有patterns 3 | remote_user: root #远程ssh认证用户 4 | sudo: yes #设置`playbook sudo`操作 5 | sudo_user: yadmin #设置`playbook sudo`用户 6 | gather_facts: no #设置`facts`信息收集 7 | accelerate: no #设置`accelerate`模式 8 | accelerate_port: 5099 #设置`accelerate`端口 9 | max_fail_percentage: 30 #设置`playbook tasks`失败百分比 10 | connection: local #设置远程连接方式 11 | serial: 15 #设置`playbook`并发数目 12 | vars: #设置`playbook`变量 13 | nginx_port: 80 14 | vars_files: #设置`playbook`变量引用文件 15 | - "vars.yml" 16 | - [ "one.yml", "two.yml" ] 17 | vars_prompt: #设置通过交互模式输入变量 18 | - name: "password vaes" 19 | prompt: "Enter password" #使用`prompt`模块加密输入变量 20 | default: "secret" 21 | private: yes 22 | encrypt: "md5_crypt" 23 | confirm: yes 24 | salt: 1234 25 | salt_size: 8 26 | pre_tasks: #设置`playbook`运行之前的`tasks` 27 | - name: pre_tasks 28 | shell: hostname 29 | roles: #设置引入`role` 30 | - docker 31 | - { role: docker, version: '1.5.0', when: "ansible_system == 'Linux'", tags :[docker,install ] } 32 | - { role: docker, when: ansible_all_ipv4_addresses == '192.168.1.118' } 33 | tasks: #设置引入`task` 34 | - include: tasks.yaml 35 | - include: tasks.yaml ansible_distribution='CentOS' ansible_distribution_version='6.6' 36 | - { include: tasks.yaml, version: '1.1', package: [nginx,httpd]} 37 | - include: tasks_192.168.1.117.yaml 38 | when: ansible_all_ipv4_addresses == '192.168.1.117' 39 | post_tasks: #设置`playbook`运行之后的`tasks` 40 | - name: post_tasks 41 | shell: hostname 42 | handlers: #设置`playbooks`的`handlers` 43 | - include: handlers.yml 44 | -------------------------------------------------------------------------------- /第4章/hosts: -------------------------------------------------------------------------------- 1 | [nginx] 2 | 192.168.1.11[6:8] 3 | [nginx:vars] 4 | ansible_python_interpreter=/usr/bin/python2.6 5 | -------------------------------------------------------------------------------- /第4章/lookups.j2: -------------------------------------------------------------------------------- 1 | worker_processes {{ ansible_processor_cores }}; 2 | IPaddress {{ ansible_eth0.ipv4.address }} 3 | -------------------------------------------------------------------------------- /第4章/nginx.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | tasks: 4 | - name: Install Nginx Package 5 | yum: name=nginx state=present 6 | 7 | - name: Copy Nginx.conf 8 | template: src=./nginx.conf.j2 dest=/etc/nginx/nginx.conf owner=root group=root mode=0644 validate='nginx -t -c %s' 9 | notify: 10 | - Retart Nginx Service 11 | 12 | handlers: 13 | - name: ReStart Nginx Service 14 | service: name=nginx state=restarted 15 | -------------------------------------------------------------------------------- /第8章/group_vars/all: -------------------------------------------------------------------------------- 1 | --- 2 | zabbix_server: 192.168.1.100 3 | zabbix_proxy: 192.168.1.115 4 | ansible_ssh_user: root 5 | -------------------------------------------------------------------------------- /第8章/hosts: -------------------------------------------------------------------------------- 1 | [zabbix-server] 2 | 192.168.1.100 hostname=server.shencan.net 3 | [zabbix-proxy] 4 | 192.168.1.115 hostname=proxy.shencan.net 5 | [zabbix-agent] 6 | 192.168.1.111 hostname=agent.shencan.net 7 | 8 | -------------------------------------------------------------------------------- /第8章/roles/base/files/RPM-GPG-KEY-EPEL-6: -------------------------------------------------------------------------------- 1 | -----BEGIN PGP PUBLIC KEY BLOCK----- 2 | Version: GnuPG v1.4.5 (GNU/Linux) 3 | 4 | mQINBEvSKUIBEADLGnUj24ZVKW7liFN/JA5CgtzlNnKs7sBg7fVbNWryiE3URbn1 5 | JXvrdwHtkKyY96/ifZ1Ld3lE2gOF61bGZ2CWwJNee76Sp9Z+isP8RQXbG5jwj/4B 6 | M9HK7phktqFVJ8VbY2jfTjcfxRvGM8YBwXF8hx0CDZURAjvf1xRSQJ7iAo58qcHn 7 | XtxOAvQmAbR9z6Q/h/D+Y/PhoIJp1OV4VNHCbCs9M7HUVBpgC53PDcTUQuwcgeY6 8 | pQgo9eT1eLNSZVrJ5Bctivl1UcD6P6CIGkkeT2gNhqindRPngUXGXW7Qzoefe+fV 9 | QqJSm7Tq2q9oqVZ46J964waCRItRySpuW5dxZO34WM6wsw2BP2MlACbH4l3luqtp 10 | Xo3Bvfnk+HAFH3HcMuwdaulxv7zYKXCfNoSfgrpEfo2Ex4Im/I3WdtwME/Gbnwdq 11 | 3VJzgAxLVFhczDHwNkjmIdPAlNJ9/ixRjip4dgZtW8VcBCrNoL+LhDrIfjvnLdRu 12 | vBHy9P3sCF7FZycaHlMWP6RiLtHnEMGcbZ8QpQHi2dReU1wyr9QgguGU+jqSXYar 13 | 1yEcsdRGasppNIZ8+Qawbm/a4doT10TEtPArhSoHlwbvqTDYjtfV92lC/2iwgO6g 14 | YgG9XrO4V8dV39Ffm7oLFfvTbg5mv4Q/E6AWo/gkjmtxkculbyAvjFtYAQARAQAB 15 | tCFFUEVMICg2KSA8ZXBlbEBmZWRvcmFwcm9qZWN0Lm9yZz6JAjYEEwECACAFAkvS 16 | KUICGw8GCwkIBwMCBBUCCAMEFgIDAQIeAQIXgAAKCRA7Sd8qBgi4lR/GD/wLGPv9 17 | qO39eyb9NlrwfKdUEo1tHxKdrhNz+XYrO4yVDTBZRPSuvL2yaoeSIhQOKhNPfEgT 18 | 9mdsbsgcfmoHxmGVcn+lbheWsSvcgrXuz0gLt8TGGKGGROAoLXpuUsb1HNtKEOwP 19 | Q4z1uQ2nOz5hLRyDOV0I2LwYV8BjGIjBKUMFEUxFTsL7XOZkrAg/WbTH2PW3hrfS 20 | WtcRA7EYonI3B80d39ffws7SmyKbS5PmZjqOPuTvV2F0tMhKIhncBwoojWZPExft 21 | HpKhzKVh8fdDO/3P1y1Fk3Cin8UbCO9MWMFNR27fVzCANlEPljsHA+3Ez4F7uboF 22 | p0OOEov4Yyi4BEbgqZnthTG4ub9nyiupIZ3ckPHr3nVcDUGcL6lQD/nkmNVIeLYP 23 | x1uHPOSlWfuojAYgzRH6LL7Idg4FHHBA0to7FW8dQXFIOyNiJFAOT2j8P5+tVdq8 24 | wB0PDSH8yRpn4HdJ9RYquau4OkjluxOWf0uRaS//SUcCZh+1/KBEOmcvBHYRZA5J 25 | l/nakCgxGb2paQOzqqpOcHKvlyLuzO5uybMXaipLExTGJXBlXrbbASfXa/yGYSAG 26 | iVrGz9CE6676dMlm8F+s3XXE13QZrXmjloc6jwOljnfAkjTGXjiB7OULESed96MR 27 | XtfLk0W5Ab9pd7tKDR6QHI7rgHXfCopRnZ2VVQ== 28 | =V/6I 29 | -----END PGP PUBLIC KEY BLOCK----- 30 | -------------------------------------------------------------------------------- /第8章/roles/base/files/RPM-GPG-KEY-ZABBIX: -------------------------------------------------------------------------------- 1 | -----BEGIN PGP PUBLIC KEY BLOCK----- 2 | Version: GnuPG v1.4.5 (GNU/Linux) 3 | 4 | mQGiBFCNJaYRBAC4nIW8o2NyOIswb82Xn3AYSMUcNZuKB2fMtpu0WxSXIRiX2BwC 5 | YXx8cIEQVYtLRBL5o0JdmoNCjW6jd5fOVem3EmOcPksvzzRWonIgFHf4EI2n1KJc 6 | JXX/nDC+eoh5xW35mRNFN/BEJHxxiRGGbp2MCnApwgrZLhOujaCGAwavGwCgiG4D 7 | wKMZ4xX6Y2Gv3MSuzMIT0bcEAKYn3WohS+udp0yC3FHDj+oxfuHpklu1xuI3y6ha 8 | 402aEFahNi3wr316ukgdPAYLbpz76ivoouTJ/U2MqbNLjAspDvlnHXXyqPM5GC6K 9 | jtXPqNrRMUCrwisoAhorGUg/+S5pyXwsWcJ6EKmA80pR9HO+TbsELE5bGe/oc238 10 | t/2oBAC3zcQ46wPvXpMCNFb+ED71qDOlnDYaaAPbjgkvnp+WN6nZFFyevjx180Kw 11 | qWOLnlNP6JOuFW27MP75MDPDpbAAOVENp6qnuW9dxXTN80YpPLKUxrQS8vWPnzkY 12 | WtUfF75pEOACFVTgXIqEgW0E6oww2HJi9zF5fS8IlFHJztNYtbQgWmFiYml4IFNJ 13 | QSA8cGFja2FnZXJAemFiYml4LmNvbT6IYAQTEQIAIAUCUI0lpgIbAwYLCQgHAwIE 14 | FQIIAwQWAgMBAh4BAheAAAoJENE9WOR56l7UhUwAmgIGZ39U6D2w2oIWDD8m7KV3 15 | oI06AJ9EnOxMMlxEjTkt9lEvGhEX1bEh7bkBDQRQjSWmEAQAqx+ecOzBbhqMq5hU 16 | l39cJ6l4aocz6EZ9mSSoF/g+HFz6WYnPAfRaYyfLmZdtF5rGBDD4ysalYG5yD59R 17 | Mv5tNVf/CEx+JAPMhp6JCBkGRaH+xHws4eBPGkea4rGNVP3L3rA7g+c1YXZICGRI 18 | OOH7CIzIZ/w6aFGsPp7xM35ogncAAwUD/3s8Nc1OLDy81DC6rGpxfEURd5pvd/j0 19 | D5Di0WSBEcHXp5nThDz6ro/Vr0/FVIBtT97tmBHX27yBS3PqxxNRIjZ0GSWQqdws 20 | Q8o3YT+RHjBugXn8CzTOvIn+2QNMA8EtGIZPpCblJv8q6MFPi9m7avQxguMqufgg 21 | fAk7377Rt9RqiEkEGBECAAkFAlCNJaYCGwwACgkQ0T1Y5HnqXtQx4wCfcJZINKVq 22 | kQIoV3KTQAIzr6IvbZoAn12XXt4GP89xHuzPDZ86YJVAgnfK 23 | =+200 24 | -----END PGP PUBLIC KEY BLOCK----- 25 | -------------------------------------------------------------------------------- /第8章/roles/base/files/epel.repo: -------------------------------------------------------------------------------- 1 | [epel] 2 | name=Extra Packages for Enterprise Linux 6 - $basearch 3 | #baseurl=http://download.fedoraproject.org/pub/epel/6/$basearch 4 | mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-6&arch=$basearch 5 | failovermethod=priority 6 | enabled=1 7 | gpgcheck=1 8 | gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6 9 | 10 | [epel-debuginfo] 11 | name=Extra Packages for Enterprise Linux 6 - $basearch - Debug 12 | #baseurl=http://download.fedoraproject.org/pub/epel/6/$basearch/debug 13 | mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-debug-6&arch=$basearch 14 | failovermethod=priority 15 | enabled=0 16 | gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6 17 | gpgcheck=1 18 | 19 | [epel-source] 20 | name=Extra Packages for Enterprise Linux 6 - $basearch - Source 21 | #baseurl=http://download.fedoraproject.org/pub/epel/6/SRPMS 22 | mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-source-6&arch=$basearch 23 | failovermethod=priority 24 | enabled=0 25 | gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6 26 | gpgcheck=1 27 | -------------------------------------------------------------------------------- /第8章/roles/base/files/zabbix.repo: -------------------------------------------------------------------------------- 1 | [zabbix] 2 | name=Zabbix Official Repository - $basearch 3 | baseurl=http://repo.zabbix.com/zabbix/2.4/rhel/6/$basearch/ 4 | enabled=1 5 | gpgcheck=1 6 | gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX 7 | 8 | [zabbix-non-supported] 9 | name=Zabbix Official Repository non-supported - $basearch 10 | baseurl=http://repo.zabbix.com/non-supported/rhel/6/$basearch/ 11 | enabled=1 12 | gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX 13 | gpgcheck=1 14 | -------------------------------------------------------------------------------- /第8章/roles/base/tasks/main.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: set hostname 3 | hostname: name={{ hostname }} 4 | 5 | - name: Change network files 6 | shell: sed -i "s/HOSTNAME=.*/HOSTNAME={{ hostname }}/g" /etc/sysconfig/network 7 | 8 | - name: Stop Iptables 9 | service: name=iptables state=stopped enabled=no 10 | 11 | - name: disable seliunx 12 | shell: /usr/sbin/setenforce 0 && sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/sysconfig/selinux 13 | 14 | - name: Install libselinux-python 15 | raw: yum install libselinux-python -y 16 | 17 | - name: copy epel yum source 18 | copy: src={{ item.src }} dest={{ item.dest }} owner=root group=root mode=644 19 | with_items: 20 | - {src: epel.repo, dest: /etc/yum.repos.d/epel.repo } 21 | - {src: RPM-GPG-KEY-EPEL-6, dest: /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6 } 22 | - {src: RPM-GPG-KEY-ZABBIX, dest: /etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX } 23 | - {src: zabbix.repo, dest: /etc/yum.repos.d/zabbix.repo } 24 | - name: copy /etc/hosts files 25 | template: src=hosts.j2 dest=/etc/hosts owner=root group=root mode=644 26 | -------------------------------------------------------------------------------- /第8章/roles/base/templates/hosts.j2: -------------------------------------------------------------------------------- 1 | 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 2 | ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 3 | {% for host in groups['all'] %} 4 | {{ hostvars[host]['inventory_hostname'] }} {{ hostvars[host]['hostname'] }} 5 | {% endfor %} 6 | -------------------------------------------------------------------------------- /第8章/roles/zabbix-agent/tasks/main.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Install Zabbix-Agent 3 | yum: name=zabbix-agent state=latest 4 | - name: Copy /etc/zabbix/zabbix_agentd.conf 5 | template: src=zabbix_agentd.conf dest=/etc/zabbix/zabbix_agentd.conf owner=root group=root mode=644 6 | - name: Start zabbix_agnet 7 | service: name=zabbix-agent state=started enabled=yes 8 | -------------------------------------------------------------------------------- /第8章/roles/zabbix-agent/templates/zabbix_agentd.conf: -------------------------------------------------------------------------------- 1 | # This is a config file for the Zabbix agent daemon (Unix) 2 | # To get more information about Zabbix, visit http://www.zabbix.com 3 | 4 | ############ GENERAL PARAMETERS ################# 5 | 6 | ### Option: PidFile 7 | # Name of PID file. 8 | # 9 | # Mandatory: no 10 | # Default: 11 | # PidFile=/tmp/zabbix_agentd.pid 12 | 13 | PidFile=/var/run/zabbix/zabbix_agentd.pid 14 | 15 | ### Option: LogFile 16 | # Name of log file. 17 | # If not set, syslog is used. 18 | # 19 | # Mandatory: no 20 | # Default: 21 | # LogFile= 22 | 23 | LogFile=/var/log/zabbix/zabbix_agentd.log 24 | 25 | ### Option: LogFileSize 26 | # Maximum size of log file in MB. 27 | # 0 - disable automatic log rotation. 28 | # 29 | # Mandatory: no 30 | # Range: 0-1024 31 | # Default: 32 | # LogFileSize=1 33 | 34 | LogFileSize=0 35 | 36 | ### Option: DebugLevel 37 | # Specifies debug level 38 | # 0 - basic information about starting and stopping of Zabbix processes 39 | # 1 - critical information 40 | # 2 - error information 41 | # 3 - warnings 42 | # 4 - for debugging (produces lots of information) 43 | # 44 | # Mandatory: no 45 | # Range: 0-4 46 | # Default: 47 | # DebugLevel=3 48 | 49 | ### Option: SourceIP 50 | # Source IP address for outgoing connections. 51 | # 52 | # Mandatory: no 53 | # Default: 54 | # SourceIP= 55 | 56 | ### Option: EnableRemoteCommands 57 | # Whether remote commands from Zabbix server are allowed. 58 | # 0 - not allowed 59 | # 1 - allowed 60 | # 61 | # Mandatory: no 62 | # Default: 63 | # EnableRemoteCommands=0 64 | 65 | ### Option: LogRemoteCommands 66 | # Enable logging of executed shell commands as warnings. 67 | # 0 - disabled 68 | # 1 - enabled 69 | # 70 | # Mandatory: no 71 | # Default: 72 | # LogRemoteCommands=0 73 | 74 | ##### Passive checks related 75 | 76 | ### Option: Server 77 | # List of comma delimited IP addresses (or hostnames) of Zabbix servers. 78 | # Incoming connections will be accepted only from the hosts listed here. 79 | # If IPv6 support is enabled then '127.0.0.1', '::127.0.0.1', '::ffff:127.0.0.1' are treated equally. 80 | # 81 | # Mandatory: no 82 | # Default: 83 | # Server= 84 | 85 | Server={{ zabbix_server }},{{ zabbix_proxy }} 86 | 87 | ### Option: ListenPort 88 | # Agent will listen on this port for connections from the server. 89 | # 90 | # Mandatory: no 91 | # Range: 1024-32767 92 | # Default: 93 | ListenPort=10051 94 | 95 | ### Option: ListenIP 96 | # List of comma delimited IP addresses that the agent should listen on. 97 | # First IP address is sent to Zabbix server if connecting to it to retrieve list of active checks. 98 | # 99 | # Mandatory: no 100 | # Default: 101 | ListenIP={{ inventory_hostname }} 102 | 103 | ### Option: StartAgents 104 | # Number of pre-forked instances of zabbix_agentd that process passive checks. 105 | # If set to 0, disables passive checks and the agent will not listen on any TCP port. 106 | # 107 | # Mandatory: no 108 | # Range: 0-100 109 | # Default: 110 | # StartAgents=3 111 | 112 | ##### Active checks related 113 | 114 | ### Option: ServerActive 115 | # List of comma delimited IP:port (or hostname:port) pairs of Zabbix servers for active checks. 116 | # If port is not specified, default port is used. 117 | # IPv6 addresses must be enclosed in square brackets if port for that host is specified. 118 | # If port is not specified, square brackets for IPv6 addresses are optional. 119 | # If this parameter is not specified, active checks are disabled. 120 | # Example: ServerActive=127.0.0.1:20051,zabbix.domain,[::1]:30051,::1,[12fc::1] 121 | # 122 | # Mandatory: no 123 | # Default: 124 | # ServerActive= 125 | 126 | ServerActive={{ zabbix_proxy }}:10052 127 | 128 | ### Option: Hostname 129 | # Unique, case sensitive hostname. 130 | # Required for active checks and must match hostname as configured on the server. 131 | # Value is acquired from HostnameItem if undefined. 132 | # 133 | # Mandatory: no 134 | # Default: 135 | # Hostname= 136 | 137 | Hostname={{ hostname }} 138 | 139 | ### Option: HostnameItem 140 | # Item used for generating Hostname if it is undefined. Ignored if Hostname is defined. 141 | # Does not support UserParameters or aliases. 142 | # 143 | # Mandatory: no 144 | # Default: 145 | # HostnameItem=system.hostname 146 | 147 | ### Option: HostMetadata 148 | # Optional parameter that defines host metadata. 149 | # Host metadata is used at host auto-registration process. 150 | # An agent will issue an error and not start if the value is over limit of 255 characters. 151 | # If not defined, value will be acquired from HostMetadataItem. 152 | # 153 | # Mandatory: no 154 | # Range: 0-255 characters 155 | # Default: 156 | # HostMetadata= 157 | 158 | ### Option: HostMetadataItem 159 | # Optional parameter that defines an item used for getting host metadata. 160 | # Host metadata is used at host auto-registration process. 161 | # During an auto-registration request an agent will log a warning message if 162 | # the value returned by specified item is over limit of 255 characters. 163 | # This option is only used when HostMetadata is not defined. 164 | # 165 | # Mandatory: no 166 | # Default: 167 | # HostMetadataItem= 168 | 169 | ### Option: RefreshActiveChecks 170 | # How often list of active checks is refreshed, in seconds. 171 | # 172 | # Mandatory: no 173 | # Range: 60-3600 174 | # Default: 175 | # RefreshActiveChecks=120 176 | 177 | ### Option: BufferSend 178 | # Do not keep data longer than N seconds in buffer. 179 | # 180 | # Mandatory: no 181 | # Range: 1-3600 182 | # Default: 183 | # BufferSend=5 184 | 185 | ### Option: BufferSize 186 | # Maximum number of values in a memory buffer. The agent will send 187 | # all collected data to Zabbix Server or Proxy if the buffer is full. 188 | # 189 | # Mandatory: no 190 | # Range: 2-65535 191 | # Default: 192 | # BufferSize=100 193 | 194 | ### Option: MaxLinesPerSecond 195 | # Maximum number of new lines the agent will send per second to Zabbix Server 196 | # or Proxy processing 'log' and 'logrt' active checks. 197 | # The provided value will be overridden by the parameter 'maxlines', 198 | # provided in 'log' or 'logrt' item keys. 199 | # 200 | # Mandatory: no 201 | # Range: 1-1000 202 | # Default: 203 | # MaxLinesPerSecond=100 204 | 205 | ############ ADVANCED PARAMETERS ################# 206 | 207 | ### Option: Alias 208 | # Sets an alias for an item key. It can be used to substitute long and complex item key with a smaller and simpler one. 209 | # Multiple Alias parameters may be present. Multiple parameters with the same Alias key are not allowed. 210 | # Different Alias keys may reference the same item key. 211 | # For example, to retrieve the ID of user 'zabbix': 212 | # Alias=zabbix.userid:vfs.file.regexp[/etc/passwd,^zabbix:.:([0-9]+),,,,\1] 213 | # Now shorthand key zabbix.userid may be used to retrieve data. 214 | # Aliases can be used in HostMetadataItem but not in HostnameItem parameters. 215 | # 216 | # Mandatory: no 217 | # Range: 218 | # Default: 219 | 220 | ### Option: Timeout 221 | # Spend no more than Timeout seconds on processing 222 | # 223 | # Mandatory: no 224 | # Range: 1-30 225 | # Default: 226 | # Timeout=3 227 | 228 | ### Option: AllowRoot 229 | # Allow the agent to run as 'root'. If disabled and the agent is started by 'root', the agent 230 | # will try to switch to the user specified by the User configuration option instead. 231 | # Has no effect if started under a regular user. 232 | # 0 - do not allow 233 | # 1 - allow 234 | # 235 | # Mandatory: no 236 | # Default: 237 | # AllowRoot=0 238 | 239 | ### Option: User 240 | # Drop privileges to a specific, existing user on the system. 241 | # Only has effect if run as 'root' and AllowRoot is disabled. 242 | # 243 | # Mandatory: no 244 | # Default: 245 | # User=zabbix 246 | 247 | ### Option: Include 248 | # You may include individual files or all files in a directory in the configuration file. 249 | # Installing Zabbix will create include directory in /usr/local/etc, unless modified during the compile time. 250 | # 251 | # Mandatory: no 252 | # Default: 253 | # Include= 254 | 255 | Include=/etc/zabbix/zabbix_agentd.d/ 256 | 257 | # Include=/usr/local/etc/zabbix_agentd.userparams.conf 258 | # Include=/usr/local/etc/zabbix_agentd.conf.d/ 259 | # Include=/usr/local/etc/zabbix_agentd.conf.d/*.conf 260 | 261 | ####### USER-DEFINED MONITORED PARAMETERS ####### 262 | 263 | ### Option: UnsafeUserParameters 264 | # Allow all characters to be passed in arguments to user-defined parameters. 265 | # 0 - do not allow 266 | # 1 - allow 267 | # 268 | # Mandatory: no 269 | # Range: 0-1 270 | # Default: 271 | UnsafeUserParameters=1 272 | 273 | ### Option: UserParameter 274 | # User-defined parameter to monitor. There can be several user-defined parameters. 275 | # Format: UserParameter=, 276 | # See 'zabbix_agentd' directory for examples. 277 | # 278 | # Mandatory: no 279 | # Default: 280 | # UserParameter= 281 | 282 | ####### LOADABLE MODULES ####### 283 | 284 | ### Option: LoadModulePath 285 | # Full path to location of agent modules. 286 | # Default depends on compilation options. 287 | # 288 | # Mandatory: no 289 | # Default: 290 | # LoadModulePath=${libdir}/modules 291 | 292 | ### Option: LoadModule 293 | # Module to load at agent startup. Modules are used to extend functionality of the agent. 294 | # Format: LoadModule= 295 | # The modules must be located in directory specified by LoadModulePath. 296 | # It is allowed to include multiple LoadModule parameters. 297 | # 298 | # Mandatory: no 299 | # Default: 300 | # LoadModule= 301 | -------------------------------------------------------------------------------- /第8章/roles/zabbix-proxy/tasks/main.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Install Mysql-Server and zabbix-server 3 | yum: name={{ item }} state=latest 4 | with_items: 5 | - mysql-server 6 | - zabbix-proxy 7 | - zabbix-proxy-mysql 8 | - name: Init Mysql 9 | shell: mysql_install_db 10 | - name: Start mysql-server 11 | service: name=mysqld state=started enabled=yes 12 | - name: Set mysql admin password 13 | shell: /usr/bin/mysqladmin -u root password 'ansible' 14 | - name: Create Zabbix master databases 15 | shell: mysql -u root -pansible -e 'create database zabbix_proxy character set utf8 collate utf8_bin;' 16 | - name: Set Zabbix Master databases grant 17 | shell: mysql -u root -pansible -e 'grant all privileges on zabbix_proxy.* to zabbix@localhost identified by "proxy";' 18 | - name: Import zabbix initial data (schema.sql) 19 | shell: mysql -u zabbix -pproxy zabbix_proxy < schema.sql chdir=/usr/share/doc/zabbix-proxy-mysql-2.4.6/create/ 20 | - name: Copy /etc/zabbix/zabbix_proxy.conf files 21 | template: src=zabbix_proxy.conf dest=/etc/zabbix/zabbix_proxy.conf owner=root group=root mode=644 22 | - name: Start Zabbix-Server and httpd 23 | service: name=zabbix-proxy state=started enabled=yes 24 | 25 | -------------------------------------------------------------------------------- /第8章/roles/zabbix-proxy/templates/zabbix_proxy.conf: -------------------------------------------------------------------------------- 1 | ProxyMode=0 2 | Server= {{ zabbix_server }} 3 | ServerPort=10052 4 | Hostname={{ hostname }} 5 | 6 | ListenPort=10052 7 | 8 | 9 | LogFile=/var/log/zabbix/zabbix_proxy.log 10 | 11 | LogFileSize=1024 12 | 13 | DebugLevel=3 14 | 15 | 16 | 17 | PidFile=/var/run/zabbix/zabbix_proxy.pid 18 | 19 | DBHost=localhost 20 | 21 | 22 | DBName=zabbix_proxy 23 | 24 | 25 | DBUser=zabbix 26 | 27 | DBPassword=proxy 28 | 29 | 30 | DBSocket=/var/lib/mysql/mysql.sock 31 | 32 | DBPort=3306 33 | 34 | ######### PROXY SPECIFIC PARAMETERS ############# 35 | 36 | ProxyLocalBuffer=6 37 | 38 | ProxyOfflineBuffer=12 39 | 40 | ### Option: HeartbeatFrequency 41 | # Frequency of heartbeat messages in seconds. 42 | # Used for monitoring availability of Proxy on server side. 43 | # 0 - heartbeat messages disabled. 44 | # For a proxy in the passive mode this parameter will be ignored. 45 | # 46 | # Mandatory: no 47 | # Range: 0-3600 48 | # Default: 49 | # HeartbeatFrequency=60 50 | 51 | ### Option: ConfigFrequency 52 | # How often proxy retrieves configuration data from Zabbix Server in seconds. 53 | # For a proxy in the passive mode this parameter will be ignored. 54 | # 55 | # Mandatory: no 56 | # Range: 1-3600*24*7 57 | # Default: 58 | ConfigFrequency=300 59 | 60 | ### Option: DataSenderFrequency 61 | # Proxy will send collected data to the Server every N seconds. 62 | # For a proxy in the passive mode this parameter will be ignored. 63 | # 64 | # Mandatory: no 65 | # Range: 1-3600 66 | # Default: 67 | DataSenderFrequency=1 68 | 69 | ############ ADVANCED PARAMETERS ################ 70 | 71 | ### Option: StartPollers 72 | # Number of pre-forked instances of pollers. 73 | # 74 | # Mandatory: no 75 | # Range: 0-1000 76 | # Default: 77 | StartPollers=60 78 | 79 | ### Option: StartIPMIPollers 80 | # Number of pre-forked instances of IPMI pollers. 81 | # 82 | # Mandatory: no 83 | # Range: 0-1000 84 | # Default: 85 | StartIPMIPollers=1 86 | 87 | 88 | StartPollersUnreachable=20 89 | 90 | StartTrappers=20 91 | 92 | StartPingers=20 93 | 94 | StartDiscoverers=4 95 | 96 | ### Option: StartHTTPPollers 97 | # Number of pre-forked instances of HTTP pollers. 98 | # 99 | # Mandatory: no 100 | # Range: 0-1000 101 | # Default: 102 | # StartHTTPPollers=1 103 | 104 | ### Option: JavaGateway 105 | # IP address (or hostname) of Zabbix Java gateway. 106 | # Only required if Java pollers are started. 107 | # 108 | # Mandatory: no 109 | # Default: 110 | # JavaGateway= 111 | 112 | ### Option: JavaGatewayPort 113 | # Port that Zabbix Java gateway listens on. 114 | # 115 | # Mandatory: no 116 | # Range: 1024-32767 117 | # Default: 118 | # JavaGatewayPort=10052 119 | 120 | ### Option: StartJavaPollers 121 | # Number of pre-forked instances of Java pollers. 122 | # 123 | # Mandatory: no 124 | # Range: 0-1000 125 | # Default: 126 | # StartJavaPollers=0 127 | 128 | ### Option: StartVMwareCollectors 129 | # Number of pre-forked vmware collector instances. 130 | # 131 | # Mandatory: no 132 | # Range: 0-250 133 | # Default: 134 | # StartVMwareCollectors=0 135 | 136 | ### Option: VMwareFrequency 137 | # How often Zabbix will connect to VMware service to obtain a new data. 138 | # 139 | # Mandatory: no 140 | # Range: 10-86400 141 | # Default: 142 | # VMwareFrequency=60 143 | 144 | ### Option: VMwarePerfFrequency 145 | # How often Zabbix will connect to VMware service to obtain performance data. 146 | # 147 | # Mandatory: no 148 | # Range: 10-86400 149 | # Default: 150 | # VMwarePerfFrequency=60 151 | 152 | ### Option: VMwareCacheSize 153 | # Size of VMware cache, in bytes. 154 | # Shared memory size for storing VMware data. 155 | # Only used if VMware collectors are started. 156 | # 157 | # Mandatory: no 158 | # Range: 256K-2G 159 | # Default: 160 | # VMwareCacheSize=8M 161 | 162 | ### Option: VMwareTimeout 163 | # Specifies how many seconds vmware collector waits for response from VMware service. 164 | # 165 | # Mandatory: no 166 | # Range: 1-300 167 | # Default: 168 | # VMwareTimeout=10 169 | 170 | ### Option: SNMPTrapperFile 171 | # Temporary file used for passing data from SNMP trap daemon to the proxy. 172 | # Must be the same as in zabbix_trap_receiver.pl or SNMPTT configuration file. 173 | # 174 | # Mandatory: no 175 | # Default: 176 | # SNMPTrapperFile=/tmp/zabbix_traps.tmp 177 | 178 | ### Option: StartSNMPTrapper 179 | # If 1, SNMP trapper process is started. 180 | # 181 | # Mandatory: no 182 | # Range: 0-1 183 | # Default: 184 | # StartSNMPTrapper=0 185 | 186 | ### Option: ListenIP 187 | # List of comma delimited IP addresses that the trapper should listen on. 188 | # Trapper will listen on all network interfaces if this parameter is missing. 189 | # 190 | # Mandatory: no 191 | # Default: 192 | ListenIP={{ inventory_hostname }} 193 | 194 | ### Option: HousekeepingFrequency 195 | # How often Zabbix will perform housekeeping procedure (in hours). 196 | # Housekeeping is removing outdated information from the database. 197 | # To prevent Housekeeper from being overloaded, no more than 4 times HousekeepingFrequency 198 | # hours of outdated information are deleted in one housekeeping cycle. 199 | # To lower load on proxy startup housekeeping is postponed for 30 minutes after proxy start. 200 | # 201 | # Mandatory: no 202 | # Range: 1-24 203 | # Default: 204 | HousekeepingFrequency=24 205 | 206 | ### Option: CacheSize 207 | # Size of configuration cache, in bytes. 208 | # Shared memory size, for storing hosts and items data. 209 | # 210 | # Mandatory: no 211 | # Range: 128K-8G 212 | # Default: 213 | # CacheSize=8M 214 | 215 | ### Option: StartDBSyncers 216 | # Number of pre-forked instances of DB Syncers 217 | # 218 | # Mandatory: no 219 | # Range: 1-100 220 | # Default: 221 | StartDBSyncers=6 222 | 223 | ### Option: HistoryCacheSize 224 | # Size of history cache, in bytes. 225 | # Shared memory size for storing history data. 226 | # 227 | # Mandatory: no 228 | # Range: 128K-2G 229 | # Default: 230 | # HistoryCacheSize=8M 231 | 232 | ### Option: HistoryTextCacheSize 233 | # Size of text history cache, in bytes. 234 | # Shared memory size for storing character, text or log history data. 235 | # 236 | # Mandatory: no 237 | # Range: 128K-2G 238 | # Default: 239 | # HistoryTextCacheSize=16M 240 | 241 | ### Option: Timeout 242 | # Specifies how long we wait for agent, SNMP device or external check (in seconds). 243 | # 244 | # Mandatory: no 245 | # Range: 1-30 246 | # Default: 247 | # Timeout=3 248 | 249 | ### Option: TrapperTimeout 250 | # Specifies how many seconds trapper may spend processing new data. 251 | # 252 | # Mandatory: no 253 | # Range: 1-300 254 | # Default: 255 | # TrapperTimeout=300 256 | 257 | ### Option: UnreachablePeriod 258 | # After how many seconds of unreachability treat a host as unavailable. 259 | # 260 | # Mandatory: no 261 | # Range: 1-3600 262 | # Default: 263 | # UnreachablePeriod=45 264 | 265 | ### Option: UnavailableDelay 266 | # How often host is checked for availability during the unavailability period, in seconds. 267 | # 268 | # Mandatory: no 269 | # Range: 1-3600 270 | # Default: 271 | # UnavailableDelay=60 272 | 273 | ### Option: UnreachableDelay 274 | # How often host is checked for availability during the unreachability period, in seconds. 275 | # 276 | # Mandatory: no 277 | # Range: 1-3600 278 | # Default: 279 | # UnreachableDelay=15 280 | 281 | ### Option: ExternalScripts 282 | # Full path to location of external scripts. 283 | # Default depends on compilation options. 284 | # 285 | # Mandatory: no 286 | # Default: 287 | # ExternalScripts=${datadir}/zabbix/externalscripts 288 | 289 | ExternalScripts=/usr/lib/zabbix/externalscripts 290 | 291 | ### Option: FpingLocation 292 | # Location of fping. 293 | # Make sure that fping binary has root ownership and SUID flag set. 294 | # 295 | # Mandatory: no 296 | # Default: 297 | # FpingLocation=/usr/sbin/fping 298 | 299 | ### Option: Fping6Location 300 | # Location of fping6. 301 | # Make sure that fping6 binary has root ownership and SUID flag set. 302 | # Make empty if your fping utility is capable to process IPv6 addresses. 303 | # 304 | # Mandatory: no 305 | # Default: 306 | # Fping6Location=/usr/sbin/fping6 307 | 308 | ### Option: SSHKeyLocation 309 | # Location of public and private keys for SSH checks and actions. 310 | # 311 | # Mandatory: no 312 | # Default: 313 | # SSHKeyLocation= 314 | 315 | ### Option: LogSlowQueries 316 | # How long a database query may take before being logged (in milliseconds). 317 | # Only works if DebugLevel set to 3 or 4. 318 | # 0 - don't log slow queries. 319 | # 320 | # Mandatory: no 321 | # Range: 1-3600000 322 | # Default: 323 | # LogSlowQueries=0 324 | 325 | ### Option: TmpDir 326 | # Temporary directory. 327 | # 328 | # Mandatory: no 329 | # Default: 330 | # TmpDir=/tmp 331 | 332 | ### Option: AllowRoot 333 | # Allow the proxy to run as 'root'. If disabled and the proxy is started by 'root', the proxy 334 | # will try to switch to the user specified by the User configuration option instead. 335 | # Has no effect if started under a regular user. 336 | # 0 - do not allow 337 | # 1 - allow 338 | # 339 | # Mandatory: no 340 | # Default: 341 | # AllowRoot=0 342 | 343 | ### Option: User 344 | # Drop privileges to a specific, existing user on the system. 345 | # Only has effect if run as 'root' and AllowRoot is disabled. 346 | # 347 | # Mandatory: no 348 | # Default: 349 | # User=zabbix 350 | 351 | ### Option: Include 352 | # You may include individual files or all files in a directory in the configuration file. 353 | # Installing Zabbix will create include directory in /usr/local/etc, unless modified during the compile time. 354 | # 355 | # Mandatory: no 356 | # Default: 357 | # Include= 358 | 359 | # Include=/usr/local/etc/zabbix_proxy.general.conf 360 | # Include=/usr/local/etc/zabbix_proxy.conf.d/ 361 | # Include=/usr/local/etc/zabbix_proxy.conf.d/*.conf 362 | 363 | ### Option: SSLCertLocation 364 | # Location of SSL client certificates. 365 | # This parameter is used only in web monitoring. 366 | # 367 | # Mandatory: no 368 | # Default: 369 | # SSLCertLocation=${datadir}/zabbix/ssl/certs 370 | 371 | ### Option: SSLKeyLocation 372 | # Location of private keys for SSL client certificates. 373 | # This parameter is used only in web monitoring. 374 | # 375 | # Mandatory: no 376 | # Default: 377 | # SSLKeyLocation=${datadir}/zabbix/ssl/keys 378 | 379 | ### Option: SSLCALocation 380 | # Location of certificate authority (CA) files for SSL server certificate verification. 381 | # If not set, system-wide directory will be used. 382 | # This parameter is used only in web monitoring. 383 | # 384 | # Mandatory: no 385 | # Default: 386 | # SSLCALocation= 387 | 388 | ####### LOADABLE MODULES ####### 389 | 390 | ### Option: LoadModulePath 391 | # Full path to location of proxy modules. 392 | # Default depends on compilation options. 393 | # 394 | # Mandatory: no 395 | # Default: 396 | # LoadModulePath=${libdir}/modules 397 | 398 | ### Option: LoadModule 399 | # Module to load at proxy startup. Modules are used to extend functionality of the proxy. 400 | # Format: LoadModule= 401 | # The modules must be located in directory specified by LoadModulePath. 402 | # It is allowed to include multiple LoadModule parameters. 403 | # 404 | # Mandatory: no 405 | # Default: 406 | # LoadModule= 407 | -------------------------------------------------------------------------------- /第8章/roles/zabbix-server/tasks/main.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Install Mysql-Server and zabbix-server 3 | yum: name={{ item }} state=latest 4 | with_items: 5 | - mysql-server 6 | - zabbix-server 7 | - zabbix-server-mysql 8 | - zabbix-web-mysql 9 | - name: Init Mysql 10 | shell: mysql_install_db 11 | - name: Start mysql-server 12 | service: name=mysqld state=started enabled=yes 13 | - name: Set mysql admin password 14 | shell: /usr/bin/mysqladmin -u root password 'ansible' 15 | - name: Create Zabbix master databases 16 | shell: mysql -u root -pansible -e 'create database zabbix_master character set utf8 collate utf8_bin;' 17 | - name: Set Zabbix Master databases grant 18 | shell: mysql -u root -pansible -e 'grant all privileges on zabbix_master.* to zabbix@localhost identified by "master";' 19 | - name: Import zabbix initial data (schema.sql) 20 | shell: mysql -u zabbix -pmaster zabbix_master < schema.sql chdir=/usr/share/doc/zabbix-server-mysql-2.4.6/create 21 | - name: Import zabbix initial data (images.sql) 22 | shell: mysql -u zabbix -pmaster zabbix_master < images.sql chdir=/usr/share/doc/zabbix-server-mysql-2.4.6/create 23 | - name: Import zabbix initial data (data.sql) 24 | shell: mysql -u zabbix -pmaster zabbix_master < data.sql chdir=/usr/share/doc/zabbix-server-mysql-2.4.6/create 25 | - name: Copy /etc/zabbix/zabbix_server.conf files 26 | template: src=zabbix_server.conf dest=/etc/zabbix/zabbix_server.conf owner=root group=root mode=644 27 | - name: change PHP timezone 28 | shell: sed -e 's@;date.timezone =.*@date.timezone = Asia/Shanghai@g' /etc/php.ini 29 | - name: Start Zabbix-Server and httpd 30 | service: name={{ item }} state=started enabled=yes 31 | with_items: 32 | - zabbix-server 33 | - httpd 34 | -------------------------------------------------------------------------------- /第8章/roles/zabbix-server/templates/zabbix_server.conf: -------------------------------------------------------------------------------- 1 | ListenPort=10052 2 | LogFile=/var/log/zabbix/zabbix_server.log 3 | LogFileSize=1024 4 | DebugLevel=3 5 | PidFile=/var/run/zabbix/zabbix_server.pid 6 | DBHost= localhost 7 | DBName=zabbix_master 8 | DBUser=zabbix 9 | DBPassword=master 10 | DBSocket=/var/lib/mysql/mysql.sock 11 | DBPort=3306 12 | StartPollers=20 13 | StartIPMIPollers=0 14 | StartPollersUnreachable=5 15 | StartTrappers=15 16 | StartPingers=4 17 | StartDiscoverers=6 18 | StartHTTPPollers=1 19 | StartTimers=4 20 | ### Option: JavaGateway 21 | # IP address (or hostname) of Zabbix Java gateway. 22 | # Only required if Java pollers are started. 23 | # 24 | # Mandatory: no 25 | # Default: 26 | # JavaGateway= 27 | ### Option: JavaGatewayPort 28 | # Port that Zabbix Java gateway listens on. 29 | # 30 | # Mandatory: no 31 | # Range: 1024-32767 32 | # Default: 33 | # JavaGatewayPort=10052 34 | 35 | ### Option: StartJavaPollers 36 | # Number of pre-forked instances of Java pollers. 37 | # 38 | # Mandatory: no 39 | # Range: 0-1000 40 | # Default: 41 | # StartJavaPollers=0 42 | 43 | ### Option: StartVMwareCollectors 44 | # Number of pre-forked vmware collector instances. 45 | # 46 | # Mandatory: no 47 | # Range: 0-250 48 | # Default: 49 | # StartVMwareCollectors=0 50 | 51 | ### Option: VMwareFrequency 52 | # How often Zabbix will connect to VMware service to obtain a new data. 53 | # 54 | # Mandatory: no 55 | # Range: 10-86400 56 | # Default: 57 | # VMwareFrequency=60 58 | 59 | ### Option: VMwarePerfFrequency 60 | # How often Zabbix will connect to VMware service to obtain performance data. 61 | # 62 | # Mandatory: no 63 | # Range: 10-86400 64 | # Default: 65 | # VMwarePerfFrequency=60 66 | 67 | ### Option: VMwareCacheSize 68 | # Size of VMware cache, in bytes. 69 | # Shared memory size for storing VMware data. 70 | # Only used if VMware collectors are started. 71 | # 72 | # Mandatory: no 73 | # Range: 256K-2G 74 | # Default: 75 | # VMwareCacheSize=8M 76 | 77 | ### Option: VMwareTimeout 78 | # Specifies how many seconds vmware collector waits for response from VMware service. 79 | # 80 | # Mandatory: no 81 | # Range: 1-300 82 | # Default: 83 | # VMwareTimeout=10 84 | 85 | ### Option: SNMPTrapperFile 86 | # Temporary file used for passing data from SNMP trap daemon to the server. 87 | # Must be the same as in zabbix_trap_receiver.pl or SNMPTT configuration file. 88 | # 89 | # Mandatory: no 90 | # Default: 91 | # SNMPTrapperFile=/tmp/zabbix_traps.tmp 92 | 93 | SNMPTrapperFile=/var/log/snmptt/snmptt.log 94 | 95 | ### Option: StartSNMPTrapper 96 | # If 1, SNMP trapper process is started. 97 | # 98 | # Mandatory: no 99 | # Range: 0-1 100 | # Default: 101 | StartSNMPTrapper=0 102 | 103 | 104 | ListenIP=0.0.0.0 105 | 106 | 107 | HousekeepingFrequency=24 108 | 109 | MaxHousekeeperDelete=0 110 | 111 | ### Option: SenderFrequency 112 | # How often Zabbix will try to send unsent alerts (in seconds). 113 | # 114 | # Mandatory: no 115 | # Range: 5-3600 116 | # Default: 117 | # SenderFrequency=30 118 | 119 | CacheSize=10M 120 | 121 | ### Option: CacheUpdateFrequency 122 | # How often Zabbix will perform update of configuration cache, in seconds. 123 | # 124 | # Mandatory: no 125 | # Range: 1-3600 126 | # Default: 127 | CacheUpdateFrequency=60 128 | 129 | ### Option: StartDBSyncers 130 | # Number of pre-forked instances of DB Syncers 131 | # 132 | # Mandatory: no 133 | # Range: 1-100 134 | # Default: 135 | StartDBSyncers=7 136 | 137 | ### Option: HistoryCacheSize 138 | # Size of history cache, in bytes. 139 | # Shared memory size for storing history data. 140 | # 141 | # Mandatory: no 142 | # Range: 128K-2G 143 | # Default: 144 | HistoryCacheSize=8M 145 | 146 | ### Option: TrendCacheSize 147 | # Size of trend cache, in bytes. 148 | # Shared memory size for storing trends data. 149 | # 150 | # Mandatory: no 151 | # Range: 128K-2G 152 | # Default: 153 | # TrendCacheSize=4M 154 | 155 | ### Option: HistoryTextCacheSize 156 | # Size of text history cache, in bytes. 157 | # Shared memory size for storing character, text or log history data. 158 | # 159 | # Mandatory: no 160 | # Range: 128K-2G 161 | # Default: 162 | # HistoryTextCacheSize=16M 163 | 164 | ### Option: ValueCacheSize 165 | # Size of history value cache, in bytes. 166 | # Shared memory size for caching item history data requests. 167 | # Setting to 0 disables value cache. 168 | # 169 | # Mandatory: no 170 | # Range: 0,128K-64G 171 | # Default: 172 | # ValueCacheSize=8M 173 | 174 | ### Option: Timeout 175 | # Specifies how long we wait for agent, SNMP device or external check (in seconds). 176 | # 177 | # Mandatory: no 178 | # Range: 1-30 179 | # Default: 180 | Timeout=30 181 | 182 | ### Option: TrapperTimeout 183 | # Specifies how many seconds trapper may spend processing new data. 184 | # 185 | # Mandatory: no 186 | # Range: 1-300 187 | # Default: 188 | # TrapperTimeout=300 189 | 190 | ### Option: UnreachablePeriod 191 | # After how many seconds of unreachability treat a host as unavailable. 192 | # 193 | # Mandatory: no 194 | # Range: 1-3600 195 | # Default: 196 | # UnreachablePeriod=45 197 | 198 | ### Option: UnavailableDelay 199 | # How often host is checked for availability during the unavailability period, in seconds. 200 | # 201 | # Mandatory: no 202 | # Range: 1-3600 203 | # Default: 204 | # UnavailableDelay=60 205 | 206 | ### Option: UnreachableDelay 207 | # How often host is checked for availability during the unreachability period, in seconds. 208 | # 209 | # Mandatory: no 210 | # Range: 1-3600 211 | # Default: 212 | # UnreachableDelay=15 213 | 214 | ### Option: AlertScriptsPath 215 | # Full path to location of custom alert scripts. 216 | # Default depends on compilation options. 217 | # 218 | # Mandatory: no 219 | # Default: 220 | # AlertScriptsPath=${datadir}/zabbix/alertscripts 221 | 222 | AlertScriptsPath=/usr/lib/zabbix/alertscripts 223 | 224 | ### Option: ExternalScripts 225 | # Full path to location of external scripts. 226 | # Default depends on compilation options. 227 | # 228 | # Mandatory: no 229 | # Default: 230 | # ExternalScripts=${datadir}/zabbix/externalscripts 231 | 232 | ExternalScripts=/usr/lib/zabbix/externalscripts 233 | 234 | ### Option: FpingLocation 235 | # Location of fping. 236 | # Make sure that fping binary has root ownership and SUID flag set. 237 | # 238 | # Mandatory: no 239 | # Default: 240 | # FpingLocation=/usr/sbin/fping 241 | 242 | ### Option: Fping6Location 243 | # Location of fping6. 244 | # Make sure that fping6 binary has root ownership and SUID flag set. 245 | # Make empty if your fping utility is capable to process IPv6 addresses. 246 | # 247 | # Mandatory: no 248 | # Default: 249 | # Fping6Location=/usr/sbin/fping6 250 | 251 | ### Option: SSHKeyLocation 252 | # Location of public and private keys for SSH checks and actions. 253 | # 254 | # Mandatory: no 255 | # Default: 256 | # SSHKeyLocation= 257 | 258 | ### Option: LogSlowQueries 259 | # How long a database query may take before being logged (in milliseconds). 260 | # Only works if DebugLevel set to 3 or 4. 261 | # 0 - don't log slow queries. 262 | # 263 | # Mandatory: no 264 | # Range: 1-3600000 265 | # Default: 266 | LogSlowQueries=2000 267 | 268 | ### Option: TmpDir 269 | # Temporary directory. 270 | # 271 | # Mandatory: no 272 | # Default: 273 | TmpDir=/dev/shm 274 | 275 | ### Option: StartProxyPollers 276 | # Number of pre-forked instances of pollers for passive proxies. 277 | # 278 | # Mandatory: no 279 | # Range: 0-250 280 | # Default: 281 | # StartProxyPollers=1 282 | 283 | ### Option: ProxyConfigFrequency 284 | # How often Zabbix Server sends configuration data to a Zabbix Proxy in seconds. 285 | # This parameter is used only for proxies in the passive mode. 286 | # 287 | # Mandatory: no 288 | # Range: 1-3600*24*7 289 | # Default: 290 | # ProxyConfigFrequency=3600 291 | 292 | ### Option: ProxyDataFrequency 293 | # How often Zabbix Server requests history data from a Zabbix Proxy in seconds. 294 | # This parameter is used only for proxies in the passive mode. 295 | # 296 | # Mandatory: no 297 | # Range: 1-3600 298 | # Default: 299 | # ProxyDataFrequency=1 300 | 301 | ### Option: AllowRoot 302 | # Allow the server to run as 'root'. If disabled and the server is started by 'root', the server 303 | # will try to switch to the user specified by the User configuration option instead. 304 | # Has no effect if started under a regular user. 305 | # 0 - do not allow 306 | # 1 - allow 307 | # 308 | # Mandatory: no 309 | # Default: 310 | # AllowRoot=0 311 | 312 | ### Option: User 313 | # Drop privileges to a specific, existing user on the system. 314 | # Only has effect if run as 'root' and AllowRoot is disabled. 315 | # 316 | # Mandatory: no 317 | # Default: 318 | # User=zabbix 319 | 320 | ### Option: Include 321 | # You may include individual files or all files in a directory in the configuration file. 322 | # Installing Zabbix will create include directory in /usr/local/etc, unless modified during the compile time. 323 | # 324 | # Mandatory: no 325 | # Default: 326 | # Include= 327 | 328 | # Include=/usr/local/etc/zabbix_server.general.conf 329 | # Include=/usr/local/etc/zabbix_server.conf.d/ 330 | # Include=/usr/local/etc/zabbix_server.conf.d/*.conf 331 | 332 | ### Option: SSLCertLocation 333 | # Location of SSL client certificates. 334 | # This parameter is used only in web monitoring. 335 | # 336 | # Mandatory: no 337 | # Default: 338 | # SSLCertLocation=${datadir}/zabbix/ssl/certs 339 | 340 | ### Option: SSLKeyLocation 341 | # Location of private keys for SSL client certificates. 342 | # This parameter is used only in web monitoring. 343 | # 344 | # Mandatory: no 345 | # Default: 346 | # SSLKeyLocation=${datadir}/zabbix/ssl/keys 347 | 348 | ### Option: SSLCALocation 349 | # Override the location of certificate authority (CA) files for SSL server certificate verification. 350 | # If not set, system-wide directory will be used. 351 | # This parameter is used only in web monitoring. 352 | # 353 | # Mandatory: no 354 | # Default: 355 | # SSLCALocation= 356 | 357 | ####### LOADABLE MODULES ####### 358 | 359 | ### Option: LoadModulePath 360 | # Full path to location of server modules. 361 | # Default depends on compilation options. 362 | # 363 | # Mandatory: no 364 | # Default: 365 | # LoadModulePath=${libdir}/modules 366 | 367 | ### Option: LoadModule 368 | # Module to load at server startup. Modules are used to extend functionality of the server. 369 | # Format: LoadModule= 370 | # The modules must be located in directory specified by LoadModulePath. 371 | # It is allowed to include multiple LoadModule parameters. 372 | # 373 | # Mandatory: no 374 | # Default: 375 | # LoadModule= 376 | -------------------------------------------------------------------------------- /第8章/site.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: all 3 | roles: 4 | - { role: base, tags: base} 5 | - { role: zabbix-server, when: "'zabbix-server' in group_names", tags: server} 6 | - { role: zabbix-proxy, when: "'zabbix-proxy' in group_names", tags: proxy } 7 | - { role: zabbix-agent, tags: agent} 8 | -------------------------------------------------------------------------------- /第9章/group_vars/all: -------------------------------------------------------------------------------- 1 | --- 2 | ansible_ssh_pass: 123456 3 | -------------------------------------------------------------------------------- /第9章/group_vars/haproxy: -------------------------------------------------------------------------------- 1 | --- 2 | mode: http 3 | balance: roundrobin 4 | -------------------------------------------------------------------------------- /第9章/group_vars/mysql: -------------------------------------------------------------------------------- 1 | --- 2 | mysql_port: 3306 3 | user: ansible 4 | password: ansible 5 | database: ansible 6 | -------------------------------------------------------------------------------- /第9章/hosts: -------------------------------------------------------------------------------- 1 | [apache] 2 | 172.17.0.3 3 | 172.17.0.4 4 | [mysql] 5 | 172.17.0.2 6 | [haproxy] 7 | 172.17.0.1 8 | -------------------------------------------------------------------------------- /第9章/roles/apache/tasks/main.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Install Apache and PHP 3 | yum: name={{ item }} state=present 4 | with_items: 5 | - httpd 6 | - php 7 | - php-mysql 8 | - libsemanage-python 9 | - libselinux-python 10 | - name: Copy index.php.j2 11 | template: src=index.php.j2 dest=/var/www/html/index.php 12 | - name: http service state 13 | service: name=httpd state=started enabled=yes 14 | -------------------------------------------------------------------------------- /第9章/roles/apache/templates/index.php.j2: -------------------------------------------------------------------------------- 1 | 11 | -------------------------------------------------------------------------------- /第9章/roles/base/files/CentOS-Base.repo: -------------------------------------------------------------------------------- 1 | # CentOS-Base.repo 2 | # 3 | # The mirror system uses the connecting IP address of the client and the 4 | # update status of each mirror to pick mirrors that are updated to and 5 | # geographically close to the client. You should use this for CentOS updates 6 | # unless you are manually picking other mirrors. 7 | # 8 | # If the mirrorlist= does not work for you, as a fall back you can try the 9 | # remarked out baseurl= line instead. 10 | # 11 | # 12 | 13 | [base] 14 | name=CentOS-$releasever - Base - mirrors.ustc.edu.cn 15 | baseurl=http://mirrors.ustc.edu.cn/centos/$releasever/os/$basearch/ 16 | #mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os 17 | gpgcheck=1 18 | gpgkey=http://mirrors.ustc.edu.cn/centos/RPM-GPG-KEY-CentOS-6 19 | 20 | #released updates 21 | [updates] 22 | name=CentOS-$releasever - Updates - mirrors.ustc.edu.cn 23 | baseurl=http://mirrors.ustc.edu.cn/centos/$releasever/updates/$basearch/ 24 | #mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates 25 | gpgcheck=1 26 | gpgkey=http://mirrors.ustc.edu.cn/centos/RPM-GPG-KEY-CentOS-6 27 | 28 | #additional packages that may be useful 29 | [extras] 30 | name=CentOS-$releasever - Extras - mirrors.ustc.edu.cn 31 | baseurl=http://mirrors.ustc.edu.cn/centos/$releasever/extras/$basearch/ 32 | #mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras 33 | gpgcheck=1 34 | gpgkey=http://mirrors.ustc.edu.cn/centos/RPM-GPG-KEY-CentOS-6 35 | 36 | #additional packages that extend functionality of existing packages 37 | [centosplus] 38 | name=CentOS-$releasever - Plus - mirrors.ustc.edu.cn 39 | baseurl=http://mirrors.ustc.edu.cn/centos/$releasever/centosplus/$basearch/ 40 | #mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus 41 | gpgcheck=1 42 | enabled=0 43 | gpgkey=http://mirrors.ustc.edu.cn/centos/RPM-GPG-KEY-CentOS-6 44 | 45 | #contrib - packages by Centos Users 46 | [contrib] 47 | name=CentOS-$releasever - Contrib - mirrors.ustc.edu.cn 48 | baseurl=http://mirrors.ustc.edu.cn/centos/$releasever/contrib/$basearch/ 49 | #mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=contrib 50 | gpgcheck=1 51 | enabled=0 52 | gpgkey=http://mirrors.ustc.edu.cn/centos/RPM-GPG-KEY-CentOS-6 53 | -------------------------------------------------------------------------------- /第9章/roles/base/files/epel.repo: -------------------------------------------------------------------------------- 1 | [epel] 2 | name=Extra Packages for Enterprise Linux 6 - $basearch 3 | baseurl=http://mirrors.ustc.edu.cn/epel/6/$basearch 4 | #mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-6&arch=$basearch 5 | failovermethod=priority 6 | enabled=1 7 | gpgcheck=1 8 | gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6 9 | 10 | [epel-debuginfo] 11 | name=Extra Packages for Enterprise Linux 6 - $basearch - Debug 12 | baseurl=http://mirrors.ustc.edu.cn/epel/6/$basearch/debug 13 | #mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-debug-6&arch=$basearch 14 | failovermethod=priority 15 | enabled=0 16 | gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6 17 | gpgcheck=1 18 | 19 | [epel-source] 20 | name=Extra Packages for Enterprise Linux 6 - $basearch - Source 21 | baseurl=http://mirrors.ustc.edu.cn/epel/6/SRPMS 22 | #mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-source-6&arch=$basearch 23 | failovermethod=priority 24 | enabled=0 25 | gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6 26 | gpgcheck=1 27 | -------------------------------------------------------------------------------- /第9章/roles/base/tasks/main.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - copy: src=CentOS-Base.repo dest=/etc/yum.repos.d/CentOS-Base.repo owner=root group=root mode=644 3 | - copy: src=epel.repo dest=/etc/yum.repos.d/epel.repo owner=root group=root mode=644 4 | -------------------------------------------------------------------------------- /第9章/roles/haproxy/handers/main.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: restart haproxy 3 | service: name=haproxy state=reloaded 4 | -------------------------------------------------------------------------------- /第9章/roles/haproxy/tasks/main.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Install haproxy 3 | yum: name={{ item }} state=present 4 | with_items: 5 | - haproxy 6 | - name: Copy harpoxy.cf 7 | template: src=haproxy.cfg.j2 dest=/etc/haproxy/haproxy.cfg owner=root group=root mode=644 8 | notify: 9 | - restart haproxy 10 | - name: Start haproxy 11 | service: name=haproxy state=started enabled=yes 12 | -------------------------------------------------------------------------------- /第9章/roles/haproxy/templates/haproxy.cf.j2: -------------------------------------------------------------------------------- 1 | global 2 | log 127.0.0.1 local2 3 | chroot /var/lib/haproxy 4 | pidfile /var/run/haproxy.pid 5 | maxconn 4000 6 | user root 7 | group root 8 | daemon 9 | 10 | global 11 | maxconn 100000 12 | daemon 13 | nbproc 1 14 | log 127.0.0.1 local3 info 15 | 16 | defaults 17 | option http-keep-alive 18 | maxconn 100000 19 | mode {{ mode }} 20 | option httplog 21 | option dontlognull 22 | option http-server-close 23 | option redispatch 24 | retries 3 25 | timeout connect 5s 26 | timeout client 20s 27 | timeout server 10s 28 | 29 | frontend ansible 30 | bind {{ ansible_default_ipv4.address }}:80 31 | mode {{ mode }} 32 | log global 33 | default_backend apache 34 | 35 | backend apache 36 | option httpchk HEAD / HTTP/1.0 37 | balance {{ balance }} 38 | {% for host in groups['apache'] %} 39 | server {{ hostvars[host].ansible_hostname }} {{ hostvars[host].ansible_default_ipv4.address }}:80 check inter 3000 rise 3 fall 2 40 | {% endfor %} 41 | -------------------------------------------------------------------------------- /第9章/roles/mysql/handers/main.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: restart mysql 3 | service: name=mysqld state=restarted 4 | -------------------------------------------------------------------------------- /第9章/roles/mysql/tasks/main.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Install Mysql-server 3 | yum: name={{ item }} state=installed 4 | with_items: 5 | - mysql-server 6 | - MySQL-python 7 | - name: Copy my.cnf 8 | template: src=my.cnf.j2 dest=/etc/my.cnf 9 | notify: 10 | - restart mysql 11 | - name: Start Mysql 12 | service: name=mysqld state=started enabled=yes 13 | - name: Create Database 14 | mysql_db: name={{ database }} state=present 15 | - name: Create Users 16 | mysql_user: name={{ user }} password={{ password }} priv=*.*:ALL host='%' state=present 17 | -------------------------------------------------------------------------------- /第9章/site.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Init base environment for all hosts 3 | hosts: all #所有主机引用base角色 4 | roles: 5 | - { role: base, tags: base } 6 | - name: Install Mysql 7 | hosts: mysql #mysql主机组引用mysql角色 8 | roles: 9 | - { role: mysql, tags: mysql } 10 | - name: Install Apache and PHP 11 | hosts: apache #apache主机组引用apache角色 12 | roles: 13 | - { role: apache, tags: apache } 14 | - name: Install Haproxy 15 | hosts: haproxy #haproxy主机组引用haproxy角色 16 | roles: 17 | - { role: haproxy, tags: haproxy } 18 | --------------------------------------------------------------------------------