ansible笔记

摘要:
使用目录列表。Zookeperid使用主机名的最后一个数字来确定文件是否为默认文件。如果是,请清除blockinfile+lookup。使用替换+查找。使用ansible2.4 api调用列表。我们有如下列表(主机是server7-13)(py3)[root@jumpserverapp]#catserver_elk.yml主机:~server[7-9]$:~server1[
目录

列表的使用
zookeeper id 使用主机名最后的编号
判断一个文件是否是默认的,如果是就清空
blockinfile+lookup使用
replace+lookup使用
ansible2.4 api 调用

列表的使用

我们有一个列表如下(主机为server7-13)

(py3) [root@jumpserver app]# cat server_elk.yml
- hosts:  ~server[7-9]$:~server1[0-3]$
  vars:
    topics_list:
      - test
      - test1
    cluster_list:
      - server7
      - server8
      - server9
      - server10
      - server11
      - server12
      - server13
  roles:
   # - common
    - elk

如我们需要用logstash往es里面写,下面是我们需要的效果

input {
  kafka {
    bootstrap_servers => "server7:9096,server8:9096,server9:9096,server10:9096,server11:9096,server12:9096,server13:9096"
    topics => ["test","test1"]
  }
}
filter {
  json {
    source => "message"
  }
  mutate {
  convert => { "upstream_response_time" => "float" }
  convert => { "request_time" => "float" }
  convert => { "status" => "integer" }
  remove_field => "message"
  }
  geoip {
      source => "remote_addr"
      add_field => [ "[geoip][coordinates]", "%{[geoip][longitude]}" ]
      add_field => [ "[geoip][coordinates]", "%{[geoip][latitude]}"  ]
  }
  mutate {
    convert => [ "[geoip][coordinates]", "float"]
  }
}

output {
  elasticsearch {
    hosts => ["server7:9200","server8:9200","server9:9200","server10:9200","server11:9200","server12:9200","server13:9200"]
    index => "logstash-%{[type]}-%{+YYYY.MM.dd}"
  }
}

ansible的template可以这样写

input {
  kafka {
    bootstrap_servers => "{{ cluster_list|map('regex_replace', '^(.*)$', '\1:9096')|join(',') }}"
    topics => [{{ topics_list|map('regex_replace', '^(.*)$', '"\1"')|join(',') }}]
  }
}
filter {
  json {
    source => "message"
  }
  mutate {
  convert => { "upstream_response_time" => "float" }
  convert => { "request_time" => "float" }
  convert => { "status" => "integer" }
  remove_field => "message"
  }
  geoip {
      source => "remote_addr"
      add_field => [ "[geoip][coordinates]", "%{[geoip][longitude]}" ]
      add_field => [ "[geoip][coordinates]", "%{[geoip][latitude]}"  ]
  }
  mutate {
    convert => [ "[geoip][coordinates]", "float"]
  }
}

output {
  elasticsearch {
    hosts => [{{ cluster_list|map('regex_replace', '^(.*)$', '"\1:9200"')|join(',') }}]
    index => "logstash-%{[type]}-%{+YYYY.MM.dd}"
  }
}

zookeeper id 使用主机名最后的编号

如server7的myid就是7

[root@server11 ~]# cat /opt/zookeeper/data/myid
11

template 中需要

# cat  roles/common/templates/myid.j2
{{ ansible_hostname|replace('-','/') |basename}}

判断一个文件是否是默认的,如果是就清空

比如我们安装filebeat,然后/etc/filebeat/filebeat.yml这个文件是默认的话,我们就需要清空,不是我们需要用blockinfile往里面填东西,由于有多次添加的需要,而且还需要做成状态的所以有了这个需求

- name: reset file config is the /etc/filebeat/filebeat.yml file is default
  shell: "[[ $(md5sum /etc/filebeat/filebeat.yml) == 582eb1601bde332db2d09d2ee2d8286b* ]] && > /etc/filebeat/filebeat.yml"
  ignore_errors: True

blockinfile + lookup 使用

lookup 可以lookup很多东西如dnsfile等等具体可以看(官方文档)[http://docs.ansible.com/ansible/latest/playbooks_lookups.html]

- name: copy filebeat header config
  blockinfile:
    path: /etc/filebeat/filebeat.yml
    block: "{{ lookup('template', 'header.yml') }}"
    marker: "# {mark} filebeat header"
    insertbefore: BOF
  notify:
    - restart filebeat


- name: copy filebeat.prospectors config
  blockinfile:
    path: /etc/filebeat/filebeat.yml
    block: "{{ lookup('template', 'input_type.yml') }}"
    marker: "# {mark} filebeat {{ document_type }}"
    insertafter: "# END filebeat header"
  notify:
    - restart filebeat

- name: copy filebeat output config
  blockinfile:
    path: /etc/filebeat/filebeat.yml
    block: "{{ lookup('template', 'output.yml') }}"
    marker: "# {mark} filebeat output"
    insertafter: EOF
  notify:
    - restart filebeat

replace + lookup 使用

这个file文件就放在roles/nginx_conf/files下面

- name: add access_log_json
  blockinfile:
    path: "{{ nginx_file }}"
    marker: "# {mark} access_log_json "
    insertafter: 'http_x_forwarded_for"'
    content: "{{ lookup('file', './access_log_json') }}"
    backup: yes
  notify:
    - reload nginx

- name: change file to access_log_json
  replace:
    path: "{{ nginx_file }}"
    regexp: 'access_log  {{ logfile }} main;'
    replace: 'access_log  {{ logfile }} access_log_json;'
    backup: yes
  notify:
    - reload nginx
# cat roles/nginx_conf/files/access_log_json
    log_format  access_log_json      '{"remote_addr":"$remote_addr","host":"$host","time_iso8601":"$time_iso8601","request":"$request","status":"$status","body_bytes_sent":"$body_bytes_sent","http_referer":"$http_referer","http_user_agent":"$http_user_agent","http_x_forwarded_for":"$http_x_forwarded_for","upstream_response_time":"$upstream_response_time","uri":"$uri","request_time":"$request_time"}'

ansible2.4 api 调用

需要更改的地方就是inventory的地方,sources改成自己inventory文件的位置,然后hosts配置成自己需要操作的主机名就行了,这里面好多参数其实都可以ansible --help来看,一下是根据官网的例子改写的,不过就简单的能跑shell模块了。

#!/usr/bin/env python

import json
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback import CallbackBase

class ResultCallback(CallbackBase):
    """A sample callback plugin used for performing an action as results come in

    If you want to collect all results into a single object for processing at
    the end of the execution, look into utilizing the ``json`` callback plugin
    or writing your own custom callback plugin
    """
    def v2_runner_on_failed(self, result, **kwargs):
        print(result._host)

    def v2_runner_on_unreachable(self, result):
        print("*"*10, "v2_runner_on_unreachable")
        print(result._host)

    def v2_runner_on_ok(self, result, **kwargs):
        """Print a json representation of the result

        This method could store the result in an instance attribute for retrieval later
        """
        host = result._host
        print(json.dumps({host.name: result._result}, indent=4))


Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check', 'diff'])
# initialize needed objects
loader = DataLoader()
options = Options(connection='smart', module_path='/path/to/mymodules', forks=100, become=None, become_method=None, become_user=None, check=False,
                  diff=False)
passwords = dict(vault_pass='secret')

# Instantiate our ResultCallback for handling results as they come in
results_callback = ResultCallback()

# create inventory and pass to var manager
#inventory = InventoryManager(loader=loader, sources=['localhost'])
inventory = InventoryManager(loader=loader, sources=['/etc/ansible/d_inv.py'])
variable_manager = VariableManager(loader=loader, inventory=inventory)

# create play with tasks
play_source =  dict(
        name = "Ansible Play",
        hosts = 'node1.com',
        gather_facts = 'no',
        tasks = [
            #dict(action=dict(module='shell', args='ls'), register='shell_out'),
            dict(action=dict(module='shell', args='route -n'), ),
            #dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
         ]
    )
play = Play().load(play_source, variable_manager=variable_manager, loader=loader)

# actually run it
tqm = None
try:
    tqm = TaskQueueManager(
              inventory=inventory,
              variable_manager=variable_manager,
              loader=loader,
              options=options,
              passwords=passwords,
              stdout_callback=results_callback,  # Use our custom callback instead of the ``default`` callback plugin
          )
    result = tqm.run(play)
finally:
    if tqm is not None:
        tqm.cleanup()

免责声明:文章转载自《ansible笔记》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇php word转html(可能样式会有问题 还没有空细究)Ubuntu网络配置下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Ansible安装配置及使用

一、Ansible特点 1、不需要安装客户端,通过sshd通信 2、基于模块工作,模块可以由任何序言开发 3、不仅支持命令行使用模块,也支持编写yaml格式的playbook 4、支持sudo 5、有提供UI(浏览器图形化)www.ansible.com/tower10台主机以内免费 6、开源UI https://github.com/alaxli/ans...

H3C 交换机VRRP和堆叠

1. 前言 平时对系统和主机的维护工作比较多一些, 对网络设备的配置就相对少了很多。最近为了上一批设备,针对交换机的配置也学习了一番,本文记录几个在实操中用到的实例。 2. 概念 在系统运维中,经常会用冗余的方式来保证业务、服务、系统的高可用性,而在网络中也存在冗余和高可用的方式。对于交换机来说,VRRP 和 堆叠。 2.1 MSTP 这里不准备对 STP...

Mysql双机热备实现数据库高可用

mysql双主热备,也称主主互备,目的是mysql数据库高可用,只支持双机,原因是mysql的复制是一主多从,但一个从服务器只能有一个主服务器。 双机热备的条件是双机mysql版本必须一致。 服务器分别为A(172.16.9.212)、B(172.16.9.213),配置步骤如下: 一、A->B主从备份 1、在主服务器A上创建从服务器备份的用户,IP...

Linux设备驱动程序学习(17)-USB 驱动程序(二)

内核使用2.6.29.4USB设备其实很复杂,但是Linux内核提供了一个称为USB core的子系统来处理了大部分的复杂工作,所以这里所描述的是驱动程序和USB core之间的接口。 在USB设备组织结构中,从上到下分为设备(device)、配置(config)、接口(interface)和端点(endpoint)四个层次。 对于这四个层次的简单描述如下...

RabbitMQ消息队列

  一、简介 RabbitMQ是一个在AMQP基础上完整的、可复用的企业消息系统,遵循Mozilla Public License开源协议。MQ全称Message Queue(消息队列),它是一种应用程序对应用程序的通信方式。应用程序通过读写入队列的消息(针对应用程序的数据)来通信,而无需专用连接来链接他们。消息传递指的是程序之间通过在消息中发送数据通信,...

Api网关Kong集成Consul做服务发现及在Asp.Net Core中的使用

写在前面   Api网关我们之前是用 .netcore写的 Ocelot的,使用后并没有完全达到我们的预期,花了些时间了解后觉得kong可能是个更合适的选择。 简单说下kong对比ocelot打动我的: 1、kong可以直接代替Nginx/OpenRestry做前端服务器。 2、kong的功能强大,性能不俗,生态不错,操作面板,插件丰富,社区活跃; 本文...