天天看点

ansible基础实践

ansible : 批量配置管理软件,基于Python语言实现(paramiko/PyYAML/Jinja2),简单来理解它就是一个命令。

playbook:脚本

ansible的两个集合:hosts和tasks

应用场景:不同主机执行相同命令。

安装:ansible

ansible 源码包可以从华为开源镜像站官网下载:https://mirrors.huaweicloud.com/

1创建yum源

createrepo --update  . //在原有yum源上进行更新加选项--update
           

2 创建6台虚拟机 2cpu, 1.5G以上内存,10G 以上硬盘,1块网卡(VBR)

192.168.1.10 ansible

192.168.1.11 web1

192.168.1.12 web2

192.168.1.21 db1

192.168.1.22 db2

192.168.1.33 cache

2 创建yum源(真机)

拷贝ansible相关软件到ftp目录

到软件目录下执行 : createrepo .

3 在 192.168.1.10安装ansible, 配置yum源

ansible --version

4 ansible ad-hoc 命令

ansible 主机分组名称,或主机名称【命令集合】

–list-hosts

-m 模块名称 -a 模块参数

模块真的多,需要用到再查看文档:

[[email protected] .ssh]# ansible-doc -l  //列出所有
  [[email protected] .ssh]# ansible-doc  模块名称  //查看某个模块用法
           

5 非交互生成公钥私钥对

[[email protected] ~]# ssh-keygen -t rsa -b 2048 -N ''
           

-t 指定密钥类型用

-b bits指定密钥长度。对于RSA密钥,最小要求768位,默认是2048位。DSA密钥必须恰好是1024位(FIPS186-2 标准的要求)。

-N:是指密码为空;

-q:指静默模式, 不输出显示

6 使用ansible将公钥批量部署到目标主机

[[email protected] ~]# ansible all -m authorized_key -a "user=root exclusive=true  manage_dir=true key='$(< /root/.ssh/id_rsa.pub)'" -k
           

ansible all ##所有主机

user=root ##用户

exclusive=true ###强行写入

manage_dir=true ###目标主机若没有存在,则创建,若存在,则追加覆盖

key= 密钥

7 关于常用的模块

添加用户练习

1)shell 模块

要求在 web1 ,db2 主机上添加用户nb,设置nb的密码是123,要求nb第一次登录要修改密码。

[[email protected] ~]# ansible web1,db2  -m shell -a "useradd nb"
[[email protected] ~]# ansible web1 ,db2 -m shell -a "echo 123 | passwd --stdin nb"
[[email protected] ~]# ansible web1,db2   -m shell -a "chage -d 0 nb"
           

2)script模块

要求所有web上,添加用户wk,且wk和nb不能同时出现在同一台主机上,添加用户wk要求和nb一样。

[[email protected] ~]# vim user.sh

#!/bin/bash

id nb > /dev/null

if [ $? != 0 ];then

useradd wk

echo 123 | passwd --stdin wk

chage -d 0 wk

fi

[[email protected] ~]# ansible web -m script -a ‘user.sh’

3)copy模块

若需要修改集群文件都是相同的内容,可以将集群文件拷贝到ansible进行修改,再拷贝回去。

[[email protected] ~]# ansible all -m copy -a 'src=/etc/resolv.conf  dest=/etc/resolv.conf'
           

若集群文件的内容不一样,用以下两个模块

4)lineinfile 模块:用法类似sed,

path :要修改的文件

regexp :要修改的行

line :修改以后的样子

[[email protected] ~]# ansible cache -m  lineinfile -a 'path=/etc/sysconfig/network-scripts/ifcfg-eth0 regexp="^GATEWAY" line="GATEWAY\"192.168.1.1\""'
           

5)replace 模块 :类似awk

path :要修改的文件

regexp:要修改的位置

replace:修改以后的样子

[[email protected] ~]# ansible cache -m replace -a 'path=/etc/sysconfig/network-scripts/ifcfg-eth0 regexp="1\.1" replace="1.254"'
           

6)yum 模块

name 包名,使用逗号分隔

state 动作,installed removed

[[email protected] ~]# ansible db -m yum -a 'name=mariadb-server state=installed'
           

7)service 模块

name : 服务名

state : 动作 started , stopped, restarted, enabled yes | no

[[email protected] ~]# ansible db -m service -a 'name=mariadb  state=started enabled=yes'
[[email protected] ~]# systemctl is-enabled mariadb  //查看是否启动开机自启
           

8)setup 模块:获取客户端主机信息,作用是在编写ansible脚本时,可以进行判断

json:基于文本独立与语言的轻量级数据交换格式

轻量级:只有字典和集合两种格式

继续阅读