2 安装

控制主机上安装Ansible,受控主机上安装ssh和其他软件。

2.1 控制主机

2.1.1 先决条件

  • Unix、Linux、MacOS,暂不支持Windows
  • Python 2.6或2.7,暂不支持3.x
  • ssh客户端,例如openssh
  • 在Mac上,运行下面的命令,以增大打开文件数量上限:sudo launchctl limit maxfiles 1024 unlimited

2.1.2 MacOS

最好通过Homebrew安装:

brew install ansible

2.1.3 Linux

目前主流的Linux发行版都已经有Ansible的软件包。

Redhat/CentOS/Fedora系列

(1) 配置EPEL yum源

(2) 安装Ansible:

sudo yum install ansible

Ubuntu/Debian系列

(1) 安装Ansible PPA:

$ sudo apt-get install software-properties-common
$ sudo apt-add-repository ppa:ansible/ansible
$ sudo apt-get update

(2) 安装Ansible:

sudo apt-get install ansible

2.1.4 通过Python的包管理工具pip安装

Linux中推荐这种安装方式,因为这样安装的Ansible版本最新。

如果尚未安装pip,通过下面的命令安装:

sudo easy_install pip

安装Ansible:

sudo pip install ansible

如果你不想使用root账号来安装Ansible,那么可以使用一个工具pipsi把Ansible安全地安装到一个Python virtualenv中。

$ wget https://raw.githubusercontent.com/mitsuhiko/pipsi/master/get-pipsi.py
$ python get-pipsi.py
$ pipsi install ansible

并将~/.local/bin添加到你的PATH环境变量中。

想了解更多安装细节,参考:

2.2 受控主机

2.2.1 先决条件

  • Unix、Linux、MacOS、Windows
  • ssh
  • Python 2.5+,暂不支持3.x
  • 如果Python版本是2.4,需要同时安装python-simplejson
  • 如果受控主机启用了SELinux,又需要文件/模板复制功能的话,需要安装libselinux-python
  • 如果受控主机的默认Python版本不是2.x,在Inventory文件中为相应的主机设置ansible_python_interpreter变量,指向python 2.x版本的位置。

2.2.2 安装内容

无。不需要安装任何Ansible特定的组件。

2.3 建立一台用于测试的虚拟机

2.3.1 使用Vagrant来创建测试服务器

下文假设你的电脑上已经安装Vagrant和VirtualBox。

mkdir playbooks
cd playbooks
vagrant init ubuntu/trusty64
vagrant up

将创建一台ubuntu 14.04 64位的虚拟机,并启动之。

可以运行下面的命令ssh到虚拟机中:

vagrant ssh

输入exit退出ssh会话。

获取ssh连接详细信息:

vagrant ssh-config

主要部分内容类似:

HostName 127.0.0.1
User vagrant
Port 2222
IdentityFile /Users/lorinhochstein/dev/ansiblebook/ch01/playbooks/.vagrant/machines/default/virtualbox/private_key

2.3.2 将测试服务器信息配置到inventory文件中

编写inventory文件playbooks/hosts,包含测试服务器的host和ssh等信息:

testserver ansible_ssh_host=127.0.0.1 ansible_ssh_port=2222 \
ansible_ssh_user=vagrant \
ansible_ssh_private_key_file=.vagrant/machines/default/virtualbox/private_key

2.3.3 测试通过Ansible连接服务器

$ ansible testserver -i hosts -m ping”

如果执行成功,将产生类似下面的输出:

testserver | success >> {
    "changed": false,
    "ping": "pong"
}

2.3.4 使用ansible.cfg简化inventory文件的配置

编写playbooks/ansible.cfg文件,输入下面的内容:

[defaults]
hostfile = hosts
remote_user = vagrant
private_key_file = .vagrant/machines/default/virtualbox/private_key
host_key_checking = False

该文件指定了inventory文件的位置(hostfile),ssh使用的用户名(remote_user)和ssh私钥(private_key_file)。这样,inventory文件中就可以省去同样的内容,而且运行ansible-playbook命令时也不必通过i参数指定inventory文件的位置。inventory文件playbooks/hosts可简化为:

testserver ansible_ssh_host=127.0.0.1 ansible_ssh_port=2222 \

运行ansible-playbook命令时也不需要再指定-i [inventory file]参数:

ansible testserver -m ping

如果需要以root身份来执行,加上-s参数。例如:

ansible testserver -s -a "tail /var/log/syslog"