骏马金龙 (新博客:www.junmajinlong.com)

网名骏马金龙,钟情于IT世界里的各种原理和实现机制,强迫症重症患者。爱研究、爱翻译、爱分享。特借此一亩三分田记录自己成长点滴!!!

Ansible系列(一):基本配置和使用

我写了更完善的Ansible专栏文章:一步到位玩儿透Ansible

Ansible系列文章:http://www.cnblogs.com/f-ck-need-u/p/7576137.html


Ansible是一种批量、自动部署工具,不仅可以批量,还可以自动。它主要基于ssh进行通信,不要求客户端(被控制端)安装ansible。

1.1 安装Ansible

安装方法有多种,可以下载源码后编译安装,可以从git上获取资源安装,也可以rpm包安装。rpm安装需要配置epel源。

cat <<eof>>/etc/yum.repos.d/my.repo
[epel]
name=epel
baseurl=http://mirrors.aliyun.com/epel/7Server/x86_64/
enable=1
gpgcheck=0
eof

后面几篇文章用到的环境。

主机描述IP地址主机名操作系统
ansible6_server1 192.168.100.150 server1.longshuai.com CentOS 6.6
ansible6_node1 192.168.100.59 node1.longshuai.com CentOS 6.6
ansible6_node2 192.168.100.60 node2.longshuai.com CentOS 6.6
ansible6_node3 192.168.100.61 node3.longshuai.com CentOS 6.6
ansible7_server2 192.168.100.62 server2.longshuai.com CentOS 7.2
ansible7_node1 192.168.100.63 anode1.longshuai.com CentOS 7.2
ansible7_node2 192.168.100.64 anode2.longshuai.com CentOS 7.2
ansible7_node3 192.168.100.65 anode3.longshuai.com CentOS 7.2

经多次测试,CentOS 6上安装ansible 2.3版本有可能会非常慢,需要将ansible执行的结果使用重定向或者-t选项保存到文件中,下次执行才会快。

shell> yum -y install ansible
/etc/ansible/ansible.cfg
/etc/ansible/hosts
/etc/ansible/roles
/usr/bin/ansible
/usr/bin/ansible-2
/usr/bin/ansible-2.6
/usr/bin/ansible-connection
/usr/bin/ansible-console
/usr/bin/ansible-console-2
/usr/bin/ansible-console-2.6
/usr/bin/ansible-doc
/usr/bin/ansible-doc-2
/usr/bin/ansible-doc-2.6
/usr/bin/ansible-galaxy
/usr/bin/ansible-galaxy-2
/usr/bin/ansible-galaxy-2.6
/usr/bin/ansible-playbook
/usr/bin/ansible-playbook-2
/usr/bin/ansible-playbook-2.6
/usr/bin/ansible-pull
/usr/bin/ansible-pull-2
/usr/bin/ansible-pull-2.6
/usr/bin/ansible-vault
/usr/bin/ansible-vault-2
/usr/bin/ansible-vault-2.6

使用ansible-doc可以列出相关的帮助。

ansible-doc -h
Usage: ansible-doc [options] [module...]

Options:
  -a, --all             Show documentation for all modules
  -h, --help            show this help message and exit
  -l, --list            List available modules
  -M MODULE_PATH, --module-path=MODULE_PATH
                        specify path(s) to module library (default=None)
  -s, --snippet         Show playbook snippet for specified module(s)
  -v, --verbose         verbose mode (-vvv for more, -vvvv to enable
                        connection debugging)
  --version             show program's version number and exit

其中"-l"选项用于列出ansible的模块,通常结合grep来筛选。例如找出和yum相关的可用模块。

ansible-doc -l | grep yum
yum                                Manages packages with the `yum' package manager   
yum_repository                     Add or remove YUM repositories

再使用"-s"选项可以获取指定模块的使用帮助。例如,获取yum模块的使用语法。

ansible-doc -s yum
- name: Manages packages with the `yum' package manager
  action: yum
      conf_file           # The remote yum configuration file to use for the transaction.
      disable_gpg_check   # Whether to disable the GPG checking of signatures of packages being  
                            installed. Has an effect only if state is `present' or  `latest'.
      disablerepo         # `Repoid' of repositories to disable for the install/update operation. 
                            These repos will not persist beyond the transaction. When specifying 
                            multiple repos, separate them with a ",".
      enablerepo          # `Repoid' of repositories to enable for the install/update operation. 
                            These repos will not persist beyond the transaction. When specifying 
                            multiple repos, separate them with a ",".
      exclude             # Package name(s) to exclude when state=present, or latest
      installroot         # Specifies an alternative installroot, relative to which all packages
                            will be installed.
      list                # Package name to run the equivalent of yum list <package> against.
      name=               # Package name, or package specifier with version, like `name-1.0'. 
                            When using state=latest, this can be '*' which means run: yum -y update.
                            You can also pass a url or a local path to a rpm file(using state=present).
                            To operate on several packages this can accept a comma separated list of
                            packages or (as of 2.0) a list of packages.
      skip_broken         # Resolve depsolve problems by removing packages that are causing problems
                            from the trans‐ action.
      state               # Whether to install (`present' or `installed', `latest'), or remove 
                            (`absent' or `removed') a package.
      update_cache        # Force yum to check if cache is out of date and redownload if needed. Has
                            an effect only if state is `present' or `latest'.
      validate_certs      # This only applies if using a https url as the source of the rpm.
                            e.g. for localinstall. If set to `no', the SSL certificates will not be 
                            validated. This should only set to `no' used on personally controlled 
                            sites using self-signed certificates as it avoids verifying the source 
                            site. Prior to 2.1 the code worked as if this was set to `yes'.

例如使用yum安装unix2dos包。

ansible 192.168.100.60 -m yum -a "name=unix2dos state=present"

其中192.168.100.60是被ansible远程控制的机器,即要在此机器上安装unix2dos,下一小节将说明如何指定待控制主机。"-m"指定模块名称,"-a"用于为模块指定各模块参数,例如name和state。

ansible命令选项和各模块的使用方法见:Ansible系列(二):选项和常用模块

1.2 配置ansible

1.2.1 环境配置

Ansible配置以ini格式存储配置数据,在Ansible中几乎所有配置都可以通过Ansible的Playbook或环境变量来重新赋值。在运行Ansible命令时,命令将会按照以下顺序查找配置文件。

  • ANSIBLE_CONFIG:首先,Ansible命令会检查环境变量,及这个环境变量指向的配置文件。
  • ./ansible.cfg:其次,将会检查当前目录下的ansible.cfg配置文件。
  • ~/.ansible.cfg:再次,将会检查当前用户home目录下的.ansible.cfg配置文件。
  • /etc/ansible/ansible.cfg:最后,将会检查在用软件包管理工具安装Ansible时自动产生的配置文件。

1、使用化境变量方式来配置

大多数的Ansible参数可以通过设置带有ANSIBLE_开头的环境变量进行配置,参数名称必须都是大写字母,如下配置:

export ANSIBLE_SUDO_USER=root

设置了环境变量之后,ANSIBLE_SUDO_USER就可以在后续操作中直接引用。

2、设置ansible.cfg配置参数

Ansible有很多配置参数,以下是几个默认的配置参数:

inventory = /etc/ansible/hosts
library = /usr/share/my_modules/
forks = 5
sudo_user = root
remote_port = 22
host_key_checking = False
timeout = 20
log_path = /var/log/ansible.log

inventory:该参数表示inventory文件的位置,资源清单(inventory)就是Ansible需要连接管理的一些主机列表。
library:Ansible的所有操作都使用模块来执行实现,这个library参数就是指向存放Ansible模块的目录。
forks:设置默认情况下Ansible最多能有多少个进程同时工作,默认5个进程并行处理。具体需要设置多少个,可以根据控制端性能和被管理节点的数量来确定。
sudo_user:设置默认执行命令的用户,也可以在playbook中重新设置这个参数。
remote_port:指定连接被管理节点的管理端口,默认是22,除非设置了特殊的SSH端口,否则不需要修改此参数。
host_key_checking:设置是否检查SSH主机的密钥。可以设置为True或False。即ssh的主机再次验证。
timeout:设置SSH连接的超时间隔,单位是秒。
log_path:Ansible默认不记录日志,如果想把Ansible系统的输出记录到日志文件中,需要设置log_path。需要注意,模块将会调用被管节点的(r)syslog来记录,执行Ansible的用户需要有写入日志的权限。

1.2.2 SSH互信配置

将ansible server的ssh公钥分发到各被管节点上。

在ansible6_server1和ansible_server2上:

ssh-keygen -t rsa -f ~/.ssh/id_rsa -N ''
ssh-copy-id root@192.168.100.59
ssh-copy-id root@192.168.100.60
ssh-copy-id root@192.168.100.61
ssh-copy-id root@192.168.100.62
ssh-copy-id root@192.168.100.63
ssh-copy-id root@192.168.100.64
ssh-copy-id root@192.168.100.65
ssh-copy-id root@192.168.100.150

也可以使用ansible自身来批量添加密钥到被控节点上。使用ansible的authorized_key模块即可。见后文常见模块介绍部分。

以下是借助expect工具实现非交互式的ssh-copy-id,免得总是询问远程用户的登录密码。

# 安装expect
[root@server2 ~]# yum -y install expect

# expect脚本
[root@server2 ~]# cat auto_sshcopyid.exp 
#!/usr/bin/expect

set timeout 10
set user_hostname [lindex $argv 0]
set password [lindex $argv 1]

spawn ssh-copy-id $user_hostname
expect {
        "(yes/no)?"
        {
                send "yes\n"
                expect "*password: " { send "$password\n" }
        }
        "*password: " { send "$password\n" }
}

expect eof

# 批量调用expect的shell脚本
[root@server2 ~]# cat sshkey.sh 
#!/bin/bash

ip=`echo -n "$(seq -s "," 59 65),150" | xargs -d "," -i echo 192.168.100.{}`
password="123456"
#user_host=`awk '{print $3}' /root/.ssh/id_rsa.pub`

for i in $ip;do
        /root/auto_sshcopyid.exp root@$i $password &>>/tmp/a.log
        ssh root@$i "echo $i ok"
done

# 执行shell脚本配置互信
[root@server2 ~]# chmod +x /root/{sshkey.sh,auto_sshcopyid.exp}
[root@server2 ~]# ./sshkey.sh

1.2.3 简单测试

向默认的inventory文件/etc/ansible/hosts中添加上几个被管节点清单。

在ansible6_server1上:

cat >>/etc/ansible/hosts<<eof
192.168.100.59
192.168.100.60
192.168.100.61
192.168.100.62
192.168.100.63
192.168.100.64
192.168.100.65
[centos6]
192.168.100.59
192.168.100.60
192.168.100.61
[centos7]
192.168.100.63
192.168.100.64
192.168.100.65
[centos:children]
centos6
centos7
eof

在ansible7_server2上:

cat >>/etc/ansible/hosts<<eof
192.168.100.150
192.168.100.59
192.168.100.60
192.168.100.61
192.168.100.63
192.168.100.64
192.168.100.65
[centos6]
192.168.100.59
192.168.100.60
192.168.100.61
[centos7]
192.168.100.63
192.168.100.64
192.168.100.65
[centos:children]
centos6
centos7
eof

使用ping模块测试被管节点。能成功,说明ansible能控制该节点。

ansible 192.168.100.59 -m ping
ansible centos6 -m ping
192.168.100.59 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.100.60 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.100.61 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

如果要指定非root用户运行ansible命令,则加上"--sudo"或"-s"来提升为sudo_user配置项所指定用户的权限。

ansible webservers -m ping -u ansible --sudo

或者使用become提升权限。

ansible webservers -m ping -b --become-user=root --become-method=sudo

1.3 inventory

inventory用于定义ansible要管理的主机列表,可以定义单个主机和主机组。上面的/etc/ansible/hosts就是默认的inventory。下面展示了inventory常用的定义规则。

cat -n /etc/ansible/hosts
1 192.168.100.59:22
2 192.168.100.60 ansible_ssh_pass='123456' ansible_ssh_port=22
3 [nginx]
4 192.168.100.5[7:9]
5 [nginx:vars]
6 ansible_ssh_pass='123456'
7 [webservers:children]
8 nginx

第一行和第二行单独定义主机,第一行带上了连接被管节点的端口,第二行带上了单独传递给ssh的参数,分别是ssh连接时的登录远程用户的密码参数和ssh的连接端口。
第三行和第四行定义的是nginx主机组,该组中包含了192.168.100.57到59这3台主机。还支持字母的扩展,如"web[a-d]"。
第五行和第六行定义了要传递给nginx主机组的变量。若定义为"[all:vars]"或"[*:vars]"则表示传递给所有主机的变量。
第七和第八行定义了一个新的主机组webservers,该组的组成员有nginx组。

可以指定多个inventory配置文件,只需在ansible的配置文件如/etc/ansible/ansible.cfg中将inventory指令设置为对应的文件或目录即可,如果是目录,那么此目录下的所有文件都是inventory文件。

inventory文件中可以使用一些内置变量,绝大多数ansible的连接和权限变量都可以在此使用,见ansible命令解释。常见的有:

  • ansible_ssh_host: ansible使用ssh要连接的主机。
  • ansible_ssh_port: ssh的端口。默认为22。
  • ansible_ssh_user: ssh登录的用户名。默认为root。
  • ansible_ssh_pass: ssh登录远程用户时的认证密码。
  • ansible_ssh_private_key_file: ssh登录远程用户时的认证私钥。(?)
  • ansible_connection: 使用何种模式连接到远程主机。默认值为smart(智能),表示当本地ssh支持持久连接(controlpersist)时采用ssh连接,否则采用python的paramiko ssh连接。
  • ansible_shell_type: 指定远程主机执行命令时的shell解析器,默认为sh(不是bash,它们是有区别的,也不是全路径)。
  • ansible_python_interpreter: 远程主机上的python解释器路径。默认为/usr/bin/python。
  • ansible_*_interpreter:使用什么解释器。例如,sh、bash、awk、sed、expect、ruby等等。

其中有几个参数可以在配置文件ansible.cfg中指定,但指定的指令不太一样,以下是对应的配置项:

  • remote_port: 对应于ansible_ssh_port。
  • remote_user: 对应于ansible_ssh_user。
  • private_key_file: 对应于ansible_ssh_private_key_file。
  • excutable: 对应于ansible_shell_type。但有一点不一样,excutable必须指定全路径,而后者只需指定basename。

如果定义了"ansible_ssh_host",那么其前面的主机名就称为别名。例如,以下inventory文件中nginx就是一个别名,真正连接的对象是192.168.100.65。

nginx ansible_ssh_host=192.168.100.65 ansible_ssh_port=22

当inventory中有任何一台有效主机时,ansible就默认隐式地可以使用"localhost"作为本机,但inventory中没有任何主机时是不允许使用它的,且"all"或"*"所代表的所有主机也不会包含localhost。例如:

ansible localhost -i /path/to/inventory_file -m MODULE -a "ARGS"
ansible all -i /path/to/inventory_file -m MODULE -a "ARGS"
ansible * -i /path/to/inventory_file -m MODULE -a "ARGS"

inventory_hostname是ansible中可以使用的一个变量,该变量代表的是每个主机在inventory中的主机名称。例如"192.168.100.59"。这是目前遇到的第一个变量。

posted @ 2017-09-19 18:03  骏马金龙  阅读(11362)  评论(1编辑  收藏  举报