ansible基本概念
ansible作用
1、实现远程连接主机
2、批量配置,批量操作,ansible可以对主机进行组划分,也可以把名下所有的主机进行划分,进行批量的操作。
3、远程自动化运维(脚本------playbook)
ansible是什么
ansible是基于python语言开发的,配置管理和部署应用的工具。批量的配置、部署、管理上百台主机。
ansible只要在一台主机上就可以对其他主机进行操作。
ansible的工作模式
没有固定的客户端这一说法,不是c/s。使用模块来进行工作,ansible的模块有很多,真正在目标主机上执行任务的是模块。
ansible的特性
幂等性,计算机种的概念,在幂等操作中,无论执行多少次,结果都是一样的,多次执行相同的操作,不会产生不同的结果。
在ansible中,如果你的操作是符合幂等性,那么不会对目标主机产生额外的副作用。
ansible的组件
1、lnventory:主机清单,主机组。
2、modules:模块
3、plugins:插件
4、playbooks:剧本(脚本)
ansible的优点
- 部署快,只要能上网,或者有源码包,安装部署很简单。
- 基于yuml格式编写的脚本。
- 同一台服务器上多次执行同一个任务没有任何副作用。
ansible的缺点
- 语法要专门学
- 主机和目标主机必须都是linux,至少有两台服务器,主机和server。
安装ansible
架构
doc1:192.168.254.40,ansible
doc2:192.168.254.41
配置doc1
apt -y install ansible #下载 ansible
设置密钥对

apt -y install sshpass #下载sshpass
传送密钥对

配置/etc/ansible/hosts文件,用来分主机组


补充知识

- 表示IP地址192.168.233.10-192.168.233.19
配置文件ansible.cfg
创建两个配置文件ansible.cfg和hosts,具体配置如下


- host_key_checking = False #禁止使用ssh的密钥检查
- inventory = /etc/ansible/hosts #指定主机清单的文件
- forks = 20 #同时可以对多少主机进行配置,默认是5,可以提高执行的速度
- pipelining = True #减少对ssh会话中的操作,提高性能
- strategy = free #任务会立即对下一个主机并行执行,不用等待其他主机完成
- retry_files_enabled = False #如果任务失败,禁用自动重试的功能

- 所有主机自动使用root用户和123密码
- 所有主机自动使用22端口
有这两个配置文件可以不需要进行设置密钥对,直接添加IP地址到相应的主机组,直接执行命令。

ansible模块
command模块
默认模块,就是在目标主机执行命令,不支持管道符,也不能使用重定向。


- ansible:固定开头
- -m:指定模块
- -a:指定参数(指定操作)
- 'date':具体要执行的命令


- 无法使用cd,需要使用chdir
判断文件是否存在

- creates: 判断指定的文件是否存在,如果存在,不执行后续的操作。
- removes:判断指定的文件是否存在,如果存在,执行后面的操作。
shell模块
就是command模块的升级,但是可以使用管道符,可以重定向还可以使用连接符链接多个命令。


- &&:逻辑且,所有的命令都必须执行成功才算完成
- ;:逻辑或,成功一个即可


cron模块
-m cron
minute/hour/day/month/weekday:分/时/日/月/周
name:计划任务的名称
job:计划的执行的命令
1、创建定时任务9月1号8.30执行ls /opt命令,定时任务名字是zw1

2、删除定时任务zw1

user和group模块
-m user
-m group
name 用户名或者组名,必有参数
state=present | absent
创建 删除
shell:默认就是/bin/bash
create_home yes | no:替换用户的家目录
remove=yes | no:删除用户时,是否删除家目录
password:创建用户的登录密码
system yes | no:表示该用户是否是系统用户
1、创建用户zw1

2、修改家目录和删除用户

3、创建组和删除组和user一样

copy复制模块
dest:文件复制到目标主机的位置
src:源文件,要复制的文件
mode:修改目标文件权限
owner:文件的所有者
group:文件的所在组
content:复制输出的内容到目标主机,使用content就不能使用src
1、复制本机文件到目标主机目录下

2、复制内容到目标主机目录下的文件中

3、复制本机目录到目标主机目录

- 如果复制目录,源文件是目录,那么目标的路径也必须是目录才可以复制
file 模块
和copy模块有相似之处,有owner、group、mode。
path:目标主机的文件路径
state:Link做软连接,touch创建,absent删除
1、给目标主机创建文件

2、给目标主机创建软连接

- src:指定创建的文件为软连接
3、给目标主机删除文件

hostname模块
设置目标主机的主机名

ping模块
测试与目标主机连通性

安装/卸载模块apt/yum
给目标主机安装软件

给目标主机卸载软件

service模块
对服务状态继续控制
也可以用command模块或者shell模块完成------------systemctl
name=软件名
enabled=true------开机自启
state=started | stopped | restarted 开停 重启
1、开启目标主机的httpd服务,以及修改访问页和访问

2、开启nginx服务并设置成开机自启

iptables模块
1、禁用web1里面主机的80端口

2、删除上面的策略

firewalld模块(centos)
1、目标主机开放80端口(TCP 协议),并将其应用于公共区域,设置为永久生效,并立即应用。

2、关闭上面的策略

script模块
指定本地的脚本,然后脚本中的命令在目标主机执行,结果也是输出到目标主机。

setup模块
通过facts组件收集节点信息,查看目标主机的配置信息。
1、查看目标主机地址信息

2、查看目标主机cpu信息

查看目标主机内核信息
