ansible剧本
ansible中有两种模式,分别是ad-hoc模式和playbook模式
ad-hoc简而言之,就是"临时命令"
- 临时的看下远程机器的内存信息
- 临时的批量分发一个配置文件
特别小的需求,临时命令就解决
大需求,部署软件这样的复杂需求,就写剧本
https://docs.ansible.com/ansible/latest/user_guide/intro_adhoc.html
临时命令非常适合您很少重复的任务,例如,如果您想在圣诞节假期关闭实验室中的所有机器
Ansible ad hoc 命令使用/usr/bin/ansible命令行工具在一个或多个托管节点上自动执行单个任务,ad hoc 命令既快速又简单,但它们不可重复使用
一.剧本是什么
既然要写剧本,就得按照剧本的格式去编写
【比如一个电影剧本】
电影名
演员
场景
时间
事件
台词
道具
ansible剧本,一系列的任务,按照我们期望的结果编排在一起
hosts: 定义主机角色
tasks: 具体执行的任务
- 演员列表: 老王
场景:
- 场景1:
动作1:
- 场景2:
动作1:
对比playbook的语法
- hosts: 需要执行的机器,nfs
tasks:
- 任务1:安装nfs
动作: yum install nfs
- 任务2:创建数据目录
动作: mkdir -p xxxx
在playbook中,列表是定义一个局部环境,名字可有可无,表示定义一个范围,范围内的属性都属于该列表
要注意的是每一个playbook都必须包含hosts、tasks选项,也就是你剧本,至少得有
- hosts、某个人、某个机器
- tasks、这人要做什么、这机器要做什么
二.修改ansible的输出结果为json
json 数据转换格式,专有的语法
可以在网络中传输
发给后端 python (python的数据类型,去解析json的数据格式,处理)
也可以发给前端 (js, js解析json的数据格式,然后处理)
运维怎么处理json,jq命令,(获取到json数据后,提取json的数据)
# 1.修改ansible的配置文件,让它输出的结果是一个json
[root@ansible-1 opt]#vim /etc/ansible/ansible.cfg
[defaults]
stdout_callback = json
bin_ansible_callbacks = True
74 stdout_callback = json
213 bin_ansible_callbacks = true
json的作用就是
定义了一堆 键值对的数据格式
根据key就可以拿到value
{ "key": "value" } 读作字典形式
可以看到,此时ansible的命令输出结果,全部变为了json的格式
devops 运维开发
python
都是开发工程师做的
这些json数据,就可以发给后端,去处理,再最终发给前端
三.yaml语法
ansible软件的playbook编写需要遵循YAML语法,因此我们得先学一下YAML语法结构
在线json转换yaml
安装nginx的示例对比
ad-hoc命令模式
[root@m01 ~]# ansible web -m yum -a "name=nginx state=absent"
[root@m01 ~]# ansible web -m shell -a "rpm -qa nginx warn=false"
范例:
[root@ansible-1 ~]# ansible web -m yum -a "name=nginx state=absent"
{
"custom_stats": {},
"global_custom_stats": {},
"plays": [
{
"play": {
"duration": {
"end": "2024-04-23T07:47:40.138387Z",
"start": "2024-04-23T07:47:25.119969Z"
},
"id": "000c2963-21e0-25a6-0ccc-00000000000b",
"name": "Ansible Ad-Hoc"
},
"tasks": [
{
"hosts": {
"10.0.1.185": {
"_ansible_no_log": false,
"action": "yum",
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"removed": [
"nginx"
]
},
"invocation": {
"module_args": {
"allow_downgrade": false,
"autoremove": false,
"bugfix": false,
"conf_file": null,
"disable_excludes": null,
"disable_gpg_check": false,
"disable_plugin": [],
"disablerepo": [],
"download_dir": null,
"download_only": false,
"enable_plugin": [],
"enablerepo": [],
"exclude": [],
"install_repoquery": true,
"install_weak_deps": true,
"installroot": "/",
"list": null,
"lock_timeout": 30,
"name": [
"nginx"
],
"releasever": null,
"security": false,
"skip_broken": false,
"state": "absent",
"update_cache": false,
"update_only": false,
"use_backend": "auto",
"validate_certs": true
}
},
"msg": "",
"rc": 0,
"results": [
"Loaded plugins: fastestmirror\nResolving Dependencies\n--> Running transaction check\n---> Package nginx.x86_64 1:1.20.1-10.el7 will be erased\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nRemoving:\n nginx x86_64 1:1.20.1-10.el7 @epel 1.7 M\n\nTransaction Summary\n================================================================================\nRemove 1 Package\n\nInstalled size: 1.7 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Erasing : 1:nginx-1.20.1-10.el7.x86_64 1/1 \n Verifying : 1:nginx-1.20.1-10.el7.x86_64 1/1 \n\nRemoved:\n nginx.x86_64 1:1.20.1-10.el7 \n\nComplete!\n"
]
},
"10.0.1.186": {
"_ansible_no_log": false,
"action": "yum",
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"invocation": {
"module_args": {
"allow_downgrade": false,
"autoremove": false,
"bugfix": false,
"conf_file": null,
"disable_excludes": null,
"disable_gpg_check": false,
"disable_plugin": [],
"disablerepo": [],
"download_dir": null,
"download_only": false,
"enable_plugin": [],
"enablerepo": [],
"exclude": [],
"install_repoquery": true,
"install_weak_deps": true,
"installroot": "/",
"list": null,
"lock_timeout": 30,
"name": [
"nginx"
],
"releasever": null,
"security": false,
"skip_broken": false,
"state": "absent",
"update_cache": false,
"update_only": false,
"use_backend": "auto",
"validate_certs": true
}
},
"msg": "",
"rc": 0,
"results": [
"nginx is not installed"
]
},
"10.0.1.187": {
"_ansible_no_log": false,
"action": "yum",
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"invocation": {
"module_args": {
"allow_downgrade": false,
"autoremove": false,
"bugfix": false,
"conf_file": null,
"disable_excludes": null,
"disable_gpg_check": false,
"disable_plugin": [],
"disablerepo": [],
"download_dir": null,
"download_only": false,
"enable_plugin": [],
"enablerepo": [],
"exclude": [],
"install_repoquery": true,
"install_weak_deps": true,
"installroot": "/",
"list": null,
"lock_timeout": 30,
"name": [
"nginx"
],
"releasever": null,
"security": false,
"skip_broken": false,
"state": "absent",
"update_cache": false,
"update_only": false,
"use_backend": "auto",
"validate_certs": true
}
},
"msg": "",
"rc": 0,
"results": [
"nginx is not installed"
]
}
},
"task": {
"duration": {
"end": "2024-04-23T07:47:40.138387Z",
"start": "2024-04-23T07:47:25.178908Z"
},
"id": "000c2963-21e0-25a6-0ccc-00000000000d",
"name": "yum"
}
}
]
}
],
"stats": {
"10.0.1.185": {
"changed": 1,
"failures": 0,
"ignored": 0,
"ok": 1,
"rescued": 0,
"skipped": 0,
"unreachable": 0
},
"10.0.1.186": {
"changed": 0,
"failures": 0,
"ignored": 0,
"ok": 1,
"rescued": 0,
"skipped": 0,
"unreachable": 0
},
"10.0.1.187": {
"changed": 0,
"failures": 0,
"ignored": 0,
"ok": 1,
"rescued": 0,
"skipped": 0,
"unreachable": 0
}
}
}
[root@ansible-1 ~]# ansible web -m shell -a "rpm -qa nginx warn=false"
{
"custom_stats": {},
"global_custom_stats": {},
"plays": [
{
"play": {
"duration": {
"end": "2024-04-23T07:48:05.183783Z",
"start": "2024-04-23T07:48:04.079601Z"
},
"id": "000c2963-21e0-a6d8-9999-00000000000b",
"name": "Ansible Ad-Hoc"
},
"tasks": [
{
"hosts": {
"10.0.1.185": {
"_ansible_no_log": false,
"action": "command",
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"cmd": "rpm -qa nginx",
"delta": "0:00:00.308892",
"end": "2024-04-23 15:48:04.849073",
"invocation": {
"module_args": {
"_raw_params": "rpm -qa nginx",
"_uses_shell": true,
"argv": null,
"chdir": null,
"creates": null,
"executable": null,
"removes": null,
"stdin": null,
"stdin_add_newline": true,
"strip_empty_ends": true,
"warn": false
}
},
"rc": 0,
"start": "2024-04-23 15:48:04.540181",
"stderr": "",
"stderr_lines": [],
"stdout": "",
"stdout_lines": []
},
"10.0.1.186": {
"_ansible_no_log": false,
"action": "command",
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"cmd": "rpm -qa nginx",
"delta": "0:00:00.579037",
"end": "2024-04-23 15:48:05.131347",
"invocation": {
"module_args": {
"_raw_params": "rpm -qa nginx",
"_uses_shell": true,
"argv": null,
"chdir": null,
"creates": null,
"executable": null,
"removes": null,
"stdin": null,
"stdin_add_newline": true,
"strip_empty_ends": true,
"warn": false
}
},
"rc": 0,
"start": "2024-04-23 15:48:04.552310",
"stderr": "",
"stderr_lines": [],
"stdout": "",
"stdout_lines": []
},
"10.0.1.187": {
"_ansible_no_log": false,
"action": "command",
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"cmd": "rpm -qa nginx",
"delta": "0:00:00.600383",
"end": "2024-04-23 15:48:05.163444",
"invocation": {
"module_args": {
"_raw_params": "rpm -qa nginx",
"_uses_shell": true,
"argv": null,
"chdir": null,
"creates": null,
"executable": null,
"removes": null,
"stdin": null,
"stdin_add_newline": true,
"strip_empty_ends": true,
"warn": false
}
},
"rc": 0,
"start": "2024-04-23 15:48:04.563061",
"stderr": "",
"stderr_lines": [],
"stdout": "",
"stdout_lines": []
}
},
"task": {
"duration": {
"end": "2024-04-23T07:48:05.183783Z",
"start": "2024-04-23T07:48:04.097785Z"
},
"id": "000c2963-21e0-a6d8-9999-00000000000d",
"name": "shell"
}
}
]
}
],
"stats": {
"10.0.1.185": {
"changed": 1,
"failures": 0,
"ignored": 0,
"ok": 1,
"rescued": 0,
"skipped": 0,
"unreachable": 0
},
"10.0.1.186": {
"changed": 1,
"failures": 0,
"ignored": 0,
"ok": 1,
"rescued": 0,
"skipped": 0,
"unreachable": 0
},
"10.0.1.187": {
"changed": 1,
"failures": 0,
"ignored": 0,
"ok": 1,
"rescued": 0,
"skipped": 0,
"unreachable": 0
}
}
}
[root@ansible-1 ~]#
转变为playbook写法...
ansible web -m yum -a "name=nginx state=installed"
ansible web -m systemd -a "name=nginx state=started"
范例:
[root@ansible-1 ~]# ansible web -m yum -a "name=nginx state=installed"
{
"custom_stats": {},
"global_custom_stats": {},
"plays": [
{
"play": {
"duration": {
"end": "2024-04-23T07:49:51.061800Z",
"start": "2024-04-23T07:49:19.221027Z"
},
"id": "000c2963-21e0-dfca-59c5-00000000000b",
"name": "Ansible Ad-Hoc"
},
"tasks": [
{
"hosts": {
"10.0.1.185": {
"_ansible_no_log": false,
"action": "yum",
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"installed": [
"nginx"
]
},
"invocation": {
"module_args": {
"allow_downgrade": false,
"autoremove": false,
"bugfix": false,
"conf_file": null,
"disable_excludes": null,
"disable_gpg_check": false,
"disable_plugin": [],
"disablerepo": [],
"download_dir": null,
"download_only": false,
"enable_plugin": [],
"enablerepo": [],
"exclude": [],
"install_repoquery": true,
"install_weak_deps": true,
"installroot": "/",
"list": null,
"lock_timeout": 30,
"name": [
"nginx"
],
"releasever": null,
"security": false,
"skip_broken": false,
"state": "installed",
"update_cache": false,
"update_only": false,
"use_backend": "auto",
"validate_certs": 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 nginx.x86_64 1:1.20.1-10.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n nginx x86_64 1:1.20.1-10.el7 epel 588 k\n\nTransaction Summary\n================================================================================\nInstall 1 Package\n\nTotal download size: 588 k\nInstalled size: 1.7 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : 1:nginx-1.20.1-10.el7.x86_64 1/1 \n Verifying : 1:nginx-1.20.1-10.el7.x86_64 1/1 \n\nInstalled:\n nginx.x86_64 1:1.20.1-10.el7 \n\nComplete!\n"
]
},
"10.0.1.186": {
"_ansible_no_log": false,
"action": "yum",
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"installed": [
"nginx"
]
},
"invocation": {
"module_args": {
"allow_downgrade": false,
"autoremove": false,
"bugfix": false,
"conf_file": null,
"disable_excludes": null,
"disable_gpg_check": false,
"disable_plugin": [],
"disablerepo": [],
"download_dir": null,
"download_only": false,
"enable_plugin": [],
"enablerepo": [],
"exclude": [],
"install_repoquery": true,
"install_weak_deps": true,
"installroot": "/",
"list": null,
"lock_timeout": 30,
"name": [
"nginx"
],
"releasever": null,
"security": false,
"skip_broken": false,
"state": "installed",
"update_cache": false,
"update_only": false,
"use_backend": "auto",
"validate_certs": 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 nginx.x86_64 1:1.20.1-10.el7 will be installed\n--> Processing Dependency: nginx-filesystem = 1:1.20.1-10.el7 for package: 1:nginx-1.20.1-10.el7.x86_64\n--> Processing Dependency: libcrypto.so.1.1(OPENSSL_1_1_0)(64bit) for package: 1:nginx-1.20.1-10.el7.x86_64\n--> Processing Dependency: libssl.so.1.1(OPENSSL_1_1_0)(64bit) for package: 1:nginx-1.20.1-10.el7.x86_64\n--> Processing Dependency: libssl.so.1.1(OPENSSL_1_1_1)(64bit) for package: 1:nginx-1.20.1-10.el7.x86_64\n--> Processing Dependency: nginx-filesystem for package: 1:nginx-1.20.1-10.el7.x86_64\n--> Processing Dependency: redhat-indexhtml for package: 1:nginx-1.20.1-10.el7.x86_64\n--> Processing Dependency: libcrypto.so.1.1()(64bit) for package: 1:nginx-1.20.1-10.el7.x86_64\n--> Processing Dependency: libprofiler.so.0()(64bit) for package: 1:nginx-1.20.1-10.el7.x86_64\n--> Processing Dependency: libssl.so.1.1()(64bit) for package: 1:nginx-1.20.1-10.el7.x86_64\n--> Running transaction check\n---> Package centos-indexhtml.noarch 0:7-9.el7.centos will be installed\n---> Package gperftools-libs.x86_64 0:2.6.1-1.el7 will be installed\n---> Package nginx-filesystem.noarch 1:1.20.1-10.el7 will be installed\n---> Package openssl11-libs.x86_64 1:1.1.1k-7.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n nginx x86_64 1:1.20.1-10.el7 epel 588 k\nInstalling for dependencies:\n centos-indexhtml noarch 7-9.el7.centos base 92 k\n gperftools-libs x86_64 2.6.1-1.el7 base 272 k\n nginx-filesystem noarch 1:1.20.1-10.el7 epel 24 k\n openssl11-libs x86_64 1:1.1.1k-7.el7 epel 1.5 M\n\nTransaction Summary\n================================================================================\nInstall 1 Package (+4 Dependent packages)\n\nTotal download size: 2.4 M\nInstalled size: 6.7 M\nDownloading packages:\n--------------------------------------------------------------------------------\nTotal 846 kB/s | 2.4 MB 00:02 \nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : 1:openssl11-libs-1.1.1k-7.el7.x86_64 1/5 \n Installing : 1:nginx-filesystem-1.20.1-10.el7.noarch 2/5 \n Installing : centos-indexhtml-7-9.el7.centos.noarch 3/5 \n Installing : gperftools-libs-2.6.1-1.el7.x86_64 4/5 \n Installing : 1:nginx-1.20.1-10.el7.x86_64 5/5 \n Verifying : gperftools-libs-2.6.1-1.el7.x86_64 1/5 \n Verifying : centos-indexhtml-7-9.el7.centos.noarch 2/5 \n Verifying : 1:nginx-filesystem-1.20.1-10.el7.noarch 3/5 \n Verifying : 1:nginx-1.20.1-10.el7.x86_64 4/5 \n Verifying : 1:openssl11-libs-1.1.1k-7.el7.x86_64 5/5 \n\nInstalled:\n nginx.x86_64 1:1.20.1-10.el7 \n\nDependency Installed:\n centos-indexhtml.noarch 0:7-9.el7.centos gperftools-libs.x86_64 0:2.6.1-1.el7\n nginx-filesystem.noarch 1:1.20.1-10.el7 openssl11-libs.x86_64 1:1.1.1k-7.el7\n\nComplete!\n"
]
},
"10.0.1.187": {
"_ansible_no_log": false,
"action": "yum",
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"installed": [
"nginx"
]
},
"invocation": {
"module_args": {
"allow_downgrade": false,
"autoremove": false,
"bugfix": false,
"conf_file": null,
"disable_excludes": null,
"disable_gpg_check": false,
"disable_plugin": [],
"disablerepo": [],
"download_dir": null,
"download_only": false,
"enable_plugin": [],
"enablerepo": [],
"exclude": [],
"install_repoquery": true,
"install_weak_deps": true,
"installroot": "/",
"list": null,
"lock_timeout": 30,
"name": [
"nginx"
],
"releasever": null,
"security": false,
"skip_broken": false,
"state": "installed",
"update_cache": false,
"update_only": false,
"use_backend": "auto",
"validate_certs": 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 nginx.x86_64 1:1.20.1-10.el7 will be installed\n--> Processing Dependency: nginx-filesystem = 1:1.20.1-10.el7 for package: 1:nginx-1.20.1-10.el7.x86_64\n--> Processing Dependency: libcrypto.so.1.1(OPENSSL_1_1_0)(64bit) for package: 1:nginx-1.20.1-10.el7.x86_64\n--> Processing Dependency: libssl.so.1.1(OPENSSL_1_1_0)(64bit) for package: 1:nginx-1.20.1-10.el7.x86_64\n--> Processing Dependency: libssl.so.1.1(OPENSSL_1_1_1)(64bit) for package: 1:nginx-1.20.1-10.el7.x86_64\n--> Processing Dependency: nginx-filesystem for package: 1:nginx-1.20.1-10.el7.x86_64\n--> Processing Dependency: redhat-indexhtml for package: 1:nginx-1.20.1-10.el7.x86_64\n--> Processing Dependency: libcrypto.so.1.1()(64bit) for package: 1:nginx-1.20.1-10.el7.x86_64\n--> Processing Dependency: libprofiler.so.0()(64bit) for package: 1:nginx-1.20.1-10.el7.x86_64\n--> Processing Dependency: libssl.so.1.1()(64bit) for package: 1:nginx-1.20.1-10.el7.x86_64\n--> Running transaction check\n---> Package centos-indexhtml.noarch 0:7-9.el7.centos will be installed\n---> Package gperftools-libs.x86_64 0:2.6.1-1.el7 will be installed\n---> Package nginx-filesystem.noarch 1:1.20.1-10.el7 will be installed\n---> Package openssl11-libs.x86_64 1:1.1.1k-7.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n nginx x86_64 1:1.20.1-10.el7 epel 588 k\nInstalling for dependencies:\n centos-indexhtml noarch 7-9.el7.centos base 92 k\n gperftools-libs x86_64 2.6.1-1.el7 base 272 k\n nginx-filesystem noarch 1:1.20.1-10.el7 epel 24 k\n openssl11-libs x86_64 1:1.1.1k-7.el7 epel 1.5 M\n\nTransaction Summary\n================================================================================\nInstall 1 Package (+4 Dependent packages)\n\nTotal download size: 2.4 M\nInstalled size: 6.7 M\nDownloading packages:\n--------------------------------------------------------------------------------\nTotal 856 kB/s | 2.4 MB 00:02 \nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : 1:openssl11-libs-1.1.1k-7.el7.x86_64 1/5 \n Installing : 1:nginx-filesystem-1.20.1-10.el7.noarch 2/5 \n Installing : centos-indexhtml-7-9.el7.centos.noarch 3/5 \n Installing : gperftools-libs-2.6.1-1.el7.x86_64 4/5 \n Installing : 1:nginx-1.20.1-10.el7.x86_64 5/5 \n Verifying : gperftools-libs-2.6.1-1.el7.x86_64 1/5 \n Verifying : centos-indexhtml-7-9.el7.centos.noarch 2/5 \n Verifying : 1:nginx-filesystem-1.20.1-10.el7.noarch 3/5 \n Verifying : 1:nginx-1.20.1-10.el7.x86_64 4/5 \n Verifying : 1:openssl11-libs-1.1.1k-7.el7.x86_64 5/5 \n\nInstalled:\n nginx.x86_64 1:1.20.1-10.el7 \n\nDependency Installed:\n centos-indexhtml.noarch 0:7-9.el7.centos gperftools-libs.x86_64 0:2.6.1-1.el7\n nginx-filesystem.noarch 1:1.20.1-10.el7 openssl11-libs.x86_64 1:1.1.1k-7.el7\n\nComplete!\n"
]
}
},
"task": {
"duration": {
"end": "2024-04-23T07:49:51.061800Z",
"start": "2024-04-23T07:49:19.237931Z"
},
"id": "000c2963-21e0-dfca-59c5-00000000000d",
"name": "yum"
}
}
]
}
],
"stats": {
"10.0.1.185": {
"changed": 1,
"failures": 0,
"ignored": 0,
"ok": 1,
"rescued": 0,
"skipped": 0,
"unreachable": 0
},
"10.0.1.186": {
"changed": 1,
"failures": 0,
"ignored": 0,
"ok": 1,
"rescued": 0,
"skipped": 0,
"unreachable": 0
},
"10.0.1.187": {
"changed": 1,
"failures": 0,
"ignored": 0,
"ok": 1,
"rescued": 0,
"skipped": 0,
"unreachable": 0
}
}
}
[root@ansible-1 ~]# ansible web -m systemd -a "name=nginx state=started"
{
"custom_stats": {},
"global_custom_stats": {},
"plays": [
{
"play": {
"duration": {
"end": "2024-04-23T07:50:16.359625Z",
"start": "2024-04-23T07:50:15.665700Z"
},
"id": "000c2963-21e0-fffa-3c71-00000000000b",
"name": "Ansible Ad-Hoc"
},
"tasks": [
{
"hosts": {
"10.0.1.185": {
"_ansible_no_log": false,
"action": "systemd",
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"invocation": {
"module_args": {
"daemon_reexec": false,
"daemon_reload": false,
"enabled": null,
"force": null,
"masked": null,
"name": "nginx",
"no_block": false,
"scope": null,
"state": "started",
"user": null
}
},
"name": "nginx",
"state": "started",
"status": {
"ActiveEnterTimestampMonotonic": "0",
"ActiveExitTimestampMonotonic": "0",
"ActiveState": "inactive",
"After": "basic.target system.slice -.mount network-online.target remote-fs.target tmp.mount systemd-journald.socket nss-lookup.target",
"AllowIsolate": "no",
"AmbientCapabilities": "0",
"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",
"CollectMode": "inactive",
"ConditionResult": "no",
"ConditionTimestampMonotonic": "0",
"Conflicts": "shutdown.target",
"ControlPID": "0",
"DefaultDependencies": "yes",
"Delegate": "no",
"Description": "The nginx HTTP and reverse proxy server",
"DevicePolicy": "auto",
"ExecMainCode": "0",
"ExecMainExitTimestampMonotonic": "0",
"ExecMainPID": "0",
"ExecMainStartTimestampMonotonic": "0",
"ExecMainStatus": "0",
"ExecReload": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx -s reload ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
"ExecStart": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
"ExecStartPre": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx -t ; 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/nginx.service",
"GuessMainPID": "yes",
"IOScheduling": "0",
"Id": "nginx.service",
"IgnoreOnIsolate": "no",
"IgnoreOnSnapshot": "no",
"IgnoreSIGPIPE": "yes",
"InactiveEnterTimestampMonotonic": "0",
"InactiveExitTimestampMonotonic": "0",
"JobTimeoutAction": "none",
"JobTimeoutUSec": "0",
"KillMode": "process",
"KillSignal": "3",
"LimitAS": "18446744073709551615",
"LimitCORE": "18446744073709551615",
"LimitCPU": "18446744073709551615",
"LimitDATA": "18446744073709551615",
"LimitFSIZE": "18446744073709551615",
"LimitLOCKS": "18446744073709551615",
"LimitMEMLOCK": "65536",
"LimitMSGQUEUE": "819200",
"LimitNICE": "0",
"LimitNOFILE": "4096",
"LimitNPROC": "3799",
"LimitRSS": "18446744073709551615",
"LimitRTPRIO": "0",
"LimitRTTIME": "18446744073709551615",
"LimitSIGPENDING": "3799",
"LimitSTACK": "18446744073709551615",
"LoadState": "loaded",
"MainPID": "0",
"MemoryAccounting": "no",
"MemoryCurrent": "18446744073709551615",
"MemoryLimit": "18446744073709551615",
"MountFlags": "0",
"Names": "nginx.service",
"NeedDaemonReload": "no",
"Nice": "0",
"NoNewPrivileges": "no",
"NonBlocking": "no",
"NotifyAccess": "none",
"OOMScoreAdjust": "0",
"OnFailureJobMode": "replace",
"PIDFile": "/run/nginx.pid",
"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",
"StopWhenUnneeded": "no",
"SubState": "dead",
"SyslogLevelPrefix": "yes",
"SyslogPriority": "30",
"SystemCallErrorNumber": "0",
"TTYReset": "no",
"TTYVHangup": "no",
"TTYVTDisallocate": "no",
"TasksAccounting": "no",
"TasksCurrent": "18446744073709551615",
"TasksMax": "18446744073709551615",
"TimeoutStartUSec": "1min 30s",
"TimeoutStopUSec": "5s",
"TimerSlackNSec": "50000",
"Transient": "no",
"Type": "forking",
"UMask": "0022",
"UnitFilePreset": "disabled",
"UnitFileState": "disabled",
"Wants": "network-online.target",
"WatchdogTimestampMonotonic": "0",
"WatchdogUSec": "0"
}
},
"10.0.1.186": {
"_ansible_no_log": false,
"action": "systemd",
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"invocation": {
"module_args": {
"daemon_reexec": false,
"daemon_reload": false,
"enabled": null,
"force": null,
"masked": null,
"name": "nginx",
"no_block": false,
"scope": null,
"state": "started",
"user": null
}
},
"name": "nginx",
"state": "started",
"status": {
"ActiveEnterTimestampMonotonic": "0",
"ActiveExitTimestampMonotonic": "0",
"ActiveState": "inactive",
"After": "system.slice network-online.target -.mount remote-fs.target tmp.mount basic.target nss-lookup.target systemd-journald.socket",
"AllowIsolate": "no",
"AmbientCapabilities": "0",
"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",
"CollectMode": "inactive",
"ConditionResult": "no",
"ConditionTimestampMonotonic": "0",
"Conflicts": "shutdown.target",
"ControlPID": "0",
"DefaultDependencies": "yes",
"Delegate": "no",
"Description": "The nginx HTTP and reverse proxy server",
"DevicePolicy": "auto",
"ExecMainCode": "0",
"ExecMainExitTimestampMonotonic": "0",
"ExecMainPID": "0",
"ExecMainStartTimestampMonotonic": "0",
"ExecMainStatus": "0",
"ExecReload": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx -s reload ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
"ExecStart": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
"ExecStartPre": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx -t ; 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/nginx.service",
"GuessMainPID": "yes",
"IOScheduling": "0",
"Id": "nginx.service",
"IgnoreOnIsolate": "no",
"IgnoreOnSnapshot": "no",
"IgnoreSIGPIPE": "yes",
"InactiveEnterTimestampMonotonic": "0",
"InactiveExitTimestampMonotonic": "0",
"JobTimeoutAction": "none",
"JobTimeoutUSec": "0",
"KillMode": "process",
"KillSignal": "3",
"LimitAS": "18446744073709551615",
"LimitCORE": "18446744073709551615",
"LimitCPU": "18446744073709551615",
"LimitDATA": "18446744073709551615",
"LimitFSIZE": "18446744073709551615",
"LimitLOCKS": "18446744073709551615",
"LimitMEMLOCK": "65536",
"LimitMSGQUEUE": "819200",
"LimitNICE": "0",
"LimitNOFILE": "4096",
"LimitNPROC": "3799",
"LimitRSS": "18446744073709551615",
"LimitRTPRIO": "0",
"LimitRTTIME": "18446744073709551615",
"LimitSIGPENDING": "3799",
"LimitSTACK": "18446744073709551615",
"LoadState": "loaded",
"MainPID": "0",
"MemoryAccounting": "no",
"MemoryCurrent": "18446744073709551615",
"MemoryLimit": "18446744073709551615",
"MountFlags": "0",
"Names": "nginx.service",
"NeedDaemonReload": "no",
"Nice": "0",
"NoNewPrivileges": "no",
"NonBlocking": "no",
"NotifyAccess": "none",
"OOMScoreAdjust": "0",
"OnFailureJobMode": "replace",
"PIDFile": "/run/nginx.pid",
"PermissionsStartOnly": "no",
"PrivateDevices": "no",
"PrivateNetwork": "no",
"PrivateTmp": "yes",
"ProtectHome": "no",
"ProtectSystem": "no",
"RefuseManualStart": "no",
"RefuseManualStop": "no",
"RemainAfterExit": "no",
"Requires": "-.mount system.slice 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",
"StopWhenUnneeded": "no",
"SubState": "dead",
"SyslogLevelPrefix": "yes",
"SyslogPriority": "30",
"SystemCallErrorNumber": "0",
"TTYReset": "no",
"TTYVHangup": "no",
"TTYVTDisallocate": "no",
"TasksAccounting": "no",
"TasksCurrent": "18446744073709551615",
"TasksMax": "18446744073709551615",
"TimeoutStartUSec": "1min 30s",
"TimeoutStopUSec": "5s",
"TimerSlackNSec": "50000",
"Transient": "no",
"Type": "forking",
"UMask": "0022",
"UnitFilePreset": "disabled",
"UnitFileState": "disabled",
"Wants": "network-online.target",
"WatchdogTimestampMonotonic": "0",
"WatchdogUSec": "0"
}
},
"10.0.1.187": {
"_ansible_no_log": false,
"action": "systemd",
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"invocation": {
"module_args": {
"daemon_reexec": false,
"daemon_reload": false,
"enabled": null,
"force": null,
"masked": null,
"name": "nginx",
"no_block": false,
"scope": null,
"state": "started",
"user": null
}
},
"name": "nginx",
"state": "started",
"status": {
"ActiveEnterTimestampMonotonic": "0",
"ActiveExitTimestampMonotonic": "0",
"ActiveState": "inactive",
"After": "systemd-journald.socket -.mount network-online.target system.slice tmp.mount nss-lookup.target remote-fs.target basic.target",
"AllowIsolate": "no",
"AmbientCapabilities": "0",
"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",
"CollectMode": "inactive",
"ConditionResult": "no",
"ConditionTimestampMonotonic": "0",
"Conflicts": "shutdown.target",
"ControlPID": "0",
"DefaultDependencies": "yes",
"Delegate": "no",
"Description": "The nginx HTTP and reverse proxy server",
"DevicePolicy": "auto",
"ExecMainCode": "0",
"ExecMainExitTimestampMonotonic": "0",
"ExecMainPID": "0",
"ExecMainStartTimestampMonotonic": "0",
"ExecMainStatus": "0",
"ExecReload": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx -s reload ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
"ExecStart": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
"ExecStartPre": "{ path=/usr/sbin/nginx ; argv[]=/usr/sbin/nginx -t ; 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/nginx.service",
"GuessMainPID": "yes",
"IOScheduling": "0",
"Id": "nginx.service",
"IgnoreOnIsolate": "no",
"IgnoreOnSnapshot": "no",
"IgnoreSIGPIPE": "yes",
"InactiveEnterTimestampMonotonic": "0",
"InactiveExitTimestampMonotonic": "0",
"JobTimeoutAction": "none",
"JobTimeoutUSec": "0",
"KillMode": "process",
"KillSignal": "3",
"LimitAS": "18446744073709551615",
"LimitCORE": "18446744073709551615",
"LimitCPU": "18446744073709551615",
"LimitDATA": "18446744073709551615",
"LimitFSIZE": "18446744073709551615",
"LimitLOCKS": "18446744073709551615",
"LimitMEMLOCK": "65536",
"LimitMSGQUEUE": "819200",
"LimitNICE": "0",
"LimitNOFILE": "4096",
"LimitNPROC": "3799",
"LimitRSS": "18446744073709551615",
"LimitRTPRIO": "0",
"LimitRTTIME": "18446744073709551615",
"LimitSIGPENDING": "3799",
"LimitSTACK": "18446744073709551615",
"LoadState": "loaded",
"MainPID": "0",
"MemoryAccounting": "no",
"MemoryCurrent": "18446744073709551615",
"MemoryLimit": "18446744073709551615",
"MountFlags": "0",
"Names": "nginx.service",
"NeedDaemonReload": "no",
"Nice": "0",
"NoNewPrivileges": "no",
"NonBlocking": "no",
"NotifyAccess": "none",
"OOMScoreAdjust": "0",
"OnFailureJobMode": "replace",
"PIDFile": "/run/nginx.pid",
"PermissionsStartOnly": "no",
"PrivateDevices": "no",
"PrivateNetwork": "no",
"PrivateTmp": "yes",
"ProtectHome": "no",
"ProtectSystem": "no",
"RefuseManualStart": "no",
"RefuseManualStop": "no",
"RemainAfterExit": "no",
"Requires": "basic.target system.slice -.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",
"TasksAccounting": "no",
"TasksCurrent": "18446744073709551615",
"TasksMax": "18446744073709551615",
"TimeoutStartUSec": "1min 30s",
"TimeoutStopUSec": "5s",
"TimerSlackNSec": "50000",
"Transient": "no",
"Type": "forking",
"UMask": "0022",
"UnitFilePreset": "disabled",
"UnitFileState": "disabled",
"Wants": "network-online.target",
"WatchdogTimestampMonotonic": "0",
"WatchdogUSec": "0"
}
}
},
"task": {
"duration": {
"end": "2024-04-23T07:50:16.359625Z",
"start": "2024-04-23T07:50:15.682383Z"
},
"id": "000c2963-21e0-fffa-3c71-00000000000d",
"name": "systemd"
}
}
]
}
],
"stats": {
"10.0.1.185": {
"changed": 1,
"failures": 0,
"ignored": 0,
"ok": 1,
"rescued": 0,
"skipped": 0,
"unreachable": 0
},
"10.0.1.186": {
"changed": 1,
"failures": 0,
"ignored": 0,
"ok": 1,
"rescued": 0,
"skipped": 0,
"unreachable": 0
},
"10.0.1.187": {
"changed": 1,
"failures": 0,
"ignored": 0,
"ok": 1,
"rescued": 0,
"skipped": 0,
"unreachable": 0
}
}
}
playbook模式
- 语法的对齐,不得多一个少一个空格
- 输入法保证英文
[root@m01 scripts]# cat nginx.yaml -n
1 # install nginx yaml ,by yiyuan
2 - hosts: all
3 tasks:
4 - name: Install nginx Package
5 yum: name=nginx state=present
6 - name: Copy Nginx.conf
7 copy: src=./nginx.conf dest=/etc/nginx/nginx.conf mode=0644
范例:
解释如上的playbook代码,按行解释
1.表示注释信息,可以用#,也可以用 --- 三个短横线
2.定义playbook管理的目标主机,all表示所有的主机,也可以写 主机组名
3.定义playbok所有的任务集合信息,比如该文件,定义了2个任务 ,安装nginx,拷贝nginx配置文件
4.定义了任务的名词,自定义的帮助信息
5.定义任务的具体操作,比如这里用yum模块实现nginx的安装
6.注释信息
7.第六、第七两行作用是使用copy模块,把本地当前的nginx.conf配置文件,分发给其他所有客户端机器,且授权
yaml风格1 ,字典参数格
1.先写好yaml
[root@ansible-1 opt]# cat install_nginx.yml
---
- name: 这是一个安装nginx的剧本
hosts: nfs
tasks: # 缩进调整,使其成为'- hosts:'下的子项
- name: 01 安装nginx
yum:
name: nginx
state: present # 更改"installed"为"present",这是yum模块的标准用法
- name: 02 启动nginx
ansible.builtin.systemd: # 全限定模块名更安全,避免因core library问题导致的错误
name: nginx
state: started
2.可以去验证yaml语法是否正确
方法1,用ansible-playbook命令
ansible-playbook -C install_nginx.yml
范例:
[root@ansible-1 opt]# ansible-playbook -C install_nginx.yml
{
"custom_stats": {},
"global_custom_stats": {},
"plays": [
{
"play": {
"duration": {
"end": "2024-04-23T08:01:53.859229Z",
"start": "2024-04-23T08:01:42.339043Z"
},
"id": "000c2963-21e0-f9bb-c85b-00000000000a",
"name": "\u8fd9\u662f\u4e00\u4e2a\u5b89\u88c5nginx\u7684\u5267\u672c"
},
"tasks": [
{
"hosts": {
"10.0.1.188": {
"_ansible_no_log": false,
"_ansible_verbose_override": true,
"action": "gather_facts",
"ansible_facts": {
"ansible_all_ipv4_addresses": [
"10.0.1.188"
],
"ansible_all_ipv6_addresses": [
"fe80::67e4:cfd9:948:8ab8"
],
"ansible_apparmor": {
"status": "disabled"
},
"ansible_architecture": "x86_64",
"ansible_bios_date": "11/12/2020",
"ansible_bios_version": "6.00",
"ansible_cmdline": {
"BOOT_IMAGE": "/vmlinuz-3.10.0-1160.114.2.el7.x86_64",
"LANG": "en_US.UTF-8",
"crashkernel": "auto",
"net.ifnames": "0",
"quiet": true,
"rhgb": true,
"ro": true,
"root": "UUID=12981d89-222f-4ee2-b1c7-5dc7560cd13c"
},
"ansible_date_time": {
"date": "2024-04-23",
"day": "23",
"epoch": "1713859313",
"hour": "16",
"iso8601": "2024-04-23T08:01:53Z",
"iso8601_basic": "20240423T160153010832",
"iso8601_basic_short": "20240423T160153",
"iso8601_micro": "2024-04-23T08:01:53.010832Z",
"minute": "01",
"month": "04",
"second": "53",
"time": "16:01:53",
"tz": "CST",
"tz_offset": "+0800",
"weekday": "Tuesday",
"weekday_number": "2",
"weeknumber": "17",
"year": "2024"
},
"ansible_default_ipv4": {
"address": "10.0.1.188",
"alias": "eth0",
"broadcast": "10.0.1.255",
"gateway": "10.0.1.2",
"interface": "eth0",
"macaddress": "00:0c:29:6f:65:4e",
"mtu": 1500,
"netmask": "255.255.255.0",
"network": "10.0.1.0",
"type": "ether"
},
"ansible_default_ipv6": {},
"ansible_device_links": {
"ids": {
"sr0": [
"ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001"
]
},
"labels": {},
"masters": {},
"uuids": {
"sda1": [
"04cb4c4e-727f-43e6-bd0a-0063bf3268a4"
],
"sda2": [
"12981d89-222f-4ee2-b1c7-5dc7560cd13c"
],
"sda3": [
"df895761-902b-4692-81f7-d76e08aa18c3"
],
"sda5": [
"e2b4e0b4-f016-4cd0-a697-5b0eadbe11fd"
]
}
},
"ansible_devices": {
"sda": {
"holders": [],
"host": "SCSI storage controller: Broadcom / LSI 53c1030 PCI-X Fusion-MPT Dual Ultra320 SCSI (rev 01)",
"links": {
"ids": [],
"labels": [],
"masters": [],
"uuids": []
},
"model": "VMware Virtual S",
"partitions": {
"sda1": {
"holders": [],
"links": {
"ids": [],
"labels": [],
"masters": [],
"uuids": [
"04cb4c4e-727f-43e6-bd0a-0063bf3268a4"
]
},
"sectors": "2097152",
"sectorsize": 512,
"size": "1.00 GB",
"start": "2048",
"uuid": "04cb4c4e-727f-43e6-bd0a-0063bf3268a4"
},
"sda2": {
"holders": [],
"links": {
"ids": [],
"labels": [],
"masters": [],
"uuids": [
"12981d89-222f-4ee2-b1c7-5dc7560cd13c"
]
},
"sectors": "195311616",
"sectorsize": 512,
"size": "93.13 GB",
"start": "2099200",
"uuid": "12981d89-222f-4ee2-b1c7-5dc7560cd13c"
},
"sda3": {
"holders": [],
"links": {
"ids": [],
"labels": [],
"masters": [],
"uuids": [
"df895761-902b-4692-81f7-d76e08aa18c3"
]
},
"sectors": "97654784",
"sectorsize": 512,
"size": "46.57 GB",
"start": "197410816",
"uuid": "df895761-902b-4692-81f7-d76e08aa18c3"
},
"sda4": {
"holders": [],
"links": {
"ids": [],
"labels": [],
"masters": [],
"uuids": []
},
"sectors": "2",
"sectorsize": 512,
"size": "1.00 KB",
"start": "295065600",
"uuid": null
},
"sda5": {
"holders": [],
"links": {
"ids": [],
"labels": [],
"masters": [],
"uuids": [
"e2b4e0b4-f016-4cd0-a697-5b0eadbe11fd"
]
},
"sectors": "8388608",
"sectorsize": 512,
"size": "4.00 GB",
"start": "295067648",
"uuid": "e2b4e0b4-f016-4cd0-a697-5b0eadbe11fd"
}
},
"removable": "0",
"rotational": "1",
"sas_address": null,
"sas_device_handle": null,
"scheduler_mode": "deadline",
"sectors": "419430400",
"sectorsize": "512",
"size": "200.00 GB",
"support_discard": "0",
"vendor": "VMware,",
"virtual": 1
},
"sr0": {
"holders": [],
"host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)",
"links": {
"ids": [
"ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001"
],
"labels": [],
"masters": [],
"uuids": []
},
"model": "VMware IDE CDR10",
"partitions": {},
"removable": "1",
"rotational": "1",
"sas_address": null,
"sas_device_handle": null,
"scheduler_mode": "deadline",
"sectors": "2097151",
"sectorsize": "512",
"size": "1024.00 MB",
"support_discard": "0",
"vendor": "NECVMWar",
"virtual": 1
}
},
"ansible_distribution": "CentOS",
"ansible_distribution_file_parsed": true,
"ansible_distribution_file_path": "/etc/redhat-release",
"ansible_distribution_file_variety": "RedHat",
"ansible_distribution_major_version": "7",
"ansible_distribution_release": "Core",
"ansible_distribution_version": "7.9",
"ansible_dns": {
"nameservers": [
"114.114.114.114"
],
"search": [
"localdomain"
]
},
"ansible_domain": "",
"ansible_effective_group_id": 0,
"ansible_effective_user_id": 0,
"ansible_env": {
"HOME": "/root",
"LANG": "en_US.UTF-8",
"LESSOPEN": "||/usr/bin/lesspipe.sh %s",
"LOGNAME": "root",
"LS_COLORS": "rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:",
"MAIL": "/var/mail/root",
"PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin",
"PWD": "/root",
"SHELL": "/bin/bash",
"SHLVL": "2",
"SSH_CLIENT": "10.0.1.184 37704 22",
"SSH_CONNECTION": "10.0.1.184 37704 10.0.1.188 22",
"SSH_TTY": "/dev/pts/1",
"TERM": "xterm",
"USER": "root",
"_": "/usr/bin/python"
},
"ansible_eth0": {
"active": true,
"device": "eth0",
"features": {
"busy_poll": "off [fixed]",
"fcoe_mtu": "off [fixed]",
"generic_receive_offload": "on",
"generic_segmentation_offload": "on",
"highdma": "off [fixed]",
"hw_tc_offload": "off [fixed]",
"l2_fwd_offload": "off [fixed]",
"large_receive_offload": "off [fixed]",
"loopback": "off [fixed]",
"netns_local": "off [fixed]",
"ntuple_filters": "off [fixed]",
"receive_hashing": "off [fixed]",
"rx_all": "off",
"rx_checksumming": "off",
"rx_fcs": "off",
"rx_gro_hw": "off [fixed]",
"rx_udp_tunnel_port_offload": "off [fixed]",
"rx_vlan_filter": "on [fixed]",
"rx_vlan_offload": "on",
"rx_vlan_stag_filter": "off [fixed]",
"rx_vlan_stag_hw_parse": "off [fixed]",
"scatter_gather": "on",
"tcp_segmentation_offload": "on",
"tx_checksum_fcoe_crc": "off [fixed]",
"tx_checksum_ip_generic": "on",
"tx_checksum_ipv4": "off [fixed]",
"tx_checksum_ipv6": "off [fixed]",
"tx_checksum_sctp": "off [fixed]",
"tx_checksumming": "on",
"tx_fcoe_segmentation": "off [fixed]",
"tx_gre_csum_segmentation": "off [fixed]",
"tx_gre_segmentation": "off [fixed]",
"tx_gso_partial": "off [fixed]",
"tx_gso_robust": "off [fixed]",
"tx_ipip_segmentation": "off [fixed]",
"tx_lockless": "off [fixed]",
"tx_nocache_copy": "off",
"tx_scatter_gather": "on",
"tx_scatter_gather_fraglist": "off [fixed]",
"tx_sctp_segmentation": "off [fixed]",
"tx_sit_segmentation": "off [fixed]",
"tx_tcp6_segmentation": "off [fixed]",
"tx_tcp_ecn_segmentation": "off [fixed]",
"tx_tcp_mangleid_segmentation": "off",
"tx_tcp_segmentation": "on",
"tx_udp_tnl_csum_segmentation": "off [fixed]",
"tx_udp_tnl_segmentation": "off [fixed]",
"tx_vlan_offload": "on [fixed]",
"tx_vlan_stag_hw_insert": "off [fixed]",
"udp_fragmentation_offload": "off [fixed]",
"vlan_challenged": "off [fixed]"
},
"hw_timestamp_filters": [],
"ipv4": {
"address": "10.0.1.188",
"broadcast": "10.0.1.255",
"netmask": "255.255.255.0",
"network": "10.0.1.0"
},
"ipv6": [
{
"address": "fe80::67e4:cfd9:948:8ab8",
"prefix": "64",
"scope": "link"
}
],
"macaddress": "00:0c:29:6f:65:4e",
"module": "e1000",
"mtu": 1500,
"pciid": "0000:02:01.0",
"promisc": false,
"speed": 1000,
"timestamping": [
"tx_software",
"rx_software",
"software"
],
"type": "ether"
},
"ansible_fibre_channel_wwn": [],
"ansible_fips": false,
"ansible_form_factor": "Other",
"ansible_fqdn": "nfs",
"ansible_hostname": "nfs",
"ansible_hostnqn": "",
"ansible_interfaces": [
"lo",
"eth0"
],
"ansible_is_chroot": false,
"ansible_iscsi_iqn": "",
"ansible_kernel": "3.10.0-1160.114.2.el7.x86_64",
"ansible_kernel_version": "#1 SMP Wed Mar 20 15:54:52 UTC 2024",
"ansible_lo": {
"active": true,
"device": "lo",
"features": {
"busy_poll": "off [fixed]",
"fcoe_mtu": "off [fixed]",
"generic_receive_offload": "on",
"generic_segmentation_offload": "on",
"highdma": "on [fixed]",
"hw_tc_offload": "off [fixed]",
"l2_fwd_offload": "off [fixed]",
"large_receive_offload": "off [fixed]",
"loopback": "on [fixed]",
"netns_local": "on [fixed]",
"ntuple_filters": "off [fixed]",
"receive_hashing": "off [fixed]",
"rx_all": "off [fixed]",
"rx_checksumming": "on [fixed]",
"rx_fcs": "off [fixed]",
"rx_gro_hw": "off [fixed]",
"rx_udp_tunnel_port_offload": "off [fixed]",
"rx_vlan_filter": "off [fixed]",
"rx_vlan_offload": "off [fixed]",
"rx_vlan_stag_filter": "off [fixed]",
"rx_vlan_stag_hw_parse": "off [fixed]",
"scatter_gather": "on",
"tcp_segmentation_offload": "on",
"tx_checksum_fcoe_crc": "off [fixed]",
"tx_checksum_ip_generic": "on [fixed]",
"tx_checksum_ipv4": "off [fixed]",
"tx_checksum_ipv6": "off [fixed]",
"tx_checksum_sctp": "on [fixed]",
"tx_checksumming": "on",
"tx_fcoe_segmentation": "off [fixed]",
"tx_gre_csum_segmentation": "off [fixed]",
"tx_gre_segmentation": "off [fixed]",
"tx_gso_partial": "off [fixed]",
"tx_gso_robust": "off [fixed]",
"tx_ipip_segmentation": "off [fixed]",
"tx_lockless": "on [fixed]",
"tx_nocache_copy": "off [fixed]",
"tx_scatter_gather": "on [fixed]",
"tx_scatter_gather_fraglist": "on [fixed]",
"tx_sctp_segmentation": "on",
"tx_sit_segmentation": "off [fixed]",
"tx_tcp6_segmentation": "on",
"tx_tcp_ecn_segmentation": "on",
"tx_tcp_mangleid_segmentation": "on",
"tx_tcp_segmentation": "on",
"tx_udp_tnl_csum_segmentation": "off [fixed]",
"tx_udp_tnl_segmentation": "off [fixed]",
"tx_vlan_offload": "off [fixed]",
"tx_vlan_stag_hw_insert": "off [fixed]",
"udp_fragmentation_offload": "on",
"vlan_challenged": "on [fixed]"
},
"hw_timestamp_filters": [],
"ipv4": {
"address": "127.0.0.1",
"broadcast": "",
"netmask": "255.0.0.0",
"network": "127.0.0.0"
},
"ipv6": [
{
"address": "::1",
"prefix": "128",
"scope": "host"
}
],
"mtu": 65536,
"promisc": false,
"timestamping": [
"rx_software",
"software"
],
"type": "loopback"
},
"ansible_local": {},
"ansible_lsb": {},
"ansible_machine": "x86_64",
"ansible_machine_id": "6e61592b2a7b48cd9b99b877f1f666ec",
"ansible_memfree_mb": 607,
"ansible_memory_mb": {
"nocache": {
"free": 824,
"used": 148
},
"real": {
"free": 607,
"total": 972,
"used": 365
},
"swap": {
"cached": 0,
"free": 4095,
"total": 4095,
"used": 0
}
},
"ansible_memtotal_mb": 972,
"ansible_mounts": [
{
"block_available": 220486,
"block_size": 4096,
"block_total": 259584,
"block_used": 39098,
"device": "/dev/sda1",
"fstype": "xfs",
"inode_available": 1048238,
"inode_total": 1048576,
"inode_used": 338,
"mount": "/boot",
"options": "rw,relatime,attr2,inode64,noquota",
"size_available": 903110656,
"size_total": 1063256064,
"uuid": "04cb4c4e-727f-43e6-bd0a-0063bf3268a4"
},
{
"block_available": 0,
"block_size": 4096,
"block_total": 0,
"block_used": 0,
"device": "/etc/auto.misc",
"fstype": "autofs",
"inode_available": 0,
"inode_total": 0,
"inode_used": 0,
"mount": "/misc",
"options": "rw,relatime,fd=5,pgrp=841,timeout=300,minproto=5,maxproto=5,indirect,pipe_ino=19726",
"size_available": 0,
"size_total": 0,
"uuid": "N/A"
},
{
"block_available": 12192644,
"block_size": 4096,
"block_total": 12200888,
"block_used": 8244,
"device": "/dev/sda3",
"fstype": "xfs",
"inode_available": 48827389,
"inode_total": 48827392,
"inode_used": 3,
"mount": "/data",
"options": "rw,relatime,attr2,inode64,noquota",
"size_available": 49941069824,
"size_total": 49974837248,
"uuid": "df895761-902b-4692-81f7-d76e08aa18c3"
},
{
"block_available": 23855375,
"block_size": 4096,
"block_total": 24402032,
"block_used": 546657,
"device": "/dev/sda2",
"fstype": "xfs",
"inode_available": 97617318,
"inode_total": 97655808,
"inode_used": 38490,
"mount": "/",
"options": "rw,relatime,attr2,inode64,noquota",
"size_available": 97711616000,
"size_total": 99950723072,
"uuid": "12981d89-222f-4ee2-b1c7-5dc7560cd13c"
}
],
"ansible_nodename": "nfs",
"ansible_os_family": "RedHat",
"ansible_pkg_mgr": "yum",
"ansible_proc_cmdline": {
"BOOT_IMAGE": "/vmlinuz-3.10.0-1160.114.2.el7.x86_64",
"LANG": "en_US.UTF-8",
"crashkernel": "auto",
"net.ifnames": "0",
"quiet": true,
"rhgb": true,
"ro": true,
"root": "UUID=12981d89-222f-4ee2-b1c7-5dc7560cd13c"
},
"ansible_processor": [
"0",
"GenuineIntel",
"12th Gen Intel(R) Core(TM) i5-12400F"
],
"ansible_processor_cores": 1,
"ansible_processor_count": 1,
"ansible_processor_threads_per_core": 1,
"ansible_processor_vcpus": 1,
"ansible_product_name": "VMware Virtual Platform",
"ansible_product_serial": "VMware-56 4d a0 0c 8b 68 9a 49-39 ac 71 1b 22 6f 65 4e",
"ansible_product_uuid": "0CA04D56-688B-499A-39AC-711B226F654E",
"ansible_product_version": "None",
"ansible_python": {
"executable": "/usr/bin/python",
"has_sslcontext": true,
"type": "CPython",
"version": {
"major": 2,
"micro": 5,
"minor": 7,
"releaselevel": "final",
"serial": 0
},
"version_info": [
2,
7,
5,
"final",
0
]
},
"ansible_python_version": "2.7.5",
"ansible_real_group_id": 0,
"ansible_real_user_id": 0,
"ansible_selinux": {
"status": "disabled"
},
"ansible_selinux_python_present": true,
"ansible_service_mgr": "systemd",
"ansible_ssh_host_key_ecdsa_public": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBOhUx+a8YJO1GpebRccWjLX4t2I0jNeGySRtN8BHCf6ccxQ2O870W7+k7XcmcNq6qaudzSKUlbeps59gkdv37JE=",
"ansible_ssh_host_key_ed25519_public": "AAAAC3NzaC1lZDI1NTE5AAAAIIUUXpv59fwJcIET9g//QvsPdVf3qDiaW4dSkwR/PYBY",
"ansible_ssh_host_key_rsa_public": "AAAAB3NzaC1yc2EAAAADAQABAAABAQCpy87znpCKGF7XeVy6QpEpOdT0NeAsi6lMMt2oJ0SGWDB/bpPhkaUVpoF8k0iSpK/mVV9Geutmr2uB4DLWGQqNbBDpfZ76MxVOSn+Tuz/nVdDomwnoMy0DTbow026FZbX9TVUGL+Ng+m2Q7xoU25bsnj5zG0k15kx+3lqkpLpbifQXle59CHttrNmQpENcbfrxrXa7AjTM/8MHjsNDw9yeWmeQhglCKxStHU4+E2Ahdz4hwyEnupW5Bp+HMOrGnljjQXLy79ak+uXqnnFCfYJ635xIrvzonWD1bijkNYlDVRf8cIQB6Dk7sWaTVa9Kf2bWR5/DoF3tCta7MeQJlHIv",
"ansible_swapfree_mb": 4095,
"ansible_swaptotal_mb": 4095,
"ansible_system": "Linux",
"ansible_system_capabilities": [
"cap_chown",
"cap_dac_override",
"cap_dac_read_search",
"cap_fowner",
"cap_fsetid",
"cap_kill",
"cap_setgid",
"cap_setuid",
"cap_setpcap",
"cap_linux_immutable",
"cap_net_bind_service",
"cap_net_broadcast",
"cap_net_admin",
"cap_net_raw",
"cap_ipc_lock",
"cap_ipc_owner",
"cap_sys_module",
"cap_sys_rawio",
"cap_sys_chroot",
"cap_sys_ptrace",
"cap_sys_pacct",
"cap_sys_admin",
"cap_sys_boot",
"cap_sys_nice",
"cap_sys_resource",
"cap_sys_time",
"cap_sys_tty_config",
"cap_mknod",
"cap_lease",
"cap_audit_write",
"cap_audit_control",
"cap_setfcap",
"cap_mac_override",
"cap_mac_admin",
"cap_syslog",
"35",
"36+ep"
],
"ansible_system_capabilities_enforced": "True",
"ansible_system_vendor": "VMware, Inc.",
"ansible_uptime_seconds": 18953,
"ansible_user_dir": "/root",
"ansible_user_gecos": "root",
"ansible_user_gid": 0,
"ansible_user_id": "root",
"ansible_user_shell": "/bin/bash",
"ansible_user_uid": 0,
"ansible_userspace_architecture": "x86_64",
"ansible_userspace_bits": "64",
"ansible_virtualization_role": "guest",
"ansible_virtualization_type": "VMware",
"discovered_interpreter_python": "/usr/bin/python",
"gather_subset": [
"all"
],
"module_setup": true
},
"changed": false,
"deprecations": [],
"warnings": []
}
},
"task": {
"duration": {
"end": "2024-04-23T08:01:53.055454Z",
"start": "2024-04-23T08:01:42.343687Z"
},
"id": "000c2963-21e0-f9bb-c85b-000000000011",
"name": "Gathering Facts"
}
},
{
"hosts": {
"10.0.1.188": {
"_ansible_no_log": false,
"action": "yum",
"changed": true,
"changes": {
"installed": [
"nginx"
]
},
"invocation": {
"module_args": {
"allow_downgrade": false,
"autoremove": false,
"bugfix": false,
"conf_file": null,
"disable_excludes": null,
"disable_gpg_check": false,
"disable_plugin": [],
"disablerepo": [],
"download_dir": null,
"download_only": false,
"enable_plugin": [],
"enablerepo": [],
"exclude": [],
"install_repoquery": true,
"install_weak_deps": true,
"installroot": "/",
"list": null,
"lock_timeout": 30,
"name": [
"nginx"
],
"releasever": null,
"security": false,
"skip_broken": false,
"state": "present",
"update_cache": false,
"update_only": false,
"use_backend": "auto",
"validate_certs": true
}
},
"results": []
}
},
"task": {
"duration": {
"end": "2024-04-23T08:01:53.521724Z",
"start": "2024-04-23T08:01:53.060396Z"
},
"id": "000c2963-21e0-f9bb-c85b-00000000000c",
"name": "01 \u5b89\u88c5nginx"
}
},
{
"hosts": {
"10.0.1.188": {
"_ansible_no_log": false,
"action": "ansible.builtin.systemd",
"changed": true,
"invocation": {
"module_args": {
"daemon_reexec": false,
"daemon_reload": false,
"enabled": null,
"force": null,
"masked": null,
"name": "nginx",
"no_block": false,
"scope": null,
"state": "started",
"user": null
}
},
"msg": "Service nginx not found on host, assuming it will exist on full run"
}
},
"task": {
"duration": {
"end": "2024-04-23T08:01:53.859229Z",
"start": "2024-04-23T08:01:53.526320Z"
},
"id": "000c2963-21e0-f9bb-c85b-00000000000d",
"name": "02 \u542f\u52a8nginx"
}
}
]
}
],
"stats": {
"10.0.1.188": {
"changed": 2,
"failures": 0,
"ignored": 0,
"ok": 3,
"rescued": 0,
"skipped": 0,
"unreachable": 0
}
}
}
yaml中定义hosts的信息语法
# 方式一:定义所管理的主机IP地址
- hosts: 192.168.178.111
tasks:
动作...
# 方式二:定义所管理主机的名字
- hosts: backup01
tasks:
动作...
# 方式三:定义管理主机
- hosts: 192.168.178.111, rsync01
tasks:
动作...
# 方式四:管理所有主机
- hosts: all
tasks:
动作...
关于剧本的tasks任务部分
- tasks任务部分,就是决定用什么模块,做什么事,以及模块对应的参数的风格
字典风格的模块参数
[root@ansible-1 opt]#cat install_nginx.yml
---
- name: 这是一个安装nginx的剧本
hosts: 192.168.106.7,192.168.106.8,nfs
tasks:
- name: 01 安装nginx
yum:
name: nginx
state: installed
- name: 02 启动nginx
systemd:
name: nginx
state: started
变量风格的模块参数
[root@ansible-1 opt]#cat vars_install_nginx.yml
---
- name: 这是一个安装nginx的剧本
hosts: 192.168.106.7,192.168.106.8,nfs
tasks:
- name: 01 安装nginx
yum: name=nginx state=installed
- name: 02 启动nginx
systemd: name=nginx state=started
- name: 03 设置nginx开机自启
systemd: name=nginx enabled=yes
四.yaml支持的数据类型
yaml这个语法中,只有三个数据类型
- 字典类型,特点就是 key : value形式
- 列表形式,特点是 通过 短横线定义
- 纯变量形式
数据类型
YAML 支持以下几种数据类型:
对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)
数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)
纯量(scalars):单个的、不可再分的值
我们都以python的数据类型来称呼yaml中支持的数据类型
yaml中字典
key : value类型
字典键值对使用冒号结构表示 key: value,冒号后面要加一个空格
支持字典嵌套
yaml中列表
python
[ 1,2,3,"汉字","你好" ,["我是嵌套的列表,第一个元素"] ]
shell中也支持列表,(数组) 3.
以 - 短横线开头,表示构成一个列表
在python中列表形式为 [1,2,3,'a','b','老王']
shell也支持列表(数组),表示形式为,功能比较单一
[root@ansible-1 opt]##students=("老王" "张三" "老王")
[root@ansible-1 opt]##set|grep students
students=([0]="老王" [1]="张三" [2]="老王")
[root@ansible-1 opt]##echo ${students[0]}
老王
[root@ansible-1 opt]##echo ${students[1]}
张三
[root@ansible-1 opt]##echo ${students[2]}
老王
yaml中纯变量
表示单纯的变量,支持数据类型有
- 字符串
- 布尔值
- 整数
- 浮点数
- Null
- 时间
- 日期
写一个安装nfs的playbook,遵循yaml语法
1.安装nfs服务
2.创建nfs配置文件
3.启动nfs服务
范例:
编写如下的yaml语法
记住,yaml就三个属性
列表 -
字典 "name": "我是值"
字典
"students": "我是学生"
"students":
- 老王
老六
老赵
纯变量
现在有一个json的数据格式如下
如下示例,分别用到了 字典,列表,纯变量
[
{
"老师":"老王",
"男同学": [老六,老赵,四原],
"女同学": [五原]
}
]
转变为yaml格式
- "老师": 老王
"男同学":
- 老六
老赵
四原
"女同学":
- 五原
yaml支持的数据类型
字典
"key": "value" ,转化为json类型去看,{ "key":value }
纯变量的形式
列表的形式
一个短横线 - ,转变为json类型看效果 就是 [ ]
关于yaml的短横线定义列表)
短横线用于定义列表
多个短横线,同一个缩进下的元素,表示一个列表中的多个元素
- xxx
- ooo
- ddd
- ccc
"xxx", "ooo","ddd","ccc"
识别为,同一个列表下的多个元素
一个短横线,同一个缩进下的元素,表示是一个整体,大字符串
- xxx
ooo
ddd
ccc
其实处理的数据是 "xxx ooo ddd ccc"
拿yaml转json测试,查看效果
[ https:// rsync.bejson.com/json/json2yaml/](https:// rsync.bejson.com/json/json2yaml/)
具体的yaml
将如下的ad-hoc转为yaml格式
#1.先写ad-hoc命令模式
#2.对比理解转为yaml
ansible web -m file -a "path=/etc/foo.conf owner=foo group=foo mode=0644"
# 写name字段,是表示定义剧本的注释,这一次任务的名称
# 写成字典风格的 模块参数
# 同一个缩进下,表示是一个整体,是一个大字符串
- name: 修改文件的属性
file:
path: /etc/foo.conf
owner: foo
group: foo
mode: 0644
五.json
语法
JSON 语法是 JavaScript 对象表示语法的子集。
数据在名称/值对中
数据由逗号分隔
大括号 {} 保存字典
中括号 [] 保存列表,列表可以包含多个对象
JSON 值可以是:
- 数字(整数或浮点数)
- 字符串(在双引号中)
- 逻辑值(true 或 false)
- 数组(在中括号中)
- 对象(在大括号中)
- null
json的语法实例
{
"students":null,
"age":18,
"male":true,
"手机号":[
152100000000,
16800000000
],
"你快乐吗":"我很快乐"
}
学习如何提取json的数据
根据key,提取value
前端通过js代码提取
后端 通过python代码提取
运维通过jq命令提取
jq命令
1.安装jq命令
yum install jq -y
2.简单json数据提取
[root@ansible-1 opt]# echo '{"name":"德玛西亚","price":6888}'|jq
[root@ansible-1 opt]# echo '{"name":"德玛西亚","price":6888}'|jq '.name'
"德玛西亚"
[root@ansible-1 opt]# echo '{"name":"德玛西亚","price":6888}'|jq '.price'
6888
[root@ansible-1 opt]# echo '{"name":"德玛西亚","price":6888}'|jq '.price,.name'
6888
"德玛西亚"
提取名字的值,价格
必须使用jq命令的过滤器,如下的语法
语法是通过 . 提取,比如 jq '.name,.price'
[root@ansible-1 opt]##echo '{"name":"德玛西亚","price":6888}'|jq '.name'
"德玛西亚"
[root@ansible-1 opt]##echo '{"name":"德玛西亚","price":6888}'|jq '.price'
6888
[root@ansible-1 opt]##echo '{"name":"德玛西亚","price":6888}'|jq '.name,.price'
"德玛西亚"
6888
3.数据再多一点
[root@ansible-1 opt]# echo '{"name":"德玛西亚","price":6888,"hero_loge":"https:// rsync.tukuppt.com/muban/zanyjwnk.html"}'|jq '.name,.price,.hero_loge'
"德玛西亚"
6888
"https:// rsync.tukuppt.com/muban/zanyjwnk.html"
4.串行执行,提取复杂的json数据,数据可能会有列表嵌套
串行执行(jq提供的管道符)
也就是字典套字典;
列表套字典;一层层嵌套,一层层拆,提取数据;
[root@ansible-1 opt]#echo '{"students":[{"name":"老王","age":18},{"name":"老六","female":true},{"name":"老赵","address":"china"}]}'|jq
{
"students": [
{
"name": "老王",
"age": 18
},
{
"name": "老六",
"female": true
},
{
"name": "老赵",
"address": "china"
}
]
}
一层层拆,先拆外面的字典
[root@ansible-1 opt]#echo '{"students":[{"name":"老王","age":18},{"name":"老六","female":true},{"name":"老赵","address":"china"}]}'|jq '.students'
[
{
"name": "老王",
"age": 18
},
{
"name": "老六",
"female": true
},
{
"name": "老赵",
"address": "china"
}
]
拆列表(默认提取所有列表数据)
[root@ansible-1 opt]#echo '{"students":[{"name":"老王","age":18},{"name":"老六","female":true},{"name":"老赵","address":"china"}]}'|jq '.students | .[]'
{
"name": "老王",
"age": 18
}
{
"name": "老六",
"female": true
}
{
"name": "老赵",
"address": "china"
}
提取字典数据(根据上一层提取列表数据的数量找)
[root@ansible-1 opt]#echo '{"students":[{"name":"老王","age":18},{"name":"老六","female":true},{"name":"老赵","address":"china"}]}'|jq '.students |.[] |.name'
"老王"
"老六"
"老赵"
指定列表序号
列表序号默认从0开始,依次增长
[root@ansible-1 opt]#echo '{"students":[{"name":"老王","age":18},{"name":"老六","female":true},{"name":"老赵","address":"china"}]}'|jq '.students | .[0]'
{
"name": "老王",
"age": 18
}
[root@ansible-1 opt]#echo '{"students":[{"name":"老王","age":18},{"name":"老六","female":true},{"name":"老赵","address":"china"}]}'|jq '.students | .[1]'
{
"name": "老六",
"female": true
}
[root@ansible-1 opt]#echo '{"students":[{"name":"老王","age":18},{"name":"老六","female":true},{"name":"老赵","address":"china"}]}'|jq '.students | .[2]'
{
"name": "老赵",
"address": "china"
}
提取出china的值
[root@ansible-1 opt]#echo '{"students":[{"name":"老王","age":18},{"name":"老六","female":true},{"name":"老赵","address":"china"}]}'|jq '.students | .[2] | .address'
"china"
提取天气json数据
[ http:// rsync.tianqiapi.com/api?version=v9&appid=23035354&appsecret=8YvlPNrz](http:// rsync.tianqiapi.com/api?version=v9&appid=23035354&appsecret=8YvlPNrz)
提取
1.上海
[root@ansible-1 opt]#cat tianqi.json | jq '.city'
"上海"
2.China
[root@ansible-1 opt]#cat tianqi.json | jq '.countryEn'
"China"
3. 11号的天气数据
[root@ansible-1 opt]#cat tianqi.json |jq '.data| .[3]'
4. 11号的天气数据,紫外线情况
[root@ansible-1 opt]#cat tianqi.json |jq '.data| .[3] | .index'
5. 8号的空气指数(air_tips)
[root@ansible-1 opt]#cat tianqi.json |jq '.data | .[0]|.air_tips'
六.json转yaml
[ 在线JSON转yaml,yaml转JSON-BeJSON.com](https:// rsync.bejson.com/json/json2yaml/)
yaml是一个数据交互格式的类型,用在很多软件中
比如 ansible-playbook 使用了yaml语法
saltstack 也是使用yaml写脚本
docker file
k8s资源文件
以及如今云原生的各种软件也都支持yaml语法
json这个数据交互格式,语法是如下,是用于在网络中进行数据传输的
{ "key": "value" , "key2":"value2" }
json传递给后端后,后端需要解析为当前编程语言的数据类型,才可以继续使用,解析
python举例
json数据 ,如{ "key": "value" , "key2":"value2" }
发给python后,要进行解析 ↓
python中的字典类型,{ "key": "value" , "key2":"value2" }
{key:value}字典
[学生,老师]列表
20 数字 整形类型
"广州" 字符串类型 3.4.
[
{
"2226": {
"老师": "老王",
"学生们": [
{
"老六": [
{
"年龄": 20,
"地址": "上海"
}
],
"老赵": [
{
"年龄": 22,
"地址": "北京"
}
],
"四原": [
{
"年龄": 24,
"地址": "深圳"
}
]
}
]
}
}
] 28.29.
- "2226":
"老师": "老王"
"学生们":
- "老六":
- "年龄": 20
"地址": "上海"
"老赵":
- "年龄": 22
"地址": "北京"
"四原":
- "年龄": 24
"地址": "深圳" 12.
七.jq命令处理json
1.提取出老王
[root@ansible-1 opt]#cat test1.json |jq '.[] |."2226" |."老师"'
"老王"
[root@ansible-1 opt]#cat test1.json |jq '.[0] |."2226" |."老师"'
"老王"
2.提取出学生列表
[root@ansible-1 opt]#cat test1.json |jq '.[0] |."2226" |."学生们"'
2.1 提取出这个列表中的值
[root@ansible-1 opt]#cat test1.json |jq '.[0] |."2226" |."学生们" |.[]'
3.提取出四原的资料
[root@ansible-1 opt]#cat test1.json |jq '.[0] |."2226" |."学生们" |.[0] |."四原" |.[] |."地址",."年龄"'
"深圳"
24
4.提取出老赵的资料
[root@ansible-1 opt]#cat test1.json |jq '.[0] |."2226" |."学生们" |.[0] |."老赵" |.[] |."地址",."年龄"'
"北京"
22
5.提取出老六的地址
[root@ansible-1 opt]#cat test1.json |jq '.[] |."2226" |."学生们" |.[] |."老六" |.[] |."地址",."年龄"'
"上海"
20
6.提取出四原的年龄
[root@ansible-1 opt]#cat test1.json |jq '.[] |."2226" |."学生们" |.[] |."四原" |.[] |."年龄"'
八.一键部署rsync\nfs\nginx
一键部署,能够通过脚本化,整合所有的部署操作,以及一些优化操作;
部署每一个服务,一个服务,一个剧本;
一个install.yml 脚本,所有的服务全给装好了 150行
(nfs,rsync,nginx)
ansible-playbook install.yml
一大堆日志,你连调试都很难调试
日志就是ansible记录下,远程操作了服务器,返回的修改状态,修改结果
1.你的剧本执行的是正确的
2.远程服务器返回的执行结果也是正确的,状态是没问题的
所以,建议一个服务一个剧本
install_nfs.yml
install_nginx.yaml
...
1.先想好ad-hoc命令模式该怎么写
- 因为简单,便于快速的思考出用什么内置模块去解决运维部署的需求
- 以及ad-hoc命令模式写好了
- 主机组
- 模块名
- 模块参数名
全都出来了
如部署nfs, nginx,rsync,lsync等任意服务,都可以参考如下的步骤套路
1.安装软件
2.修改配置文件
3.创建配置文件所需数据
4.启动服务
5.后续动作...
针对每一个需求,思考对应要用什么ansible内置模块,即可把问题解决
2.转变为playbook,只是写yaml,以及遵循yaml的规范即可
先写好ad-hoc模式(服务端)
然后再转换为playbook即可,这样有个参考,简单点。
# 1.安装rsync
ansible backup -m yum -a 'name=rsync state=installed'
# 2.发送配置文件模板、以及密码文件
ansible backup -m copy -a 'src=/script/rsyncd.conf dest=/etc/rsyncd.conf'
ansible backup -m copy -a 'src=/script/rsync.passwd dest=/etc/rsync.passwd mode=600'
# 3.创建用户、组信息
ansible backup -m group -a 'name=rsync gid=1000'
ansible backup -m user -a 'name=rsync uid=1000 group=rsync create_home=no shell=/sbin/nologin'
# 4.备份目录创建与授权
ansible backup -m file -a 'path=/backup owner=rsync group=rsync mode=755 state=directory '
ansible backup -m file -a 'path=/data owner=rsync group=rsync mode=755 state=directory'
# 5.启动服务,设置开机自启
ansible backup -m systemd -a 'name=rsyncd state=started enabled=yes'
改造为playbook剧本
可以参考官网写法
https://docs.ansible.com/ansible/latest/user_guide/playbooks_intro.html#playbook-execution
其实写法很简单,批量改造就完事了,等于号赋值操作,改写为冒号形式。
建议别用中文
- hosts: backup
tasks:
- name: 01安装rsync
yum:
name: rsync
state: installed
- name: 02 发送配置文件模板
copy:
src: /script/rsyncd.conf
dest: /etc/rsyncd.conf
- name: 02 发送密码文件
copy:
src: /script/rsync.passwd
dest: /etc/rsync.passwd
mode: '600'
- name: 03 创建rsync用户组
group:
name: rsync
gid: 1000
- name: 04 创建rsync用户
user:
name: rsync
uid: 1000
group: rsync
create_home: no
shell: /sbin/nologin
- name: 05 备份目录创建与授权/data
file:
path: /data
state: directory
owner: rsync
group: rsync
mode: '755'
- name: 06 备份目录创建与授权/backup
file:
path: /backup
state: directory
owner: rsync
group: rsync
mode: '755'
- name: 07 启动服务
systemd:
name: rsyncd
state: started
enabled: yes
自己写的,二个版本
第一版:
[root@ansible-1 opt]# cat rsync.yml
---
- hosts : backup
tasks:
- name: 安装 rsync
yum:
name: rsync
state: installed
- name: 发送配置文件模版
copy:
src: /script/rsyncd.conf
dest: /etc/rsyncd.conf
- name: 发送密码文件
copy:
src: /script/rsync.passwd
dest: /etc/rsync.passwd
mode: '600'
- name: 创建 rsync用户组
group:
name: rsync
gid: 1000
- name: 创建 rsync用户
user:
name: rsync
uid: 1000
group: rsync
create_home: no
shell: /sbin/nologin
- name: 备份目录创建与授权/data
file:
path: /backup
state: directory
owner: rsync
group: rsync
mode: '755'
- name: 启动服务
systemd:
name: rsyncd
state: started
enabled: yes
第二版:
[root@ansible-1 opt]# cat rsyn.yml
---
- hosts: backup
tasks:
- name: 安装 rsync
yum:
name: rsync
state: installed
- name: 发送配置文件模版
copy:
src: /script/rsyncd.conf
dest: /etc/rsyncd.conf
- name: 发送密码文件
copy:
src: /script/rsync.passwd
dest: /etc/rsync.passwd
mode: '0600' # 修正权限模式,原为'600',YAML中建议前导零表示八进制数
- name: 创建 rsync用户组
group:
name: rsync
gid: 1000
- name: 创建 rsync用户
user:
name: rsync
uid: 1000
group: rsync
create_home: no
shell: /sbin/nologin
- name: 备份目录创建与授权/data # 注意,原任务描述中的路径与实际设置的路径不符,已修正为'/backup'
file:
path: /backup
state: directory
owner: rsync
group: rsync
mode: '755'
- name: 启动并启用 rsync 服务
systemd:
name: rsyncd
state: started
enabled: yes
创建rsync配置文件,密码文件
注意是master-61机器
[root@master-61 /my-playbook]#cat /script/rsyncd.conf
uid = rsync
gid = rsync
port = 873
fake super = yes
use chroot = no
max connections = 200
timeout = 600
ignore errors
read only = false
list = false
auth users = rsync_backup
secrets file = /etc/rsync.passwd
log file = /var/log/rsyncd.log
[backup]
comment = chaoge rsync backup!
path = /backup
[data]
comment = yuchaoit.cn rsync!
path = /data
密码文件
[root@master-61 /my-playbook]#cat /script/rsync.passwd
rsync_backup:laotian666
再次测试执行
[root@master-61 /my-playbook]#ansible-playbook -C install_rsync.yaml
结果
PLAY RECAP ************************************************************************************************************************
172.16.1.41 : ok=9 changed=7 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
实质性执行playbook
ansible-playbook install_rsync.yaml
检查rsyncd部署情况(必须验证你的部署情况)
[root@master-61 /my-playbook]#ansible backup -a "ls -l /etc/rsync.passwd"
172.16.1.41 | CHANGED | rc=0 >>
-rw------- 1 root root 23 Apr 26 17:05 /etc/rsync.passwd
[root@master-61 /my-playbook]#ansible backup -a "cat /etc/rsync.passwd"
172.16.1.41 | CHANGED | rc=0 >>
rsync_backup:laotian666
[root@master-61 /my-playbook]#ansible backup -a "systemctl status rsyncd"
测试rsync是否可用
[root@master-61 /my-playbook]#export RSYNC_PASSWORD=laotian666
[root@master-61 /my-playbook]#rsync -avzp /tmp/chaoge.log rsync_backup@rsync-41::data
[root@master-61 /my-playbook]#ansible backup -a "ls /data"
172.16.1.41 | CHANGED | rc=0 >>
chaoge.log
梳理剧本的操作全过程
复制
1.写好ad-hoc命令模式,便于转变剧本
2. 写ansible-playbook剧本,遵循正确的yaml,以及剧本规范
3.创建剧本中使用到的对应的数据文件
- name: 02 发送配置文件模板
copy:
src: /script/rsyncd.conf
dest: /etc/rsyncd.conf
mkdir /script/
touch /script/rsyncd.conf
vim /script/rsyncd.conf
4.才是测试剧本运行
ansible-playbook -C install_rsync.yml
5.正确安装剧本
ansible-playbook install_rsync.yml
6.验证rsync是否可用
master61数据同步
7.确认
install_rsync.yml 的确一键部署,安装好了rsync服务端
8.其他服务,按照这个思路来操作就,重复操作即可
实战--使用剧本部署rsync
0.部署安装ansible
#安装ansible
yum install epel-release ansible libselinux-python -y
yum install ansible -y
ansible --version
#编写清单文件
vim /etc/ansible/hosts
[web]
10.0.1.185
10.0.1.186
10.0.1.187
[nfs]
10.0.1.188
[backup]
10.0.1.189
#配置免密秘钥
第一种方式:
ssh-keygen
ssh-copy-id [email protected]:
ssh 10.0.185 ip a
第二种方式:
#关闭不检查key
vim /etc/ansible/ansible.cfg
71 host_key_checking = False
[root@ansible-1 ~]# tailf /etc/ansible/hosts
10.0.1.185 ansible_port=22 ansible_user=root ansible_password='553214'
10.0.1.186 ansible_port=22 ansible_user=root ansible_password='553214'
10.0.1.187 ansible_port=22 ansible_user=root ansible_password='553214'
[nfs]
10.0.1.188 ansible_port=22 ansible_user=root ansible_password='553214'
[backup]
10.0.1.189 ansible_port=22 ansible_user=root ansible_password='553214'
#创建剧本目录
mkdir -p /etc/ansible/playbook
#创建服务配置文件目录
mkdir -p /etc/ansible/conf
#测试:
ansible all -m shell -a "hostname"
#关闭warning提示sftp
vi /etc/ansible/ansible.cfg
[ssh_connection]
407 scp_if_ssh=True
重新执行ansible,报错不存在了
1.环境:
主机名 wanIP lanIP 服务 角色
ansible-master 10.0.1.2 10.0.1.184 Ansible 控制端
web01 10.0.1.2 10.0.1.185 rsync客户端 被控端
web02 10.0.1.2 10.0.1.186 rsync客户端 被控端
web03 10.0.1.2 10.0.1.187 rsync客户端 被控端
nfs 10.0.1.2 10.0.1.188 rsync客户端 被控端
backup 10.0.1.2 10.0.1.189 rsync服务端 服务端
2 流程分析
1.安装ansible
2.优化ansible
3.推送公钥
4.开启防火墙
5.开启80 443 873 nfs等端口和服务白名单
6.关闭selinux
7.创建同一的用户
1.web backup nfs 安装rsync
2.拷贝rsync配置文件
3.创建服务端backup的备份目录
4.copy密码文件
5.把客户端密码加入环境全局变量文件
6.启动rsync,并加入开机自启动
3.配置主机清单
mkdir /root/ansible/rsync -p && \
vim /root/ansible/rsync/hosts
[web]
10.0.1.185 ansible_port=22 ansible_user=root ansible_password='553214'
10.0.1.186 ansible_port=22 ansible_user=root ansible_password='553214'
10.0.1.187 ansible_port=22 ansible_user=root ansible_password='553214'
[nfs]
10.0.1.188 ansible_port=22 ansible_user=root ansible_password='553214'
[backup]
10.0.1.189 ansible_port=22 ansible_user=root ansible_password='553214'
4.写入rsync配置文件
mkdir -p /etc/ansible/conf
vim /etc/ansible/conf/rsyncd.conf
uid = rsync
gid = rsync
port = 873
fake super = yes
use chroot = no
max connections = 200
timeout = 600
ignore errors
read only = false
list = false
auth users = backup
secrets file = /etc/rsync.passwd
log file = /var/log/rsyncd.log
[backup]
comment = welcome to oldboyedu backup!
path = /backup
5.创建rsync剧本(yaml)
mkdir -p /etc/ansible/playbook
vim /etc/ansible/playbook/rsync/rsync.yml
##第一版(只有rsync服务端有免密密码)
---
- hosts: all
become: yes # 确保使用 root 权限执行任务
tasks:
- name: Install Rsync Server
yum:
name: rsync
state: present
- name: selicent pass for web and nfs servers
copy:
content: "export RSYNC_PASSWORD=123"
dest: /etc/profile.d/rsync.pass
owner: root
group: root
mode: 0600
when: ansible_hostname is match "(web|nfs)*"
- name: Source rsync.pass for environment setup
shell: "source /etc/profile.d/rsync.pass"
when: ansible_hostname is match "(web|nfs)*"
- name: Configure Rsync Conf for backup servers
copy:
src: /etc/ansible/conf/rsyncd.conf
dest: /etc/rsyncd.conf
owner: root
group: root
mode: 0644
when: ansible_hostname is match "backup*"
- name: Create rsync group if not exists (for backup servers)
group:
name: rsync
state: present
when: ansible_hostname is match "backup*"
- name: Create rsync user (for backup servers)
user:
name: rsync
group: rsync
state: present
system: yes
when: ansible_hostname is match "backup*"
- name: Create Backup Dir (for backup servers)
file:
path: /backup
state: directory
owner: rsync
group: rsync
mode: 0755
when: ansible_hostname is match "backup*"
- name: Create PASS File (for backup servers)
copy:
content: backup:123
dest: /etc/rsync.passwd
owner: root
group: root
mode: 0600
when: ansible_hostname is match "backup*"
- hosts: all
tasks:
- name: Start Rsync Server
service:
name: rsyncd
state: started
enabled: true
##yaml配置注解
---
- hosts: all
become: yes # 确保使用 root 权限执行任务
tasks:
- name: 安装 Rsync 服务
yum:
name: rsync
state: present
- name: 为 Web 和 NFS 服务器设置 rsync 密码环境变量
copy:
content: "export RSYNC_PASSWORD=123"
dest: /etc/profile.d/rsync.pass
owner: root
group: root
mode: 0600
when: ansible_hostname is match "(web|nfs)*"
- name: 应用 rsync 密码环境变量
shell: "source /etc/profile.d/rsync.pass"
when: ansible_hostname is match "(web|nfs)*"
- name: 为备份服务器配置 Rsync 配置文件
copy:
src: /etc/ansible/conf/rsyncd.conf
dest: /etc/rsyncd.conf
owner: root
group: root
mode: 0644
when: ansible_hostname is match "backup*"
- name: 如果不存在,则创建 rsync 组(仅针对备份服务器)
group:
name: rsync
state: present
when: ansible_hostname is match "backup*"
- name: 创建 rsync 用户(属于 rsync 组,仅针对备份服务器)
user:
name: rsync
group: rsync
state: present
system: yes
when: ansible_hostname is match "backup*"
- name: 创建备份目录(仅针对备份服务器)
file:
path: /backup
state: directory
owner: rsync
group: rsync
mode: 0755
when: ansible_hostname is match "backup*"
- name: 创建密码文件(仅针对备份服务器)
copy:
content: backup:123
dest: /etc/rsync.passwd
owner: root
group: root
mode: 0600
when: ansible_hostname is match "backup*"
- hosts: all
tasks:
- name: 启动 Rsync 服务并设置开机启动
service:
name: rsyncd
state: started
enabled: true
6.执行剧本
1.执行base.yml
[root@m01 ~]# ansible-playbook ansible/base.yml
2.执行rsync.yml
[root@m01 ~]# ansible-playbook ansible/rsync/rsync.yml -i /root/ansible/rsync/hosts
7.测试(在任何一台客户端上)
[root@nfs ~]# rsync -avz /etc/hosts [email protected]::backup
Password:
sending incremental file list
sent 48 bytes received 20 bytes 27.20 bytes/sec
total size is 352 speedup is 5.18
[root@nfs ~]# rsync -avz --password-file=/etc/rsync.passwd /etc/hosts [email protected]::backup
sending incremental file list
sent 48 bytes received 20 bytes 136.00 bytes/sec
total size is 352 speedup is 5.18
#tips:免密文件在客户端上,只需要创建一个与服务端一样的密码就可以了,不要有账户,不然验证失败
ansible剧本目录:
mkdir -p /etc/ansible/my-playbook
标签:rsync,01,name,no,nginx,ansible,剧本
From: https://www.cnblogs.com/nwq1101/p/18161006