Ansible基本配置使用

Ansible基本配置使用

环境:

OS hostname IP
centos7 server 192.168.220.138
centos7 client 192.168.220.139

ansible概述

Ansible是一款为类Unix系统开发的自由开源的配置和自动化工具。它用Python写成,类似于saltstack和Puppet,但是有一个不同和优点是我们不需要在节点中安装任何客户端。它使用SSH来和节点进行通信。Ansible基于 Python paramiko 开发,分布式,无需客户端,轻量级,配置语法使用 YMAL 及 Jinja2模板语言,更强的远程命令执行操作.

在这里插入图片描述

由上面的图可以看到 Ansible 的组成由 5 个部分组成:

  • Ansible : ansible核心

  • Modules: 包括 Ansible 自带的核心模块及自定义模块)

  • Plugins : 完成模块功能的补充,包括连接插件、邮件插件等

  • Playbooks : 剧本;定义 Ansible 多任务配置文件,由Ansible 自动执行

  • Inventory : 定义 Ansible 管理主机的清单

流程:ansible读取主机清单,然后读取playbooks获取对主机的操作。之后调用核心模块,之后通过ssh方式部署管理主机。

安装配置ansible

[root@server ~]# yum install epel-release -y	#设置epel仓库
[root@server ~]# yum install ansible -y			#安装ansible
[root@server ~]# ansible --version				#查看ansible版本
ansible 2.8.2
  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)]
语法及常用参数
ansible [-i 主机清单] [-f 批次] [组名] [-m 模块名称] [-a 模块参数]
-v, --verbose         verbose mode (-vvv for more, -vvvv to enable	显示过程
                        connection debugging)

指定host文件路径,默认/etc/ansible/hosts
-i INVENTORY, --inventory=INVENTORY, --inventory-file=INVENTORY
                        specify inventory host path or comma separated host
                        list. --inventory-file is deprecated          

开启同步进程的个数
 -f FORKS, --forks=FORKS
                        specify number of parallel processes to use
                        (default=5)

指定使用的module名称,默认使用command
-m MODULE_NAME, --module-name=MODULE_NAME
                        module name to execute (default=command)
                       
指定module参数
-a MODULE_ARGS, --args=MODULE_ARGS
                        module arguments
             
提示输入ssh密码,而不是基于密钥验证
-k, --ask-pass      ask for connection password
    --private-key=PRIVATE_KEY_FILE, --key-file=PRIVATE_KEY_FILE

检测此命令会改变哪些内容,不会真正的去执行
-C, --check           don't make any changes; instead, try to predict some
                        of the changes that may occur

定义主机清单

ansible基于ssh连接-i (inventory)参数后指定的远程主机时,也可以写端口,用户,密码。
格式:ansible_ssh_port:指定ssh端口   ansible_ssh_user:指定 ssh 用户 ansible_ssh_pass:指定 ssh 用户登录是认证密码(明文密码不安全)  ansible_sudo_pass:指明 sudo 时候的密码

[root@server ~]# cd /etc/ansible/
[root@server ansible]# ls
ansible.cfg  hosts  roles

[root@server ansible]# vim hosts
增加一个主机组
[client]
192.168.220.138

[root@server ansible]# ssh-keygen 
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
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:
SHA256:NNsMvserq78+kCl0Cpi0LyHtJKLZfEEFZF3RAVqS50Q root@server
The key's randomart image is:
+---[RSA 2048]----+
|   .++o+E+..     |
| . .. o+o .      |
|.+..  .++        |
|*o+ o .o.*       |
|+Boo + oS o      |
|o.+.+ +  o       |
|  .. . .. o      |
|        .. .     |
|      .+*=.      |
+----[SHA256]-----+

[root@server ansible]# ssh-copy-id 192.168.220.139
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '192.168.220.139 (192.168.220.139)' can't be established.
ECDSA key fingerprint is SHA256:/6JO29NCHl8uxOYuVCh1+YyB5zKFJqNTSvRuF5jl9F8.
ECDSA key fingerprint is MD5:18:50:d5:2e:eb:37:29:1f:b0:91:18:36:73:6b:a9:df.
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
[email protected]'s password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '192.168.220.139'"
and check to make sure that only the key(s) you wanted were added.

ping主机
[root@server ansible]# ansible -i /etc/ansible/hosts client -m ping
192.168.220.139 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

执行uptime命令
[root@server ansible]# ansible -m command -a 'uptime' client
192.168.220.139 | CHANGED | rc=0 >>
 16:11:35 up  6:16,  2 users,  load average: 0.00, 0.01, 0.05

常用模块

1、3个远程命令模块的区别
(1)、command模块为ansible默认模块,不指定-m参数时,使用的就是command模块; comand模块比较简单,常见的命令都可以使用,但其命令的执行不是通过shell执行的,所以,像这些 "<", ">", "|", and "&"操作都不可以,当然,也就不支持管道; 缺点:不支持管道,没法批量执行命令;

[root@server ansible]# ansible -m shell -a 'free -m' client
192.168.220.139 | CHANGED | rc=0 >>
              total        used        free      shared  buff/cache   available
Mem:           1824         220        1403           8         201        1439
Swap:          2047           0        2047


(2)shell模块:使用shell模块,在远程命令通过/bin/sh来执行;所以,我们在终端输入的各种命令方式,都可以使用。

(3)scripts模块
使用scripts模块可以在本地写一个脚本,在远程服务器上执行:
[root@server ansible]# cat test.sh 
#!/bin/bash
hostname
uname -a

[root@server ansible]# ansible -i /etc/ansible/hosts client -m script -a "/etc/ansible/test.sh" 
192.168.220.139 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.220.139 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.220.139 closed."
    ], 
    "stdout": "client\r\nLinux client 3.10.0-327.el7.x86_64 #1 SMP Thu Nov 19 22:10:57 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux\r\n", 
    "stdout_lines": [
        "client", 
        "Linux client 3.10.0-327.el7.x86_64 #1 SMP Thu Nov 19 22:10:57 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux"
    ]
}

2、copy模块:向目标主机拷贝文件
[root@server ansible]# ansible -i /etc/ansible/hosts client -m copy -a "src=/etc/ansible/test.sh dest=/tmp/ owner=root group=root mode=0777"
192.168.220.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "5e571a7d52cb36f95d38288501a76cb949a6d12d", 
    "dest": "/tmp/test.sh", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "b2ad69b7b1c48f74ad42916dff6facbf", 
    "mode": "0777", 
    "owner": "root", 
    "size": 30, 
    "src": "/root/.ansible/tmp/ansible-tmp-1566203847.77-17142417839436/source", 
    "state": "file", 
    "uid": 0
}

3、file模块设置文件属性。
[root@server ansible]# ansible -i /etc/ansible/hosts client -m file -a "path=/tmp/test.sh mode=0755"
192.168.220.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0755", 
    "owner": "root", 
    "path": "/tmp/test.sh", 
    "size": 30, 
    "state": "file", 
    "uid": 0
}

4、stat模块获取远程文件信息
[root@server ansible]# ansible -i /etc/ansible/hosts client -m stat -a "path=/tmp/test.sh "
192.168.220.139 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "stat": {
        "atime": 1566203848.898032, 
        "attr_flags": "", 
        "attributes": [], 
        "block_size": 4096, 
        "blocks": 8, 
        "charset": "us-ascii", 
        "checksum": "5e571a7d52cb36f95d38288501a76cb949a6d12d", 
        "ctime": 1566203940.9678795, 
        "dev": 64768, 
        "device_type": 0, 
        "executable": true, 
        "exists": true, 
        "gid": 0, 
        "gr_name": "root", 
        "inode": 68353338, 
        "isblk": false, 
        "ischr": false, 
        "isdir": false, 
        "isfifo": false, 
        "isgid": false, 
        "islnk": false, 
        "isreg": true, 
        "issock": false, 
        "isuid": false, 
        "mimetype": "text/x-shellscript", 
        "mode": "0755", 
        "mtime": 1566203848.4100327, 
        "nlink": 1, 
        "path": "/tmp/test.sh", 
        "pw_name": "root", 
        "readable": true, 
        "rgrp": true, 
        "roth": true, 
        "rusr": true, 
        "size": 30, 
        "uid": 0, 
        "version": "18446744072366119905", 
        "wgrp": false, 
        "woth": false, 
        "writeable": true, 
        "wusr": true, 
        "xgrp": true, 
        "xoth": true, 
        "xusr": true
    }
}

5、get_url模块实现远程主机下载指定url到本地,支持sha256sum文件校验
[root@server ansible]# ansible -i /etc/ansible/hosts client -m get_url -a "url=https://mirrors.cloud.tencent.com/zabbix/zabbix/4.3/rhel/7/x86_64/zabbix-agent-4.4.0-0.1alpha1.el7.x86_64.rpm dest=/tmp/ mode=0444 force=yes"
192.168.220.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum_dest": null, 
    "checksum_src": "03d02c2b54bc01de616b26e8c148c9a44f115691", 
    "dest": "/tmp/zabbix-agent-4.4.0-0.1alpha1.el7.x86_64.rpm", 
    "elapsed": 1, 
    "gid": 0, 
    "group": "root", 
    "md5sum": "f5be56489a1607f4b390c680db5b6057", 
    "mode": "0444", 
    "msg": "OK (424648 bytes)", 
    "owner": "root", 
    "size": 424648, 
    "src": "/root/.ansible/tmp/ansible-tmp-1566205098.96-270396050201279/tmpV7LdMc", 
    "state": "file", 
    "status_code": 200, 
    "uid": 0, 
    "url": "https://mirrors.cloud.tencent.com/zabbix/zabbix/4.3/rhel/7/x86_64/zabbix-agent-4.4.0-0.1alpha1.el7.x86_64.rpm"
}


6、yum模块linux平台软件包管理。
yum模块可以提供的status状态: latest ,present,installed  #这3个代表安装;
removed, absent #后面2个是卸载

[root@server ansible]# ansible -i /etc/ansible/hosts -m yum -a "name=php state=latest" client
192.168.220.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "changes": {
        "installed": [
            "php"
        ], 
        "updated": []
    }, 
    "msg": "", 
    "obsoletes": {
        "NetworkManager": {
            "dist": "x86_64", 
            "repo": "@anaconda", 
            "version": "1:1.0.6-27.el7"
        }, 
        "grub2": {
            "dist": "x86_64", 
            "repo": "@anaconda", 
            "version": "1:2.02-0.29.el7.centos"
        }, 
        "grub2-tools": {
            "dist": "x86_64", 
            "repo": "@anaconda", 
            "version": "1:2.02-0.29.el7.centos"
        }, 
        "pygobject3-base": {
            "dist": "x86_64", 
            "repo": "@anaconda", 
            "version": "3.14.0-3.el7"
        }, 
        "rdma": {
            "dist": "noarch", 
            "repo": "@anaconda", 
            "version": "7.2_4.1_rc6-1.el7"
        }
    }, 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirrors.huaweicloud.com\n * extras: mirrors.huaweicloud.com\n * updates: mirrors.huaweicloud.com\nResolving Dependencies\n--> Running transaction check\n---> Package php.x86_64 0:5.4.16-46.el7 will be installed\n--> Processing Dependency: php-common(x86-64) = 5.4.16-46.el7 for package: php-5.4.16-46.el7.x86_64\n--> Processing Dependency: php-cli(x86-64) = 5.4.16-46.el7 for package: php-5.4.16-46.el7.x86_64\n--> Running transaction check\n---> Package php-cli.x86_64 0:5.4.16-46.el7 will be installed\n---> Package php-common.x86_64 0:5.4.16-46.el7 will be installed\n--> Processing Dependency: libzip.so.2()(64bit) for package: php-common-5.4.16-46.el7.x86_64\n--> Running transaction check\n---> Package libzip.x86_64 0:0.10.1-8.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package             Arch            Version                Repository     Size\n================================================================================\nInstalling:\n php                 x86_64          5.4.16-46.el7          base          1.4 M\nInstalling for dependencies:\n libzip              x86_64          0.10.1-8.el7           base           48 k\n php-cli             x86_64          5.4.16-46.el7          base          2.7 M\n php-common          x86_64          5.4.16-46.el7          base          565 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package (+3 Dependent packages)\n\nTotal download size: 4.7 M\nInstalled size: 17 M\nDownloading packages:\n--------------------------------------------------------------------------------\nTotal                                              2.1 MB/s | 4.7 MB  00:02     \nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : libzip-0.10.1-8.el7.x86_64                                   1/4 \n  Installing : php-common-5.4.16-46.el7.x86_64                              2/4 \n  Installing : php-cli-5.4.16-46.el7.x86_64                                 3/4 \n  Installing : php-5.4.16-46.el7.x86_64                                     4/4 \n  Verifying  : php-common-5.4.16-46.el7.x86_64                              1/4 \n  Verifying  : php-cli-5.4.16-46.el7.x86_64                                 2/4 \n  Verifying  : libzip-0.10.1-8.el7.x86_64                                   3/4 \n  Verifying  : php-5.4.16-46.el7.x86_64                                     4/4 \n\nInstalled:\n  php.x86_64 0:5.4.16-46.el7                                                    \n\nDependency Installed:\n  libzip.x86_64 0:0.10.1-8.el7             php-cli.x86_64 0:5.4.16-46.el7       \n  php-common.x86_64 0:5.4.16-46.el7       \n\nComplete!\n"
    ]
}


7、cron模块远程主机crontab配置。
[root@server ansible]# ansible -i /etc/ansible/hosts client -m cron -a "name='list dir' minute='*/30' job='ls /tmp'"
192.168.220.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "list dir"
    ]
}

8、service模块远程主机系统服务管理。
service模块常用参数:
(1)、name参数:此参数用于指定需要操作的服务名称,比如 nginx,httpd。 
(2)、state参数:此参数用于指定服务的状态,比如,我们想要启动远程主机中的httpd,则可以将 state 的值设置为 started;如果想要停止远程主机中的服务,则可以将 state 的值设置为 stopped。此参数的可用值有 started、stopped、restarted(重启)、reloaded。 
enabled参数:此参数用于指定是否将服务设置为开机 启动项,设置为 yes 表示将对应服务设置为开机启动,设置为 no 表示不会开机启动。

[root@server ansible]# ansible -i /etc/ansible/hosts -m yum -a "name=httpd state=latest" client
[root@server ansible]# ansible -i /etc/ansible/hosts -m service -a "name=httpd state=restarted" client
192.168.220.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "name": "httpd", 
    "state": "started", 
    "status": {
        "ActiveEnterTimestampMonotonic": "0", 
        "ActiveExitTimestampMonotonic": "0", 
        "ActiveState": "inactive", 
        "After": "network.target nss-lookup.target systemd-journald.socket -.mount tmp.mount system.slice basic.target remote-fs.target", 
......

9、sysctl模块远程主机sysctl配置。
开启路由转发功能
[root@server ansible]# ansible -i /etc/ansible/hosts -m sysctl -a "name=net.ipv4.ip_forward value=1 reload=yes" client
192.168.220.139 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true
}
发布了65 篇原创文章 · 获赞 48 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/DoloresOOO/article/details/99739789