在大规模的配置管理工作中,管理不同业务的机器,机器的信息都存放在ansible的inventory组件里面。在工作中,配置部署针对的主机必须先存放在Inventory里面,然后ansible才能对它进行操作。默认的Ansible的inventory是一个静态的INI格式的文件/etc/ansible/hosts。可以通过ANSIBLE_HOSTS环境变量指定或运行ansible和ansible-playbook的时候用-i参数临时设置。
修改配置文件:/etc/ansible/ansible.cfg
[root@hadoop1010 inventory]# ll
total 12
-rw-r--r-- 1 root root 93 Mar 7 18:46 docker
-rw-r--r-- 1 root root 93 Mar 7 19:36 hadoop
-rw-r--r-- 1 root root 67 Mar 7 19:29 hosts
[root@hadoop1010 inventory]# vim /etc/ansible/ansible.cfg
# config file for ansible -- https://ansible.com/
# ===============================================
# nearly all parameters can be overridden in ansible-playbook
# or with command line flags. ansible will read ANSIBLE_CONFIG,
# ansible.cfg in the current working directory, .ansible.cfg in
# the home directory or /etc/ansible/ansible.cfg, whichever it
# finds first
[defaults]
# some basic default values...
inventory = /etc/ansible/hosts,/root/ansible/inventory/hosts,/root/ansible/inventory/docker,/root/ansible/inventory/hadoop
[root@hadoop1010 inventory]# cat hadoop
[hadoop]
192.168.10.1[0:2]
[hadoop_vars]
ansible_ssh_pass='123456'
[ansible:children]
hadoop
[root@hadoop1010 inventory]# cat docker
[docker]
192.168.10.1[1:2]
[docker_vars]
ansible_ssh_pass='123456'
[ansible:children]
docker
[root@hadoop1010 inventory]# ansible hadoop -m ping -o
192.168.10.11 | SUCCESS => {"changed": false, "ping": "pong"}
192.168.10.10 | SUCCESS => {"changed": false, "ping": "pong"}
192.168.10.12 | SUCCESS => {"changed": false, "ping": "pong"}
[root@hadoop1010 inventory]# ansible docker -m ping -o
192.168.10.12 | SUCCESS => {"changed": false, "ping": "pong"}
192.168.10.11 | SUCCESS => {"changed": false, "ping": "pong"}
其实ansible中的多个inventory跟单个文件的区别不是很大,采用多个inventory的好处是可以吧不同环境的主机或不同业务的主机放在不同的Inventory文件里面,方便日常维护。
在生产工作中会有大量的主机列表。若手动维护这些列表是一件麻烦的事情。ansible还支持动态的Inventory,动态Inventory就是ansible所有的Inventory文件里面的主机列表信息和变量信息都支持从外部拉取。比如,从zabbix监控系统或是cmdb系统拉取所有的主机信息,然后用ansible进行管理。这样更方便地将Ansible与其他运维系统结合起来。
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import argparse
import sys
import json
def lists():
r = {}
host = ['192.168.10.1' + str(i) for i in range(0, 2)]
hosts = {'hosts': host}
r['docker'] = hosts
return json.dumps(r, indent=3)
def hosts(name):
r = {'ansible_ssh_pass': '123456'}
cpis = dict(r.items())
return json.dumps(cpis)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-l', '--list', help='hosts list', action='store_true')
parser.add_argument('-H', '--host', help='hosts vars')
args = vars(parser.parse_args())
if args['list']:
print(lists())
elif args['host']:
print(hosts(args['host']))
else:
parser.print_help()
动态inventory测试:
root@hadoop1010 inventory]# ll
total 16
-rw-r--r-- 1 root root 93 Mar 7 18:46 docker
-rw-r--r-- 1 root root 93 Mar 7 2023 hadoop
-rw-r--r-- 1 root root 81 Mar 7 2023 hosts
-rwxr-xr-x 1 root root 749 Mar 7 2023 hosts.py
[root@hadoop1010 inventory]# ansible -i hosts.py docker -m ping -o
192.168.10.11 | SUCCESS => {"changed": false, "ping": "pong"}
192.168.10.10 | SUCCESS => {"changed": false, "ping": "pong"}
[root@hadoop1010 inventory]#
ansible_ssh_host: 定义host ssh地址 ansible_ssh_host=192.168.10.10
ansible_ssh_port: 定义hots ssh端口 snsible_ssh_port=5000
ansible_ssh_user: 定义hosts ssh 认证用户 ansible_ssh_user=machine
ansible_ssh_pass: 定义hosts ssh认证密码 ansible_ssh_pass=‘123456’
ansible_duso: 定义hosts sudo的用户 ansible_sudo=machine
ansible_sdo_pass: 定义hosts sudo密码 ansible_sudo_pass=‘123456’
ansible_sudo_exe: 定义hosts duso 路径 ansible_sudo_exe=/usr/bin/sudo密码
ansible_ssh_private_key_file: 定义hosts私钥 ansible_ssh_private_key_file=/root/key
ansible_shell_type: 定义hosts shell类型 ansible_shell_type=bash
ansible_python_interpreter: 定义hosts任务执行python的路径 ansible_python_interpreter=/usr/bin/python2.6
ansible_interpreter: 定义hosts其他语言解析器路径 ansible_interpreter=/usr/bin/ruby
我们通常会用命令行地形式使用ansible模块,ansible自带很多模块,可以直接使用这些模块,目前Ansible已经自带了259多个模块,使用: ansible-doc -l 查看这些模块。
简单测试命令:
[root@hadoop1010 inventory]# echo `date`;ansible docker -m shell -a "sleep 3s;hostname" -f 1;echo `date`
Tue Mar 7 23:54:37 CST 2023
192.168.10.10 | SUCCESS | rc=0 >>
hadoop1010
192.168.10.11 | SUCCESS | rc=0 >>
hadoop1011
192.168.10.12 | SUCCESS | rc=0 >>
hadoop1012
Tue Mar 7 23:54:48 CST 2023
[root@hadoop1010 inventory]# echo `date`;ansible docker -m shell -a "sleep 3s;hostname" -f 10;echo `date`
Tue Mar 7 23:54:53 CST 2023
192.168.10.12 | SUCCESS | rc=0 >>
hadoop1012
192.168.10.10 | SUCCESS | rc=0 >>
hadoop1010
192.168.10.11 | SUCCESS | rc=0 >>
hadoop1011
Tue Mar 7 23:54:57 CST 2023
[root@hadoop1010 inventory]# echo `date`;ansible docker -m shell -a "sleep 3s;hostname" -f 100;echo `date`
Tue Mar 7 23:55:10 CST 2023
192.168.10.12 | SUCCESS | rc=0 >>
hadoop1012
192.168.10.11 | SUCCESS | rc=0 >>
hadoop1011
192.168.10.10 | SUCCESS | rc=0 >>
hadoop1010
Tue Mar 7 23:55:15 CST 2023
测试发现加了并行度-f,执行效率提高了很多。
[root@hadoop1010 inventory]# ansible hadoop -m copy -a "src=/etc/crontab dest=/etc/crontab"
192.168.10.12 | SUCCESS => {
"changed": false,
"checksum": "0759951e48189cfb96720fe249675fb44ace16be",
"gid": 0,
"group": "root",
"mode": "0644",
"owner": "root",
"path": "/etc/crontab",
"size": 480,
"state": "file",
"uid": 0
}
192.168.10.10 | SUCCESS => {
"changed": false,
"checksum": "0759951e48189cfb96720fe249675fb44ace16be",
"gid": 0,
"group": "root",
"mode": "0644",
"owner": "root",
"path": "/etc/crontab",
"size": 480,
"state": "file",
"uid": 0
}
[root@hadoop1010 inventory]# ansible hadoop -m yum -a 'name=httpd state=latest' -f 100 -o
192.168.10.10 | SUCCESS => {"changed": true, "msg": "", "rc": 0, "results": ["Loaded plugins: fastestmirror, langpacks\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> R
unning transaction check\n---> Package httpd.x86_64 0:2.4.6-67.el7.centos will be updated\n--> Processing Dependency: httpd = 2.4.6-67.el7.centos for package: mod_session-2.4.6-67.el7.centos.x86_64\n---> Package httpd.x86_64 0:2.4.6-98.el7.centos.6 will be an update\n--> Processing Dependency: httpd-tools = 2.4.6-98.el7.centos.6 for package: httpd-2.4.6-98.el7.centos.6.x86_64\n--> Running transaction check\n---> Package httpd-tools.x86_64 0:2.4.6-67.el7.centos will be updated\n---> Package httpd-tools.x86_64 0:2.4.6-98.el7.centos.6 will be an update\n---> Package mod_session.x86_64 0:2.4.6-67.el7.centos will be updated\n---> Package mod_session.x86_64 0:2.4.6-98.el7.centos.6 will be an update\n--> Processing Dependency: apr-util-openssl for package: mod_session-2.4.6-98.el7.centos.6.x86_64\n--> Running transaction check\n---> Package apr-util-openssl.x86_64 0:1.5.2-6.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nUpdating:\n httpd x86_64 2.4.6-98.el7.centos.6 updates 2.7 M\nInstalling for dependencies:\n apr-util-openssl x86_64 1.5.2-6.el7 os 20 k\nUpdating for dependencies:\n httpd-tools x86_64 2.4.6-98.el7.centos.6 updates 94 k\n mod_session x86_64 2.4.6-98.el7.centos.6 updates 64 k\n\nTransaction Summary\n================================================================================\nInstall ( 1 Dependent package)\nUpgrade 1 Package (+2 Dependent packages)\n\nTotal download size: 2.9 M\nDownloading packages:\nDelta RPMs disabled because /usr/bin/applydeltarpm not installed.\n--------------------------------------------------------------------------------\nTotal 1.5 MB/s | 2.9 MB 00:01 \nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Updating : httpd-tools-2.4.6-98.el7.centos.6.x86_64 1/7 \n Updating : httpd-2.4.6-98.el7.centos.6.x86_64 2/7 \n Installing : apr-util-openssl-1.5.2-6.el7.x86_64 3/7 \n Updating : mod_session-2.4.6-98.el7.centos.6.x86_64 4/7 \n Cleanup : mod_session-2.4.6-67.el7.centos.x86_64 5/7 \n Cleanup : httpd-2.4.6-67.el7.centos.x86_64 6/7 \n Cleanup : httpd-tools-2.4.6-67.el7.centos.x86_64 7/7 \n Verifying : httpd-2.4.6-98.el7.centos.6.x86_64 1/7 \n Verifying : mod_session-2.4.6-98.el7.centos.6.x86_64 2/7 \n Verifying : apr-util-openssl-1.5.2-6.el7.x86_64 3/7 \n Verifying : httpd-tools-2.4.6-98.el7.centos.6.x86_64 4/7 \n Verifying : mod_session-2.4.6-67.el7.centos.x86_64 5/7 \n Verifying : httpd-2.4.6-67.el7.centos.x86_64 6/7 \n Verifying : httpd-tools-2.4.6-67.el7.centos.x86_64 7/7 \n\nDependency Installed:\n apr-util-openssl.x86_64 0:1.5.2-6.el7 \n\nUpdated:\n httpd.x86_64 0:2.4.6-98.el7.centos.6 \n\nDependency Updated:\n httpd-tools.x86_64 0:2.4.6-98.el7.centos.6 \n mod_session.x86_64 0:2.4.6-98.el7.centos.6 \n\nComplete!\n"]}
192.168.10.11 | SUCCESS => {"changed": true, "msg": "", "rc": 0, "results": ["Loaded plugins: fastestmirror, langpacks\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> R
unning transaction check\n---> Package httpd.x86_64 0:2.4.6-67.el7.centos will be updated\n--> Processing Dependency: httpd = 2.4.6-67.el7.centos for package: mod_session-2.4.6-67.el7.centos.x86_64\n---> Package httpd.x86_64 0:2.4.6-98.el7.centos.6 will be an update\n--> Processing Dependency: httpd-tools = 2.4.6-98.el7.centos.6 for package: httpd-2.4.6-98.el7.centos.6.x86_64\n--> Running transaction check\n---> Package httpd-tools.x86_64 0:2.4.6-67.el7.centos will be updated\n---> Package httpd-tools.x86_64 0:2.4.6-98.el7.centos.6 will be an update\n---> Package mod_session.x86_64 0:2.4.6-67.el7.centos will be updated\n---> Package mod_session.x86_64 0:2.4.6-98.el7.centos.6 will be an update\n--> Processing Dependency: apr-util-openssl for package: mod_session-2.4.6-98.el7.centos.6.x86_64\n--> Running transaction check\n---> Package apr-util-openssl.x86_64 0:1.5.2-6.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nUpdating:\n httpd x86_64 2.4.6-98.el7.centos.6 updates 2.7 M\nInstalling for dependencies:\n apr-util-openssl x86_64 1.5.2-6.el7 os 20 k\nUpdating for dependencies:\n httpd-tools x86_64 2.4.6-98.el7.centos.6 updates 94 k\n mod_session x86_64 2.4.6-98.el7.centos.6 updates 64 k\n\nTransaction Summary\n================================================================================\nInstall ( 1 Dependent package)\nUpgrade 1 Package (+2 Dependent packages)\n\nTotal download size: 2.9 M\nDownloading packages:\nDelta RPMs disabled because /usr/bin/applydeltarpm not installed.\n--------------------------------------------------------------------------------\nTotal 4.1 MB/s | 2.9 MB 00:00 \nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Updating : httpd-tools-2.4.6-98.el7.centos.6.x86_64 1/7 \n Updating : httpd-2.4.6-98.el7.centos.6.x86_64 2/7 \n Installing : apr-util-openssl-1.5.2-6.el7.x86_64 3/7 \n Updating : mod_session-2.4.6-98.el7.centos.6.x86_64 4/7 \n Cleanup : mod_session-2.4.6-67.el7.centos.x86_64 5/7 \n Cleanup : httpd-2.4.6-67.el7.centos.x86_64 6/7 \n Cleanup : httpd-tools-2.4.6-67.el7.centos.x86_64 7/7 \n Verifying : httpd-2.4.6-98.el7.centos.6.x86_64 1/7 \n Verifying : mod_session-2.4.6-98.el7.centos.6.x86_64 2/7 \n Verifying : apr-util-openssl-1.5.2-6.el7.x86_64 3/7 \n Verifying : httpd-tools-2.4.6-98.el7.centos.6.x86_64 4/7 \n Verifying : mod_session-2.4.6-67.el7.centos.x86_64 5/7 \n Verifying : httpd-2.4.6-67.el7.centos.x86_64 6/7 \n Verifying : httpd-tools-2.4.6-67.el7.centos.x86_64 7/7 \n\nDependency Installed:\n apr-util-openssl.x86_64 0:1.5.2-6.el7 \n\nUpdated:\n httpd.x86_64 0:2.4.6-98.el7.centos.6 \n\nDependency Updated:\n httpd-tools.x86_64 0:2.4.6-98.el7.centos.6 \n mod_session.x86_64 0:2.4.6-98.el7.centos.6 \n\nComplete!\n"]}
[root@hadoop1010 inventory]# ansible hadoop -m shell -a "netstat -tpln|grep httpd"
192.168.10.11 | SUCCESS | rc=0 >>
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 18242/httpd
tcp 0 0 0.0.0.0:8443 0.0.0.0:* LISTEN 18242/httpd
192.168.10.12 | SUCCESS | rc=0 >>
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 18183/httpd
tcp 0 0 0.0.0.0:8443 0.0.0.0:* LISTEN 18183/httpd
192.168.10.10 | SUCCESS | rc=0 >>
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 11663/httpd
tcp 0 0 0.0.0.0:8443 0.0.0.0:* LISTEN 11663/httpd
[root@hadoop1010 inventory]# ansible hadoop -m service -a 'name=httpd state=stopped' -f 100 -o
192.168.10.10 | SUCCESS => {"changed": true, "name": "httpd", "state": "stopped", "status": {"ActiveEnterTimestamp": "Tue 2023-03-07 16:04:45 CST", "ActiveEnterTimestampMonotonic": "2526690314"
, "ActiveExitTimestampMonotonic": "0", "ActiveState": "active", "After": "-.mount systemd-journald.socket remote-fs.target network.target nss-lookup.target tmp.mount system.slice basic.target", "AllowIsolate": "no", "AmbientCapabilities": "0", "AssertResult": "yes", "AssertTimestamp": "Tue 2023-03-07 16:04:44 CST", "AssertTimestampMonotonic": "2526408337", "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": "yes", "ConditionTimestamp": "Tue 2023-03-07 16:04:44 CST", "ConditionTimestampMonotonic": "2526408337", "Conflicts": "shutdown.target", "ControlGroup": "/system.slice/httpd.service", "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": "11663", "ExecMainStartTimestamp": "Tue 2023-03-07 16:04:44 CST", "ExecMainStartTimestampMonotonic": "2526409566", "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=[Tue 2023-03-07 16:04:44 CST] ; stop_time=[n/a] ; pid=11663 ; 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", "InactiveExitTimestamp": "Tue 2023-03-07 16:04:44 CST", "InactiveExitTimestampMonotonic": "2526409602", "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": "15582", "LimitRSS": "18446744073709551615", "LimitRTPRIO": "0", "LimitRTTIME": "18446744073709551615", "LimitSIGPENDING": "15582", "LimitSTACK": "18446744073709551615", "LoadState": "loaded", "MainPID": "11663", "MemoryAccounting": "no", "MemoryCurrent": "84697088", "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": "system.slice -.mount basic.target", "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", "StatusText": "Total requests: 0; Current requests/sec: 0; Current traffic: 0 B/sec", "StopWhenUnneeded": "no", "SubState": "running", "SyslogLevelPrefix": "yes", "SyslogPriority": "30", "SystemCallErrorNumber": "0", "TTYReset": "no", "TTYVHangup": "no", "TTYVTDisallocate": "no", "TasksAccounting": "no", "TasksCurrent": "7", "TasksMax": "18446744073709551615", "TimeoutStartUSec": "1min 30s", "TimeoutStopUSec": "1min 30s", "TimerSlackNSec": "50000", "Transient": "no", "Type": "notify", "UMask": "0022", "UnitFilePreset": "disabled", "UnitFileState": "disabled", "WatchdogTimestamp": "Tue 2023-03-07 16:04:45 CST", "WatchdogTimestampMonotonic": "2526690275", "WatchdogUSec": "0"}}192.168.10.12 | SUCCESS => {"changed": true, "name": "httpd", "state": "stopped", "status": {"ActiveEnterTimestamp": "Tue 2023-03-07 16:04:45 CST", "ActiveEnterTimestampMonotonic": "2518831853"
, "ActiveExitTimestampMonotonic": "0", "ActiveState": "active", "After": "network.target system.slice remote-fs.target systemd-journald.socket nss-lookup.target tmp.mount -.mount basic.target", "AllowIsolate": "no", "AmbientCapabilities": "0", "AssertResult": "yes", "AssertTimestamp": "Tue 2023-03-07 16:04:44 CST", "AssertTimestampMonotonic": "2518561304", "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": "yes", "ConditionTimestamp": "Tue 2023-03-07 16:04:44 CST", "ConditionTimestampMonotonic": "2518561304", "Conflicts": "shutdown.target", "ControlGroup": "/system.slice/httpd.service", "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": "18183", "ExecMainStartTimestamp": "Tue 2023-03-07 16:04:44 CST", "ExecMainStartTimestampMonotonic": "2518563358", "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=[Tue 2023-03-07 16:04:44 CST] ; stop_time=[n/a] ; pid=18183 ; 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", "InactiveExitTimestamp": "Tue 2023-03-07 16:04:44 CST", "InactiveExitTimestampMonotonic": "2518563428", "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": "15584", "LimitRSS": "18446744073709551615", "LimitRTPRIO": "0", "LimitRTTIME": "18446744073709551615", "LimitSIGPENDING": "15584", "LimitSTACK": "18446744073709551615", "LoadState": "loaded", "MainPID": "18183", "MemoryAccounting": "no", "MemoryCurrent": "94916608", "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": "system.slice -.mount basic.target", "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", "StatusText": "Total requests: 0; Current requests/sec: 0; Current traffic: 0 B/sec", "StopWhenUnneeded": "no", "SubState": "running", "SyslogLevelPrefix": "yes", "SyslogPriority": "30", "SystemCallErrorNumber": "0", "TTYReset": "no", "TTYVHangup": "no", "TTYVTDisallocate": "no", "TasksAccounting": "no", "TasksCurrent": "7", "TasksMax": "18446744073709551615", "TimeoutStartUSec": "1min 30s", "TimeoutStopUSec": "1min 30s", "TimerSlackNSec": "50000", "Transient": "no", "Type": "notify", "UMask": "0022", "UnitFilePreset": "disabled", "UnitFileState": "disabled", "WatchdogTimestamp": "Tue 2023-03-07 16:04:45 CST", "WatchdogTimestampMonotonic": "2518831813", "WatchdogUSec": "0"}}192.168.10.11 | SUCCESS => {"changed": true, "name": "httpd", "state": "stopped", "status": {"ActiveEnterTimestamp": "Tue 2023-03-07 16:04:45 CST", "ActiveEnterTimestampMonotonic": "2521760220"
, "ActiveExitTimestampMonotonic": "0", "ActiveState": "active", "After": "tmp.mount system.slice nss-lookup.target systemd-journald.socket basic.target -.mount remote-fs.target network.target", "AllowIsolate": "no", "AmbientCapabilities": "0", "AssertResult": "yes", "AssertTimestamp": "Tue 2023-03-07 16:04:44 CST", "AssertTimestampMonotonic": "2521497141", "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": "yes", "ConditionTimestamp": "Tue 2023-03-07 16:04:44 CST", "ConditionTimestampMonotonic": "2521497140", "Conflicts": "shutdown.target", "ControlGroup": "/system.slice/httpd.service", "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": "18242", "ExecMainStartTimestamp": "Tue 2023-03-07 16:04:44 CST", "ExecMainStartTimestampMonotonic": "2521498748", "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=[Tue 2023-03-07 16:04:44 CST] ; stop_time=[n/a] ; pid=18242 ; 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", "InactiveExitTimestamp": "Tue 2023-03-07 16:04:44 CST", "InactiveExitTimestampMonotonic": "2521498797", "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": "15584", "LimitRSS": "18446744073709551615", "LimitRTPRIO": "0", "LimitRTTIME": "18446744073709551615", "LimitSIGPENDING": "15584", "LimitSTACK": "18446744073709551615", "LoadState": "loaded", "MainPID": "18242", "MemoryAccounting": "no", "MemoryCurrent": "84500480", "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": "system.slice -.mount basic.target", "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", "StatusText": "Total requests: 0; Current requests/sec: 0; Current traffic: 0 B/sec", "StopWhenUnneeded": "no", "SubState": "running", "SyslogLevelPrefix": "yes", "SyslogPriority": "30", "SystemCallErrorNumber": "0", "TTYReset": "no", "TTYVHangup": "no", "TTYVTDisallocate": "no", "TasksAccounting": "no", "TasksCurrent": "7", "TasksMax": "18446744073709551615", "TimeoutStartUSec": "1min 30s", "TimeoutStopUSec": "1min 30s", "TimerSlackNSec": "50000", "Transient": "no", "Type": "notify", "UMask": "0022", "UnitFilePreset": "disabled", "UnitFileState": "disabled", "WatchdogTimestamp": "Tue 2023-03-07 16:04:45 CST", "WatchdogTimestampMonotonic": "2521760187", "WatchdogUSec": "0"}}
[root@hadoop1010 inventory]# ansible hadoop -m shell -a "netstat -tpln|grep httpd"
192.168.10.12 | FAILED | rc=1 >>
non-zero return code
192.168.10.10 | FAILED | rc=1 >>
non-zero return code
192.168.10.11 | FAILED | rc=1 >>
non-zero return code
#普通加密:
[root@hadoop1010 inventory]# python3 -c 'import crypt; print (crypt.crypt("123456","machine110"))'
maBYdC7TaW1Vk
[root@hadoop1010 inventory]# ansible hadoop -m user -a 'name=machine10 password="maBYdC7TaW1Vk"' -f 5 -o
192.168.10.12 | SUCCESS => {"append": false, "changed": true, "comment": "", "group": 1007, "home": "/home/machine10", "move_home": false, "name": "machine10", "password": "NOT_LOGGING_PASSWORD
", "shell": "/bin/bash", "state": "present", "uid": 1007}192.168.10.10 | SUCCESS => {"append": false, "changed": true, "comment": "", "group": 1007, "home": "/home/machine10", "move_home": false, "name": "machine10", "password": "NOT_LOGGING_PASSWORD
", "shell": "/bin/bash", "state": "present", "uid": 1007}192.168.10.11 | SUCCESS => {"append": false, "changed": true, "comment": "", "group": 1007, "home": "/home/machine10", "move_home": false, "name": "machine10", "password": "NOT_LOGGING_PASSWORD
", "shell": "/bin/bash", "state": "present", "uid": 1007}[root@hadoop1010 inventory]# ansible hadoop -m user -a 'name=machine110 password="maBYdC7TaW1Vk"' -f 5 -o
192.168.10.12 | SUCCESS => {"changed": true, "comment": "", "createhome": true, "group": 1008, "home": "/home/machine110", "name": "machine110", "password": "NOT_LOGGING_PASSWORD", "shell": "/b
in/bash", "state": "present", "system": false, "uid": 1008}192.168.10.10 | SUCCESS => {"changed": true, "comment": "", "createhome": true, "group": 1008, "home": "/home/machine110", "name": "machine110", "password": "NOT_LOGGING_PASSWORD", "shell": "/b
in/bash", "state": "present", "system": false, "uid": 1008}192.168.10.11 | SUCCESS => {"changed": true, "comment": "", "createhome": true, "group": 1008, "home": "/home/machine110", "name": "machine110", "password": "NOT_LOGGING_PASSWORD", "shell": "/b
in/bash", "state": "present", "system": false, "uid": 1008}[root@hadoop1010 inventory]# ssh 192.168.10.11 -l machine110
[email protected]'s password:
[machine110@hadoop1011 ~]$ logout
Connection to 192.168.10.11 closed.
[root@hadoop1010 inventory]# ssh 192.168.10.12 -l machine110
[email protected]'s password:
[machine110@hadoop1012 ~]$ logout
Connection to 192.168.10.12 closed.
[root@hadoop1010 inventory]#
#python 3.x 版本(sha512 加密算法):
[root@hadoop1010 inventory]# pip3 install passlib
WARNING: Running pip install with root privileges is generally not a good idea. Try `pip3 install --user` instead.
Collecting passlib
Downloading https://files.pythonhosted.org/packages/3b/a4/ab6b7589382ca3df236e03faa71deac88cae040af60c071a78d254a62172/passlib-1.7.4-py2.py3-none-any.whl (525kB)
100% |████████████████████████████████| 532kB 226kB/s
Installing collected packages: passlib
Successfully installed passlib-1.7.4
[root@hadoop1010 inventory]# python3.6
Python 3.6.8 (default, Nov 16 2020, 16:55:22)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from passlib.hash import sha512_crypt
#设置密码为:machine
[root@hadoop1010 inventory]# python3 -c 'from passlib.hash import sha512_crypt; import getpass; print (sha512_crypt.encrypt(getpass.getpass()))'
Password:
$6$rounds=656000$BJMIzZasbvoswqQH$qMmlcpWbFAyD5o/8VrnW9RM1twr0gTz/QG/N4Fp6D6idGRONVtIyisqtsBla/Q0LD034AIIhdRQgbRbawkAC81
[root@hadoop1010 inventory]# ansible hadoop -m user -a 'name=machine111 password="$6$rounds=656000$BJMIzZasbvoswqQH$qMmlcpWbFAyD5o/8VrnW9RM1twr0gTz/QG/N4Fp6D6idGRONVtIyisqtsBla/Q0LD034AIIhdRQg
bRbawkAC81"' -f 5 -o192.168.10.10 | SUCCESS => {"changed": true, "comment": "", "createhome": true, "group": 1009, "home": "/home/machine111", "name": "machine111", "password": "NOT_LOGGING_PASSWORD", "shell": "/b
in/bash", "state": "present", "system": false, "uid": 1009}192.168.10.12 | SUCCESS => {"changed": true, "comment": "", "createhome": true, "group": 1009, "home": "/home/machine111", "name": "machine111", "password": "NOT_LOGGING_PASSWORD", "shell": "/b
in/bash", "state": "present", "system": false, "uid": 1009}192.168.10.11 | SUCCESS => {"changed": true, "comment": "", "createhome": true, "group": 1009, "home": "/home/machine111", "name": "machine111", "password": "NOT_LOGGING_PASSWORD", "shell": "/b
in/bash", "state": "present", "system": false, "uid": 1009}[root@hadoop1010 inventory]# ssh 192.168.10.11 -l machine111
#测试登录成功
[email protected]'s password:
[machine111@hadoop1011 ~]$
playbook是ansible进行配置管理的组件,实际生产工作中,编写playbook进行自动化运维
facts组件时ansible用于采集被管机器设备信息的一个功能,可以使用setup模块查机器的所有facts信息,可用filter来查看指定的信息。
root@hadoop1010 inventory]# ansible hadoop -m yum -a 'name=facter state=latest'
192.168.10.12 | SUCCESS => {
"changed": true,
"msg": "warning: /var/cache/yum/x86_64/7/epel/packages/facter-2.4.1-1.el7.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID 352c64e5: NOKEY\nImporting GPG key 0x352C64E5:\n Userid : \"
Fedora EPEL (7) \"\n Fingerprint: 91e9 7d7c 4a5e 96f1 7f3e 888f 6a2f aea2 352c 64e5\n From : http://mirrors.cloud.tencent.com/epel/RPM-GPG-KEY-EPEL-7\n" , "rc": 0,
"results": [
"Loaded plugins: fastestmirror, langpacks\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package facter.x86_64 0:2.4.1-1.el7 wi
ll be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n facter x86_64 2.4.1-1.el7 epel 101 k\n\nTransaction Summary\n================================================================================\nInstall 1 Package\n\nTotal download size: 101 k\nInstalled size: 271 k\nDownloading packages:\nPublic key for facter-2.4.1-1.el7.x86_64.rpm is not installed\nRetrieving key from http://mirrors.cloud.tencent.com/epel/RPM-GPG-KEY-EPEL-7\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : facter-2.4.1-1.el7.x86_64 1/1 \n Verifying : facter-2.4.1-1.el7.x86_64 1/1 \n\nInstalled:\n facter.x86_64 0:2.4.1-1.el7 \n\nComplete!\n" ]
}
192.168.10.11 | SUCCESS => {
"changed": true,
"msg": "warning: /var/cache/yum/x86_64/7/epel/packages/facter-2.4.1-1.el7.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID 352c64e5: NOKEY\nImporting GPG key 0x352C64E5:\n Userid : \"
Fedora EPEL (7) \"\n Fingerprint: 91e9 7d7c 4a5e 96f1 7f3e 888f 6a2f aea2 352c 64e5\n From : http://mirrors.cloud.tencent.com/epel/RPM-GPG-KEY-EPEL-7\n" , "rc": 0,
"results": [
"Loaded plugins: fastestmirror, langpacks\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package facter.x86_64 0:2.4.1-1.el7 wi
ll be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n facter x86_64 2.4.1-1.el7 epel 101 k\n\nTransaction Summary\n================================================================================\nInstall 1 Package\n\nTotal download size: 101 k\nInstalled size: 271 k\nDownloading packages:\nPublic key for facter-2.4.1-1.el7.x86_64.rpm is not installed\nRetrieving key from http://mirrors.cloud.tencent.com/epel/RPM-GPG-KEY-EPEL-7\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : facter-2.4.1-1.el7.x86_64 1/1 \n Verifying : facter-2.4.1-1.el7.x86_64 1/1 \n\nInstalled:\n facter.x86_64 0:2.4.1-1.el7 \n\nComplete!\n" ]
}
192.168.10.10 | SUCCESS => {
"changed": true,
"msg": "",
"rc": 0,
"results": [
"Loaded plugins: fastestmirror, langpacks\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package facter.x86_64 0:2.4.1-1.el7 wi
ll be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n facter x86_64 2.4.1-1.el7 epel 101 k\n\nTransaction Summary\n================================================================================\nInstall 1 Package\n\nTotal download size: 101 k\nInstalled size: 271 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : facter-2.4.1-1.el7.x86_64 1/1 \n Verifying : facter-2.4.1-1.el7.x86_64 1/1 \n\nInstalled:\n facter.x86_64 0:2.4.1-1.el7 \n\nComplete!\n" ]
}
[root@hadoop1010 inventory]# ansible hadoop -m shell -a 'rpm -qa httpd facter'
[WARNING]: Consider using yum, dnf or zypper module rather than running rpm
192.168.10.11 | SUCCESS | rc=0 >>
httpd-2.4.6-98.el7.centos.6.x86_64
facter-2.4.1-1.el7.x86_64
192.168.10.12 | SUCCESS | rc=0 >>
httpd-2.4.6-98.el7.centos.6.x86_64
facter-2.4.1-1.el7.x86_64
192.168.10.10 | SUCCESS | rc=0 >>
facter-2.4.1-1.el7.x86_64
httpd-2.4.6-98.el7.centos.6.x86_64
[root@hadoop1010 inventory]# ansible hadoop -m facter
192.168.10.10 | SUCCESS => {
"architecture": "x86_64",
"bios_release_date": "11/12/2020",
"bios_vendor": "Phoenix Technologies LTD",
"bios_version": "6.00",
"blockdevice_sda_model": "VMware Virtual S",
"blockdevice_sda_size": 53687091200,
"blockdevice_sda_vendor": "VMware,",
"blockdevice_sr0_model": "VMware SATA CD00",
"blockdevice_sr0_size": 8694792192,
"blockdevice_sr0_vendor": "NECVMWar",
"blockdevices": "sda,sr0",
"boardmanufacturer": "Intel Corporation",
"boardproductname": "440BX Desktop Reference Platform",
"boardserialnumber": "None",
"changed": false,
"domain": "localdomain",
"facterversion": "2.4.1",
"filesystems": "xfs",
"fqdn": "hadoop1010.localdomain",
"gid": "root",
"hardwareisa": "x86_64",
"hardwaremodel": "x86_64",
"hostname": "hadoop1010",
"id": "root",
"interfaces": "docker0,ens33,flannel_1,lo",
"ipaddress": "172.30.24.1",
"ipaddress_docker0": "172.30.24.1",
"ipaddress_ens33": "192.168.10.10",
"ipaddress_flannel_1": "172.30.24.0",
"ipaddress_lo": "127.0.0.1",
"is_virtual": true,
"kernel": "Linux",
"kernelmajversion": "4.19",
"kernelrelease": "4.19.12-1.el7.elrepo.x86_64",
"kernelversion": "4.19.12",
"macaddress": "02:42:0f:5b:a7:51",
"macaddress_docker0": "02:42:0f:5b:a7:51",
"macaddress_ens33": "00:0c:29:66:35:7d",
"macaddress_flannel_1": "5e:9c:ed:8d:bf:c2",
"manufacturer": "VMware, Inc.",
"memoryfree": "2.91 GB",
"memoryfree_mb": "2979.63",
"memorysize": "3.83 GB",
"memorysize_mb": "3921.13",
"mtu_docker0": 1500,
"mtu_ens33": 1500,
"mtu_flannel_1": 1450,
"mtu_lo": 65536,
"netmask": "255.255.255.0",
"netmask_docker0": "255.255.255.0",
"netmask_ens33": "255.255.255.0",
"netmask_flannel_1": "255.255.255.255",
"netmask_lo": "255.0.0.0",
"network_docker0": "172.30.24.0",
"network_ens33": "192.168.10.0",
"network_flannel_1": "172.30.24.0",
"network_lo": "127.0.0.0",
"operatingsystem": "CentOS",
"operatingsystemmajrelease": "7",
"operatingsystemrelease": "7.4.1708",
"os": {
"family": "RedHat",
"name": "CentOS",
"release": {
"full": "7.4.1708",
"major": "7",
"minor": "4"
}
},
"osfamily": "RedHat",
"partitions": {
"sda1": {
"filesystem": "xfs",
"mount": "/boot",
"size": "2097152",
"uuid": "984f99bd-0b89-4270-8ec0-296e8765f63c"
},
"sda2": {
"filesystem": "LVM2_member",
"size": "102758400"
}
},
"path": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/home/hadoop-2.6.5/bin:/home/hadoop-2.6.5/sbin:/home/java/bin:/home/zookeeper/bin",
"physicalprocessorcount": 2,
"processor0": "11th Gen Intel(R) Core(TM) i5-11320H @ 3.20GHz",
"processor1": "11th Gen Intel(R) Core(TM) i5-11320H @ 3.20GHz",
"processorcount": 2,
"processors": {
"count": 2,
"models": [
"11th Gen Intel(R) Core(TM) i5-11320H @ 3.20GHz",
"11th Gen Intel(R) Core(TM) i5-11320H @ 3.20GHz"
],
"physicalcount": 2
},
"productname": "VMware Virtual Platform",
"ps": "ps -ef",
"rubyplatform": "x86_64-linux",
"rubysitedir": "/usr/local/share/ruby/site_ruby/",
"rubyversion": "2.0.0",
"selinux": false,
"serialnumber": "VMware-56 4d e1 7d 04 4b e5 79-c3 b1 65 80 f6 66 35 7d",
"sshecdsakey": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFBgzEnfN0Qxw0Zabi7p06kE2u+zmWRUB0JpxTQBdgRpS5KLHzPfAydR7/egNSjfuzlvzqU0CeToiyWqtanxXmo=",
"sshed25519key": "AAAAC3NzaC1lZDI1NTE5AAAAIHUQZVeOEA/4YoGe8T9ZHQR3pg253QD9BWnt7KRQDCH2",
"sshfp_ecdsa": "SSHFP 3 1 83f193529c42860b08b2973e43e8d9210172dacd\nSSHFP 3 2 0c6571c721d71600538a5bdb6998f45904d732e6c9d69fc5cfc73ae47da24f4b",
"sshfp_ed25519": "SSHFP 4 1 6a4a1b8eeb6b9d0f16620a0d5c3d3c01b540be93\nSSHFP 4 2 cb4b230ae9f8e5f645d0b4c122d6fa84b230f20b47f1a4b6b1f98177affd927b",
"sshfp_rsa": "SSHFP 1 1 20b5c4fbfeafb859fb644fe7ea887982aa37c552\nSSHFP 1 2 39f2e18e727e04d034ca6dce45603d9a0eeed8201841f293c680cee8651260e3",
"sshrsakey": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDrus8AgKdZ6lsPqCfaIuUMPbc8XRMiw0BrMTK92bk24HKc9ABQ3mowDjZXfj1s9OpVIAX4bSHSqxzLpvdZEEv911pvz2Zllxvu0xbwnjbhJJBiywMk/GDuq+oTYeEY3viGoOmGA4q8ZbPkgzV
FxRmg3OLUc8vFasrnXQ60iS20gFhuZVMxrBM58TUOubZaqiUDaOxkMPIY+TzP7+Vox24N1YTIwfh6vEsA/jPICDvZo3QecAwMnEg7yKAs0q3sDiDZozCou3o7qJZUM3QOTVKhLqYnWh97zruWErWo6fdkGHzTkOCMV5VnYYtPpiuxUCBHt4gLVBvd1tkCwSJtOap7", "state": "absent",
"swapfree": "0.00 MB",
"swapfree_mb": "0.00",
"swapsize": "0.00 MB",
"swapsize_mb": "0.00",
"system_uptime": {
"days": 0,
"hours": 1,
"seconds": 5574,
"uptime": "1:32 hours"
},
"timezone": "CST",
"type": "Other",
"uniqueid": "a8c00a0a",
"uptime": "1:32 hours",
"uptime_days": 0,
"uptime_hours": 1,
"uptime_seconds": 5574,
"uuid": "7DE14D56-4B04-79E5-C3B1-6580F666357D",
"virtual": "vmware"
}
实际生产工作过程中,很多不同业务需要编写很多playbook文件,如果时间久了,维护playbook是一件艰难的事情,这个时候我们就可以采用role的方式管理playbook。
role只是对我们日常使用的playbook的目录结构进行一些规范,与日常的playbook没什么区别。
部署nginx的playbook目录:
role的所有文件内容都是在nginx目录下。
playbook调测过程实例:
[root@hadoop1010 roles]# cd /etc/ansible/roles
[root@hadoop1010 roles]# mkdir nginx
[root@hadoop1010 roles]# cd nginx/
[root@hadoop1010 nginx]# mkdir {files,handlers,tasks,templates,vars}
[root@hadoop1010 nginx]# ansible-playbook -i hosts site.yaml
ERROR! Syntax Error while loading YAML.
The error appears to have been in '/etc/ansible/roles/nginx/site.yaml': line 3, column 10, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- hosts: 192.168.10.12
roles:
^ here
exception type: <class 'yaml.scanner.ScannerError'>
exception: mapping values are not allowed in this context
in "" , line 3, column 10
[root@hadoop1010 nginx]# ansible-playbook --syntax-check site.yaml
ERROR! Syntax Error while loading YAML.
The error appears to have been in '/etc/ansible/roles/nginx/site.yaml': line 3, column 10, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- hosts: 192.168.10.12
roles:
^ here
exception type: <class 'yaml.scanner.ScannerError'>
exception: mapping values are not allowed in this context
in "" , line 3, column 1
[root@hadoop1010 nginx]# ansible-playbook --syntax-check site.yaml
ERROR! Syntax Error while loading YAML.
The error appears to have been in '/etc/ansible/roles/nginx/tasks/main.yaml': line 3, column 9, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- name: Install nginx package
yum: name=nginx-{{version}} state=present
^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:
with_items:
- {{ foo }}
Should be written as:
with_items:
- "{{ foo }}"
exception type: <class 'yaml.scanner.ScannerError'>
exception: mapping values are not allowed in this context
in "" , line 3, column 9
[root@hadoop1010 nginx]# vim site.yaml
[root@hadoop1010 nginx]# vim tasks/main.yaml
[root@hadoop1010 nginx]# ansible-playbook --syntax-check site.yaml
ERROR! Syntax Error while loading YAML.
The error appears to have been in '/etc/ansible/roles/nginx/handlers/main.yaml': line 3, column 13, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- name: restart nginx
service: name=nginx state=restarted
^ here
exception type: <class 'yaml.scanner.ScannerError'>
exception: mapping values are not allowed in this context
in ""
[root@hadoop1010 nginx]# vim handlers/main.yaml
[root@hadoop1010 nginx]# ansible-playbook --syntax-check site.yaml
playbook: site.yaml
[root@hadoop1010 nginx]# ansible-playbook --syntax-check site.yaml
playbook: site.yaml
[root@hadoop1010 nginx]# ansible-playbook -i hosts site.yaml
PLAY [192.168.10.12] ****************************************************************************************************************************************************************************
TASK [Gathering Facts] **************************************************************************************************************************************************************************
ok: [192.168.10.12]
TASK [nginx : Install nginx package] ************************************************************************************************************************************************************
changed: [192.168.10.12]
TASK [nginx : Copy nginx.conf Template] *********************************************************************************************************************************************************
changed: [192.168.10.12]
TASK [nginx : Copy index html] ******************************************************************************************************************************************************************
changed: [192.168.10.12]
TASK [nginx : make sure nginx service running] **************************************************************************************************************************************************
fatal: [192.168.10.12]: FAILED! => {"changed": false, "msg": "Unable to start service nginx: Job for nginx.service failed because the control process exited with error code. See \"systemctl sta
tus nginx.service\" and \"journalctl -xe\" for details.\n"} to retry, use: --limit @/etc/ansible/roles/nginx/site.retry
PLAY RECAP **************************************************************************************************************************************************************************************
192.168.10.12 : ok=4 changed=3 unreachable=0 failed=1
[root@hadoop1010 nginx]# vim templates/nginx.conf.j2
[root@hadoop1010 nginx]# ansible-playbook -i hosts site.yaml
PLAY [192.168.10.12] ****************************************************************************************************************************************************************************
TASK [Gathering Facts] **************************************************************************************************************************************************************************
ok: [192.168.10.12]
TASK [nginx : Install nginx package] ************************************************************************************************************************************************************
ok: [192.168.10.12]
TASK [nginx : Copy nginx.conf Template] *********************************************************************************************************************************************************
ok: [192.168.10.12]
TASK [nginx : Copy index html] ******************************************************************************************************************************************************************
ok: [192.168.10.12]
TASK [nginx : make sure nginx service running] **************************************************************************************************************************************************
fatal: [192.168.10.12]: FAILED! => {"changed": false, "msg": "Unable to start service nginx: Job for nginx.service failed because the control process exited with error code. See \"systemctl sta
tus nginx.service\" and \"journalctl -xe\" for details.\n"} to retry, use: --limit @/etc/ansible/roles/nginx/site.retry
PLAY RECAP **************************************************************************************************************************************************************************************
192.168.10.12 : ok=4 changed=0 unreachable=0 failed=1
[root@hadoop1010 nginx]# vim templates/nginx.conf.j2
[root@hadoop1010 nginx]# vim templates/nginx.conf.j2
[root@hadoop1010 nginx]# grep ansible_processor_cores * -R
templates/nginx.conf.j2:woker_processes {{ansible_processor_cores}};
[root@hadoop1010 nginx]# vim templates/nginx.conf.j2
[root@hadoop1010 nginx]# ansible-playbook -i hosts site.yaml
PLAY [192.168.10.12] ****************************************************************************************************************************************************************************
TASK [Gathering Facts] **************************************************************************************************************************************************************************
ok: [192.168.10.12]
TASK [nginx : Install nginx package] ************************************************************************************************************************************************************
ok: [192.168.10.12]
TASK [nginx : Copy nginx.conf Template] *********************************************************************************************************************************************************
ok: [192.168.10.12]
TASK [nginx : Copy index html] ******************************************************************************************************************************************************************
ok: [192.168.10.12]
TASK [nginx : make sure nginx service running] **************************************************************************************************************************************************
ok: [192.168.10.12]
PLAY RECAP **************************************************************************************************************************************************************************************
192.168.10.12 : ok=5 changed=0 unreachable=0 failed=0
[root@hadoop1010 nginx]# tree .
.
├── files
│ └── index.html
├── handlers
│ └── main.yaml
├── hosts
├── site.retry
├── site.yaml
├── tasks
│ └── main.yaml
├── templates
│ └── nginx.conf.j2
└── vars
5 directories, 7 files