Ansible快速入门

1.ansible简介

ansible是基于 Python 开发的,是比 puppet 和 saltstack 更轻量级的运维自动化工具。无服务器端,使用时直接运行命令即可,不需要在被管控主机上安装任何客户端,所以任何一台机器只要安装了 ansible 就可以管控其他主机。基于模块工作,可使用任意语言开发模块。也可使用 yaml 语言定制剧本 playbook;基于SSH工作;可实现多级指挥。

ansible与puppet等相比,其号称是无客户端Agent的,而且这个也确实在很多台机器上进行运维时不用一台一台安装或者升级客户端确实带来了一定的便利。Ansible之所以不需要agent,原理在于其将要执行的命令或者脚本通过sftp的方式传到要执行的对象机器,然后通过ssh远程执行,执行之后清理现场将sftp传过去的文件删除,好像一切都没有发生过的一样,这个就是ansible不需要agent的原理。

2.安装配置

2.1 准备工作

准备3台服务器(虚拟机),进行下面操作。(相关操作可以参考前面的博文)

(1)关闭selinux和Firewalls

(2)编辑 hosts 文件

(3)免密登录

2.2 安装

[root@node1 ~]# yum install -y epel-release
[root@node1 ~]# yum install -y ansible

2.3 配置

(1)配置/etc/ansible/hosts

[root@node1 ~]# echo [hadoop] >> /etc/ansible/hosts
[root@node1 ~]# echo 192.168.80.131 >> /etc/ansible/hosts
[root@node1 ~]# echo 192.168.80.132 >> /etc/ansible/hosts
[root@node1 ~]# echo 192.168.80.133 >> /etc/ansible/hosts

备注:hadoop为自定义的主机组名。

(2)配置/etc/ansible/ansible.cfg

[root@node1 ~]# vi /etc/ansible/ansible.cfg
  • 禁用每次执行ansbile命令检查ssh key host
# uncomment this to disable SSH key host checking
host_key_checking = False
  • 开启日志记录
# logging is off by default unless this path is defined
# if so defined, consider logrotate
log_path = /var/log/ansible.log
  • ansible连接加速配置
[accelerate]
#accelerate_port = 5099
#accelerate_timeout = 30
#accelerate_connect_timeout = 5.0

# The daemon timeout is measured in minutes. This time is measured
# from the last activity to the accelerate daemon.
#accelerate_daemon_timeout = 30

# If set to yes, accelerate_multi_key will allow multiple
# private keys to be uploaded to it, though each user must
# have access to the system via SSH to add a new key. The default
# is "no".
accelerate_multi_key = yes

3.简单应用

3.1 测试是否ping通三台机器

[root@node1 ~]# ansible all -m ping
192.168.80.132 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.80.131 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.80.133 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
[root@node1 ~]#

3.2 参数说明

  • “-m” 指定模块名,常用的有command shell copy
  • “-a” 指定相应命令
[root@node1 ~]# ansible 192.168.80.133 -m command -a 'date'
192.168.80.133 | SUCCESS | rc=0 >>
Thu Sep 28 10:13:42 EDT 2017

[root@node1 ~]#

3.3 组

[root@node1 ~]# ansible hadoop -m command -a 'date'
192.168.80.133 | SUCCESS | rc=0 >>
Thu Sep 28 10:13:20 EDT 2017

192.168.80.132 | SUCCESS | rc=0 >>
Thu Sep 28 10:13:20 EDT 2017

192.168.80.131 | SUCCESS | rc=0 >>
Thu Sep 28 10:13:20 EDT 2017

[root@node1 ~]# 

这里的hadoop为之前自定义的主机组名。

3.4 复制文件

[root@node1 ~]# ansible hadoop -m copy -a 'src=/root/anaconda-ks.cfg dest=/tmp'
192.168.80.133 | SUCCESS => {
    "changed": true, 
    "checksum": "1164e252b37fc6173742711faf3afa5e31183a1c", 
    "dest": "/tmp/anaconda-ks.cfg", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "b7def69510b769910900b72774ec5ed8", 
    "mode": "0644", 
    "owner": "root", 
    "size": 1264, 
    "src": "/root/.ansible/tmp/ansible-tmp-1506608198.34-225731074231863/source", 
    "state": "file", 
    "uid": 0
}
192.168.80.132 | SUCCESS => {
    "changed": true, 
    "checksum": "1164e252b37fc6173742711faf3afa5e31183a1c", 
    "dest": "/tmp/anaconda-ks.cfg", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "b7def69510b769910900b72774ec5ed8", 
    "mode": "0644", 
    "owner": "root", 
    "size": 1264, 
    "src": "/root/.ansible/tmp/ansible-tmp-1506608198.28-107461270200220/source", 
    "state": "file", 
    "uid": 0
}
192.168.80.131 | SUCCESS => {
    "changed": true, 
    "checksum": "1164e252b37fc6173742711faf3afa5e31183a1c", 
    "dest": "/tmp/anaconda-ks.cfg", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "b7def69510b769910900b72774ec5ed8", 
    "mode": "0644", 
    "owner": "root", 
    "size": 1264, 
    "src": "/root/.ansible/tmp/ansible-tmp-1506608198.51-114681015236449/source", 
    "state": "file", 
    "uid": 0
}
[root@node1 ~]#
[root@node1 ~]# ls /tmp|grep cfg
anaconda-ks.cfg
[root@node2 ~]# ls /tmp|grep cfg
anaconda-ks.cfg
[root@node2 ~]# 
[root@node3 ~]# ls /tmp|grep cfg
anaconda-ks.cfg
[root@node3 ~]#

3.6 远程执行Shell脚本

首先在本地创建一个脚本,然后分发到远程节点,最后在远程节点执行脚本。

[root@node1 ~]# echo '#!/bin/bash' >/tmp/test.sh
[root@node1 ~]# echo 'date' >> /tmp/test.sh
[root@node1 ~]# cat /tmp/test.sh
#!/bin/bash
date
[root@node1 ~]# ansible 192.168.80.133 -m copy -a "src=/tmp/test.sh dest=/tmp/test.sh mode=0755"
192.168.80.133 | SUCCESS => {
    "changed": true, 
    "checksum": "782d676e0b7dd360d486f89a77a03eb4623dfc6b", 
    "dest": "/tmp/test.sh", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "7c73186c5baeeced9773809d51f55903", 
    "mode": "0755", 
    "owner": "root", 
    "size": 17, 
    "src": "/root/.ansible/tmp/ansible-tmp-1506610170.95-70838345469547/source", 
    "state": "file", 
    "uid": 0
}
[root@node1 ~]# ansible 192.168.80.133 -m shell -a "/tmp/test.sh"
192.168.80.133 | SUCCESS | rc=0 >>
Thu Sep 28 10:49:54 EDT 2017

[root@node1 ~]# 

3.6 yum安装

[root@node1 ~]# ansible 192.168.80.133 -m yum -a "name=vim"
192.168.80.133 | SUCCESS => {
    "changed": false, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "vim-enhanced-2:7.4.160-1.el7_3.1.x86_64 providing vim is already installed"
    ]
}
[root@node1 ~]#
[root@node1 ~]# ansible 192.168.80.133 -m yum -a "name=httpd"
192.168.80.133 | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirrors.aliyun.com\n * extras: mirrors.aliyun.com\n * updates: mirrors.aliyun.com\nResolving Dependencies\n--> Running transaction check\n---> Package httpd.x86_64 0:2.4.6-67.el7.centos.2 will be installed\n--> Processing Dependency: httpd-tools = 2.4.6-67.el7.centos.2 for package: httpd-2.4.6-67.el7.centos.2.x86_64\n--> Processing Dependency: /etc/mime.types for package: httpd-2.4.6-67.el7.centos.2.x86_64\n--> Processing Dependency: libaprutil-1.so.0()(64bit) for package: httpd-2.4.6-67.el7.centos.2.x86_64\n--> Processing Dependency: libapr-1.so.0()(64bit) for package: httpd-2.4.6-67.el7.centos.2.x86_64\n--> Running transaction check\n---> Package apr.x86_64 0:1.4.8-3.el7 will be installed\n---> Package apr-util.x86_64 0:1.5.2-6.el7 will be installed\n---> Package httpd-tools.x86_64 0:2.4.6-67.el7.centos.2 will be installed\n---> Package mailcap.noarch 0:2.1.41-2.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package           Arch         Version                     Repository     Size\n================================================================================\nInstalling:\n httpd             x86_64       2.4.6-67.el7.centos.2       updates       2.7 M\nInstalling for dependencies:\n apr               x86_64       1.4.8-3.el7                 base          103 k\n apr-util          x86_64       1.5.2-6.el7                 base           92 k\n httpd-tools       x86_64       2.4.6-67.el7.centos.2       updates        88 k\n mailcap           noarch       2.1.41-2.el7                base           31 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package (+4 Dependent packages)\n\nTotal download size: 3.0 M\nInstalled size: 10 M\nDownloading packages:\n--------------------------------------------------------------------------------\nTotal                                              1.7 MB/s | 3.0 MB  00:01     \nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : apr-1.4.8-3.el7.x86_64                                       1/5 \n  Installing : apr-util-1.5.2-6.el7.x86_64                                  2/5 \n  Installing : httpd-tools-2.4.6-67.el7.centos.2.x86_64                     3/5 \n  Installing : mailcap-2.1.41-2.el7.noarch                                  4/5 \n  Installing : httpd-2.4.6-67.el7.centos.2.x86_64                           5/5 \n  Verifying  : mailcap-2.1.41-2.el7.noarch                                  1/5 \n  Verifying  : httpd-tools-2.4.6-67.el7.centos.2.x86_64                     2/5 \n  Verifying  : apr-util-1.5.2-6.el7.x86_64                                  3/5 \n  Verifying  : apr-1.4.8-3.el7.x86_64                                       4/5 \n  Verifying  : httpd-2.4.6-67.el7.centos.2.x86_64                           5/5 \n\nInstalled:\n  httpd.x86_64 0:2.4.6-67.el7.centos.2                                          \n\nDependency Installed:\n  apr.x86_64 0:1.4.8-3.el7                      apr-util.x86_64 0:1.5.2-6.el7   \n  httpd-tools.x86_64 0:2.4.6-67.el7.centos.2    mailcap.noarch 0:2.1.41-2.el7   \n\nComplete!\n"
    ]
}
[root@node1 ~]#

3.7 服务管理

开启 httpd 服务,并关闭开机启动。

[root@node1 ~]# ansible 192.168.80.133 -m service -a "name=httpd state=started enabled=no"
192.168.80.133 | SUCCESS => {
    "changed": true, 
    "enabled": false, 
    "name": "httpd", 
    "state": "started", 
    "status": {
        "ActiveEnterTimestampMonotonic": "0", 
        "ActiveExitTimestampMonotonic": "0", 
        "ActiveState": "inactive", 
        "After": "tmp.mount system.slice systemd-journald.socket basic.target nss-lookup.target -.mount remote-fs.target network.target", 
        "AllowIsolate": "no", 
        "AssertResult": "no", 
        "AssertTimestampMonotonic": "0", 
        "Before": "shutdown.target", 
        "BlockIOAccounting": "no", 
        "BlockIOWeight": "18446744073709551615", 
        "CPUAccounting": "no", 
        "CPUQuotaPerSecUSec": "infinity", 
        "CPUSchedulingPolicy": "0", 
        "CPUSchedulingPriority": "0", 
        "CPUSchedulingResetOnFork": "no", 
        "CPUShares": "18446744073709551615", 
        "CanIsolate": "no", 
        "CanReload": "yes", 
        "CanStart": "yes", 
        "CanStop": "yes", 
        "CapabilityBoundingSet": "18446744073709551615", 
        "ConditionResult": "no", 
        "ConditionTimestampMonotonic": "0", 
        "Conflicts": "shutdown.target", 
        "ControlPID": "0", 
        "DefaultDependencies": "yes", 
        "Delegate": "no", 
        "Description": "The Apache HTTP Server", 
        "DevicePolicy": "auto", 
        "Documentation": "man:httpd(8) man:apachectl(8)", 
        "EnvironmentFile": "/etc/sysconfig/httpd (ignore_errors=no)", 
        "ExecMainCode": "0", 
        "ExecMainExitTimestampMonotonic": "0", 
        "ExecMainPID": "0", 
        "ExecMainStartTimestampMonotonic": "0", 
        "ExecMainStatus": "0", 
        "ExecReload": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -k graceful ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "ExecStart": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -DFOREGROUND ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "ExecStop": "{ path=/bin/kill ; argv[]=/bin/kill -WINCH ${MAINPID} ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "FailureAction": "none", 
        "FileDescriptorStoreMax": "0", 
        "FragmentPath": "/usr/lib/systemd/system/httpd.service", 
        "GuessMainPID": "yes", 
        "IOScheduling": "0", 
        "Id": "httpd.service", 
        "IgnoreOnIsolate": "no", 
        "IgnoreOnSnapshot": "no", 
        "IgnoreSIGPIPE": "yes", 
        "InactiveEnterTimestampMonotonic": "0", 
        "InactiveExitTimestampMonotonic": "0", 
        "JobTimeoutAction": "none", 
        "JobTimeoutUSec": "0", 
        "KillMode": "control-group", 
        "KillSignal": "18", 
        "LimitAS": "18446744073709551615", 
        "LimitCORE": "18446744073709551615", 
        "LimitCPU": "18446744073709551615", 
        "LimitDATA": "18446744073709551615", 
        "LimitFSIZE": "18446744073709551615", 
        "LimitLOCKS": "18446744073709551615", 
        "LimitMEMLOCK": "65536", 
        "LimitMSGQUEUE": "819200", 
        "LimitNICE": "0", 
        "LimitNOFILE": "4096", 
        "LimitNPROC": "7208", 
        "LimitRSS": "18446744073709551615", 
        "LimitRTPRIO": "0", 
        "LimitRTTIME": "18446744073709551615", 
        "LimitSIGPENDING": "7208", 
        "LimitSTACK": "18446744073709551615", 
        "LoadState": "loaded", 
        "MainPID": "0", 
        "MemoryAccounting": "no", 
        "MemoryCurrent": "18446744073709551615", 
        "MemoryLimit": "18446744073709551615", 
        "MountFlags": "0", 
        "Names": "httpd.service", 
        "NeedDaemonReload": "no", 
        "Nice": "0", 
        "NoNewPrivileges": "no", 
        "NonBlocking": "no", 
        "NotifyAccess": "main", 
        "OOMScoreAdjust": "0", 
        "OnFailureJobMode": "replace", 
        "PermissionsStartOnly": "no", 
        "PrivateDevices": "no", 
        "PrivateNetwork": "no", 
        "PrivateTmp": "yes", 
        "ProtectHome": "no", 
        "ProtectSystem": "no", 
        "RefuseManualStart": "no", 
        "RefuseManualStop": "no", 
        "RemainAfterExit": "no", 
        "Requires": "basic.target -.mount", 
        "RequiresMountsFor": "/var/tmp", 
        "Restart": "no", 
        "RestartUSec": "100ms", 
        "Result": "success", 
        "RootDirectoryStartOnly": "no", 
        "RuntimeDirectoryMode": "0755", 
        "SameProcessGroup": "no", 
        "SecureBits": "0", 
        "SendSIGHUP": "no", 
        "SendSIGKILL": "yes", 
        "Slice": "system.slice", 
        "StandardError": "inherit", 
        "StandardInput": "null", 
        "StandardOutput": "journal", 
        "StartLimitAction": "none", 
        "StartLimitBurst": "5", 
        "StartLimitInterval": "10000000", 
        "StartupBlockIOWeight": "18446744073709551615", 
        "StartupCPUShares": "18446744073709551615", 
        "StatusErrno": "0", 
        "StopWhenUnneeded": "no", 
        "SubState": "dead", 
        "SyslogLevelPrefix": "yes", 
        "SyslogPriority": "30", 
        "SystemCallErrorNumber": "0", 
        "TTYReset": "no", 
        "TTYVHangup": "no", 
        "TTYVTDisallocate": "no", 
        "TimeoutStartUSec": "1min 30s", 
        "TimeoutStopUSec": "1min 30s", 
        "TimerSlackNSec": "50000", 
        "Transient": "no", 
        "Type": "notify", 
        "UMask": "0022", 
        "UnitFilePreset": "disabled", 
        "UnitFileState": "disabled", 
        "Wants": "system.slice", 
        "WatchdogTimestampMonotonic": "0", 
        "WatchdogUSec": "0"
    }
}
[root@node1 ~]# 
[root@node3 ~]# systemctl status httpd
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
   Active: active (running) since Thu 2017-09-28 10:42:17 EDT; 1min 51s ago
     Docs: man:httpd(8)
           man:apachectl(8)
 Main PID: 3068 (httpd)
   Status: "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec"
   CGroup: /system.slice/httpd.service
           ├─3068 /usr/sbin/httpd -DFOREGROUND
           ├─3069 /usr/sbin/httpd -DFOREGROUND
           ├─3070 /usr/sbin/httpd -DFOREGROUND
           ├─3071 /usr/sbin/httpd -DFOREGROUND
           ├─3072 /usr/sbin/httpd -DFOREGROUND
           └─3073 /usr/sbin/httpd -DFOREGROUND

Sep 28 10:42:17 node3 systemd[1]: Starting The Apache HTTP Server...
Sep 28 10:42:17 node3 httpd[3068]: AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 192.168.80.133. Set the 'ServerName' directiv... this message
Sep 28 10:42:17 node3 systemd[1]: Started The Apache HTTP Server.
Hint: Some lines were ellipsized, use -l to show in full.
[root@node3 ~]#

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏我的博客

filter_input()详解,$_GET,$_POST,$_ENV,$_SERVER,$_SESSION,$_REQUEST

filter_input() 函数从脚本外部获取输入,并进行过滤。 本函数用于对来自非安全来源的变量进行验证,比如用户的输入。 本函数可从各种来源获取输入: I...

3235
来自专栏nummy

sublime3 配置go开发环境

在sublime下选择【工具菜单】,选择【编译系统】,继续选择【新编译系统】,在弹出的文件内写入如下代码:

461
来自专栏青枫的专栏

教你如何解决Sublime Text 3使用中出现的中文乱码问题

Sublime Text 3 是一个非常不错的源代码及文本编辑器,但是不支持GB2312和GBK编码在很多情况下会非常麻烦。

943
来自专栏刘远飞的专栏

CentOS6.5系统yum安装LAMP环境

采用Linux下二进制模式来安装LAMP,适合初学者,测试使用。

6100
来自专栏python3

centos7安装openvpn

OpenVPN 是一个基于 OpenSSL 库的应用层 VPN 实现。和传统 VPN 相比,它的优点是简单易用。 允许参与建立VPN的单点使用共享金钥,电子证书...

1021
来自专栏三木的博客

使用gerrit作为代码评审工具

需求描述 其实作为项目代码的maintainer,一直习惯于mailing list + git的代码评审及管理,无奈公司主推敏捷+devops,老板让改用ge...

2266
来自专栏晓晨的专栏

CentOS 7 源码编译安装 Nginx

https://www.cnblogs.com/visec479/p/5145624.html

863
来自专栏不想当开发的产品不是好测试

jenkins修改时区

查看jenkins目前的时区 访问http://your-jenkins/systemInfo,查看user.timezone变量的值 ? 默认是纽约时间 修改...

22710
来自专栏张善友的专栏

在CentOS 6.3下安装OpenPetra 的 Mono 3.0.6 部署包

这篇文章记录的是在CentOS 6.3下安装《OpenPetra 以及CentOS Mono 3.0 部署包》提到的 Mono 3.0.6 部署包。 首先下载r...

1868
来自专栏鬼谷君

saltstack 初始化LINUX系统

前面我们已经了解了saltstack的基础功能,现在就可以使用saltstack为初始化新安装的linux系统。

926

扫码关注云+社区