ansible

概览

Ansible is an open source community project sponsored by Red Hat

Ansible is an agentless automation tool that by default manages machines over the SSH protocol.

Once installed, Ansible does not add a database, and there will be no daemons to start or keep running. You only need to install it on one machine (which could easily be a laptop) and it can manage an entire fleet of remote machines from that central point. When Ansible manages remote machines, it does not leave software installed or running on them, so there’s no real question about how to upgrade Ansible when moving to a new version.

Ansible一般安装在控制节点上(Control node),被Ansible控制或管理起来的节点,称之为被管理节点(Managed node)

安装

########################################## 先决条件 ###############################################################
On the Control node, currently Ansible can be run from any machine with Python 2 (version 2.7) or Python 3 (versions 3.5 and higher) installed. This includes Red Hat, Debian, CentOS, macOS, any of the BSDs, and so on. Windows is not supported for the control node.

On the managed nodes, you need a way to communicate, which is normally SSH. By default this uses SFTP. If that’s not available, you can switch to SCP in ansible.cfg. You also need Python 2 (version 2.6 or later) or Python 3 (version 3.5 or later).

########################################## 开始安装 ###############################################################
需要启用EPEL源
yum install ansible
=============================================================================================================================================================================================
 Package                                                          Arch                                Version                                      Repository                           Size
=============================================================================================================================================================================================
Installing:
 ansible                                                          noarch                              2.9.9-1.el7                                  epel                                 17 M
Installing for dependencies:
 PyYAML                                                           x86_64                              3.10-11.el7                                  base                                153 k
 libyaml                                                          x86_64                              0.1.4-11.el7_0                               base                                 55 k
 python-babel                                                     noarch                              0.9.6-8.el7                                  base                                1.4 M
 python-backports                                                 x86_64                              1.0-8.el7                                    base                                5.8 k
 python-backports-ssl_match_hostname                              noarch                              3.5.0.1-1.el7                                base                                 13 k
 python-cffi                                                      x86_64                              1.6.0-5.el7                                  base                                218 k
 python-enum34                                                    noarch                              1.0.4-1.el7                                  base                                 52 k
 python-httplib2                                                  noarch                              0.9.2-1.el7                                  extras                              115 k
 python-idna                                                      noarch                              2.4-1.el7                                    base                                 94 k
 python-ipaddress                                                 noarch                              1.0.16-2.el7                                 base                                 34 k
 python-jinja2                                                    noarch                              2.7.2-4.el7                                  base                                519 k
 python-markupsafe                                                x86_64                              0.11-10.el7                                  base                                 25 k
 python-paramiko                                                  noarch                              2.1.1-9.el7                                  base                                269 k
 python-ply                                                       noarch                              3.4-11.el7                                   base                                123 k
 python-pycparser                                                 noarch                              2.14-1.el7                                   base                                104 k
 python-setuptools                                                noarch                              0.9.8-7.el7                                  base                                397 k
 python2-cryptography                                             x86_64                              1.7.2-2.el7                                  base                                502 k
 python2-jmespath                                                 noarch                              0.9.4-2.el7                                  epel                                 41 k
 python2-pyasn1                                                   noarch                              0.1.9-7.el7                                  base                                100 k
 sshpass                                                          x86_64                              1.06-2.el7                                   extras                               21 k
=============================================================================================================================================================================================

Installing Ansible with pip

Please make sure you have the latest version of pip before installing Ansible.

$ sudo pip install ansible

Getting Started

https://docs.ansible.com/ansible/latest/user_guide/intro_getting_started.html

################################################### 机器准备 ##################################
192.168.1.113  x1
192.168.1.114  x2
192.168.1.118  x3
x1机器安装了Ansible,3台机器已经互相做好免密,并且
ssh x1 echo hello
ssh x2 echo hello
ssh x3 echo hello
如上的yes应当已经搞好

##################################### 添加主机清单 ###################################################
cat << 'EOF' >> /etc/ansible/hosts
x1
x2
x3
EOF

##################################### 测试连通性 ###################################################
[root@x1 ~]# ansible all -m ping
x2 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
x3 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
x1 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

#####################################################  其它测试 ##################################
ansible all -a "/bin/echo hello"

Introduction to ad-hoc commands

直接在命令批量远程操作机器(ad-hoc),另外还有一种是书写playbook的方式

ansible [pattern] -m [module] -a "[module options]"

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

ansible webservers -m file -a "dest=/srv/foo/b.txt mode=600 owner=mdehaan group=mdehaan"

ansible all -m shell -a 'cat /etc/os-release'

ansible all  -m copy -a "src=/root/node_exporter-1.0.0.linux-amd64.tar.gz  dest=/tmp"
ansible all  -m copy -a "src=/root/node_exporter-1.0.0.linux-amd64.tar.gz  dest=/tmp"
上面的命令连续执行两次,可以发现第1次输出为黄色,表明系统已经做了修改,第2次输出为绿色表明无任何修改,可以看到Ansible的强大之处,具有幂等性

ansible foo.example.com -m yum -a "name=httpd state=installed"

主机清单

在Ansible里把需要管理的机器提前放到配置文件里,默认是/etc/ansible/hosts

################################################ 简单主机分组 ##################################
[webservers]
10.0.0.31
10.0.0.41
10.0.0.61
[web01]
10.0.0.8

################################################# IP地址合并 ##################################
添加三台主机至webserver
[webservers]
web1.as4k.com
web2.as4k.com
web3.as4k.com

添加三台主机至webserver
[webservers]
web[1:3].as4k.com

####################################### 直接加上密码验证 ##################################
web1.as4k.com ansible_ssh_pass='123456'
web2.as4k.com ansible_ssh_pass='123456'
web3.as4k.com ansible_ssh_pass='123456'

Ansible提示颜色信息说明

翔黄色:对远程节点进行相应修改 帽子绿:对远程节点不进行相应修改,或者只是对远程节点信息进行查看 深红色:操作执行命令有异常 浅紫色:表示对命令执行发出警告信息(可能存在的问题,给你一下建议)

剧本 Playbook

剧本是用人类易读语言YAML,来描述对被管理机器需要进行的一些列操作。模块是商店,被管理机器是原材料,剧本就是做菜手册。上面按顺序记录了,如何把被管理机器一步步打造成指定的样子。

########################################### 快速入门 ###################################################
test.yaml
# the first playbook
- hosts: nfs
  tasks:
    - name: copy files form m01 to nfs
      copy: src=/root/httpd.conf dest=/root/ mode=777
缩进必须是**两个**空格,nfs是在主机清单中定义好的名称,对应着相应的主机名。name是  
注释信息,copy是模块名称,后面是模块的参数。井号(#)用于注释。

ansible-playbook test.yaml

上面的命令也可以换行书写
- hosts: nfs
  tasks:
    - name: copy files form m01 to nfs
      copy: src=/root/httpd.conf
            dest=/root/
            mode=777

########################################### 在剧本中使用shell模块 ##################################
shell和command模块比较特殊,其后直接接命令,不再是key=value的形式。

tasks:
  - name: show ip address
    command: hostname -I

########################################### Handlers - 事件处理器 ##################################
Running Operations On Change,在很多时候我们需要配置一些服务启动,但这些服务的启动  
往往都是有条件的,那就是**当配置文件发生变化时**自动重启,这时就需要使用notify,  
只要检测到配置文件变化,即调用对应的handlers处理,示例如下:

- name: template configuration file
  template:
    src: template.j2
    dest: /etc/foo.conf
  notify:
     - restart memcached
     - restart apache

handlers:
    - name: restart memcached
      service:
        name: memcached
        state: restarted
    - name: restart apache
      service:
        name: apache
        state: restarted

使用handlers要注意,此时name名称就是一一对应的,不仅仅是注释。

########################################### 语法检查和预执行 ###################################################
YAML对空格的要求非常严格,可使用:

    ansible-playbook --syntax-check test.yaml

检查语法是否错误,还可以使用:

    ansible-playbook -C test.yaml

大C参数表示预执行,不会真正修改被管理机器的东西,会提前告知我们可能发生的变化,错误。

看一下哪些机器被该剧本管理:

    ansible-playbook playbook.yaml --list-hosts

执行时输出详细信息:

    ansible-playbook test.yaml -C --verbose

参考资料

ansible puppet saltstack三款自动化运维工具的对比
https://blog.csdn.net/qq_26848099/article/details/79400801

https://docs.ansible.com/