kdeploy 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/README.md CHANGED
@@ -1,1030 +1,195 @@
1
1
  # Kdeploy
2
2
 
3
- ```
4
- _ _
5
- /\ /\__| | ___ _ __ | | ___ _ _
6
- / //_/ _` |/ _ \ '_ \| |/ _ \| | | |
7
- / __ \ (_| | __/ |_) | | (_) | |_| |
8
- \/ \/\__,_|\___| .__/|_|\___/ \__, |
9
- |_| |___/
10
-
11
- ⚡ Lightweight Agentless Deployment Tool
12
- 🚀 Deploy with confidence, scale with ease
13
- ```
14
-
15
- [![Gem Version](https://badge.fury.io/rb/kdeploy.svg)](https://badge.fury.io/rb/kdeploy)
16
- [![Build Status](https://github.com/kevin197011/kdeploy/workflows/CI/badge.svg)](https://github.com/kevin197011/kdeploy/actions)
17
-
18
- Kdeploy 是一个现代化的轻量级 agentless 运维部署工具,类似于 Chef、Puppet 和 Ansible。它采用优雅的 Ruby DSL 语法,支持并发执行、统计分析和完整的部署生命周期管理。
3
+ A lightweight agentless deployment automation tool written in Ruby.
19
4
 
20
- ## 特性
5
+ ## 🌟 Features
21
6
 
22
- - 🚀 **轻量级**: 无需在目标服务器安装 agent,基于 SSH 连接
23
- - 🎨 **现代界面**: 美观的 ASCII 艺术字和彩色输出界面
24
- - 🔧 **DSL 语法**: 简洁优雅的 Ruby DSL 配置语法
25
- - **并发执行**: 支持多主机并发操作和智能并发控制
26
- - 🛠️ **批量操作**: 高效的批量 Shell 命令执行
27
- - 🔒 **安全连接**: 基于 SSH 的安全连接,支持密钥认证
28
- - 📝 **实时输出**: 命令执行结果实时显示,包含详细执行时间统计
29
- - 🎯 **角色管理**: 灵活的基于角色的主机分组管理
30
- - 📋 **Inventory 管理**: 强大的 YAML 格式主机清单,支持群组和变量继承
31
- - 🧩 **Heredoc 语法**: 支持多行 Shell 脚本的 heredoc 语法
32
- - 🎨 **ERB 模板**: 内置 ERB 模板引擎,支持动态配置文件生成
33
- - 🏷️ **变量替换**: 支持 `{{variable}}` 和 `${variable}` 双重模板语法
34
- - 🖥️ **混合执行**: 支持本地命令执行和混合部署场景
35
- - 📊 **统计分析**: 自动收集部署统计,支持性能分析和趋势监控
36
- - 🔄 **脚本库**: 丰富的预制脚本模板,覆盖完整部署生命周期
37
- - 🧩 **模块化架构**: 支持脚本模块化组织,可复用通用任务组件
38
- - 🛡️ **错误恢复**: 智能错误处理和自动重试机制
7
+ - 🔑 **Agentless Remote Deployment**: Uses SSH for secure remote execution
8
+ - 📝 **Elegant Ruby DSL**: Simple and expressive task definition
9
+ - 🚀 **Concurrent Execution**: Efficient parallel task processing
10
+ - 📤 **File Upload Support**: Easy file and template deployment
11
+ - 📊 **Task Status Tracking**: Real-time execution monitoring
12
+ - 🔄 **ERB Template Support**: Dynamic configuration generation
13
+ - 🎯 **Role-based Deployment**: Target specific server roles
14
+ - 🔍 **Dry Run Mode**: Preview tasks before execution
39
15
 
40
- ## 📦 安装
16
+ ## 📦 Installation
41
17
 
42
- 将以下内容添加到您的 Gemfile
18
+ Add this line to your application's Gemfile:
43
19
 
44
20
  ```ruby
45
21
  gem 'kdeploy'
46
22
  ```
47
23
 
48
- 然后执行:
24
+ And then execute:
49
25
 
50
26
  ```bash
51
27
  $ bundle install
52
28
  ```
53
29
 
54
- 或者直接安装:
30
+ Or install it yourself as:
55
31
 
56
32
  ```bash
57
33
  $ gem install kdeploy
58
34
  ```
59
35
 
60
- ## 🚀 快速开始
61
-
62
- ### 1. 初始化项目
63
-
64
- ```bash
65
- $ kdeploy init myapp
66
- $ cd myapp
67
- ```
68
-
69
- kdeploy 会自动创建完整的项目结构,包含多个实用脚本范例:
70
-
71
- ```
72
- myapp/
73
- ├── deploy.rb # 主部署脚本
74
- ├── inventory.yml # 主机清单配置
75
- ├── config/ # 配置文件目录
76
- │ └── kdeploy.yml # 全局配置文件
77
- ├── scripts/ # 🆕 完整脚本库
78
- │ ├── common_tasks.rb # 🆕 通用任务模块(可复用)
79
- │ ├── setup.rb # 服务器初始化
80
- │ ├── database.rb # 数据库管理
81
- │ ├── backup.rb # 备份操作
82
- │ ├── monitoring.rb # 监控和健康检查
83
- │ ├── rollback.rb # 回滚操作
84
- │ └── cleanup.rb # 清理维护
85
- └── templates/ # ERB模板文件
86
- ├── nginx.conf.erb # Nginx配置模板
87
- ├── app.service.erb # Systemd服务模板
88
- ├── deploy.sh.erb # 部署脚本模板
89
- └── backup.sh.erb # 备份脚本模板
90
- ```
91
-
92
- ### 2. 配置服务器清单
93
-
94
- 编辑 `inventory.yml` 配置主机清单:
95
-
96
- ```yaml
97
- # 全局变量
98
- vars:
99
- application: myapp
100
- version: 1.0.0
101
- deploy_to: /opt/myapp
102
- environment: production
103
-
104
- # 主机群组
105
- groups:
106
- webservers:
107
- hosts:
108
- - web1.example.com
109
- - web2.example.com
110
- vars:
111
- nginx_port: 80
112
- app_port: 3000
113
-
114
- databases:
115
- hosts:
116
- - db1.example.com
117
- vars:
118
- postgres_port: 5432
119
- backup_enabled: true
120
-
121
- production:
122
- children:
123
- - webservers
124
- - databases
125
- vars:
126
- environment: production
127
-
128
- # 主机详细配置
129
- hosts:
130
- web1.example.com:
131
- user: deploy
132
- port: 22
133
- roles: [web, app]
134
- ssh:
135
- key_file: ~/.ssh/id_rsa
136
- verify_host_key: false
137
- vars:
138
- server_id: 1
139
-
140
- web2.example.com:
141
- user: deploy
142
- port: 22
143
- roles: [web, app]
144
- ssh:
145
- key_file: ~/.ssh/id_rsa
146
- verify_host_key: false
147
- vars:
148
- server_id: 2
149
-
150
- db1.example.com:
151
- user: deploy
152
- port: 22
153
- roles: [database]
154
- ssh:
155
- key_file: ~/.ssh/id_rsa
156
- verify_host_key: false
157
- vars:
158
- server_id: 3
159
- master: true
160
- ```
161
-
162
- ### 3. 使用预制脚本
163
-
164
- kdeploy 提供了完整的脚本库,覆盖部署的各个阶段:
165
-
166
- #### 🔧 服务器初始化
167
- ```bash
168
- # 首次部署前执行,安装依赖和配置环境
169
- $ kdeploy deploy scripts/setup.rb
170
- ```
171
-
172
- #### 💾 数据库管理
173
- ```bash
174
- # 数据库相关操作
175
- $ kdeploy deploy scripts/database.rb # 创建数据库、迁移、备份
176
- ```
177
-
178
- #### 🚀 应用部署
179
- ```bash
180
- # 主要应用部署
181
- $ kdeploy deploy deploy.rb
182
- ```
183
-
184
- #### 📊 健康监控
185
- ```bash
186
- # 系统和应用健康检查
187
- $ kdeploy deploy scripts/monitoring.rb
188
- ```
189
-
190
- #### 💾 备份操作
191
- ```bash
192
- # 应用和数据备份
193
- $ kdeploy deploy scripts/backup.rb
194
- ```
195
-
196
- #### 🔙 回滚操作
197
- ```bash
198
- # 紧急回滚和恢复
199
- $ kdeploy deploy scripts/rollback.rb
200
- ```
201
-
202
- #### 🧹 清理维护
203
- ```bash
204
- # 系统清理和维护
205
- $ kdeploy deploy scripts/cleanup.rb
206
- ```
207
-
208
- #### 🧩 通用任务模块
209
- ```bash
210
- # 使用通用任务模块进行基础设置
211
- $ kdeploy deploy scripts/common_tasks.rb --task setup_environment
212
-
213
- # 执行安全加固
214
- $ kdeploy deploy scripts/common_tasks.rb --task security_hardening
215
-
216
- # 在主脚本中引入模块化任务
217
- # deploy.rb 中自动包含: include 'scripts/common_tasks.rb' if File.exist?('scripts/common_tasks.rb')
218
- ```
36
+ ## 🚀 Quick Start
219
37
 
220
- ### 4. 部署工作流示例
38
+ 1. Initialize a new project:
221
39
 
222
40
  ```bash
223
- # 1. 验证配置
224
- $ kdeploy validate deploy.rb
225
-
226
- # 2. 首次服务器设置
227
- $ kdeploy deploy scripts/setup.rb
228
-
229
- # 3. 设置数据库
230
- $ kdeploy deploy scripts/database.rb
231
-
232
- # 4. 执行应用部署
233
- $ kdeploy deploy deploy.rb --verbose
234
-
235
- # 5. 健康检查
236
- $ kdeploy deploy scripts/monitoring.rb
237
-
238
- # 6. 查看统计信息
239
- $ kdeploy stats summary
41
+ $ kdeploy init my-deployment
240
42
  ```
241
43
 
242
- ## 📊 统计和监控功能
243
-
244
- Kdeploy 提供了强大的内置统计功能,自动跟踪所有部署活动:
245
-
246
- ### 📈 自动收集的统计数据
247
-
248
- - ✅ **成功/失败统计**: 部署、任务和命令级别的成功失败率
249
- - ⏱️ **性能指标**: 详细的执行时间和性能数据
250
- - 📅 **历史趋势**: 按日期分组的性能趋势分析
251
- - 🎯 **失败分析**: 识别最常失败的任务和错误模式
252
- - 🌍 **全局统计**: 跨会话的累计统计数据
253
-
254
- ### 🔍 统计命令
255
-
256
- ```bash
257
- # 查看统计概要
258
- $ kdeploy stats summary
259
-
260
- # 查看部署统计
261
- $ kdeploy stats deployments
262
-
263
- # 查看任务统计
264
- $ kdeploy stats tasks
265
-
266
- # 查看失败统计
267
- $ kdeploy stats failures
268
-
269
- # 查看性能趋势
270
- $ kdeploy stats trends
271
-
272
- # 查看全局统计
273
- $ kdeploy stats global
274
-
275
- # 导出统计数据
276
- $ kdeploy stats export --export monthly_report.json
44
+ 2. Edit the deployment configuration:
277
45
 
278
- # 清空统计数据
279
- $ kdeploy stats clear
280
-
281
- # 指定时间范围(天数)
282
- $ kdeploy stats summary --days 7
283
-
284
- # JSON格式输出
285
- $ kdeploy stats tasks --format json
286
- ```
287
-
288
- ### 📊 统计输出示例
289
-
290
- ```bash
291
- $ kdeploy stats summary
292
-
293
- 📊 Kdeploy Statistics Summary (Last 30 days)
294
- =====================================================
295
-
296
- 📦 Deployment Summary:
297
- Total Deployments: 15
298
- Successful: 13 (86.7%)
299
- Failed: 2 (13.3%)
300
- Average Duration: 45.2s
301
-
302
- 🔧 Task Summary:
303
- Total Tasks: 89
304
- Successful: 84 (94.4%)
305
- Failed: 5 (5.6%)
306
- Average Duration: 12.8s
307
-
308
- 🌍 Global Statistics:
309
- Total Deployments: 156
310
- Session Duration: 2h 34m
311
- Most Active Day: 2025-06-28 (8 deployments)
312
- ```
313
-
314
- ## 🔧 模块化脚本组织
315
-
316
- Kdeploy 支持模块化脚本组织,让您可以将复杂的部署逻辑拆分成可重用的组件。
317
-
318
- ### 📋 模块化引入语法
319
-
320
- 在 `deploy.rb` 主脚本中,您可以引入其他脚本文件:
321
-
322
- ```ruby
323
- # 引入通用任务模块(如果文件存在)
324
- include 'scripts/common_tasks.rb' if File.exist?('scripts/common_tasks.rb')
325
-
326
- # 引入项目特定任务
327
- include 'scripts/myapp_tasks.rb' if File.exist?('scripts/myapp_tasks.rb')
328
-
329
- # 引入环境特定任务
330
- include 'scripts/production_tasks.rb' if File.exist?('scripts/production_tasks.rb')
331
- include 'scripts/staging_tasks.rb' if File.exist?('scripts/staging_tasks.rb')
332
- ```
333
-
334
- ### 🏗️ common_tasks.rb - 通用任务库
335
-
336
- Kdeploy 自动生成 `scripts/common_tasks.rb` 文件,包含常用的基础设施任务:
337
-
338
- #### 环境设置任务
339
46
  ```ruby
340
- # 基础环境设置
341
- task 'setup_environment', on: :all do
342
- run 'sudo timedatectl set-timezone UTC', ignore_errors: true
343
- run 'sudo apt-get update -qq', ignore_errors: true
344
- run 'sudo apt-get install -y -qq htop curl wget vim git unzip', ignore_errors: true
345
- end
346
-
347
- # SSL证书配置
348
- task 'setup_ssl', on: :webservers do
349
- run 'sudo apt-get install -y certbot python3-certbot-nginx', ignore_errors: true
350
- run 'sudo certbot --nginx --dry-run -d {{hostname}}', ignore_errors: true
351
- end
352
-
353
- # 日志轮转配置
354
- task 'setup_log_rotation', on: :all do
355
- run <<~LOGROTATE
356
- sudo tee /etc/logrotate.d/{{application}} > /dev/null << 'EOF'
357
- {{deploy_to}}/shared/logs/*.log {
358
- daily
359
- missingok
360
- rotate 52
361
- compress
362
- delaycompress
363
- notifempty
364
- create 644 {{user}} {{user}}
365
- }
366
- EOF
367
- LOGROTATE
368
- end
369
- ```
370
-
371
- #### 安全加固任务
372
- ```ruby
373
- # 系统安全强化
374
- task 'security_hardening', on: :all do
375
- # 禁用root登录
376
- run 'sudo sed -i "s/PermitRootLogin yes/PermitRootLogin no/" /etc/ssh/sshd_config', ignore_errors: true
377
-
378
- # 配置防火墙
379
- run 'sudo ufw --force reset', ignore_errors: true
380
- run 'sudo ufw default deny incoming', ignore_errors: true
381
- run 'sudo ufw default allow outgoing', ignore_errors: true
382
- run 'sudo ufw allow ssh', ignore_errors: true
383
- run 'sudo ufw allow {{nginx_port || 80}}', ignore_errors: true
384
- run 'sudo ufw --force enable', ignore_errors: true
385
-
386
- # 安装fail2ban
387
- run 'sudo apt-get install -y fail2ban', ignore_errors: true
388
- run 'sudo systemctl enable fail2ban', ignore_errors: true
389
- end
390
- ```
391
-
392
- #### 应急处理任务
393
- ```ruby
394
- # 紧急停止所有服务
395
- task 'emergency_stop', on: :all do
396
- run 'echo "🚨 Emergency stop initiated on {{hostname}}"'
397
- run 'sudo systemctl stop {{application}}', ignore_errors: true
398
- run 'sudo systemctl stop nginx', ignore_errors: true
399
- end
400
-
401
- # 紧急启动所有服务
402
- task 'emergency_start', on: :all do
403
- run 'echo "🚨 Emergency start initiated on {{hostname}}"'
404
- run 'sudo systemctl start nginx', ignore_errors: true
405
- run 'sudo systemctl start {{application}}', ignore_errors: true
406
- end
407
- ```
408
-
409
- ### 🔗 使用模块化任务
410
-
411
- #### 在主脚本中调用模块化任务
412
-
413
- ```ruby
414
- # deploy.rb - 主部署脚本
415
- include 'scripts/common_tasks.rb' if File.exist?('scripts/common_tasks.rb')
416
-
417
- # 完整部署工作流,使用通用任务
418
- task 'full_setup_with_common_tasks' do
419
- run_task 'pre_deploy_checks' # 来自 common_tasks.rb
420
- run_task 'setup_environment' # 来自 common_tasks.rb
421
- run_task 'security_hardening' # 来自 common_tasks.rb
422
- run_task 'performance_tuning' # 来自 common_tasks.rb
423
- run_task 'deploy' # 来自当前文件
424
- run_task 'verify_deployment' # 来自 common_tasks.rb
425
- end
426
-
427
- # 应急处理演示
428
- task 'emergency_procedures_demo' do
429
- # 这些任务来自 common_tasks.rb:
430
- # run_task 'emergency_stop' # 停止所有服务
431
- # run_task 'emergency_start' # 启动所有服务
432
- # run_task 'health_check_all' # 综合健康检查
433
- end
434
- ```
435
-
436
- #### 单独执行模块化任务
437
-
438
- ```bash
439
- # 执行通用环境设置
440
- kdeploy deploy scripts/common_tasks.rb --task setup_environment
441
-
442
- # 执行安全加固
443
- kdeploy deploy scripts/common_tasks.rb --task security_hardening
444
-
445
- # 应急操作
446
- kdeploy deploy scripts/common_tasks.rb --task emergency_stop
447
- kdeploy deploy scripts/common_tasks.rb --task emergency_start
448
-
449
- # 部署验证
450
- kdeploy deploy scripts/common_tasks.rb --task verify_deployment
451
- ```
452
-
453
- ### 📁 项目特定任务模块
454
-
455
- 创建项目特定的任务文件:
456
-
457
- ```ruby
458
- # scripts/myapp_tasks.rb
459
- task 'install_nodejs', on: :webservers do
460
- run 'curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -'
461
- run 'sudo apt-get install -y nodejs'
462
- run 'node --version && npm --version'
463
- end
464
-
465
- task 'build_frontend', on: :webservers do
466
- run 'cd {{deploy_to}} && npm install'
467
- run 'cd {{deploy_to}} && npm run build'
468
- end
469
-
470
- task 'deploy_myapp' do
471
- run_task 'setup_environment' # 来自 common_tasks.rb
472
- run_task 'install_nodejs' # 来自当前文件
473
- run_task 'build_frontend' # 来自当前文件
474
- run_task 'verify_deployment' # 来自 common_tasks.rb
475
- end
476
- ```
47
+ # deploy.rb
477
48
 
478
- ### 🌍 环境特定任务
49
+ # Define hosts
50
+ host "web01", user: "ubuntu", ip: "10.0.0.1", key: "~/.ssh/id_rsa"
51
+ host "web02", user: "ubuntu", ip: "10.0.0.2", key: "~/.ssh/id_rsa"
479
52
 
480
- ```ruby
481
- # scripts/production_tasks.rb
482
- task 'production_ssl_setup', on: :webservers do
483
- run 'sudo certbot --nginx -d {{hostname}} --non-interactive --agree-tos --email admin@{{hostname}}'
484
- end
53
+ # Define roles
54
+ role :web, %w[web01 web02]
485
55
 
486
- task 'production_monitoring', on: :all do
487
- run 'sudo apt-get install -y datadog-agent'
488
- run 'sudo systemctl enable datadog-agent'
489
- end
490
-
491
- # scripts/staging_tasks.rb
492
- task 'staging_debug_mode', on: :webservers do
493
- run 'export DEBUG=true'
494
- run 'export LOG_LEVEL=debug'
56
+ # Define tasks
57
+ task :deploy, roles: :web do
58
+ run "sudo systemctl stop nginx"
59
+ upload_template "./config/nginx.conf.erb", "/etc/nginx/nginx.conf",
60
+ domain_name: "example.com",
61
+ port: 3000
62
+ run "sudo systemctl start nginx"
495
63
  end
496
64
  ```
497
65
 
498
- ### 💡 模块化最佳实践
499
-
500
- 1. **按功能分组**: 将相关任务放在同一个模块中
501
- 2. **条件引入**: 使用 `if File.exist?` 确保文件存在性检查
502
- 3. **任务命名**: 使用清晰的任务名称,避免冲突
503
- 4. **文档注释**: 为每个模块添加详细的使用说明
504
- 5. **测试验证**: 使用 `kdeploy validate` 验证脚本语法
505
-
506
- ### 🚀 模块化工作流示例
66
+ 3. Run the deployment:
507
67
 
508
68
  ```bash
509
- # 1. 完整的生产环境部署
510
- kdeploy deploy deploy.rb --task full_setup_with_common_tasks
511
-
512
- # 2. 分步骤执行
513
- kdeploy deploy scripts/common_tasks.rb --task setup_environment
514
- kdeploy deploy scripts/common_tasks.rb --task security_hardening
515
- kdeploy deploy deploy.rb --task deploy
516
- kdeploy deploy scripts/common_tasks.rb --task verify_deployment
517
-
518
- # 3. 环境特定配置
519
- kdeploy deploy scripts/production_tasks.rb --task production_ssl_setup
520
-
521
- # 4. 应急处理
522
- kdeploy deploy scripts/common_tasks.rb --task emergency_stop
523
- kdeploy deploy scripts/common_tasks.rb --task emergency_start
524
- ```
525
-
526
- 这种模块化组织方式让您可以:
527
- - 🔄 **复用代码**: 在多个项目间共享通用任务
528
- - 🎯 **专注职责**: 每个模块专注特定功能领域
529
- - 🔧 **灵活组合**: 根据需要灵活组合不同模块
530
- - 📝 **易于维护**: 模块化结构便于维护和测试
531
-
532
- ## 🛠️ 脚本库详解
533
-
534
- ### setup.rb - 服务器初始化脚本
535
-
536
- 完整的服务器环境准备:
537
-
538
- ```ruby
539
- # 安装系统依赖
540
- task 'install_dependencies', on: :all do
541
- run 'sudo apt-get update'
542
- run 'sudo apt-get install -y curl git build-essential'
543
- run 'sudo apt-get install -y nginx postgresql redis-server'
544
- end
545
-
546
- # 创建应用用户
547
- task 'setup_user', on: :all do
548
- run 'sudo useradd -m -s /bin/bash {{user}}', allow_failure: true
549
- run 'sudo mkdir -p /home/{{user}}/.ssh'
550
- run 'sudo cp ~/.ssh/authorized_keys /home/{{user}}/.ssh/'
551
- run 'sudo chown -R {{user}}:{{user}} /home/{{user}}/.ssh'
552
- end
553
-
554
- # 配置防火墙
555
- task 'setup_firewall', on: :all do
556
- run 'sudo ufw allow ssh'
557
- run 'sudo ufw allow {{nginx_port || 80}}'
558
- run 'sudo ufw --force enable'
559
- end
69
+ $ kdeploy execute deploy.rb
560
70
  ```
561
71
 
562
- ### database.rb - 数据库管理脚本
72
+ ## 📖 Usage Guide
563
73
 
564
- 数据库生命周期管理:
74
+ ### Host Definition
565
75
 
566
76
  ```ruby
567
- # 创建数据库
568
- task 'create_database', on: :databases do
569
- run 'sudo -u postgres createdb {{application}}_{{environment}}', allow_failure: true
570
- run 'sudo -u postgres createuser {{application}}_user', allow_failure: true
571
- run %(sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE {{application}}_{{environment}} TO {{application}}_user;")
572
- end
573
-
574
- # 数据库迁移
575
- task 'migrate', on: :databases do
576
- run 'cd {{deploy_to}} && npm run migrate'
577
- end
77
+ # Single host
78
+ host "web01",
79
+ user: "ubuntu",
80
+ ip: "10.0.0.1",
81
+ key: "~/.ssh/id_rsa"
578
82
 
579
- # 数据库备份
580
- task 'backup', on: :databases do
581
- run 'mkdir -p /backup/{{application}}'
582
- run 'pg_dump {{application}}_{{environment}} > /backup/{{application}}/backup_$(date +%Y%m%d_%H%M%S).sql'
83
+ # Multiple hosts
84
+ %w[web01 web02 web03].each do |name|
85
+ host name,
86
+ user: "ubuntu",
87
+ ip: "10.0.0.#{name[-1]}",
88
+ key: "~/.ssh/id_rsa"
583
89
  end
584
90
  ```
585
91
 
586
- ### monitoring.rb - 监控健康检查脚本
587
-
588
- 全面的系统和应用监控:
92
+ ### Role Management
589
93
 
590
94
  ```ruby
591
- # 系统健康检查
592
- task 'system_health', on: :all do
593
- run 'echo "=== System Health for {{hostname}} ==="'
594
- run 'uptime'
595
- run 'df -h'
596
- run 'free -h'
597
- run 'ps aux --sort=-%cpu | head -10'
598
- end
95
+ # Define roles
96
+ role :web, %w[web01 web02]
97
+ role :db, %w[db01 db02]
98
+ role :all, %w[web01 web02 db01 db02]
599
99
 
600
- # 应用健康检查
601
- task 'app_health', on: :webservers do
602
- run 'systemctl status {{application}}', allow_failure: true
603
- run 'curl -f http://localhost:{{app_port}}/health || echo "Health check failed"',
604
- timeout: 10, allow_failure: true
100
+ # Use roles in tasks
101
+ task :deploy_web, roles: :web do
102
+ # Tasks for web servers
605
103
  end
606
104
 
607
- # 性能监控
608
- task 'performance_check', on: :webservers do
609
- run 'curl -w "Connect: %{time_connect}s, Total: %{time_total}s\\n" -s -o /dev/null http://localhost:{{app_port}}/',
610
- timeout: 15, allow_failure: true
105
+ task :backup_db, roles: :db do
106
+ # Tasks for database servers
611
107
  end
612
108
  ```
613
109
 
614
- ### rollback.rb - 回滚操作脚本
615
-
616
- 灵活的回滚和恢复机制:
110
+ ### Task Definition
617
111
 
618
112
  ```ruby
619
- # 快速回滚到上一版本
620
- task 'rollback', on: :webservers do
621
- run 'cd {{deploy_to}} && git log --oneline -5'
622
- run 'cd {{deploy_to}} && git reset --hard HEAD~1'
623
- run 'sudo systemctl restart {{application}}'
113
+ # Basic task
114
+ task :simple do
115
+ run "echo 'Hello, World!'"
624
116
  end
625
117
 
626
- # 回滚到指定版本
627
- task 'rollback_to_commit', on: :webservers do |hosts, commit_hash|
628
- commit_hash ||= ENV['COMMIT_HASH']
629
- raise 'Please specify COMMIT_HASH environment variable' unless commit_hash
630
-
631
- run "cd {{deploy_to}} && git reset --hard #{commit_hash}"
632
- run 'sudo systemctl restart {{application}}'
118
+ # Role-based task
119
+ task :deploy, roles: :web do
120
+ run "sudo systemctl stop nginx"
121
+ upload "./config/nginx.conf", "/etc/nginx/nginx.conf"
122
+ run "sudo systemctl start nginx"
633
123
  end
634
124
 
635
- # 维护模式
636
- task 'maintenance_on', on: :webservers do
637
- run 'echo "maintenance" > {{deploy_to}}/public/maintenance.txt'
638
- run 'sudo nginx -s reload'
125
+ # Host-specific task
126
+ task :maintenance, on: %w[web01] do
127
+ run "sudo apt-get update"
128
+ run "sudo apt-get upgrade -y"
639
129
  end
640
130
  ```
641
131
 
642
- ## 🎨 模板系统
132
+ ### Template Support
643
133
 
644
- ### ERB 模板示例
134
+ Create an ERB template (`config/nginx.conf.erb`):
645
135
 
646
- `templates/nginx.conf.erb`:
647
136
  ```erb
648
- # Nginx configuration for <%= application %>
649
137
  server {
650
- listen <%= nginx_port || 80 %>;
651
- server_name <%= hostname %>;
652
- root <%= deploy_to %>/public;
138
+ listen 80;
139
+ server_name <%= domain_name %>;
653
140
 
654
141
  location / {
655
- try_files $uri $uri/ @app;
656
- }
657
-
658
- location @app {
659
- proxy_pass http://127.0.0.1:<%= app_port || 3000 %>;
142
+ proxy_pass http://localhost:<%= port %>;
660
143
  proxy_set_header Host $host;
661
144
  proxy_set_header X-Real-IP $remote_addr;
662
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
663
- }
664
-
665
- # Static files cache
666
- location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
667
- expires 1y;
668
- add_header Cache-Control "public, immutable";
669
145
  }
670
-
671
- access_log /var/log/nginx/<%= application %>_access.log;
672
- error_log /var/log/nginx/<%= application %>_error.log;
673
146
  }
674
147
  ```
675
148
 
676
- ### 使用模板
677
-
678
- ```ruby
679
- task 'configure_nginx', on: :webservers do
680
- upload_template 'nginx.conf', '/etc/nginx/sites-available/{{application}}'
681
- run 'sudo ln -sf /etc/nginx/sites-available/{{application}} /etc/nginx/sites-enabled/'
682
- run 'sudo nginx -t && sudo systemctl reload nginx'
683
- end
684
- ```
685
-
686
- ## 🖥️ 命令行接口
687
-
688
- ### 主要命令
689
-
690
- ```bash
691
- # 项目管理
692
- kdeploy init [PROJECT_NAME] # 初始化新项目
693
- kdeploy validate SCRIPT # 验证部署脚本
694
- kdeploy config # 显示当前配置
695
-
696
- # 部署执行
697
- kdeploy deploy SCRIPT # 执行部署脚本
698
- kdeploy execute SCRIPT # 执行脚本(别名)
699
-
700
- # 统计分析
701
- kdeploy stats summary # 统计概要
702
- kdeploy stats deployments # 部署统计
703
- kdeploy stats tasks # 任务统计
704
- kdeploy stats failures # 失败统计
705
- kdeploy stats trends # 性能趋势
706
- kdeploy stats global # 全局统计
707
- kdeploy stats export # 导出数据
708
- kdeploy stats clear # 清空统计
709
-
710
- # 帮助信息
711
- kdeploy version # 显示版本
712
- kdeploy help # 显示帮助
713
- kdeploy help [COMMAND] # 特定命令帮助
714
- ```
715
-
716
- ### 命令选项
717
-
718
- ```bash
719
- # 配置选项
720
- -c, --config FILE # 指定配置文件
721
- -i, --inventory FILE # 指定inventory文件
722
- -v, --verbose # 详细输出模式
723
- -l, --log-file FILE # 指定日志文件
724
-
725
- # 执行选项
726
- --dry-run # 干运行模式
727
- --parallel # 并行执行
728
-
729
- # 统计选项
730
- --days N # 指定天数范围
731
- --format FORMAT # 输出格式(table|json)
732
- --export FILE # 导出文件路径
733
- ```
734
-
735
- ## 📋 DSL 语法参考
736
-
737
- ### 基础语法
738
-
739
- ```ruby
740
- # 加载主机清单
741
- inventory 'inventory.yml'
742
-
743
- # 定义变量
744
- set 'application', 'myapp'
745
- set 'version', '1.0.0'
746
-
747
- # 定义主机
748
- host '192.168.1.100', user: 'deploy', port: 22
749
-
750
- # 定义任务
751
- task 'deploy', on: :webservers do
752
- run 'echo "Deploying to {{hostname}}"'
753
- end
754
-
755
- # 本地命令
756
- local 'echo "Starting deployment"'
757
- ```
758
-
759
- ### 高级语法
760
-
761
- ```ruby
762
- # 条件执行
763
- task 'conditional_task', on: :all do
764
- run 'echo "Production server"', only: :production
765
- run 'echo "Staging server"', except: :production
766
- end
767
-
768
- # 错误处理
769
- task 'robust_task', on: :all do
770
- run 'risky_command',
771
- allow_failure: true,
772
- timeout: 30,
773
- retry_count: 3
774
- end
775
-
776
- # 并发控制
777
- task 'parallel_task', on: :all, parallel: true, max_concurrent: 5 do
778
- run 'long_running_command'
779
- end
780
-
781
- # Heredoc 语法
782
- task 'complex_task', on: :all do
783
- run <<~SCRIPT
784
- echo "Starting complex deployment"
785
- cd {{deploy_to}}
786
-
787
- if [ -d .git ]; then
788
- git pull origin {{branch}}
789
- else
790
- git clone {{repo_url}} .
791
- fi
792
-
793
- npm install --production
794
- sudo systemctl restart {{application}}
795
- echo "Deployment completed"
796
- SCRIPT
797
- end
798
- ```
799
-
800
- ### 变量和模板
801
-
802
- ```ruby
803
- # 变量使用(两种语法)
804
- run 'echo "Application: {{application}}"'
805
- run 'echo "Version: ${version}"'
806
-
807
- # 内置变量
808
- run 'echo "Hostname: {{hostname}}"'
809
- run 'echo "User: {{user}}"'
810
- run 'echo "Port: {{port}}"'
811
-
812
- # 模板上传
813
- upload_template 'config.erb', '/etc/myapp/config.yml'
814
- ```
815
-
816
- ## ⚙️ 配置文件
817
-
818
- 创建 `config/kdeploy.yml`:
819
-
820
- ```yaml
821
- # 最大并发任务数
822
- max_concurrent_tasks: 10
823
-
824
- # 网络超时设置
825
- ssh_timeout: 30
826
- command_timeout: 300
827
-
828
- # 重试设置
829
- retry_count: 3
830
- retry_delay: 1
831
-
832
- # 日志设置
833
- log_level: info
834
- log_file: kdeploy.log
835
-
836
- # 默认设置
837
- default_user: deploy
838
- default_port: 22
839
-
840
- # SSH选项
841
- ssh_options:
842
- verify_host_key: never
843
- non_interactive: true
844
- use_agent: true
845
- forward_agent: false
846
-
847
- # 路径设置
848
- inventory_file: inventory.yml
849
- template_dir: templates
850
- ```
851
-
852
- ## 🎯 实际使用案例
853
-
854
- ### Node.js 应用部署
149
+ Use the template in your task:
855
150
 
856
151
  ```ruby
857
- # deploy.rb
858
- inventory 'inventory.yml'
859
-
860
- task 'deploy_nodejs', on: :webservers do
861
- run <<~DEPLOY
862
- echo "Deploying Node.js app to {{hostname}}"
863
-
864
- # 备份当前版本
865
- if [ -d "{{deploy_to}}/current" ]; then
866
- sudo mv {{deploy_to}}/current {{deploy_to}}/backup_$(date +%s)
867
- fi
868
-
869
- # 创建部署目录
870
- sudo mkdir -p {{deploy_to}}
871
- cd {{deploy_to}}
872
-
873
- # 获取最新代码
874
- if [ -d ".git" ]; then
875
- git fetch origin
876
- git reset --hard origin/{{branch}}
877
- else
878
- git clone {{repo_url}} .
879
- git checkout {{branch}}
880
- fi
881
-
882
- # 安装依赖
883
- npm install --production
884
-
885
- # 构建应用
886
- npm run build
887
-
888
- # 重启服务
889
- sudo systemctl restart {{application}}
890
-
891
- echo "✅ Deployment completed successfully"
892
- DEPLOY
893
- end
894
-
895
- # 健康检查
896
- task 'health_check', on: :webservers do
897
- run 'curl -f http://localhost:{{app_port}}/health',
898
- timeout: 30,
899
- retry_count: 3
152
+ task :deploy_config do
153
+ upload_template "./config/nginx.conf.erb", "/etc/nginx/sites-available/myapp.conf",
154
+ domain_name: "example.com",
155
+ port: 3000
900
156
  end
901
157
  ```
902
158
 
903
- ### Docker 应用部署
904
-
905
- ```ruby
906
- task 'deploy_docker', on: :webservers do
907
- run <<~DOCKER_DEPLOY
908
- echo "Deploying Docker application"
909
-
910
- # 拉取最新镜像
911
- docker pull {{image_name}}:{{version}}
912
-
913
- # 停止旧容器
914
- docker stop {{application}} || true
915
- docker rm {{application}} || true
916
-
917
- # 启动新容器
918
- docker run -d \
919
- --name {{application}} \
920
- -p {{app_port}}:3000 \
921
- -e NODE_ENV={{environment}} \
922
- {{image_name}}:{{version}}
923
-
924
- # 等待容器启动
925
- sleep 10
926
-
927
- echo "✅ Docker deployment completed"
928
- DOCKER_DEPLOY
929
- end
930
- ```
931
-
932
- ### 数据库迁移
933
-
934
- ```ruby
935
- task 'database_migration', on: :databases do
936
- run <<~MIGRATION
937
- echo "Running database migration"
938
-
939
- # 备份数据库
940
- pg_dump {{application}}_{{environment}} > \
941
- /backup/pre_migration_$(date +%Y%m%d_%H%M%S).sql
942
-
943
- # 执行迁移
944
- cd {{deploy_to}}
945
- NODE_ENV={{environment}} npm run migrate
946
-
947
- echo "✅ Database migration completed"
948
- MIGRATION
949
- end
950
- ```
951
-
952
- ## 🔧 故障排除
953
-
954
- ### 常见问题
955
-
956
- 1. **SSH 连接失败**
957
- ```bash
958
- # 检查SSH连接
959
- ssh -vvv user@hostname
960
-
961
- # 验证密钥
962
- ssh-add -l
963
- ```
964
-
965
- 2. **权限问题**
966
- ```ruby
967
- # 使用sudo执行命令
968
- run 'sudo systemctl restart nginx'
969
-
970
- # 检查文件权限
971
- run 'ls -la {{deploy_to}}'
972
- ```
973
-
974
- 3. **超时问题**
975
- ```ruby
976
- # 增加超时时间
977
- run 'long_command', timeout: 300
978
-
979
- # 或在配置文件中设置
980
- command_timeout: 600
981
- ```
982
-
983
- ### 调试技巧
159
+ ### Command Line Options
984
160
 
985
161
  ```bash
986
- # 详细输出模式
987
- kdeploy deploy script.rb --verbose
988
-
989
- # 干运行模式
990
- kdeploy deploy script.rb --dry-run
162
+ # Execute with dry run
163
+ kdeploy execute deploy.rb --dry-run
991
164
 
992
- # 查看配置
993
- kdeploy config
165
+ # Limit to specific hosts
166
+ kdeploy execute deploy.rb --limit web01,web02
994
167
 
995
- # 验证脚本
996
- kdeploy validate script.rb
168
+ # Set parallel execution count
169
+ kdeploy execute deploy.rb --parallel 5
997
170
 
998
- # 查看日志
999
- tail -f kdeploy.log
171
+ # Execute specific task
172
+ kdeploy execute deploy.rb deploy_web
1000
173
  ```
1001
174
 
1002
- ## 🤝 贡献
1003
-
1004
- 我们欢迎社区贡献!请参考以下指南:
1005
-
1006
- 1. Fork 项目
1007
- 2. 创建功能分支 (`git checkout -b feature/amazing-feature`)
1008
- 3. 提交更改 (`git commit -m 'Add amazing feature'`)
1009
- 4. 推送到分支 (`git push origin feature/amazing-feature`)
1010
- 5. 创建 Pull Request
175
+ ## 🔧 Development
1011
176
 
1012
- ## 📄 许可证
177
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
1013
178
 
1014
- 本项目采用 MIT 许可证。详情请参阅 [LICENSE](LICENSE) 文件。
179
+ To install this gem onto your local machine, run `bundle exec rake install`.
1015
180
 
1016
- ## 🔗 相关链接
181
+ ## 🤝 Contributing
1017
182
 
1018
- - [项目主页](https://github.com/kevin197011/kdeploy)
1019
- - [文档中心](https://github.com/kevin197011/kdeploy/wiki)
1020
- - [问题反馈](https://github.com/kevin197011/kdeploy/issues)
1021
- - [发布日志](https://github.com/kevin197011/kdeploy/releases)
183
+ 1. Fork it
184
+ 2. Create your feature branch (`git checkout -b feature/my-new-feature`)
185
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
186
+ 4. Push to the branch (`git push origin feature/my-new-feature`)
187
+ 5. Create a new Pull Request
1022
188
 
1023
- ## 💬 社区支持
189
+ ## 📝 License
1024
190
 
1025
- - GitHub Issues: [报告问题](https://github.com/kevin197011/kdeploy/issues)
1026
- - GitHub Discussions: [社区讨论](https://github.com/kevin197011/kdeploy/discussions)
191
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
1027
192
 
1028
- ---
193
+ ## 🔍 Code of Conduct
1029
194
 
1030
- **Kdeploy** - 让部署变得简单而强大 🚀
195
+ Everyone interacting in the Kdeploy project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/kdeploy/blob/main/CODE_OF_CONDUCT.md).