三、Ansible基础

一、安装Ansile

# Redhat/CentOS Linux上,Ansible目前放在的epel源中
# Fedora默认源中包含ansible,直接安装包既可
[root@master ~]# yum install epel-release
[root@master ~]# yum install ansible -y

配置Ansible管理节点和主机的连接(master)

[root@node1 ~]# ssh-keygen    # 生成ssh key
# 拷贝ssh key到远程主机,ssh的时候就不需要输入密码了
[root@node1 ~]# ssh-copy-id root@10.211.55.12
 # ssh的时候不会提示是否保存key
[root@node1 ~]# ssh-keyscan 10.211.55.12 >>~/.ssh/known_hosts
# 10.211.55.12 SSH-2.0-OpenSSH_6.6.1
# 10.211.55.12 SSH-2.0-OpenSSH_6.6.1

二、Ansible的 Host Inventory

什么是Host Invenory(主机目录,主机清单)

Host Inventory是配置文件,用来告诉Ansible需要管理那些主机。并且把这些主机根据需分类。
可以根据用途分类:数据库节点,服务节点等;根据地点分类:中部,西部机房。

Host Inventory配置文件

默认的配置文件是:/etc/ansible/hosts

案例:

最简单的host文件:

192.168.1.50
aserver.example.org
bserver.example.org

带分类的hosts文件:

mail.example.com
[webservers]
foo.example.com
bar.example.com
[dbservers]
one.example.com
two.example.com
three.example.com

三、Ansible用命令管理主机

语法

Ansible 提供了一个命令行工具,在官方文档中起给命令行起了一个名字叫Ad-Hoc Commands.

ansible命令的格式是:

ansible <host-pattern> [options]

检查ansible安装环境

$ansible all -m ping -u bruce

执行命令

在所有的server上,以当前bash的同名用户,在远程主机执行"echo bash"

$ansible all -a "/bin/echo hello"

拷贝文件

拷贝文件/etc/host到远程机器(组)atlanta,位置为/tmp/hosts

$ansible web -m copy -a "src=/etc/hosts dest=/tmp/hosts"

安装包

远程机器(组)webservers安装yum包

$ansible web -m yum -a "name=acne state-present"

添加用户

$ansible all -m user -a "name=foo password=<crypted password here>"

下载git包

$ ansible web -m git -a "repo=git://foo.example.org/repo.git dest=/srv/myapp version=HEAD"

起服务

$ ansible web -m service -a "name=httpd state=started"

并行执行

启动10个并行进行执行重起

$ansible lb -a "/sbin/reboot" -f 10

查看远程主机的全部系统信息!!!
$ ansible all -m setup


posted @ 2018-07-22 10:12  云原生运维社区  阅读(387)  评论(0编辑  收藏  举报