Ansible

介绍:

(1)Ansible不需要安装客户端,通过sshd去通信(无密钥登录)。

(2)Ansible基于模块工作,模块可以由任何语言开发。

(3)Ansible不仅支持命令行使用模块,也支持编写Yaml格式的playbook,易于编写和阅读。

(4)Ansible安装十分简单,CentOS上可直接Yum安装。

(5)Ansible有提供UI(浏览器图形化)www.ansible.com/tower,收费的官方文档 http://docs.ansible.com/ansible/latest/index.html。

         Ansible已经被RedHat公司收购,它在Github(https://github.com/ansible/ansible)上是一个非常受欢迎的开源软件。

一 安装

(1) 环境准备

在两台机器上关闭防火墙和SELinux,并修改/etc/hosts文件。

# systemctl stop firewalld
# systemctl disable firewalld
Removed symlink /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
Removed symlink /etc/systemd/system/basic.target.wants/firewalld.service.
# setenforce 0
# vi /etc/selinux/config 
…
#     disabled - No SELinux policy is loaded.
SELINUX=disabled    //将此处改为disabled
# SELINUXTYPE= can take one of three two values:
…
# vi /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.200.71 ansible-test01    //添加两台主机的IP和主机名
192.168.200.72 ansible-test02

(2)安装 Ansible

准备两台机器anisble-01anisble-02,只需要在anisble-01上安装Ansible,先安装epel仓库。

# yum install epel-release -y 
# yum install -y ansible
# ansible --version
ansible 2.9.25
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, Nov 20 2015, 02:00:19) [GCC 4.8.5 20150623 (Red Hat 4.8.5-4)]

(3) 免密配置

anisble-01上生成密钥对ssh-keygen -t rsa,把公钥放到anisble-02上,设置密钥认证。

注意:需要将本机也配置免密。

# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
d6:b2:50:b6:24:51:86:2c:ac:08:70:c0:78:2f:b4:4f root@ansible-test01
The key's randomart image is:
+--[ RSA 2048]----+
|*... ..oo        |
|ooo o oo         |
|.+ + .. +        |
|. + E  = o       |
|   +  . S .      |
|    .  o o       |
|        .        |
|                 |
|                 |
+-----------------+
# ssh-copy-id 192.168.200.72 
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '192.168.200.72(192.168.200.72)' can't be established.
ECDSA key fingerprint is SHA256:PpgkRDlxK0Fo7pnSeJyYC9p4KYbIgATP7gM+4G5UAIg.
ECDSA key fingerprint is MD5:54:a9:14:91:fa:fc:cc:ee:30:0d:a3:5b:05:b9:97:b2.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.200.72's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '192.168.200.72'"
and check to make sure that only the key(s) you wanted were added.
# ssh 192.168.200.72
Last login: Sun Jan  9 05:57:10 2022 from 192.168.200.0
# exit
logout
Connection to 192.168.200.72 closed.

(4) 主机组设置

/etc/ansible/hosts文件中添加本机和另一台机器的IP:

# grep ^[^#] /etc/ansible/hosts
[testhost]
192.168.200.71
192.168.200.72

说明:testhost为自定义的主机组名字,下面两个IP为组内的机器IP。

二 Ansible 远程执行命令

这样就可以批量执行命令了。这里的testhost为主机组名,-m后边是模块名字,-a后面是命令。当然我们也可以直接写一个IP,针对某一台机器来执行命令。

# ansible testhost -m command -a "hostname"
192.168.200.71 | CHANGED | rc=0 >>
ansible-test01
192.168.200.72 | CHANGED | rc=0 >>
ansible-test02
# ansible 192.168.200.72 -m command -a "hostname"
192.168.200.72 | CHANGED | rc=0 >>
ansible-test02

Ansible 拷贝文件或目录

源目录会放到目标目录下面去,如果目标指定的目录不存在,它会自动创建。如果拷贝的是文件,如果dest指定的名字和源不同,并且它不是已经存在的目录,相当于拷贝过去后又重命名。但相反,如果dest是目标机器上已经存在的目录,则会直接把文件拷贝到该目录下面。

# ansible 192.168.200.72 -m copy -a "src=/etc/passwd  dest=/tmp/123"
192.168.200.72| CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "872fb7a1e755f9779b5860171b7657213946aa73", 
    "dest": "/tmp/123", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "61d58da591436e3a12f54ea96276d298", 
    "mode": "0644", 
    "owner": "root", 
    "size": 1146, 
    "src": "/root/.ansible/tmp/ansible-tmp-1641727127.76-2466-133689255775703/source", 
    "state": "file", 
    "uid": 0
}

这里的/tmp/123和源机器上的/etc/passwd是一致的,但如果目标机器上已经有/tmp/123目录,则会再/tmp/123目录下面建立passwd文件。

三 Ansible 远程执行脚本

首先创建一个shell脚本

# cat /tmp/test.sh
#!/bin/bash
echo `date` > /tmp/ansible_test.txt

然后把该脚本分发到各个机器上。

# ansible testhost -m copy -a "src=/tmp/test.sh 
dest=/tmp/test.sh 
mode=0755"
192.168.200.71 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
   "changed": true,  
    "checksum": "1a6e4af02dba1bda6fc8e23031d4447efeba0ade", 
    "dest": "/tmp/test.sh", 
    "gid": 0, 
    "group": "root", 
    "mode": "0644", 
    "owner": "root", 
    "path": "/tmp/test.sh", 
    "size": 48, 
    "state": "file", 
    "uid": 0
}
192.168.200.72 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
  "changed": true, 
    "checksum": "1a6e4af02dba1bda6fc8e23031d4447efeba0ade", 
    "dest": "/tmp/test.sh", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "edfaa4371316af8c5ba354e708fe8a97", 
    "mode": "0644", 
    "owner": "root", 
    "size": 48, 
    "src": "/root/.ansible/tmp/ansible-tmp-1641727206.43-2499-236587765379928/source", 
    "state": "file", 
    "uid": 0
}

最后是批量执行该shell脚本

# ansible testhost -m shell -a "/tmp/test.sh"
192.168.200.71 | CHANGED | rc=0 >>

192.168.200.72 | CHANGED | rc=0 >>

shell模块,还支持远程执行命令并且带管道

# ansible testhost -m shell -a "cat /etc/passwd |wc -l "
192.168.200.71| CHANGED | rc=0 >>
19
192.168.200.72 | CHANGED | rc=0 >>
19
# cat /tmp/ansible_test.txt
Sun Jan 9 06:27:28 EST 2022

运行成功。

四 Ansible 管理任务计划

创建任务计划,命名并定义工作。

# ansible testhost -m cron -a "name='test cron' job='/bin/bash/tmp/test.sh'weekday=6  state=present(默认自带)"
192.168.200.71 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "test cron"
    ]
}
192.168.200.72 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "test cron"
    ]
}

若要删除 cron 只需要加一个字段 state=absent

# ansible testhost -m cron -a "name='test cron' 
state=absent"
192.168.200.71| CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": []
}
192.168.200.72| CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": []
}

其他的时间表示 —— 分钟:minute; 小时:hour; 日期:day; 月份:month。

五 Ansible 安装 RPM 包/管理服务

使用 Yum 模块安装 httpd 服务

# ansible testhost -m yum -a "name=httpd"
192.168.200.71 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "changes": {
        "installed": [
            "httpd"
        ]
    }, 
    "msg": "", 
    "rc": 0, 
    "results": [
        …
…  
\n\nComplete!\n"
    ]
}
192.168.200.72 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "changes": {
        "installed": [
            "httpd"
        ]
    }, 
    "msg": "", 
    "rc": 0, 
    "results": [
        …
\n\nComplete!\n"
    ]
}

在 name 后面还可以加上 state=installed/removed

设置服务状态,这里的name是CentOS系统里的服务名,可以通过chkconfig –list命令查到。

# ansible testhost -m service -a "name=httpd state=started 
enabled=yes"
192.168.200.71 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "enabled": true, 
    "name": "httpd", 
    "state": "started", 
    "status": {
        …
        "WatchdogTimestampMonotonic": "0", 
        "WatchdogUSec": "0"
    }
}
192.168.200.72 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "enabled": true, 
    "name": "httpd", 
    "state": "started", 
    "status": {
       …
        "WatchdogUSec": "0"
    }
}

Ansible文档的使用:

# ansible-doc -l    //列出所有模块
fortios_router_community_list                                 Configure community lists in Fortinet's FortiOS ...
azure_rm_devtestlab_info                                      Get Azure DevTest Lab facts                     
ecs_taskdefinition                                            register a task definition in ecs               
avi_alertscriptconfig                                         Module for setup of AlertScriptConfig Avi RESTfu...
tower_receive                                                 Receive assets from Ansible Tower               
netapp_e_iscsi_target                                         NetApp E-Series manage iSCSI target configuratio...
azure_rm_acs                                                  Manage an Azure Container Service(ACS) instance 
…
# ansible-doc yum    //查看指定模块的文档
> YUM    (/usr/lib/python2.7/site-packages/ansible/modules/packaging/os/yum.py)

        Installs, upgrade, downgrades, removes, and lists packages and groups with the `yum'
        package manager. This module only works on Python 2. If you require Python 3 support
        see the [dnf] module.

  * This module is maintained by The Ansible Core Team
  * note: This module has a corresponding action plugin.

OPTIONS (= is mandatory):

- allow_downgrade
        Specify if the named package and version is allowed to downgrade a maybe already
        installed higher version of that package. Note that setting allow_downgrade=True can
        make this module behave in a non-idempotent way. The task could end up with a set of
        packages that does not match the complete list of specified packages to install
        (because dependencies between the downgraded package and others can cause changes to
        the packages which were in the earlier transaction).
        [Default: no]
        type: bool
        version_added: 2.4

 

posted @ 2022-04-22 16:18  年年哎  阅读(93)  评论(0)    收藏  举报