-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathansible.txt
More file actions
840 lines (736 loc) · 35.7 KB
/
ansible.txt
File metadata and controls
840 lines (736 loc) · 35.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
yum install ansible
easy_install pip
pip install ansible
pip3 install ansible
mac: sudo CFLAGS=-Qunused-arguments CPPFLAGS=-Qunused-arguments pip install ansible
pip install ansible -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
pip install paramiko PyYAML Jinja2 httplib2 six
http://www.ansible.com.cn/
https://github.com/ansible/ansible-examples
https://github.com/geerlingguy/ansible-role-mysql
https://github.com/ansible/ansible-container
https://github.com/openstack/openstack-ansible
https://github.com/geerlingguy/ansible-role-nginx
https://github.com/geerlingguy/ansible-role-php
https://docs.ansible.com/ansible/latest/cli/ansible-console.html
在ansible服务器端执行ssh-keygen生成密钥,将公钥复制到客户端。(可选)
在inventory文件中定义客户端信息,然后使用ping模块进行测试连接。
ansible-config [view|dump|list] [--help] [options] [ansible.cfg]
/etc/ansible/ansible.cfg
~/.ansible.cfg
/etc/ansible/hosts.inventory
$ echo "127.0.0.1" > ~/ansible_hosts
$ export ANSIBLE_HOSTS=~/ansible_hosts
$ ssh-agent bash
$ ssh-add ~/.ssh/id_rsa
ansible myhost --sudo -m raw -a "yum install -y python2 python-simplejson"
/etc/ansible/hosts
[local]
192.168.6.168
db-[a:f].example.com
www[01:50].example.com
db.example.com ansible_connection=ssh ansible_ssh_user=root
ansible_ssh_port
ansible_ssh_pass
ansible_ssh_private_key_file
ansible_python_interpreter=/usr/local/bin/python
ansible_ruby_interpreter=/usr/bin/ruby.1.9.3
[atlanta:vars]
ntp_server=ntp.atlanta.example.com
proxy=proxy.atlanta.example.com
[atlanta]
host1
host2
[raleigh]
host2
host3
[southeast:children]
atlanta
raleigh
[windows]
winserver1.example.com
winserver2.example.com
group_vars/windows.yml
ansible_ssh_user: Administrator
ansible_ssh_pass: SecretPasswordGoesHere
ansible_ssh_port: 5986
ansible_connection: winrm
/etc/ansible/group_vars/raleigh
ntp_server: acme.example.org
database_server: storage.example.org
/etc/ansible/group_vars/webservers
/etc/ansible/host_vars/foosball
ansible <pattern_goes_here> -m <module_name> -a <arguments>
pattern_goes_here:
webservers
all
*
one.example.com:two.example.com
192.168.1.*
webservers:dbservers
webservers:!phoenix 机器必须隶属 webservers 组但同时不在 phoenix组
webservers:&staging 同时隶属于 webservers 和 staging 组
webservers:dbservers:&staging:!phoenix
webservers:!{{excluded}}:&{{required}} 可以使用-e传参数
*.example.com
one*.com:dbservers
webservers[0]
webservers[0-25]
~(web|db).*\.example\.com
ansible all -m ping -u root
ansible all -m ping -u root --ask-pass
ansible all -m ping -u root
ansible all -m ping -u test --sudo
ansible all -m ping -u test --sudo --sudo-user root
ansible all -u root -a "/bin/echo hello"
ansible atlanta -a "/sbin/reboot" -f 10 并行的方式执行每次重启10个
ansible atlanta -a "/usr/bin/foo" -u username -U otheruser [--ask-sudo-pass]
ansible raleigh -m shell -a 'echo $TERM'
ansible atlanta -m copy -a "src=/etc/hosts dest=/tmp/hosts" 并行的方式同时 SCP 大量的文件到多台机器
ansible webservers -m file -a "dest=/srv/foo/a.txt mode=600"
ansible webservers -m file -a "dest=/srv/foo/b.txt mode=600 owner=mdehaan group=mdehaan"
ansible webservers -m file -a "dest=/path/to/c mode=755 owner=mdehaan group=mdehaan state=directory" 创建目录与执行 mkdir -p 效果类似
ansible webservers -m file -a "dest=/path/to/c state=absent" 删除目录(递归的删除)和删除文件
ansible webservers -m yum -a "name=acme state=present" 确认一个软件包已经安装,但不去升级它:
ansible webservers -m yum -a "name=acme-1.5 state=present" 确认一个软件包的安装版本
ansible webservers -m yum -a "name=acme state=absent" 确认一个软件包还没有安装
ansible all -m user -a "name=foo password=<crypted password here>" 创建账户
ansible all -m user -a "name=foo state=absent" 删除账户
ansible webservers -m git -a "repo=git://foo.example.org/repo.git dest=/srv/myapp version=HEAD" git 部署 webapp
ansible webservers -m service -a "name=httpd state=started" 确认某个服务在所有的webservers上都已经启动
ansible webservers -m service -a "name=httpd state=restarted"
ansible webservers -m service -a "name=httpd state=stopped"
ansible all -B 3600 -P 0 -a "/usr/bin/long_running_operation --do-stuff" 需要长时间运行的命令可以放到后台去,在命令开始运行后我们也可以检查运行的状态.如果运行命令后,不想获取返回的信息
ansible web1.example.com -m async_status -a "jid=488359678239.2844"
ansible all -B 1800 -P 60 -a "/usr/bin/long_running_operation --do-stuff" 其中 -B 1800 表示最多运行30分钟, -P 60 表示每隔60秒获取一次状态信息
ansible windows [-i inventory] -m win_ping --ask-vault-pass
ansible 6168 -m ping #测试主机是否是通的
ansible 6168 --list
ansible 6168 -m setup
ansible 6168 -m setup -a 'filter=ansible_*_mb' #查看主机内存信息
ansible 6168 -m file -a 'path=/tmp/fstab state=absent' #删除文件
ansible 6168 -m file -a "dest=/path/to/c state=directory" #创建目录-p
ansible 6168 -m file -a "dest=/path/to/c mode=755 owner=mdehaan group=mdehaan state=directory"
ansible web -m file -a 'src=/tmp/fstab dest=/tmp/fstab.link state=link'
ansible web -m file -a 'path=/tmp/ansible mode=0644 state=touch'
ansible 6168 -m copy -a 'src=/srv/myfiles/foo.conf dest=/etc/foo.conf' #复制文件
ansible 6168 -m copy -a 'content="hello world" dest=/etc/foo.conf mode=640' #复制文件
ansible 6168 -m service -a 'name=nginx state=reloaded' #nginx重新加载 started,stopped,restarted,reloaded
ansible 6168 -m service -a 'name=nginx state=started enabled=yes' #nginx是否主动启动
ansible 6168 -m shell -a 'ps aux|grep nginx'
ansible 6168 -m yum -a 'name=nginx state=latest' #安装最新nginx
ansible 6168 -m yum -a 'name="@Development tools" state=present' #安装当前的
ansible 6168 -m yum -a 'name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present'
ansible 6168 -m script -a '/root/a.sh'
ansible 6168 -m command -a "uptime"
ansible 6168 -m shell -a 'echo $HOME'
ansible 6168 -m raw -a "uptime"
ansible 6168 -m shell -a "ss -tnl | grep :80"
ansible 6168 -m shell -a "lsof -i:80"
ansible 6168 -m shell -a "service nginx status"
ansible 6168 -m git -a "repo=git://foo.example.org/repo.git dest=/srv/myapp version=HEAD"
ansible 6168 -m get_url -a 'url=http://10.1.1.116/favicon.ico dest=/tmp'
ansible 6168 -m get_url -a "url=http://www.baidu.com dest=/tmp/index.html mode=0440 force=yes"
ansible 6168 -m stat -a 'path=/etc/sysctl.conf'
ansible web -m fetch -a 'src=/etc/fstab dest=/tmp/'
ansible 6168 -m replace -a 'dest=/home/ttt.sql regexp=" DEFINER=`(.*)`@`(.*)` " replace=" DEFINER=`root`@`%` " backup=yes'
将主控方/root/a目录推送到指定节点的/tmp目录下
ansible 6168 -m synchronize -a 'src=/root/a dest=/tmp/ compress=yes'
将10.1.1.113节点的/tmp/a目录拉取到主控节点的/root目录下
ansible 10.1.1.113 -m synchronize -a 'mode=pull src=/tmp/a dest=/root/'
delete=yes 使两边的内容一样(即以推送方为主)
compress=yes 开启压缩,默认为开启
--exclude=.git 忽略同步.git结尾的文件
mode=pull 更改推送模式为拉取模式
ansible web -m command -a 'useradd tom'
ansible web -m shell -a 'echo "123456" | passwd --stdin tom'
[web]
172.16.252.143 hostname=master
172.16.254.47 hostname=host1
172.16.253.177 hostname=host2
172.16.252.182 hostname=host3
ansible web -m hostname -a 'name={{ hostname }}'
#计划任务模块,每周六1点执行
ansible web -m cron -a 'name=daycron minute="0" hour="1" weekday="5" job="ls /tmp >>/tmp/a.log"'
- cron: name="test time jobs" minute="*/1" hour="*" job="/usr/local/src/test_time.sh >> /tmp/time.log"
cron: name="test time jobs" minute="*/2" hour="*" job="/usr/local/src/test_time.sh >> /tmp/time.log"
ansible 6168 -m mysql_user -a 'name=test password=123456 state=present'
ansible-playbook e33_var_in_command.yml --extra-vars "hosts=web user=root"
ansible-playbook e33_var_in_command.yml --extra-vars "{'hosts':'vm-rhel7-1', 'user':'root'}"
ansible-playbook e33_var_in_command.yml --extra-vars "@vars.json"
--extra-vars '{"pacman":"mrs","ghosts":["inky","pinky","clyde","sue"]}'
#ansible host1 -m mount -a "name=/mnt/data src=/dev/sd0 fstype=ext3 opts=ro state=present"
sysctl: name=kernel.panic value=3 sysctl_file=/etc/sysctl.conf checks=before reload=yes
以下是定义在yml格式文件中的例子:
- sysctl: name=net.ipv4.tcp_rmem 'value=4096 87380 16777216' state=present
- sysctl: name=net.ipv4.tcp_wmem 'value=4096 65536 16777216' state=present
- sysctl: name=net.ipv6.conf.lo.disable_ipv6 value=1 state=present
- lineinfile: dest=/etc/selinux/config regexp=^SELINUX= line=SELINUX=enforcing
- lineinfile: dest=/etc/sudoers state=absent regexp="^%wheel"
- lineinfile: dest=/etc/hosts regexp='^127\.0\.0\.1' line='127.0.0.1 localhost' owner=root group=root mode=0644
- lineinfile: dest=/etc/httpd/conf/httpd.conf regexp="^Listen " insertafter="^#Listen " line="Listen 8080"
- lineinfile: dest=/etc/services regexp="^# port for http" insertbefore="^www.*80/tcp" line="# port for http by default"
# Add a line to a file if it does not exist, without passing regexp
- lineinfile: dest=/tmp/testfile line="192.168.1.99 foo.lab.net foo"
# Fully quoted because of the ': ' on the line. See the Gotchas in the YAML docs.
- lineinfile: "dest=/etc/sudoers state=present regexp='^%wheel' line='%wheel ALL=(ALL) NOPASSWD: ALL'"
- lineinfile: dest=/opt/jboss-as/bin/standalone.conf regexp='^(.*)Xms(\d+)m(.*)$' line='\1Xms${xms}m\3' backrefs=yes
# Validate the sudoers file before saving
- lineinfile: dest=/etc/sudoers state=present regexp='^%ADMIN ALL\=' line='%ADMIN ALL=(ALL) NOPASSWD:ALL' validate='visudo -cf %s'
Insert/update/remove a text block surrounded by marker lines
- name: insert/update "Match User" configuation block in /etc/ssh/sshd_config
blockinfile:
dest: /etc/ssh/sshd_config
block: |
Match User ansible-agent
PasswordAuthentication no
- name: insert/update eth0 configuration stanza in /etc/network/interfaces
(it might be better to copy files into /etc/network/interfaces.d/)
blockinfile:
dest: /etc/network/interfaces
block: |
iface eth0 inet static
address 192.168.0.1
netmask 255.255.255.0
- name: insert/update HTML surrounded by custom markers after <body> line
blockinfile:
dest: /var/www/html/index.html
marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"
insertafter: "<body>"
content: |
<h1>Welcome to {{ansible_hostname}}</h1>
<p>Last updated on {{ansible_date_time.iso8601}}</p>
- name: remove HTML as well as surrounding markers ##此文件实现将上面添加的内容删除
blockinfile:
dest: /var/www/html/index.html
marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"
content: ""
- name: insert/update "Match User" configuation block in /etc/ssh/sshd_config
blockinfile:
dest: /etc/hosts
block: |
{{item.name}} {{item.ip}}
marker: "# {mark} ANSIBLE MANAGED BLOCK {{item.name}}"
with_items:
- { name: host1, ip: 10.10.1.10 }
- { name: host2, ip: 10.10.1.11 }
- { name: host3, ip: 10.10.1.12 }
#cat blockinfile.yml
---
- hosts: web
user: root
tasks:
- name: this is test blockinfile module
blockinfile:
dest: /etc/hosts
block: |
this is a test line 1
this is a test line 2
this is a test line 3
结果:
#cat /etc/hosts
# BEGIN ANSIBLE MANAGED BLOCK
this is a test line 1
this is a test line 2
this is a test line 3
# END ANSIBLE MANAGED BLOCK
#cat blockinfile.yml
---
- hosts: 10.0.90.25
user: root
gather_facts: True
tasks:
- name: this is test blockinfile module
blockinfile:
dest: /etc/hosts
block: |
{{item.name}} {{item.ip}}
marker: "# {mark} ansible managed block {{item.name}}"
with_items:
- { name: host1, ip: 10.10.1.10}
- { name: host2, ip: 10.10.1.11}
- { name: host3, ip: 10.10.1.12}
当命令执行时间比较长时,也可以放到后台执行,这里会用到-B、-P参数,如下:
ansible all -B 3600 -a "/usr/bin/long_running_operation --do-stuff" \\后台执行命令 3600s,-B 表示后执行的时间
ansible all -m async_status -a "jid=123456789" \\检查任务的状态
ansible all -B 1800 -P 60 -a "/usr/bin/long_running_operation --do-stuff" \\后台执行命令最大时间是 1800s 即 30 分钟,-P 每 60s 检查下状态默认 15s
示例如下:
[root@361way ~]# ansible 10.212.52.252 -B 3600 -P 0 -a 'watch ls'
ansible-console
ansible-galaxy list
ansible-galaxy install DavidWittman.redis
mkdir -pv ./{nginx,memcached,httpd,mysql}/{file,templates,vars,handlers,meta,default,tasks}
http://www.jdccie.com/?p=3708
http://www.jdccie.com/?p=3706
http://www.jdccie.com/?p=3698
http://www.mamicode.com/info-detail-1428476.html
https://www.cnblogs.com/PythonOrg/p/6593910.html
--private-key
假设你有一些静态IP地址,希望设置一些别名,但不是在系统的 host 文件中设置,又或者你是通过隧道在连接,那么可以设置如下:
jumper ansible_ssh_port=5555 ansible_ssh_host=192.168.1.50
用户可以修改一下配置文件来修改设置,他们的被读取的顺序如下:
* ANSIBLE_CONFIG (一个环境变量)
* ansible.cfg (位于当前目录中)
* .ansible.cfg (位于家目录中)
* /etc/ansible/ansible.cfg
版本1.5之前的读取顺序如下:
* ansible.cfg (位于当前目录)
* ANSIBLE_CONFIG (一个环境变量)
* .ansible.cfg (位于家目录下)
* /etc/ansible/ansible.cfg
inventory = /etc/ansible/hosts
library = /usr/share/ansible
log_path=/var/log/ansible.log
module_name = command
nocolor=0
nocows=0
private_key_file=/path/to/file.pem
remote_port = 22
remote_tmp = $HOME/.ansible/tmp
remote_user = root
roles_path = /opt/mysite/roles:/opt/othersite/roles
sudo_user=root
timeout = 10
playbook
---
- hosts: webservers
vars:
http_port: 80
max_clients: 200
remote_user: root
tasks:
- name: ensure apache is at the latest version
yum: pkg=httpd state=latest
- name: write the apache config file
template: src=/srv/httpd.j2 dest=/etc/httpd.conf
notify:
- restart apache
- name: ensure apache is running
service: name=httpd state=started
handlers:
- name: restart apache
service: name=httpd state=restarted
command:/bin/echo hello world
tasks:
ping:
service: name=nginx state=started
service: name=httpd state=running
command: /sbin/setenforce 0
shell: /usr/bin/somecommand || /bin/true
shell: /usr/bin/somecommand
ignore_errors: True
copy: src=/etc/ansible/hosts dest=/etc/ansible/hosts owner=root group=root mode=0644
template
template: src=somefile.j2 dest=/etc/httpd/conf.d/{{ vhost }}
template: src=templates/foo.j2 dest=/etc/foo.conf
当一个文件的内容被改动时,重启两个 services
- name: template configuration file
template: src=template.j2 dest=/etc/foo.conf
notify:
- restart memcached
- restart apache
handlers:
- name: restart memcached
service: name=memcached state=restarted
- name: restart apache
service: name=apache state=restarted
tasks:
- include: wordpress.yml wp_user=timmy
- include: wordpress.yml wp_user=alice
- include: wordpress.yml wp_user=bob
tasks:
- { include: wordpress.yml, wp_user: timmy, ssh_keys: [ 'keys/one.txt', 'keys/two.txt' ] }
---
- hosts: all
remote_user: root
vars_files:
- "vars/common.yml"
- [ "vars/{{ ansible_os_family }}.yml", "vars/os_defaults.yml" ]
tasks:
- name: make sure apache is running
service: name={{ apache }} state=running
- name: add several users
user: name={{ item }} state=present groups=wheel
with_items:
- testuser1
- testuser2
with_items: "{{somelist}}"
- name: add several users
user: name={{ item.name }} state=present groups={{ item.groups }}
with_items:
- { name: 'testuser1', groups: 'wheel' }
- { name: 'testuser2', groups: 'root' }
---
- hosts:all
tasks:
- name: debug loops
debug: msg = "name-----> {{ item.key }} value---->{{ item.value }}"
with_items:
- {key:"one",value:"value1"}
- {key:"two",value:"value2"}
- debug: msg="{% for i in hi_var.results %} {{i.stdout}} {% endfor %}"
ansible-playbook playbook.yml -f 10 10个并发执行
ansible-playbook playbook.yml --list-hosts 查看执行会影响到哪些 hosts
vi /etc/ansible/ansible.cfg
[defaults]
host_key_checking = False
file模块
file模块主要用于远程主机上的文件操作,file模块包含如下选项:
force:需要在两种情况下强制创建软链接,一种是源文件不存在但之后会建立的情况下;另一种是目标软链接已存在,需要先取消之前的软链,然后创建新的软链,有两个选项:yes|no
group:定义文件/目录的属组
mode:定义文件/目录的权限
owner:定义文件/目录的属主
path:必选项,定义文件/目录的路径
recurse:递归的设置文件的属性,只对目录有效
src:要被链接的源文件的路径,只应用于state=link的情况
dest:被链接到的路径,只应用于state=link的情况
state: directory:如果目录不存在,创建目录
file:即使文件不存在,也不会被创建
link:创建软链接
hard:创建硬链接
touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间
absent:删除目录、文件或者取消链接文件
使用示例:
ansible test -m file -a "src=/etc/fstab dest=/tmp/fstab state=link"
ansible test -m file -a "path=/tmp/fstab state=absent"
ansible test -m file -a "path=/tmp/test state=touch"
四、copy模块
复制文件到远程主机,copy模块包含如下选项:
backup:在覆盖之前将原文件备份,备份文件包含时间信息。有两个选项:yes|no
content:用于替代"src",可以直接设定指定文件的值
dest:必选项。要将源文件复制到的远程主机的绝对路径,如果源文件是一个目录,那么该路径也必须是个目录
directory_mode:递归的设定目录的权限,默认为系统默认权限
force:如果目标主机包含该文件,但内容不同,如果设置为yes,则强制覆盖,如果为no,则只有当目标主机的目标位置不存在该文件时,才复制。默认为yes
others:所有的file模块里的选项都可以在这里使用
src:要复制到远程主机的文件在本地的地址,可以是绝对路径,也可以是相对路径。如果路径是一个目录,它将递归复制。在这种情况下,如果路径使用"/"来结尾,则只复制目录里的内容,如果没有使用"/"来结尾,则包含目录在内的整个内容全部复制,类似于rsync。
validate :The validation command to run before copying into place. The path to the file to validate is passed in via '%s' which must be present as in the visudo example below.
示例如下:
ansible test -m copy -a "src=/srv/myfiles/foo.conf dest=/etc/foo.conf owner=foo group=foo mode=0644"
ansible test -m copy -a "src=/mine/ntp.conf dest=/etc/ntp.conf owner=root group=root mode=644 backup=yes"
ansible test -m copy -a "src=/mine/sudoers dest=/etc/sudoers validate='visudo -cf %s'"
五、service模块
用于管理服务
该模块包含如下选项:
arguments:给命令行提供一些选项
enabled:是否开机启动 yes|no
name:必选项,服务名称
pattern:定义一个模式,如果通过status指令来查看服务的状态时,没有响应,就会通过ps指令在进程中根据该模式进行查找,如果匹配到,则认为该服务依然在运行
runlevel:运行级别
sleep:如果执行了restarted,在则stop和start之间沉睡几秒钟
state:对当前服务执行启动,停止、重启、重新加载等操作(started,stopped,restarted,reloaded)
使用示例:
# Example action to reload service httpd, in all cases
- service: name=httpd state=reloaded
# Example action to enable service httpd, and not touch the running state
- service: name=httpd enabled=yes
# Example action to start service foo, based on running process /usr/bin/foo
- service: name=foo pattern=/usr/bin/foo state=started
# Example action to restart network service for interface eth0
- service: name=network state=restarted args=eth0
六、cron模块
用于管理计划任务
包含如下选项:
backup:对远程主机上的原任务计划内容修改之前做备份
cron_file:如果指定该选项,则用该文件替换远程主机上的cron.d目录下的用户的任务计划
day:日(1-31,,/2,……)
hour:小时(0-23,,/2,……)
minute:分钟(0-59,,/2,……)
month:月(1-12,,/2,……)
weekday:周(0-7,*,……)
job:要执行的任务,依赖于state=present
name:该任务的描述
special_time:指定什么时候执行,参数: reboot,yearly,annually,monthly,weekly,daily,hourly
state:确认该任务计划是创建还是删除
user:以哪个用户的身份执行
示例:
ansible test -m cron -a 'name="a job for reboot" special_time=reboot job="/some/job.sh"'
ansible test -m cron -a 'name="yum autoupdate" weekday="2" minute=0 hour=12 user="root
ansible 10.212.52.252 -m cron -a 'backup="True" name="test" minute="0" hour="2" job="ls -alh > /dev/null"'
ansilbe test -m cron -a 'cron_file=ansible_yum-autoupdate state=absent'
七、yum模块
使用yum包管理器来管理软件包,其选项有:
config_file:yum的配置文件
disable_gpg_check:关闭gpg_check
disablerepo:不启用某个源
enablerepo:启用某个源
name:要进行操作的软件包的名字,也可以传递一个url或者一个本地的rpm包的路径
state:状态(present,absent,latest)
示例如下:
ansible test -m yum -a 'name=httpd state=latest'
ansible test -m yum -a 'name="@Development tools" state=present'
ansible test -m yum -a 'name=http://nginx.org/packages/centos/6/noarch/RPMS/
nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present'
yum: name=httpd enablerepo=testing state=present
- name: upgrade all packages
yum: name=* state=latest
八、user模块与group模块
user模块是请求的是useradd, userdel, usermod三个指令,goup模块请求的是groupadd, groupdel, groupmod 三个指令,具体参数这里不再细讲,直接上示例。
1、user模块示例:
- user: name=johnd comment="John Doe" uid=1040 group=admin
- user: name=james shell=/bin/bash groups=admins,developers append=yes
- user: name=johnd state=absent remove=yes
- user: name=james18 shell=/bin/zsh groups=developers expires=1422403387
#生成密钥时,只会生成公钥文件和私钥文件,和直接使用ssh-keygen指令效果相同,
不会生成authorized_keys文件。
- user: name=test generate_ssh_key=yes ssh_key_bits=2048 ssh_key_file=.ssh/id_rsa
注:指定password参数时,不能使用后面这一串密码会被直接传送到被管理主机的/etc/shadow文件中,所以需要先将密码字符串进行加密处理。然后将得到的字符串放到password中即可。
[root@361way ~]# openssl passwd -1 -salt $(< /dev/urandom tr -dc '[:alnum:]' | head -c 32)
Password:
$1$YngB4z8s$atSVltYKnDxJmWZ3s.4/80
或者
[root@361way ~]# echo "123456" | openssl passwd -1 -salt $(< /dev/urandom tr -dc '[:alnum:]'
| head -c 32) -stdin
$1$4P4PlFuE$ur9ObJiT5iHNrb9QnjaIB0
#经验证下面生成的密码串也可以正常使用,不过与/etc/shadow的格式不统一,不建议使用
[root@361way ~]# openssl passwd -salt -1 "123456"
-1yEWqqJQLC66
#使用上面的密码创建用户
[root@361way ~]#ansible all -m user -a 'name=foo password="$1$4P4PlFuE$ur9ObJiT5iHNrb9QnjaIB0"'
不同的发行版默认使用的加密方式可能会有区别,具体可以查看/etc/login.defs文件确认,centos 6.5版本使用的是SHA512加密算法,生成密码可以通过ansible官方给出的示例:
python -c "from passlib.hash import sha512_crypt;
import getpass;
print sha512_crypt.encrypt
(getpass.getpass())"
2、group示例
- group: name=somegroup state=present
九、synchronize模块
使用rsync同步文件,其参数如下:
archive: 归档,相当于同时开启recursive(递归)、links、perms、times、owner、group、-D选项都为yes ,默认该项为开启
checksum: 跳过检测sum值,默认关闭
compress:是否开启压缩
copy_links:复制链接文件,默认为no ,注意后面还有一个links参数
delete: 删除不存在的文件,默认no
dest:目录路径
dest_port:默认目录主机上的端口 ,默认是22,走的ssh协议
dirs:传速目录不进行递归,默认为no,即进行目录递归
rsync_opts:rsync参数部分
set_remote_user:主要用于/etc/ansible/hosts中定义或默认使用的用户-与rsync使用的用户不同的情况
mode: push或pull 模块,push模的话,一般用于从本机向远程主机上传文件,
pull 模式用于从远程主机上取文件
另外还有其他参数,这里不再一一说明。上几个用法:
src=some/relative/path dest=/some/absolute/path rsync_path="sudo rsync"
src=some/relative/path dest=/some/absolute/path archive=no links=yes
src=some/relative/path dest=/some/absolute/path checksum=yes times=no
src=/tmp/helloworld dest=/var/www/helloword rsync_opts=--no-motd,--exclude=.git mode=pull
十、mount模块
配置挂载点
选项:
dump
fstype:必选项,挂载文件的类型
name:必选项,挂载点
opts:传递给mount命令的参数
src:必选项,要挂载的文件
state:必选项present:只处理fstab中的配置
absent:删除挂载点
mounted:自动创建挂载点并挂载之'
umounted:卸载
示例:
name=/mnt/dvd src=/dev/sr0 fstype=iso9660 opts=ro state=present
name=/srv/disk src='LABEL=SOME_LABEL' state=present
name=/home src='UUID=b3e48f45-f933-4c8e-a700-22a159ec9077' opts=noatime state=present
ansible test -a 'dd if=/dev/zero of=/disk.img bs=4k count=1024'
ansible test -a 'losetup /dev/loop0 /disk.img'
ansible test -m filesystem 'fstype=ext4 force=yes opts=-F dev=/dev/loop0'
ansible test -m mount 'name=/mnt src=/dev/loop0 fstype=ext4 state=mounted opts=rw'
十一、get_url 模块
该模块主要用于从http、ftp、https服务器上下载文件(类似于wget),主要有如下选项:
sha256sum:下载完成后进行sha256 check;
timeout:下载超时时间,默认10s
url:下载的URL
url_password、url_username:主要用于需要用户名密码进行验证的情况
use_proxy:是事使用代理,代理需事先在环境变更中定义
示例:
- name: download foo.conf
get_url: url=http://example.com/path/file.conf dest=/etc/foo.conf mode=0440
- name: download file with sha256 check
get_url: url=http://example.com/path/file.conf dest=/etc/foo.conf sha256sum=b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c
模块部分就先介绍到这里吧,官方提供的可能用到模块有git、svn版本控制模块,sysctl 、authorized_key_module系统模块,apt、zypper、pip、gem包管理模块,find、template文件模块,mysql_db、redis数据库模块,url 网络模块等。具体可以参看官方手册模块部分;
Time Limited Background Operations
需要长时间运行的命令可以放到后台去,在命令开始运行后我们也可以检查运行的状态.如果运行命令后,不想获取返回的信息, 可执行如下命令:
$ ansible all -B 3600 -P 0 -a "/usr/bin/long_running_operation --do-stuff"
如果你确定要在命令运行后检查运行的状态,可以使用 async_status 模块.前面执行后台命令后会返回一个 job id, 将这个 id 传给 async_status 模块:
$ ansible web1.example.com -m async_status -a "jid=488359678239.2844"
获取状态的命令如下:
$ ansible all -B 1800 -P 60 -a "/usr/bin/long_running_operation --do-stuff"
其中 -B 1800 表示最多运行30分钟, -P 60 表示每隔60秒获取一次状态信息.
Polling 获取状态信息的操作会在后台工作任务启动之后开始.若你希望所有的工作任务快速启动, --forks 这个选项的值 要设置得足够大,这是前面讲过的并发进程的个数.在运行指定的时间(由``-B``选项所指定)后,远程节点上的任务进程便会被终止.
一般你只能在把需要长时间运行的命令或是软件升级这样的任务放到后台去执行.对于 copy 模块来说,即使按照前面的示例想放到 后台执行文件传输,实际上并不会如你所愿.
when: foo is defined
when: bar is not defined
vars:
epic: true
when: epic
when: not epic
when: "'reticulating splines' in output"
- command: echo {{ item }}
with_items: [ 0, 2, 4, 6, 8, 10 ]
when: item > 5
tasks:
- command: /bin/false
register: result
ignore_errors: True
- command: /bin/something
when: result|failed
- command: /bin/something_else
when: result|succeeded
- command: /bin/still/something_else
when: result|skipped
tasks:
- shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
when: foo is defined
- fail: msg="Bailing out. this play requires 'bar'"
when: bar is undefined
#when 和 循环
tasks:
- command: echo {{ item }}
with_items: [ 0, 2, 4, 6, 8, 10 ]
when: item > 5
#when和include
- include: tasks/sometasks.yml
when: "'reticulating splines' in output"
when: motd_contents.stdout.find('hi') != -1
with_items: home_dirs.stdout_lines
#when 和角色
- hosts: webservers
roles:
- { role: debian_stock_config, when: ansible_os_family == 'Debian' }
有些时候,我们想基于不同的操作系统,选择不同的配置文件,及配置文件的存放路径,可以借助with_first_found来解决:
- name: template a file
template: src={{ item }} dest=/etc/myapp/foo.conf
with_first_found:
- files:
- {{ ansible_distribution }}.conf
- default.conf
paths:
- search_location_one/somedir/
- /opt/other_location/somedir/
failed_when其实是ansible的一种错误处理机制,是由fail模块使用了when条件语句的组合效果。示例如下:
- name: this command prints FAILED when it fails
command: /usr/bin/example-command -x -y -z
register: command_result
failed_when: "'FAILED' in command_result.stderr"我们也可以直接通过fail模块和when条件语句,写成如下:
- name: this command prints FAILED when it fails
command: /usr/bin/example-command -x -y -z
register: command_result
ignore_errors: True
- name: fail the play if the previous command did not succeed
fail: msg="the command failed"
when: "'FAILED' in command_result.stderr"
当我们控制一些远程主机执行某些任务时,当任务在远程主机上成功执行,状态发生更改时,会返回changed状态响应,状态未发生更改时,会返回OK状态响应,当任务被跳过时,会返回skipped状态响应。我们可以通过changed_when来手动更改changed响应状态。示例如下:
- shell: /usr/bin/billybass --mode="take me to the river"
register: bass_result
changed_when: "bass_result.rc != 2" #只有该条task执行以后,bass_result.rc的值不为2时,才会返回changed状态
# this will never report 'changed' status
- shell: wall 'beep'
changed_when: False #当changed_when为false时,该条task在执行以后,永远不会返回changed状态
cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.j2
vim /etc/nginx/nginx.conf.j2
worker_processes {{ ansible_processor_vcpus }}; #引用内置变量获得cpu颗数
listen {{ nginxport }}; #自定义变量
users:
alice:
name: Alice Appleworth
telephone: 123-456-7890
bob:
name: Bob Bananarama
telephone: 987-654-3210
#playbook文件
tasks:
- name: Print phone records
debug: msg="User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
with_dict: users
用with_fileglob可以获取本地文件列表。示例如下:
# copy each file over that matches the given pattern
- copy: src={{ item }} dest=/etc/fooapp/ owner=root mode=600
with_fileglob:
- /playbooks/files/fooapp/*
用with_together可以达到类似Python里的zip函数的功能。示例如下:
#变量文件:
---
alpha: [ 'a', 'b', 'c', 'd' ]
numbers: [ 1, 2, 3, 4 ]
#playbook文件
tasks:
- debug: msg="{{ item.0 }} and {{ item.1 }}"
with_together:
- alpha
- numbers
with_lines指令后跟一个命令,ansible会遍历命令的输出。示例如下:
- name: Example of looping over a command result
shell: /usr/bin/frobnicate {{ item }}
with_lines: /usr/bin/frobnications_per_host --param {{ inventory_hostname }}
标签功能可以给Roles、文件、单独的任务甚至整个Playbook打上标签,然后利用这些标签来指定要运行或不运行Playbook中的个别任务。
例:
vim test.yml
---
- hosts: test
tags: deploy #给整个Playbook打一个标签
tasks:
- name: test_tags
shell: ***
tags: #为任务打标签
- test1
- test2
- include: foo.yml
tags: foo
ansible-playbook test.yml --tags "test1" #只执行test_tags任务
ansible-playbook test.yml --skip-tags "test2" #跳过test_tags任务
ansible test -m user -a "name=test shell=/bin/bash groups=admin,dba append=yes home=/home/test state=present" #新建test用户,group指定属组,groups指定附加组,'groups='删除所有附加组,append=yes增量添加属组,state默认present,表示新建。
ansible test -m user -a "name=test groups=dba append=no" #test用户附加组改为dba,append=no全量变更属组信息。
ansible test -m user -a "name=test1 generate_ssh_key=yes ssh_key_bits=2048 ssh_key_file=.ssh/id_rsa" #generate_ssh_key=yes生成SSH key,ssh_key_bits指定加密位数,默认2048,ssh_key_file指定key文件位置,默认.ssh/id_rsa,相对路径表示家目录下
ansible test -m user -a "name=test state=absent remove=yes" #删除test用户,state=absent表示删除用户,remove=yes结合state=absent相当于userdel --remove
ansible test -m user -a "name=test password=eRgUloPQMARVY" #变更用户密码,使用加密密码。
加密方式:
(a)书中介绍的mkpasswd,在redhat下不行,好像ubuntu下可以,我用的openssl,测试redhat下可行。
openssl passwd "redhat123"
eRgUloPQMARVY
(b)使用python的passlib、getpass库
ansible-playbook example.yml --tags "configuration,packages"
ansible-playbook example.yml --skip-tags "notification"
ansible db -m user -a 'name=DBA uid=505 home=/home/dba shell=/sbin/nologin'
ansible db -m user -a 'name=DBA state=absent' #state属性有:present表示添加,absend表示删除,state属性默认是present
ansible all -m shell -a 'echo "123456" | passwd foo --stdin'
absent,present,installed,removed,latest
3、通过vars_prompt来实现人机交互:
hosts: all
remote_user: root
vars_prompt:
- name: 'https_passphrase' #存储数据的变量名
prompt: 'Key Passphrase' #手工输入数据
private: yes #当该值为yes,则用户的输入不会被打印
j2:
{% if 'db1' in group_names %}
[mysqld]
server-id=1
log-bin=mysql-bin
log-bin-index=mysql-bin.index
sync-binlog=1
innodb_flush_log_at_trx_commit=1 #我们知道db1在mdb组,当db1与当前执行c一组时,我们认为当前主机即在mdb组,所以对当前主机应用mysql master的配置
{% else %}
[mysqld]
server-id=2
relay-log=relay-log
relay-log-index=relay-log.index
read-only = yes
sync_master_info = 1
sync_relay_log = 1
sync_relay_log_info = 1
relay_log_recovery = 1
skip_slave_start #当db1与当前主机不在同一组时,则认为当前主机不在mdb组,即应用my slave的配置
{% endif %}
{% for i in range(1,10) %}
test{{ i }}
{% endfor %}
{% for host in groups.web%}
server {{host.inventory_hostname}} {{ host.ansible_default_ipv4.address }}:80
{% endfor %}
{% for id in range(201,212) %}
192.168.13.{{ id }} web{{ "%03d" |format(id-200) }}.test.com
{% endfor %}
bind_address=10.0.90.27:{{ PORT | default(3306) }}
ansible一键部署高可用Kubernetes
https://github.com/zhangguanzhang/Kubernetes-ansible
https://github.com/feiskyer/kubernetes-handbook
https://kubernetes.feisky.xyz/
https://github.com/bravist/lnmp-docker
https://github.com/bcicen/ctop