ansible的常用命令
首先安装
sudo ape-get install ansible
然后分发ssh密钥,参考ssh分发。不想用密钥的用密码也是可以的
修改配置文件
vim /etc/ansible/hosts
在文件中添加主机
[sa] 149.129.95.148 39.99.132.160
也可以自定义hosts 文件
在命令中执行文件路径 : -i hostspath
对于hosts 文件的编写其中参数可以参考
ansible_ssh_host # 目标主机地址 ansible_ssh_port # 目标主机端口,默认22 ansible_ssh_user # 目标主机用户 ansible_ssh_pass # 目标主机ssh密码 ansible_sudo_pass # sudo密码 ansible_sudo_exe ansible_connection # 与主机的连接类型,比如:local,ssh或者paramiko ansible_ssh_private_key_file # 私钥地址 ansible_shell_type # 目标系统的shell类型 ansible_python_interpreter # python版本
写法:
[sa] vp1 ansible_ssh_host=192.168.1.187 ansible_ssh_port=11100 vp2 ansible_ssh_host=192.168.1.179 ansible_ssh_port=22200
sa属于标签
-u user1 可指定用户名称 ,默认root
ping 模块
ansible sa -m ping
判断是否能够连通主机
lineinfile 模块
修改配置文件
ansible sa -m lineinfile -a "dest=/root/test.txt regexp='bbb' line='bbbbbbb'"
把主机的/root/test.txt文件中的bbb替换为bbbbbbb
copy模块
用法
src :本地文件路径,可以是绝对和相对路径
dest: 不可省,如果src是目录,则dest也是目录。只能是绝对路径
group:指明文件归属组
mode:指明权限
owner:指明拥有者
content:直接写出内容,并将其复制给远程主机
如果直接写出要复制到远端主机的内容,把src=路径修改为content='内容'
command&shell模块
前者不支持管道
ansible sa -m command -a "python test.py"
ansible sa -m shell -a "python test.py"
cron 模块
用来设置corntab定时任务
用法:
job 执行命令
state 添加还是删除任务,present(添加),absent(删除),默认是添加
name 设置crontab条目的名称
minute, hour, day, month 设置运行时间
ansible da model -m cron -a "name=sync_time job='/bin/ntpdate 192.168.1.187 > /dev/null' minute=*/5"
file 模块
创建文件链接、文件夹、删除文件等
创建连接
ansible sa -m file -a "path=/tmp/fstab.link src=/tmp/fstab state=link"
创建目录
ansible sa -m file -a "path=/tmp/ansible_test state=directory"
删除文件
ansible sa -m file -a "path=/tmp/aaa state=absent"
fetch 模块
从远端获取文件
用法:
src=远端文件
dest= 保存文件到的目录
ansible sa -m fetch -a "dest=/tmp src=/etc/fstab"
group 模块
分组添加删除
用法:
gid:指明组ID
name:指明组名
state:创建或者删除,present(创建,默认选项),absent(删除)
system:yes表明创建系统用户,默认是false
ansible sa -m group -a "name=test gid=2002"
user 模块
管理用户
用法:
name= :用户的名称
uid :指明用户id号
state :present创建用户,absent删除用户
createhome :默认为yes,如果为no则不创建用户家目录
home :设置用户家目录
group :指明用户主组
groups : 指明用户附加组
password :用户加密后的值
shell : 设置用户使用的shell
absible sa -m user -a "name=a01 shell=/bin/sh uid=2003 group=2002"
yum 包管理模块
用法:
name= : 指明管理程序包包名
state :present,installed表示安装程序包,latest表明安装最新版本;absent和removed表示卸载安装包。默认是安装最新版本
ansible sa -m yum -a "name=nginx state=present"
apt 包管理模块
用法:
name= : 指明管理程序包包名
state :present,installed表示安装程序包,latest表明安装最新版本;absent和removed表示卸载安装包。默认是安装最新版本
ansible sa -m apt -a "name=nginx state=present "
service : 管理服务
用法:
name= :管理服务的名称
enabled : 是否开机启动
state : started/stopped启动或停止服务;restart重启服务;reloaded重新加载配置文件,注意如果服务没有起来会启动服务。
-became=true 表示提权
-K 表示输入密码(中断输入)
unarchive:解压模块
用法:
src=文件路径
dest=解压路径
copy: no,yes (默认是yes,yes是指从ansible主机找文件解压复制到目标机器。no只在目标机器找压缩文件,解压)
mode:指明权限
owner:指明拥有者