Ansible 安装 及 基础模块介绍

ansible 介绍

Ansible基于Python开发,集合了众多优秀运维工具的优点,实现了批量运行命令部署程序、配置系统等功能。默认通过SSH协议进行远程命令执行或下发配置,无需部署任何客户端代理软件,从而使得自动化环境部署变得更加简单。可同时支持多台主机并行管理,使得管理主机更加便捷。

ansible 安装

在管理端与 被管理端都要安装

yum install -y epel-release   ##安装epel源
yum install ansible -y

ansible --version          ##查看ansible版本

/etc/ansible 文件夹下

ansible.cfg    ##ansible的配置文件

hosts    ##ansible的主仓库,用于存储需要管理的远程主机的相关信息

roles     ##角色

cd /etc/ansible
vi hosts       ##配置主机清单
[aaa]
192.168.x.x      ##被管理端的IP
[bbb]
192.168.x.x

ssh-keygen -t rsa      ##生成秘钥
ssh-copy-id [email protected]
 ##配置密钥对验证

---------免交互代理--------------

ssh-agent bash
ssh-add

ansible 基础模块 及 实例

------command模块------
命令格式:ansible [主机] [-m 模块] [-a args]
ansible-doc -l     ##列出所有已安装的模块 注:按q退出

ansible-doc -s yum   ##-s列出yum模块描述信息和操作动作

ansible 192.168.x.x -m command -a 'date'  ##指定ip执行date

ansible aaa -m command -a 'date'       ##指定设置好的主机执行date

ansible all -m command -a 'date'        ##所有hosts主机执行date命令

ansible all -a 'ls /'      如果不加-m模块,则默认运行command模块

-----cron模块------

两种状态(state):present表示添加(可以省略),absent表示移除。

ansible-doc -s cron      ##查看cron模块信息

ansible aaa -m cron -a 'minute="*/1" job="/bin/echo heihei" name="test cron job"'
## 添加计划

ansible aaa -a 'crontab -l'  ##显示计划列表

ansible aaa -m cron -a 'name="test cron job" state=absent'    ##移除计划任务,假如该计划任务没有取名字,name=None即可

-----user模块------

user模块是请求的是useradd, userdel, usermod三个指令

ansible-doc -s user

ansible aaa -m user -a 'name="test01"'    ##创建用户test01

ansible aaa -m command -a 'tail /etc/passwd'   ##查看用户

ansible aaa -m user -a 'name="test01" state=absent'    ##删除用户test01

-----group模块-----

group模块请求的是groupadd, groupdel, groupmod 三个指令。

ansible-doc -s group

ansible aaa -m group -a 'name=mysql gid=306 system=yes'     ##添加组

ansible aaa -a 'tail /etc/group'    ##查看组

ansible aaa -m user -a 'name=test01 uid=306 system=yes group=mysql'   ##为用户指定组

ansible aaa -a 'id test01'     ##查看用户

------copy模块--------

ansible-doc -s copy

ansible aaa -m copy -a 'src=/etc/fstab dest=/opt/fstab.back owner=root mode=640'
## 将管理端/etc/fstab 复制到 被管理端的 /opt/fstab.bak  拥有者为root,权限设置为640

ansible aaa -a 'ls -l /opt'   ##查看复制情况

ansible aaa -m copy -a 'content="hello heihei!"
dest=/opt/fstab.back'  ##将hello heihei!写入/opt/fstab.back

ansible aaa -a 'cat /opt/fstab.back'   ##查看写入情况

------file模块--------
ansible-doc -s file

ansible aaa -m user -a 'name=abc system=yes'    ##创建用户

ansible aaa -m group -a 'name=abc system=yes'   ##创建组

ansible aaa -m file -a 'owner=abc group=abc mode=644 path=/opt/fstab.back'        ##修改文件的属主属组权限等

ansible aaa -m file -a 'path=/opt/fstab.link src=/opt/fstab.back state=link'      ##设置/opt/fstab.link为/opt/fstab.back的链接文件

ansible aaa -m file -a "path=/opt/fstab.back state=absent"           ##删除一个文件

ansible aaa -m file -a "path=/opt/test state=touch"             ##创建一个文件
ansible aaa -m file -a 'path=/opt/temp state=directory mode=755' ##创建目录

-----ping模块-------

ansible all -m ping

猜你喜欢

转载自blog.51cto.com/13625924/2154694