Python Linux系统管理与自动化运维之深入浅出Ansible(一)

Ansible维护模式通常由控制机和被管理机组成。因为Ansible的特性不像其他运维工具那样需要在被监控的目标上安装agent,所以我们的侧重点只需要放在安装了Ansible的服务器上(当然用于实验环境的话可以是一台笔记本,台式机或者仅仅只需要一台虚拟机即可)。Ansible可以通过SSH进行远程链接到对端主机上,然后执行你想要执行的playbook或者指令。所有的远程主机都可以在inventory中被定义。

1.:默认command

ansible test -m ping  #测试ansible是否正常
ansible test -a "whoami" 
ansible test -a "hostname"

2.实现拷贝文件:copy
ansible test -m copy -a "src=/tmp/data.txt dest=/tmp/data.txt" #实现将本地的/tmp/data.txt 拷贝到远程主机tmp/data.txt中

3.修改文件权限:file
file 将权限改为700 所有者和所属组改为anan
ansible test -m file -a"dest=/tmp/data.txt mode=700 owner=anan group=anan"

4.远程服务器安装软件:
ansible test -m yum -a "name=lrzsz state=present " -become #become类似于sudo 安装lrzsz

5.ansible-playbook实现1-4操作
ansbile-playbook test_playbook.yml

---
- hosts: test
  tasks:
  - name: test ping 
    ping:

  - name: test copy file
    copy: src=/tmp/data.txt dest=/tmp/data2.txt

  - name: test change file mode
    file: dest=/tmp/data2.txt mode=700 owner=anan group=anan

  - name: test install software
    yum: name="lrzsz" state=latest #absent present removed latest

6.列出生效的主机 (也可以通过-i指定hosts文件)\
ansible test --list-hosts\
ansible test -i hostsdir

远程服务器匹配规则

7.分组定义主机:
hosts文件如下:

[user:children]
webserver
db_server
monitor_server
docker_server
master

[webserver:children]
http_server
nginx_server

[db_server:children]
mysql_server
redis_server

[monitor_server:children]
nagios_server
zabbix_server

[container_server:children]
docker_server

[master]
10.1.11.34

[http_server]
10.1.11.35

[http_server:vars]
http_port=80
maxRequestsPerChild=808

[nginx_server]
10.1.11.36

[mysql_server]
10.1.11.37

[redis_server]
[nagios_server]
[zabbix_server]
[docker_server]

[test]
10.1.11.36

8.动态Inverntory获取

hosts表:

create table hosts(
    id int not null auto_increment,
    host varchar(15) default null,
    groupname varchar(15) default null,
    username varchar(15) default null,
    port int(11) default '22',
    primary key(id)
    )engine=InnoDB auto_increment=3 default charset=utf8mb4;


insert into hosts 
(host,groupname,username)
values(('10.1.11.35','anan','anan'),('10.1.11.36','anan','anan'),('10.1.11.37','anan','anan'));

动态获取服务器列表程序

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/7/20 16:20
# @Author  : anan
# @Site    : 
# @File    : hosts.py
# @Software: PyCharm


from __future__ import print_function
import argparse
import json
from collections import defaultdict
from contextlib import contextmanager

import pymysql

def to_json(in_dict):
    return json.dumps(in_dict,sort_keys=True,indent=2)

@contextmanager
def get_conn(**kwargs):
    conn=pymysql.connect(**kwargs)
    try:
        yield conn
    finally:
        conn.close()

def parse_args():
    parser=argparse.ArgumentParser(description="Openstack Inventory Module")
    group=parser.add_mutually_exclusive_group(required=True)
    group.add_argument('--list',action='store_true',help='List active server')
    group.add_argument('--host',help="List details about the specific host")
    return parser.parse_args()

def list_all_host(conn):
    hosts=defaultdict(list)

    with conn as cur:
        cur.execute('select * from hosts')
        rows=cur.fetchall()
        for row in rows:
            no,host,group,user,port=row
            hosts[group].append(host)
    return hosts


def get_host_detail(conn,host):
    details={}
    with conn as cur:
        cur.execute("select * from hosts where host='{0}'".format(host))
        rows=cur.fetchall()
        if rows:
            no,host,group,user,port=rows[0]
            details.update(ansible_user=user,ansible_port=port)

    return details


def main():
    parser=parse_args()
    with get_conn(host='10.1.11.37',user='root',passwd='passwd',db='test') as conn:
        if parser.list:
            hosts=list_all_host(conn)
            print(to_json(hosts))
        else:
            details=get_host_detail(conn,parser.host)
            print(to_json(details))

if __name__ == '__main__':
    main()

Inventory行为参数

![](https://raw.githubusercontent.com/ananzhoujiaan/img/master/ansibleInventory1.png
)

yaml文件编辑:


yaml语法规则

palybook2.yml

---
#一个职工的记录
name: examaple developer
job: developer
skill: elite
employed: True
foods:
  - Apple
  - Orange
  - Strawberry
  - Mango
Language:
  ruby: elite
  Python: elite
  dotnet: Lame

*ansible目前已经提供了超过950个模块:用户可以根据自己喜欢的编程语言编写第三方模块
(学习和使用Ansible模块)*
ansible-doc file
ansible-doc -l file

常用模块:

1.ping

ansible test -m ping

2.远程命令模块

ansible test -a "hostname"
ansible test -m command -a 'hostname'
ansible test -m command -a '/sbin/shutdown -t now'
ansible test -m shell -a 'cat /etc/passwd |wc -l'
ansible test -m raw -a 'cat /etc/passwd |wc -l'
ansible test -m script -a "test.sh"

3.file

ansible test -m file -a "src=/root/anan.txt dest=/root/anan.link mode=777 owner=anan state=link force=yes" #创建链接

书籍file示例:

4.copy

ansible test -m copy -a "src=/etc/ansible/test/test1.md dest=/root/test.md owner=root group=anan owner=744 backup=yes

5.user/group

ansible test -m user -a “name=anan1 createhome=yes shell=/bin/bash comment=’ananbackup’”

6.apt/yum

7.get_url

ansible test -m get_url -a "url='https://github.com/ananzhoujiaan/test2' dest=/root/"

8.unarchive 解压

9.git

ansible test -m git -a "repo=https://github.com/ananzhoujiaan/test2.git dest=/root/testfile version=HEAD"

10.stat

ansible常用模块参考:https://blog.csdn.net/pushiqiang/article/details/78249665


未完待续……

猜你喜欢

转载自blog.csdn.net/sinat_34789167/article/details/81144087