ansible的playbook的介绍-yaml

ansible的playbook是使用yaml语言写的

YAML标记语言介绍
YAML是一个可读性高的用来表达资料序列的格式。YAML参考了其他多种语言包括XML、C语言、Python、Perl以及电子邮件格式RFC2822等。Clark Evans在2001年在首次发表了这种语言另外Ingy dtNet与Oren Ben-Kiki也是这语言的共同设计者。 
YAML Ain't Markup Language即YAML不是XML。不过在开发的这种语言时YAML的意思其实是"Yet Another Markup Language"仍是一种标记语言。其特性 
YAML的可读性好 
YAML和脚本语言的交互性好 
YAML使用实现语言的数据类型 
YAML有一个一致的信息模型 
YAML易于实现 
YAML可以基于流来处理 
YAML表达能力强扩展性好

它的基本语法规则如下。
• 大小写敏感
• 使用缩进表示层级关系
• 缩进时不允许使用Tab键,只允许使用空格。
• 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可

# 表示注释,从这个字符一直到行尾,都会被解析器忽略。

yaml支持的数据类型

对象:
对象的一组键值对,使用冒号结构表示。
my_key: my_value

数组:
数据结构的子成员是一个数组,则可以在该项下面缩进一个空格
languages:
- python
- perl
- ruby

纯量
纯量是最基本的、不可再分的值
字符串
var: abc
布尔值
var: true
整数
var: 123
浮点数
var: 12.30
Null
var: ~
时间
time: 2001-12-14
日期
date 20:10:20

当需要执行的任务有多个时,需要一条一条编辑ansible命令,然后执行,而且当需要重复执行时,又要重新编辑执行,这样效率不高,因此ansible就可以利用playbook来完成将任务写到一个YAML格式的文件中,然后利用ansible-playbook进行调用该文件,从而实现了多条语句,可重复执行的效果,类似shell脚本的效果,ansible的playbook要借助YAML文件来实现,YAML文件扩展名通常为.yaml或.yml

使用playbook的基本命令格式

  1. Usage: ansible-playbook [options] playbook.yml [playbook2 ...]
  2. -C, --check 干跑一次 不会真正落地
  3. -f FORKS 做高并发
  4. --list-hosts 列出匹配的主机
  5. --syntax-check 检查语法

playbook的基础组件

  1. hosts:运行指定任务的目标主机,多个主机用:冒号分隔
  2. remote_user:在远程主机上执行任务的用户;可以全局指定,也可以单个任务指定,如果是root用户执行可以不用写,默认是root
  3. sudo_user:表示以sudo方式运行任务时,切换为哪个用户身份运行
  4. tasks 任务列表

使用palybook来管理被控机

1 创建剧本

编写ansible的剧本,创建yaml语言的文件,文件的位置可以任意,为了规范,好记,最好有一个单独的目录存放剧本

我创建了mkdir /palybook这个目录来存在剧本

:后缀名是.yaml 或 yml

[root@master ~]# vim p1.yml

  1. - hosts: web
  2. remote_user: root
  3. tasks:
  4. - name: add group
  5. group: name=IT
  6. - name: creat user
  7. user: name=alex20
  8. - hosts: 192.168.16.140
  9. remote_user: root
  10. tasks:
  11. - name: copy
  12. copy: src=/var/log/yum.log dest=/tmp/

文件翻译成python的语言的格式

文件的解释:

  1. - hosts: web # 应用的主机 web是主机组
  2. remote_user: root # 使用root来执行这个playbook
  3. tasks: # 要执行的任务
  4. - name: add group # 任务的名字,可以随意写
  5. group: name=IT # group 是执行的模块名 后面是模块的参数
  6. - name: creat user # 任务的名字
  7. user: name=alex20 # 使用user模块创建用户 alex20
  8. - hosts: 192.168.16.140 # 140这台主机执行下面的命令
  9. remote_user: root # root用户执行
  10. tasks: # 执行任务
  11. - name: copy # 任务的名字
  12. copy: src=/var/log/yum.log dest=/tmp/ # 使用copy模块来复制文件

p1.yml

执行playbook

1 测试p1.yml的语法是否正确

[root@master ~]#ansible-playbook --syntax-check p1.yml

2 测试执行
[root@master ~]# ansible-playbook --check p1.yml
3 运行
[root@master ~]# ansible-playbook p1.yml

  1. - hosts: web
  2. remote_user: root
  3. tasks:
  4. - name: add group
  5. group: name=IT
  6. - name: creat user
  7. user: name=alex20
  8. - hosts: 192.168.16.140
  9. remote_user: root
  10. tasks:
  11. - name: copy
  12. copy: src=/var/log/yum.log dest=/tmp/
  13. [root@bogon palybook]# ansible-playbook p1.yml
  14.  
  15. PLAY [web] *********************************************************************************************
  16.  
  17. TASK [Gathering Facts] *********************************************************************************
  18. ok: [192.168.16.138]
  19. ok: [192.168.16.139]
  20.  
  21. TASK [add group] ***************************************************************************************
  22. ok: [192.168.16.139]
  23. ok: [192.168.16.138]
  24.  
  25. TASK [creat user] **************************************************************************************
  26. ok: [192.168.16.139]
  27. ok: [192.168.16.138]
  28.  
  29. PLAY [192.168.16.140] **********************************************************************************
  30.  
  31. TASK [Gathering Facts] *********************************************************************************
  32. ok: [192.168.16.140]
  33.  
  34. TASK [copy] ********************************************************************************************
  35. ok: [192.168.16.140]
  36.  
  37. PLAY RECAP *********************************************************************************************
  38. 192.168.16.138 : ok= changed= unreachable= failed= skipped= rescued= ignored=
  39. 192.168.16.139 : ok= changed= unreachable= failed= skipped= rescued= ignored=
  40. 192.168.16.140 : ok= changed= unreachable= failed= skipped= rescued= ignored=

剧本局用幂等性 : 幂等性 不管执行多少次,等到的结果都是一样的

2 剧本的传参- 5种方式

编写playbook

  1. [root@bogon palybook]# cat p2.yml
  2. - hosts: web
  3. remote_user: root
  4. tasks:
  5. - name: create{{user}}
  6. user: name={{user}}

cat p2.yml

2.1  在命令行中使用-e 传参:

ansible-playbook  -e user=alex21 p2.yml 

  1. PLAY [web] *********************************************************************************************
  2.  
  3. TASK [Gathering Facts] *********************************************************************************
  4. ok: [192.168.16.138]
  5. ok: [192.168.16.139]
  6.  
  7. TASK [createalex21] ************************************************************************************
  8. changed: [192.168.16.139]
  9. changed: [192.168.16.138]
  10.  
  11. PLAY RECAP *********************************************************************************************
  12. 192.168.16.138 : ok= changed= unreachable= failed= skipped= rescued= ignored=
  13. 192.168.16.139 : ok= changed= unreachable= failed= skipped= rescued= ignored=

ansible-playbook -e user=alex21 p2.yml

在web主机组上查看用户alex1创建成功

2.2 在hosts文件中实现传参

编写vim /etc/ansible/hosts文件

  1. [web]
  2. 192.168.16.138 user=alex23
  3. 192.168.16.139 user=alex24

vim /etc/ansible/hosts

ansible-playbook   p2.yml

  1. PLAY [web] *********************************************************************************************
  2.  
  3. TASK [Gathering Facts] *********************************************************************************
  4. ok: [192.168.16.139]
  5. ok: [192.168.16.138]
  6.  
  7. TASK [createalex23] ************************************************************************************
  8. changed: [192.168.16.139]
  9. changed: [192.168.16.138]
  10.  
  11. PLAY RECAP *********************************************************************************************
  12. 192.168.16.138 : ok= changed= unreachable= failed= skipped= rescued= ignored=
  13. 192.168.16.139 : ok= changed= unreachable= failed= skipped= rescued= ignored=

ansible-playbook p2.yml

在被控节点发现在138上创建alex23

在被控节点发现在138上创建alex24

2.3 编写vim /etc/ansible/hosts文件

  1. [web]
  2. 192.168.16.138
  3. 192.168.16.139
  4. [web:vars]
  5. user=alex25

ansible-playbook   p2.yml

  1. PLAY [web] *********************************************************************************************
  2.  
  3. TASK [Gathering Facts] *********************************************************************************
  4. ok: [192.168.16.138]
  5. ok: [192.168.16.139]
  6.  
  7. TASK [createalex25] ************************************************************************************
  8. changed: [192.168.16.138]
  9. changed: [192.168.16.139]
  10.  
  11. PLAY RECAP *********************************************************************************************
  12. 192.168.16.138 : ok= changed= unreachable= failed= skipped= rescued= ignored=
  13. 192.168.16.139 : ok= changed= unreachable= failed= skipped= rescued= ignored=

ansible-playbook p2.yml

在被控节点上创建alex25的用户

2.4 在palybook中传参

编写playbook

  1. - hosts: web
  2. vars:
  3. - user: alex26
  4. remote_user: root
  5. tasks:
  6. - name: create{{user}}
  7. user: name={{user}}

ansible-playbook  p2.yml

  1. PLAY [web] *********************************************************************************************
  2.  
  3. TASK [Gathering Facts] *********************************************************************************
  4. ok: [192.168.16.139]
  5. ok: [192.168.16.138]
  6.  
  7. TASK [createalex26] ************************************************************************************
  8. changed: [192.168.16.139]
  9. changed: [192.168.16.138]
  10.  
  11. PLAY RECAP *********************************************************************************************
  12. 192.168.16.138 : ok= changed= unreachable= failed= skipped= rescued= ignored=
  13. 192.168.16.139 : ok= changed= unreachable= failed= skipped= rescued= ignored=

ansible-playbook p2.yml

在被控节点上创建 alex26

2.5 利用 register传参

使用registe之前先看一个例子

编写playbook. p3.yml

  1. [root@bogon palybook]# cat p3.yml
  2. - hosts: web
  3. remote_user: root
  4. tasks:
  5. - name: yum
  6. yum: name=bc
  7. - name: sum
  8. shell: echo "4+2"| bc
  9. register: he
  10. - name: echo
  11. shell: echo {{he}} > /tmp/sum.txt

cat p3.yml

在被控机上可以看到,是字典形式的,前面都有u 这是代表unicode

  1. cat sum.txt
  2. {stderr_lines: [], uchanged: True, uend: u2019-- ::59.209104, failed: False, ustdout: u6, ucmd:uecho "4+2"| bc, urc: , ustart: u2019-- ::59.204147, ustderr: u, udelta: u0::00.004957, stdout_lines: [u6]}

正确的写法:

编写playbook. p3.yml

  1. [root@bogon palybook]# cat p3.yml
  2. - hosts: web
  3. remote_user: root
  4. tasks:
  5. - name: yum
  6. yum: name=bc
  7. - name: sum
  8. shell: echo "4+2"| bc
  9. register: he
  10. - name: echo
  11. shell: echo {{he.stdout}} > /tmp/sum.txt

被控机:

  1. [root@bogon tmp]# cat sum.txt

使用register创建用户alex27

  1. [root@bogon palybook]# cat p4.yml
  2. - hosts: web
  3. remote_user: root
  4. tasks:
  5. - name: yum
  6. yum: name=bc
  7. - name: sum
  8. shell: echo "25+2"| bc
  9. register: user
  10. - name: add user{{user.stdout}}
  11. user: name=alex{{user.stdout}}

cat p4.yml

ansible-playbook  p4.yml

总结: 传参的优先级

-e > playbook > hosts 文件

3 使用tag

tag使用标记执行的模块的,可以选择单独执行某一个模块

现有 p5.yml 的文件,已知在被控节点上,已经安装好了,redis软件,如果我们执行copy模块来把主控节点的# ceshi

文件拷贝到被控节点上/etc/redis.conf上,

我们可以使用tag是执行copy 模块

  1. [root@bogon palybook]# cat p5.yml
  2. - hosts: web
  3. remote_user: root
  4. tasks:
  5. - name: install redis
  6. yum: name=redis
  7. - name: copy
  8. copy: src=/etc/redis.conf dest=/etc/redis.conf
  9. - name: service redis start
  10. service: name=redis state=started

具体的写法

1 我在节点的//etc/redis.conf 文件的最后添加了 # ceshi 来检验,copy模块是否成功
如果多个模块有tags标签,.想运行多个模块,可以用逗号将tags名字分开
ansible-playbook -t copyfile p5.yml

  1. PLAY [web] *********************************************************************************************
  2.  
  3. TASK [Gathering Facts] *********************************************************************************
  4. ok: [192.168.16.139]
  5. ok: [192.168.16.138]
  6.  
  7. TASK [copy] ********************************************************************************************
  8. changed: [192.168.16.139]
  9. changed: [192.168.16.138]
  10.  
  11. PLAY RECAP *********************************************************************************************
  12. 192.168.16.138 : ok= changed= unreachable= failed= skipped= rescued= ignored=
  13. 192.168.16.139 : ok= changed= unreachable= failed= skipped= rescued= ignored=

ansible-playbook -t copyfile p5.yml

从运行的结果中可以看出只运行了 copy模块

在被控节点上:看到,说明copy成功

[root@bogon tmp]# tail -1 /etc/redis.conf
# ceshi

4 补充模块:setup

用来收集被控端主机的信息:

ansible 192.168.16.169 -m setup

  1. 192.168.16.138 | SUCCESS => {
  2. "ansible_facts": {
  3. "ansible_all_ipv4_addresses": [
  4. "192.168.16.138"
  5. ],
  6. "ansible_all_ipv6_addresses": [],
  7. "ansible_apparmor": {
  8. "status": "disabled"
  9. },
  10. "ansible_architecture": "x86_64",
  11. "ansible_bios_date": "07/31/2013",
  12. "ansible_bios_version": "6.00",
  13. "ansible_cmdline": {
  14. "BOOT_IMAGE": "/vmlinuz-3.10.0-327.el7.x86_64",
  15. "LANG": "en_US.UTF-8",
  16. "crashkernel": "auto",
  17. "quiet": true,
  18. "rd.lvm.lv": "centos/swap",
  19. "rhgb": true,
  20. "ro": true,
  21. "root": "/dev/mapper/centos-root"
  22. },
  23. "ansible_date_time": {
  24. "date": "2019-07-17",
  25. "day": "",
  26. "epoch": "",
  27. "hour": "",
  28. "iso8601": "2019-07-17T07:36:32Z",
  29. "iso8601_basic": "20190717T153632604168",
  30. "iso8601_basic_short": "20190717T153632",
  31. "iso8601_micro": "2019-07-17T07:36:32.604252Z",
  32. "minute": "",
  33. "month": "",
  34. "second": "",
  35. "time": "15:36:32",
  36. "tz": "CST",
  37. "tz_offset": "+0800",
  38. "weekday": "Wednesday",
  39. "weekday_number": "",
  40. "weeknumber": "",
  41. "year": ""
  42. },
  43. "ansible_default_ipv4": {
  44. "address": "192.168.16.138",
  45. "alias": "eno16777736",
  46. "broadcast": "192.168.16.255",
  47. "gateway": "192.168.16.2",
  48. "interface": "eno16777736",
  49. "macaddress": "00:0c:29:ba:8f:d2",
  50. "mtu": ,
  51. "netmask": "255.255.255.0",
  52. "network": "192.168.16.0",
  53. "type": "ether"
  54. },
  55. "ansible_default_ipv6": {},
  56. "ansible_device_links": {
  57. "ids": {
  58. "dm-0": [
  59. "dm-name-centos-root",
  60. "dm-uuid-LVM-122vaa2zigMi2y4jShiO0EFiCfRG0imyrXbbOGLi9aszGNyoVKnK0m4fBF3NclZH"
  61. ],
  62. "dm-1": [
  63. "dm-name-centos-swap",
  64. "dm-uuid-LVM-122vaa2zigMi2y4jShiO0EFiCfRG0imyiUq0NKSuO7SQHoEQMcGOaZ6JPI4yhzgR"
  65. ],
  66. "sda2": [
  67. "lvm-pv-uuid-vraMCf-JSqM-a2Uo-onaI-cVS5-3YJX-x5R6F2"
  68. ],
  69. "sr0": [
  70. "ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001"
  71. ]
  72. },
  73. "labels": {
  74. "sr0": [
  75. "CentOS\\x207\\x20x86_64"
  76. ]
  77. },
  78. "masters": {
  79. "sda2": [
  80. "dm-0",
  81. "dm-1"
  82. ]
  83. },
  84. "uuids": {
  85. "dm-0": [
  86. "47577089-a032-4e19-9648-878f5330e70d"
  87. ],
  88. "dm-1": [
  89. "a6a9dfb6-b70c-43bc-81c3-4281b8a8df46"
  90. ],
  91. "sda1": [
  92. "ae1ee2e5-f71c-4bb7-822e-01e5f145592e"
  93. ],
  94. "sr0": [
  95. "2015-12-09-23-14-10-00"
  96. ]
  97. }
  98. },
  99. "ansible_devices": {
  100. "dm-0": {
  101. "holders": [],
  102. "host": "",
  103. "links": {
  104. "ids": [
  105. "dm-name-centos-root",
  106. "dm-uuid-LVM-122vaa2zigMi2y4jShiO0EFiCfRG0imyrXbbOGLi9aszGNyoVKnK0m4fBF3NclZH"
  107. ],
  108. "labels": [],
  109. "masters": [],
  110. "uuids": [
  111. "47577089-a032-4e19-9648-878f5330e70d"
  112. ]
  113. },
  114. "model": null,
  115. "partitions": {},
  116. "removable": "",
  117. "rotational": "",
  118. "sas_address": null,
  119. "sas_device_handle": null,
  120. "scheduler_mode": "",
  121. "sectors": "",
  122. "sectorsize": "",
  123. "size": "17.47 GB",
  124. "support_discard": "",
  125. "vendor": null,
  126. "virtual":
  127. },
  128. "dm-1": {
  129. "holders": [],
  130. "host": "",
  131. "links": {
  132. "ids": [
  133. "dm-name-centos-swap",
  134. "dm-uuid-LVM-122vaa2zigMi2y4jShiO0EFiCfRG0imyiUq0NKSuO7SQHoEQMcGOaZ6JPI4yhzgR"
  135. ],
  136. "labels": [],
  137. "masters": [],
  138. "uuids": [
  139. "a6a9dfb6-b70c-43bc-81c3-4281b8a8df46"
  140. ]
  141. },
  142. "model": null,
  143. "partitions": {},
  144. "removable": "",
  145. "rotational": "",
  146. "sas_address": null,
  147. "sas_device_handle": null,
  148. "scheduler_mode": "",
  149. "sectors": "",
  150. "sectorsize": "",
  151. "size": "2.00 GB",
  152. "support_discard": "",
  153. "vendor": null,
  154. "virtual":
  155. },
  156. "fd0": {
  157. "holders": [],
  158. "host": "",
  159. "links": {
  160. "ids": [],
  161. "labels": [],
  162. "masters": [],
  163. "uuids": []
  164. },
  165. "model": null,
  166. "partitions": {},
  167. "removable": "",
  168. "rotational": "",
  169. "sas_address": null,
  170. "sas_device_handle": null,
  171. "scheduler_mode": "deadline",
  172. "sectors": "",
  173. "sectorsize": "",
  174. "size": "4.00 KB",
  175. "support_discard": "",
  176. "vendor": null,
  177. "virtual":
  178. },
  179. "sda": {
  180. "holders": [],
  181. "host": "",
  182. "links": {
  183. "ids": [],
  184. "labels": [],
  185. "masters": [],
  186. "uuids": []
  187. },
  188. "model": "VMware Virtual S",
  189. "partitions": {
  190. "sda1": {
  191. "holders": [],
  192. "links": {
  193. "ids": [],
  194. "labels": [],
  195. "masters": [],
  196. "uuids": [
  197. "ae1ee2e5-f71c-4bb7-822e-01e5f145592e"
  198. ]
  199. },
  200. "sectors": "",
  201. "sectorsize": ,
  202. "size": "500.00 MB",
  203. "start": "",
  204. "uuid": "ae1ee2e5-f71c-4bb7-822e-01e5f145592e"
  205. },
  206. "sda2": {
  207. "holders": [
  208. "centos-root",
  209. "centos-swap"
  210. ],
  211. "links": {
  212. "ids": [
  213. "lvm-pv-uuid-vraMCf-JSqM-a2Uo-onaI-cVS5-3YJX-x5R6F2"
  214. ],
  215. "labels": [],
  216. "masters": [
  217. "dm-0",
  218. "dm-1"
  219. ],
  220. "uuids": []
  221. },
  222. "sectors": "",
  223. "sectorsize": ,
  224. "size": "19.51 GB",
  225. "start": "",
  226. "uuid": null
  227. }
  228. },
  229. "removable": "",
  230. "rotational": "",
  231. "sas_address": null,
  232. "sas_device_handle": null,
  233. "scheduler_mode": "deadline",
  234. "sectors": "",
  235. "sectorsize": "",
  236. "size": "20.00 GB",
  237. "support_discard": "",
  238. "vendor": "VMware,",
  239. "virtual":
  240. },
  241. "sr0": {
  242. "holders": [],
  243. "host": "",
  244. "links": {
  245. "ids": [
  246. "ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001"
  247. ],
  248. "labels": [
  249. "CentOS\\x207\\x20x86_64"
  250. ],
  251. "masters": [],
  252. "uuids": [
  253. "2015-12-09-23-14-10-00"
  254. ]
  255. },
  256. "model": "VMware IDE CDR10",
  257. "partitions": {},
  258. "removable": "",
  259. "rotational": "",
  260. "sas_address": null,
  261. "sas_device_handle": null,
  262. "scheduler_mode": "cfq",
  263. "sectors": "",
  264. "sectorsize": "",
  265. "size": "4.03 GB",
  266. "support_discard": "",
  267. "vendor": "NECVMWar",
  268. "virtual":
  269. }
  270. },
  271. "ansible_distribution": "CentOS",
  272. "ansible_distribution_file_parsed": true,
  273. "ansible_distribution_file_path": "/etc/redhat-release",
  274. "ansible_distribution_file_variety": "RedHat",
  275. "ansible_distribution_major_version": "",
  276. "ansible_distribution_release": "Core",
  277. "ansible_distribution_version": "",
  278. "ansible_dns": {
  279. "nameservers": [
  280. "192.168.16.2"
  281. ]
  282. },
  283. "ansible_domain": "",
  284. "ansible_effective_group_id": ,
  285. "ansible_effective_user_id": ,
  286. "ansible_eno16777736": {
  287. "active": true,
  288. "device": "eno16777736",
  289. "features": {
  290. "busy_poll": "off [fixed]",
  291. "fcoe_mtu": "off [fixed]",
  292. "generic_receive_offload": "on",
  293. "generic_segmentation_offload": "on",
  294. "highdma": "off [fixed]",
  295. "large_receive_offload": "off [fixed]",
  296. "loopback": "off [fixed]",
  297. "netns_local": "off [fixed]",
  298. "ntuple_filters": "off [fixed]",
  299. "receive_hashing": "off [fixed]",
  300. "rx_all": "off",
  301. "rx_checksumming": "off",
  302. "rx_fcs": "off",
  303. "rx_vlan_filter": "on [fixed]",
  304. "rx_vlan_offload": "on",
  305. "rx_vlan_stag_filter": "off [fixed]",
  306. "rx_vlan_stag_hw_parse": "off [fixed]",
  307. "scatter_gather": "on",
  308. "tcp_segmentation_offload": "on",
  309. "tx_checksum_fcoe_crc": "off [fixed]",
  310. "tx_checksum_ip_generic": "on",
  311. "tx_checksum_ipv4": "off [fixed]",
  312. "tx_checksum_ipv6": "off [fixed]",
  313. "tx_checksum_sctp": "off [fixed]",
  314. "tx_checksumming": "on",
  315. "tx_fcoe_segmentation": "off [fixed]",
  316. "tx_gre_segmentation": "off [fixed]",
  317. "tx_gso_robust": "off [fixed]",
  318. "tx_ipip_segmentation": "off [fixed]",
  319. "tx_lockless": "off [fixed]",
  320. "tx_mpls_segmentation": "off [fixed]",
  321. "tx_nocache_copy": "off",
  322. "tx_scatter_gather": "on",
  323. "tx_scatter_gather_fraglist": "off [fixed]",
  324. "tx_sit_segmentation": "off [fixed]",
  325. "tx_tcp6_segmentation": "off [fixed]",
  326. "tx_tcp_ecn_segmentation": "off [fixed]",
  327. "tx_tcp_segmentation": "on",
  328. "tx_udp_tnl_segmentation": "off [fixed]",
  329. "tx_vlan_offload": "on [fixed]",
  330. "tx_vlan_stag_hw_insert": "off [fixed]",
  331. "udp_fragmentation_offload": "off [fixed]",
  332. "vlan_challenged": "off [fixed]"
  333. },
  334. "hw_timestamp_filters": [],
  335. "ipv4": {
  336. "address": "192.168.16.138",
  337. "broadcast": "192.168.16.255",
  338. "netmask": "255.255.255.0",
  339. "network": "192.168.16.0"
  340. },
  341. "macaddress": "00:0c:29:ba:8f:d2",
  342. "module": "e1000",
  343. "mtu": ,
  344. "pciid": "0000:02:01.0",
  345. "promisc": false,
  346. "speed": ,
  347. "timestamping": [
  348. "tx_software",
  349. "rx_software",
  350. "software"
  351. ],
  352. "type": "ether"
  353. },
  354. "ansible_env": {
  355. "HOME": "/root",
  356. "LANG": "en_US.UTF-8",
  357. "LESSOPEN": "||/usr/bin/lesspipe.sh %s",
  358. "LOGNAME": "root",
  359. "MAIL": "/var/mail/root",
  360. "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin",
  361. "PWD": "/root",
  362. "SHELL": "/bin/bash",
  363. "SHLVL": "",
  364. "SSH_CLIENT": "192.168.16.137 60835 22",
  365. "SSH_CONNECTION": "192.168.16.137 60835 192.168.16.138 22",
  366. "SSH_TTY": "/dev/pts/2",
  367. "TERM": "xterm",
  368. "USER": "root",
  369. "XDG_RUNTIME_DIR": "/run/user/0",
  370. "XDG_SESSION_ID": "",
  371. "_": "/usr/bin/python"
  372. },
  373. "ansible_fibre_channel_wwn": [],
  374. "ansible_fips": false,
  375. "ansible_form_factor": "Other",
  376. "ansible_fqdn": "bogon",
  377. "ansible_hostname": "bogon",
  378. "ansible_hostnqn": "",
  379. "ansible_interfaces": [
  380. "lo",
  381. "eno16777736"
  382. ],
  383. "ansible_is_chroot": false,
  384. "ansible_iscsi_iqn": "",
  385. "ansible_kernel": "3.10.0-327.el7.x86_64",
  386. "ansible_lo": {
  387. "active": true,
  388. "device": "lo",
  389. "features": {
  390. "busy_poll": "off [fixed]",
  391. "fcoe_mtu": "off [fixed]",
  392. "generic_receive_offload": "on",
  393. "generic_segmentation_offload": "on",
  394. "highdma": "on [fixed]",
  395. "large_receive_offload": "off [fixed]",
  396. "loopback": "on [fixed]",
  397. "netns_local": "on [fixed]",
  398. "ntuple_filters": "off [fixed]",
  399. "receive_hashing": "off [fixed]",
  400. "rx_all": "off [fixed]",
  401. "rx_checksumming": "on [fixed]",
  402. "rx_fcs": "off [fixed]",
  403. "rx_vlan_filter": "off [fixed]",
  404. "rx_vlan_offload": "off [fixed]",
  405. "rx_vlan_stag_filter": "off [fixed]",
  406. "rx_vlan_stag_hw_parse": "off [fixed]",
  407. "scatter_gather": "on",
  408. "tcp_segmentation_offload": "on",
  409. "tx_checksum_fcoe_crc": "off [fixed]",
  410. "tx_checksum_ip_generic": "on [fixed]",
  411. "tx_checksum_ipv4": "off [fixed]",
  412. "tx_checksum_ipv6": "off [fixed]",
  413. "tx_checksum_sctp": "off [fixed]",
  414. "tx_checksumming": "on",
  415. "tx_fcoe_segmentation": "off [fixed]",
  416. "tx_gre_segmentation": "off [fixed]",
  417. "tx_gso_robust": "off [fixed]",
  418. "tx_ipip_segmentation": "off [fixed]",
  419. "tx_lockless": "on [fixed]",
  420. "tx_mpls_segmentation": "off [fixed]",
  421. "tx_nocache_copy": "off [fixed]",
  422. "tx_scatter_gather": "on [fixed]",
  423. "tx_scatter_gather_fraglist": "on [fixed]",
  424. "tx_sit_segmentation": "off [fixed]",
  425. "tx_tcp6_segmentation": "on",
  426. "tx_tcp_ecn_segmentation": "on",
  427. "tx_tcp_segmentation": "on",
  428. "tx_udp_tnl_segmentation": "off [fixed]",
  429. "tx_vlan_offload": "off [fixed]",
  430. "tx_vlan_stag_hw_insert": "off [fixed]",
  431. "udp_fragmentation_offload": "on",
  432. "vlan_challenged": "on [fixed]"
  433. },
  434. "hw_timestamp_filters": [],
  435. "ipv4": {
  436. "address": "127.0.0.1",
  437. "broadcast": "host",
  438. "netmask": "255.0.0.0",
  439. "network": "127.0.0.0"
  440. },
  441. "ipv6": [
  442. {
  443. "address": "::1",
  444. "prefix": "",
  445. "scope": "host"
  446. }
  447. ],
  448. "mtu": ,
  449. "promisc": false,
  450. "timestamping": [
  451. "rx_software",
  452. "software"
  453. ],
  454. "type": "loopback"
  455. },
  456. "ansible_local": {},
  457. "ansible_lsb": {},
  458. "ansible_lvm": {
  459. "lvs": {
  460. "root": {
  461. "size_g": "17.47",
  462. "vg": "centos"
  463. },
  464. "swap": {
  465. "size_g": "2.00",
  466. "vg": "centos"
  467. }
  468. },
  469. "pvs": {
  470. "/dev/sda2": {
  471. "free_g": "0.04",
  472. "size_g": "19.51",
  473. "vg": "centos"
  474. }
  475. },
  476. "vgs": {
  477. "centos": {
  478. "free_g": "0.04",
  479. "num_lvs": "",
  480. "num_pvs": "",
  481. "size_g": "19.51"
  482. }
  483. }
  484. },
  485. "ansible_machine": "x86_64",
  486. "ansible_machine_id": "081f932dd7fb4b96a333f27e0f3928de",
  487. "ansible_memfree_mb": ,
  488. "ansible_memory_mb": {
  489. "nocache": {
  490. "free": ,
  491. "used":
  492. },
  493. "real": {
  494. "free": ,
  495. "total": ,
  496. "used":
  497. },
  498. "swap": {
  499. "cached": ,
  500. "free": ,
  501. "total": ,
  502. "used":
  503. }
  504. },
  505. "ansible_memtotal_mb": ,
  506. "ansible_mounts": [
  507. {
  508. "block_available": ,
  509. "block_size": ,
  510. "block_total": ,
  511. "block_used": ,
  512. "device": "/dev/sda1",
  513. "fstype": "xfs",
  514. "inode_available": ,
  515. "inode_total": ,
  516. "inode_used": ,
  517. "mount": "/boot",
  518. "options": "rw,relatime,attr2,inode64,noquota",
  519. "size_available": ,
  520. "size_total": ,
  521. "uuid": "ae1ee2e5-f71c-4bb7-822e-01e5f145592e"
  522. },
  523. {
  524. "block_available": ,
  525. "block_size": ,
  526. "block_total": ,
  527. "block_used": ,
  528. "device": "/dev/mapper/centos-root",
  529. "fstype": "xfs",
  530. "inode_available": ,
  531. "inode_total": ,
  532. "inode_used": ,
  533. "mount": "/",
  534. "options": "rw,relatime,attr2,inode64,noquota",
  535. "size_available": ,
  536. "size_total": ,
  537. "uuid": "47577089-a032-4e19-9648-878f5330e70d"
  538. }
  539. ],
  540. "ansible_nodename": "bogon",
  541. "ansible_os_family": "RedHat",
  542. "ansible_pkg_mgr": "yum",
  543. "ansible_proc_cmdline": {
  544. "BOOT_IMAGE": "/vmlinuz-3.10.0-327.el7.x86_64",
  545. "LANG": "en_US.UTF-8",
  546. "crashkernel": "auto",
  547. "quiet": true,
  548. "rd.lvm.lv": [
  549. "centos/root",
  550. "centos/swap"
  551. ],
  552. "rhgb": true,
  553. "ro": true,
  554. "root": "/dev/mapper/centos-root"
  555. },
  556. "ansible_processor": [
  557. "",
  558. "GenuineIntel",
  559. "Intel(R) Core(TM) i5-4200M CPU @ 2.50GHz"
  560. ],
  561. "ansible_processor_cores": ,
  562. "ansible_processor_count": ,
  563. "ansible_processor_threads_per_core": ,
  564. "ansible_processor_vcpus": ,
  565. "ansible_product_name": "VMware Virtual Platform",
  566. "ansible_product_serial": "VMware-56 4d 95 3c 07 3c 26 00-1c 3c 27 56 a2 ba 8f d2",
  567. "ansible_product_uuid": "564D953C-073C-2600-1C3C-2756A2BA8FD2",
  568. "ansible_product_version": "None",
  569. "ansible_python": {
  570. "executable": "/usr/bin/python",
  571. "has_sslcontext": true,
  572. "type": "CPython",
  573. "version": {
  574. "major": ,
  575. "micro": ,
  576. "minor": ,
  577. "releaselevel": "final",
  578. "serial":
  579. },
  580. "version_info": [
  581. ,
  582. ,
  583. ,
  584. "final",
  585.  
  586. ]
  587. },
  588. "ansible_python_version": "2.7.5",
  589. "ansible_real_group_id": ,
  590. "ansible_real_user_id": ,
  591. "ansible_selinux": {
  592. "status": "disabled"
  593. },
  594. "ansible_selinux_python_present": true,
  595. "ansible_service_mgr": "systemd",
  596. "ansible_ssh_host_key_ecdsa_public": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBAIq8nwF4vJxd4021uQqf5zq97+bHlmOyMgre4fRvbfTqN0c04W8jI0Nekxw+l3cJh8nhefcAzAJjhbKebK7Ndc=",
  597. "ansible_ssh_host_key_ed25519_public": "AAAAC3NzaC1lZDI1NTE5AAAAIBQ4Ae+rq830BkdOrn/FcZ3ZLhntv7nYPniwU4K7qmnH",
  598. "ansible_ssh_host_key_rsa_public": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDoT4LU9LSj0whFKHRtdXL/Y9hgHCqafBn0LqPJy/Am+rXjHkGWmvC/JrhgYNk931vYiOT77KbreSpFEvumFAnr+MnyTVNnJuCLO7tgA9IvINF+Y/JwWoVobQj8vYIz0PBzDsiLSF8iGZyNcPQJFYjyh4cZqWSyo3PZxhghVIVjfcaZM9bVHvy2W7Vbh5GqCQRkkjEl5DkR+wlX+6t1MBRohTPms8VGbhpO4jI9YJtOcKGacjHoQN869Hk7X44sgPYgC41WTcJLmhba6Vkcx6z61wA0tKifvKODfMqm3VLiEOtL4Sb0oIu5Iw+VUYDEddQ8vJWRca4LjI8odsE92tDB",
  599. "ansible_swapfree_mb": ,
  600. "ansible_swaptotal_mb": ,
  601. "ansible_system": "Linux",
  602. "ansible_system_capabilities": [
  603. "cap_chown",
  604. "cap_dac_override",
  605. "cap_dac_read_search",
  606. "cap_fowner",
  607. "cap_fsetid",
  608. "cap_kill",
  609. "cap_setgid",
  610. "cap_setuid",
  611. "cap_setpcap",
  612. "cap_linux_immutable",
  613. "cap_net_bind_service",
  614. "cap_net_broadcast",
  615. "cap_net_admin",
  616. "cap_net_raw",
  617. "cap_ipc_lock",
  618. "cap_ipc_owner",
  619. "cap_sys_module",
  620. "cap_sys_rawio",
  621. "cap_sys_chroot",
  622. "cap_sys_ptrace",
  623. "cap_sys_pacct",
  624. "cap_sys_admin",
  625. "cap_sys_boot",
  626. "cap_sys_nice",
  627. "cap_sys_resource",
  628. "cap_sys_time",
  629. "cap_sys_tty_config",
  630. "cap_mknod",
  631. "cap_lease",
  632. "cap_audit_write",
  633. "cap_audit_control",
  634. "cap_setfcap",
  635. "cap_mac_override",
  636. "cap_mac_admin",
  637. "cap_syslog",
  638. "",
  639. "36+ep"
  640. ],
  641. "ansible_system_capabilities_enforced": "True",
  642. "ansible_system_vendor": "VMware, Inc.",
  643. "ansible_uptime_seconds": ,
  644. "ansible_user_dir": "/root",
  645. "ansible_user_gecos": "root",
  646. "ansible_user_gid": ,
  647. "ansible_user_id": "root",
  648. "ansible_user_shell": "/bin/bash",
  649. "ansible_user_uid": ,
  650. "ansible_userspace_architecture": "x86_64",
  651. "ansible_userspace_bits": "",
  652. "ansible_virtualization_role": "guest",
  653. "ansible_virtualization_type": "VMware",
  654. "discovered_interpreter_python": "/usr/bin/python",
  655. "gather_subset": [
  656. "all"
  657. ],
  658. "module_setup": true
  659. },
  660. "changed": false
  661. }

ansible 192.168.16.138 -m setup

参数说明:

  1. ansible_all_ipv4_addresses #ipv4的所有地址
  2. ansible_all_ipv6_addresses #ipv6的所有地址
  3. ansible_architecture #系统的架构
  4. ansible_bios_date #bios的出厂时间
  5. ansible_bios_version #bios的版本
  6. ansible_date_time #系统时间
  7. ansible_default_ipv4 #系统的默认ipv4地址
  8. ansible_default_ipv6 #系统默认的ipv6地址
  9. ansible_distribution #系统的名称
  10. ansible_distribution_major_version #系统的主版本号
  11. ansible_dns #系统dns
  12. ansible_env #系统环境
  13. ansible_kernel #系统内核版本
  14. ansible_machine #系统架构
  15. ansible_memtotal_mb #系统的内存大小
  16. ansible_os_family #系统的家族
  17. ansible_pkg_mgr #系统包的管理工具
  18. ansible_nodename #系统主机名
  19. ansible_processor_cores #每颗cpu上的核心数
  20. ansible_processor_count #cpu的颗数
  21. ansible_processor_vcpus #cpu的总数= 颗数*核数
  22. ansible_python #python版本
  23. ansible_system #系统

5  template模块补充

template 和copy的模块的功能一样 ,都是向远程主机上传送文件的,可以copy是送的是原封不动的文件,template 可以将文件中的变量渲染出来

现有如下的文件,我们想把/etc/redis.conf 文件 传到远程的主机上,但/etc/redis.conf 问bind 的ip 是远程主机的ip,这时需要使用 template

  1. [root@bogon palybook]# cat p5.yml
  2. - hosts: web
  3. remote_user: root
  4. tasks:
  5. - name: copy
  6. copy: src=/etc/redis.conf dest=/etc/redis.conf
  7. - name: service redis start
  8. service: name=redis state=started

看主机的ip

ansible 192.168.16.139 -m setup -a "filter=*ipv4*"

  1. 192.168.16.139 | SUCCESS => {
  2. "ansible_facts": {
  3. "ansible_all_ipv4_addresses": [
  4. "192.168.16.139"
  5. ],
  6. "ansible_default_ipv4": {
  7. "address": "192.168.16.139",
  8. "alias": "eno16777736",
  9. "broadcast": "192.168.16.255",
  10. "gateway": "192.168.16.2",
  11. "interface": "eno16777736",
  12. "macaddress": "00:0c:29:aa:b6:83",
  13. "mtu": ,
  14. "netmask": "255.255.255.0",
  15. "network": "192.168.16.0",
  16. "type": "ether"
  17. },
  18. "discovered_interpreter_python": "/usr/bin/python"
  19. },
  20. "changed": false
  21. }

来编写主节点的/etc/redis.conf文件:

bind {{ansible_default_ipv4.address}}

主节点的剧本

  1. [root@bogon palybook]# cat p5.yml
  2. - hosts: web
  3. remote_user: root
  4. tasks:
  5. - name: copy
  6. template: src=/etc/redis.conf dest=/etc/redis.conf
  7. - name: service redis start
  8. service: name=redis state=started

ansible-playbook p5.yml

在被控节点上会看到grep bind /etc/redis.conf bind变成自己的主机ip了

bind 192.168.16.138

注意

在传输文件的时候src可以写相对路径和绝对路径

在写相对路径的时候,需要跟playbook文件同级创建templates目录

playbook的文件里写

  1. - hosts: web
  2. tasks:
  3. - name: yum
  4. yum: name=redis
  5. - name: copyfile
  6. template: src=redis.conf dest=/etc/redis.conf
  7. tags: copyfile
  8. - name: start
  9. service: name=redis state=started
  10. playbook文件同级创建templates目录

6 Handlers: 在发生改变时执行的操作(类似puppet通知机制)

在Handlers:默认是不执行的,当遇到notify 才执行,当notify 里面的内容改变了,才会触发handlers执行

  1. [root@bogon palybook]# cat p5.yml
  2. - hosts: web
  3. remote_user: root
  4. tasks:
  5. - name: copy
  6. template: src=/etc/redis.conf dest=/etc/redis.conf
  7. notify: restart
  8. - name: service redis start
  9. service: name=redis state=started
  10. handlers:
  11. - name: restart
  12. service: name=redis state=restarted

ansible-playbook   p5.yml

  1. PLAY [web] *********************************************************************************************
  2.  
  3. TASK [Gathering Facts] *********************************************************************************
  4. ok: [192.168.16.138]
  5. ok: [192.168.16.139]
  6.  
  7. TASK [copy] ********************************************************************************************
  8. changed: [192.168.16.139]
  9. changed: [192.168.16.138]
  10.  
  11. TASK [service redis start] *****************************************************************************
  12. ok: [192.168.16.138]
  13. ok: [192.168.16.139]
  14.  
  15. RUNNING HANDLER [restart] ******************************************************************************
  16. changed: [192.168.16.139]
  17. changed: [192.168.16.138]
  18.  
  19. PLAY RECAP *********************************************************************************************
  20. 192.168.16.138 : ok= changed= unreachable= failed= skipped= rescued= ignored=
  21. 192.168.16.139 : ok= changed= unreachable= failed= skipped= rescued= ignored=

7 when

条件判断

  1. - hosts: web
  2. tasks:
  3. - name: context
  4. copy: content="大弦嘈嘈如急雨" dest=/tmp/shi.txt
  5. when: ansible_distribution_major_version==""
  6. - name: context
  7. copy: content="小弦切切如私语" dest=/tmp/shi.txt
  8. when: ansible_distribution_major_version==""
  9.  
  10. - hosts: web
  11. tasks:
  12. - name: context
  13. copy: content="大弦嘈嘈如急雨" dest=/tmp/shi.txt
  14. when: user==""
  15. - name: context
  16. copy: content="小弦切切如私语" dest=/tmp/shi.txt
  17. when: user==""
  18. ansible-playbook -e user= p13.yml

8 循环

  1. - hosts: web
  2. tasks:
  3. - name: createuser
  4. user: name={{item}}
  5. with_items:
  6. - alex40
  7. - alex41
  8. - alex42
  9. - alex43
  1. - hosts: web
  2. tasks:
  3. - name: createuser
  4. user: name={{item}}
  5. with_items:
  6. - alex50
  7. - alex51
  8. - alex52
  9. - alex53
  10. - name: creategroup
  11. group: name={{item}}
  12. with_items:
  13. - wusir50
  14. - wusir51
  15. - wusir52

创建alex60 61 62 63 用户,组分别是 wusir60 61 62 63

  1. - hosts: web
  2. tasks:
  3. - name: creategroup
  4. group: name={{item}}
  5. with_items:
  6. - wusir60
  7. - wusir61
  8. - wusir62
  9. - wusir63
  10. - name: createuser
  11. user: name={{item.name}} group={{item.group}}
  12. with_items:
  13. - {"name":"alex60","group":"wusir60"}
  14. - {"name":"alex61","group":"wusir61"}
  15. - {"name":"alex62","group":"wusir62"}
  16. - {"name":"alex63","group":"wusir63"}

==================================================
php.ini
时区
on66

部署rpm包的lamp环境
- hosts: webserver
remote_user: root
tasks:
- name: install httpd
yum: name=httpd state=present
- name: install mysql-server
yum: name=mysql-server state=present
- name: install php
yum: name=php state=present
- name: httpd conf
copy: src=/home/ansible/file/httpd.conf dest=/etc/httpd/conf/httpd.conf mode=644
- name: mysql conf
copy: src=/home/ansible/file/my.cnf dest=/etc/my.cnf mode=644
- name: php conf
copy: src=/home/ansible/file/php.ini dest=/etc/php.ini mode=644
notify:
- start mysql
- start httpd
- name: service status
shell: netstat -anplt | grep -E '(mysqld|httpd)' > /tmp/lamp.status
- name: get lamp.status
fetch: src=/tmp/lamp.status dest=/tmp/
- name: test page
copy: src=/home/ansible/file/test.html dest=/var/www/html/test.html

handlers:
- name: start mysql
service: name=mysqld state=started
- name: start httpd
service: name=httpd state=started

=============================================

变量使用

常用的变量一般就两种
一种为用户自己定义的变量
一种为facts获取的变量(即ansible webserver -m setup查到的变量)
#ansible webserver -m setup //获取webserver信息

一自定义变量

1.用户在.yml文件自定义变量
示例:
[root@master ansible]# vim /home/ansible/1.yml
- hosts: webserver
remote_user: root
vars:
- var1: "abc"
- var2: 123
tasks:
- name: test vars
shell: echo "{{ var1 }} {{ var2 }}" >> /tmp/var.txt

[root@master ansible]# vim /home/ansible/1.yml
- hosts: webserver
remote_user: root
vars:
- packname: "nmap"
tasks:
- name: install package
yum: name={{ packname }} state=present

2.通过-e参数传递的变量
[root@master ansible]# ansible-playbook 1.yml -e packname=nmap
- hosts: webserver
remote_user: root
tasks:
- name: install package
yum: name={{ packname }} state=present

3.通过主机或者主机组配置文件传递的变量
主机:
[root@master ansible]# cat /etc/ansible/hosts
[webserver]
192.168.10.201 packname=nmap
192.168.10.202 packname=nmap

[root@master ansible]# ansible-playbook 1.yml
[root@master ansible]# cat 1.yml
- hosts: webserver
remote_user: root
tasks:
- name: install package
yum: name={{ packname }} state=present

主机组
[root@master ansible]# cat /etc/ansible/hosts
[webserver]
192.168.10.201
192.168.10.202
[webserver:vars]
packname=nmap

[root@master ansible]# cat 1.yml
- hosts: webserver
remote_user: root
tasks:
- name: install package
yum: name={{ packname }} state=present

二.通过facts获取的系统的变量

即ansible webserver -m setup查到的变量
1.获取系统变量
[root@master ansible]# cat 1.yml
- hosts: webserver
remote_user: root
tasks:
- name: hostname ipaddrss
shell: echo "{{ ansible_nodename}} {{ ansible_all_ipv4_addresses }}" > /tmp/facts.txt
- name: fetch file /tmp/facts
fetch: src=/tmp/facts.txt dest=/tmp

[root@master ansible]# cat /tmp/192.168.10.202/tmp/facts.txt
agent202.puppet.com [u'192.168.10.202']

2.本地facts(facts.d)自定义系统变量
客户端定义
在管控端创建如下目录:
[root@agent202 ~]# mkdir -p /etc/ansible/facts.d
创建文件:
[root@agent202 ~]# vim /etc/ansible/facts.d/test.fact
[general]
test_test1=123
test_test2=abc

[root@master ansible]# ansible webserver -m setup |grep ansible_local -A 5 //-C 5 上下5行
"ansible_local": {
"test": {
"general": {
"test_test1": "123",
"test_test2": "abc"
}
}
}

[root@master ansible]# cat 1.yml
- hosts: webserver
remote_user: root
tasks:
- name: test
shell: echo "{{ ansible_local.test.general.test_test1 }} {{ ansible_local.test.general.test_test2 }}" > /tmp/facts.txt
- name: fetch file /tmp/facts
fetch: src=/tmp/facts.txt dest=/tmp

[root@master ansible]# cat /tmp/192.168.10.202/tmp/facts.txt
123 abc

变量注册:
经常在playbook中,存储某个命令的结果在变量中,以备日后访问是很有用的. 这样使用命令模块可以在许多方面除去写站(site)特异事件,据哥例子 你可以检测某一个特定程序是否存在
这个 ‘register’ 关键词决定了把结果存储在哪个变量中
经常在playbook中,存储某个命令的结果在变量中,以备日后访问是很有用的. 这样使用命令模块可以在许多方面除去写站(site)特异事件,据哥例子 你可以检测某一个特定程序是否存在
这个 ‘register’ 关键词决定了把结果存储在哪个变量中
[root@master ansible]# cat 1.yml
- hosts: webserver
remote_user: root
tasks:
- name: user root
shell: grep ^root /etc/passwd
register: pass_contents
- name: call pass_contents
shell: echo {{ pass_contents.stdout }} > /tmp/call.txt

如想查看那些值可以引用
[root@master ansible]# cat 1.yml
- hosts: webserver
remote_user: root
tasks:
- name: user root
shell: grep ^root /etc/passwd
register: pass_contents
- name: call pass_contents
shell: echo {{ pass_contents }} > /tmp/call.txt

[root@agent202 ~]# cat /tmp/call.txt
{uchanged: True, uend: u2016-11-03 22:31:09.754515, ustdout: uroot:x:0:0:root:/root:/bin/bash, ucmd: ugrep ^root /etc/passwd, ustart: u2016-11-03 22:31:09.750428, udelta: u0:00:00.004087, ustderr: u, urc: 0, stdout_lines: [uroot:x:0:0:root:/root:/bin/bash], uwarnings: []}

剧本中的条件判断
ansible和puppet软件相同 是可以支持条件判断,使用when语句
如:
[root@master ansible]# cat 1.yml
- hosts: webserver
remote_user: root
tasks:
- name: install package nmap
yum: name=nmap state=present
when: ansible_nodename == "agent202.puppet.com"
- name: install package httpd
yum: name=nmap state=present
when: ansible_nodename == "agent201.puppet.com"

使用注册变量
[root@master ansible]# cat 1.yml
- hosts: webserver
remote_user: root
tasks:
- name: package is install
shell: rpm -q httpd|awk -F'-' '{print $1}'
register: httpd_install
- name: test httpd
service: name=httpd state=restarted
when: httpd_install.stdout == 'httpd'

- hosts: webserver
remote_user: root
tasks:
- name: mysql user
shell: grep ^mysql /etc/passwd | awk -F':' '{print $1}'
register: mysql_install
- name: test mysqld service
service: name=mysqld state=restarted
when: mysql_install.rc == 0

剧本中的循环
如:添加 abc1-abc3用户
[root@master ansible]# cat 1.yml
- hosts: webserver
remote_user: root
tasks:
- name: add new users
user: name={{ item }} state=present
with_items:
- abc1
- abc2
- abc3

剧本中的roles
你现在已经学过 tasks 和 handlers,那怎样组织 playbook 才是最好的方式呢?简单的回答就是:使用 roles ! Roles 基于一个已知的文件结构,去自动的加载某些 vars_files,tasks 以及 handlers。基于 roles 对内容进行分组,使得我们可以容易地与其他用户分享 roles 。

存放角色的位置:/etc/ansible/roles

roles/
common/ # this hierarchy represents a "role" 这里的结构代表了一个 "role"
tasks/ #
main.yml # <-- tasks file can include smaller files if warranted
handlers/ #
main.yml # <-- handlers file
templates/ # <-- files for use with the template resource
ntp.conf.j2 # <------- templates end in .j2
files/ #
bar.txt # <-- files for use with the copy resource
foo.sh # <-- script files for use with the script resource
vars/ #
main.yml # <-- variables associated with this role
defaults/ #
main.yml # <-- default lower priority variables for this role
meta/ #
main.yml # <-- role dependencies

apache/
common/
files/ 存放模块调用的文件(如:copy 和 script)
templates/ 存放模板文件
tasks/ 任务存放的目录,至少包含一个main.yml的文件,该目录下也可以有其他.yml文件,但是需要在main.yml文件中用include指令将其他.yml文件包含进来(类似 puppet)
handlers/ 存放相关触发执行器的目录,至少应该包含一个main.yml的文件,文件中定义了触发器的任务清单,该目录下也可以有其他.yml文件,但是需要在main.yml文件中用include指令将其他.yml文件包含进来
vars/  变量存放的目录,至少应该包含一个main.yml的文件,文件中定义了相关的变量及其值,该目录下也可以有其他.yml文件,但是需要在main.yml文件中用include指令将其他.yml文件包含进来
defaults/ 默认变量存放的目录,至少应该包含一个main.yml的文件,文件中定义了此角色使用的默认变量,该目录下也可以有其他.yml文件,但是需要在main.yml文件中用include指令将其他.yml文件包含进来
meta/ 用于存放此角色元数据,至少应该包含一个main.yml的文件,文件中定义当前角色的特殊设定及其依赖关系, 该目录下也可以有其他.yml文件,但是需要在main.yml文件中用include指令将其他.yml文件包含进来

如何调用定义的角色?
- hosts: webserver          
remote_user: root          
roles:             
- apache

创建一个测试roles
1.创建角色的目录结构
mkdir -pv /etc/ansible/roles/apache/{files,templates,tasks,handlers,vars,default,meta}

2.定义任务:
[root@master ansible]# vim /etc/ansible/roles/apache/tasks/main.yml
[root@master tasks]# cat /etc/ansible/roles/apache/tasks/main.yml
- name: install apache
yum: name=httpd state=present
- name: get main configure file
template: src=httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
- name: get sub configure file
template: src=robin.conf.j2 dest=/etc/httpd/conf.d/robin.conf
- name: create robin dir
file: path=/srv/robin state=directory
- name: get web page
template: src=index.html.j2 dest=/var/www/html/index.html
notify:
- restart apache

3.触发器任务:
[root@master tasks]# cat /etc/ansible/roles/apache/handlers/main.yml
- name: start apache
service: name=httpd state=present

4.准备需要的文件
[root@master files]# ls /etc/ansible/roles/apache/templates
httpd.conf.j2 index.html.j2 robin.conf.j2

ansible的剧本的更多相关文章

  1. Ansible yaml 剧本(傻瓜式)

    优化ansible安装MySQL: Ansible部署MySQL编译安装 - xiao智 - 博客园 (cnblogs.com) Ansible yaml 剧本(傻瓜式): --- - hosts: ...

  2. 2.Ansible Playbook剧本

    1.playbook?playbook翻译过来就是"剧本",那playbook组成如下 play: 定义的是主机的角色 task: 定义的是具体执行的任务 playbook: 由一 ...

  3. ansible的剧本play(四)

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAA68AAAETCAYAAADZDzDOAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjw

  4. ansible批量管理软件部署及剧本

    服务器版本信息: Centos6.9 [root@db02 ~]# uname -a Linux db02 -.el6.x86_64 # SMP Tue Mar :: UTC x86_64 x86_6 ...

  5. ansible服务及剧本编写

    第1章 ansible软件概念说明 python语言是运维人员必会的语言,而ansible是一个基于Python开发的自动化运维工具 (saltstack).其功能实现基于SSH远程连接服务:ansi ...

  6. ansible 剧本

    ansible的管理与剧本   首先我们安装一个ansible. 在7版本,直接用yum安装就可以 yum -y install ansible 然后清空ansible的配置文件,在里面写入自己需要管 ...

  7. ansible的管理与剧本

    首先我们安装一个ansible. 在7版本,直接用yum安装就可以 yum -y install ansible 然后清空ansible的配置文件,在里面写入自己需要管理的服务器的ip和相应的登陆密码 ...

  8. Linux中ansible批量管理软件部署及剧本编写

    服务器版本信息: Centos6.9 [root@db02 ~]# uname -a Linux db02 2.6.32-696.el6.x86_64 #1 SMP Tue Mar 21 19:29: ...

  9. 剧本--ansible

    剧本不喜欢, 1.1 编写剧本规范:(PYyaml语法格式文件) 剧本中有层级划分 每个层级都要用两个空格进行区分 第一级标题 第二级标题 第三级标题 强调注意:一定使用ansible软件配置剧本时, ...

随机推荐

  1. java进程被OOM干掉问题记录

    异常现象:用户环境部署了一台iserver,访问一阵后,进程没了   分析: 1.bin目录下没有崩溃日志,在tomcat的访问日志里面也没有看到有用的信息.iserver.log里面也没有信息 2. ...

  2. 使用openSSL构造一个支持https的nodejs服务器

    首先通过下面的链接下载openSSL https://slproweb.com/products/Win32OpenSSL.html 下载完毕后,执行openssl进入交互式界面: 使用命令生成pri ...

  3. h5 特效

    地址:http://www.cnblogs.com/sun927/p/5842852.html 几个别人总结的css3炫酷效果,有需要直接拿来用即可,包括以下几个效果: 1.悬浮时放大 2.悬浮时转一 ...

  4. CSS世界中那些说起来很冷的知识

    CSS世界中那些说起来很冷的知识 最近读了张鑫旭的新书<CSS世界>收获了不少对CSS的深度理解 也正值个人在公司内部进行部分章节的内容分享,于是顺带着直接把我即将分享的内容先给大家过过目 ...

  5. ActiveMQ部署和代码尝试(二)

    部署和代码尝试 1. 部署在linux 上的acvtiveMQ 要可以通过前台windows 的页面访问,必须把linux 的IP和 windows的 IP 地址配置到同一个网关下 .这种情况一般都是 ...

  6. [SCOI2016]美味——主席树+按位贪心

    原题戳这里 题解 让异或值最大显然要按位贪心,然后我们还发现加上一个\(x_i\)的效果就是所有\(a_i\)整体向右偏移了,我们对于\({a_i}\)开个主席树,支持查询一个区间中有多少个在\([L ...

  7. 题解 【NOIP2003】神经网络

    [NOIP2003]神经网络 Description 问题背景: 人工神经网络( Artificial Neural Network )是一种新兴的具有自我学习能力的计算系统,在模式识别.函数逼近及贷 ...

  8. CentOS6与7区别整理

    (1)桌面系统 [CentOS6] GNOME 2.x [CentOS7] GNOME 3.x(GNOME Shell) (2)文件系统 [CentOS6] ext4 [CentOS7] xfs (3 ...

  9. 剧终—AFO.

    /* noip一等完跪. 高考你好. 一年后山大见. AFO. */

  10. 第02组团队Git现场编程实战

    GitHub仓库地址 click here 1.组员职责分工 组员 职责分工 黄智.赵镇 百度地图API使用 潘松波.颜志鹏 写分别测评福州人均消费50以下,50-100.100-200.200以上最 ...