Class: VagrantPlugins::SshConfigManager::SshConfigManager
- Inherits:
-
Object
- Object
- VagrantPlugins::SshConfigManager::SshConfigManager
- Defined in:
- lib/vagrant_ssh_config_manager/ssh_config_manager.rb
Instance Attribute Summary collapse
-
#project_name ⇒ Object
readonly
Returns the value of attribute project_name.
-
#ssh_config_file ⇒ Object
readonly
Returns the value of attribute ssh_config_file.
Instance Method Summary collapse
-
#add_include_directive_safe ⇒ Object
Safely add include directive with conflict detection.
-
#add_ssh_entry(ssh_config_data) ⇒ Object
Add SSH configuration entry for a machine.
-
#backup_include_file ⇒ Object
Backup include file before operations.
-
#check_host_conflicts(host_name) ⇒ Object
Check for conflicts with existing SSH config.
-
#cleanup_orphaned_include_files ⇒ Object
Clean up orphaned include files (for debugging/maintenance).
-
#cleanup_project_hosts ⇒ Object
Clean up all hosts for this project.
-
#generate_isolated_host_name(machine_name) ⇒ Object
Generate host name with project isolation.
-
#generate_project_identifier ⇒ Object
Generate unique project identifier.
-
#include_directives ⇒ Object
(also: #get_include_directives)
Fetch Include directives from the SSH include file.
-
#include_file_info ⇒ Object
Get include file status and information.
-
#initialize(machine, config = nil) ⇒ SshConfigManager
constructor
A new instance of SshConfigManager.
-
#list_vagrant_projects ⇒ Object
List all Vagrant projects detected in SSH config.
-
#main_config_info ⇒ Object
Get information about main SSH config file.
-
#migrate_to_project_naming?(old_host_names) ⇒ Boolean
(also: #migrate_to_project_naming)
Migrate old naming scheme to new project-based scheme.
-
#project_hosts ⇒ Object
(also: #get_project_hosts)
List project host names.
-
#project_owns_host?(host_name) ⇒ Boolean
Check if a host belongs to this project.
-
#project_ssh_entries ⇒ Object
(also: #get_project_ssh_entries)
List all SSH entries managed by this project.
-
#project_stats ⇒ Object
(also: #get_project_stats)
Get project statistics Gather statistics about the project SSH entries.
-
#remove_include_directive_safe ⇒ Object
Remove include directive and clean up.
-
#remove_ssh_entry(host_name) ⇒ Object
Remove SSH configuration entry for a machine.
-
#restore_include_file(backup_path) ⇒ Object
Restore include file from backup.
-
#ssh_entry_exists?(host_name) ⇒ Boolean
Check if SSH entry exists for a host.
-
#update_ssh_entry(ssh_config_data) ⇒ Object
Update SSH configuration entry for a machine.
-
#validate_include_file ⇒ Object
Validate include file format and structure.
-
#validate_main_config ⇒ Object
Validate main SSH config file structure.
Constructor Details
#initialize(machine, config = nil) ⇒ SshConfigManager
Returns a new instance of SshConfigManager.
13 14 15 16 17 18 19 20 21 22 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 13 def initialize(machine, config = nil) @machine = machine @config = config || machine.config.sshconfigmanager @logger = Log4r::Logger.new('vagrant::plugins::ssh_config_manager::ssh_config_manager') # Determine SSH config file path @ssh_config_file = determine_ssh_config_file @project_name = generate_project_name @include_file_path = generate_include_file_path end |
Instance Attribute Details
#project_name ⇒ Object (readonly)
Returns the value of attribute project_name.
11 12 13 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 11 def project_name @project_name end |
#ssh_config_file ⇒ Object (readonly)
Returns the value of attribute ssh_config_file.
11 12 13 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 11 def ssh_config_file @ssh_config_file end |
Instance Method Details
#add_include_directive_safe ⇒ Object
Safely add include directive with conflict detection
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 251 def add_include_directive_safe return true if include_directive_exists? begin # Check if main config file is writable unless File.writable?(@ssh_config_file) || !File.exist?(@ssh_config_file) @logger.warn("SSH config file is not writable: #{@ssh_config_file}") return false end backup_main_config add_include_directive_with_validation true rescue StandardError => e @logger.error("Failed to add include directive safely: #{e.message}") false end end |
#add_ssh_entry(ssh_config_data) ⇒ Object
Add SSH configuration entry for a machine
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 25 def add_ssh_entry(ssh_config_data) return false unless ssh_config_data && ssh_config_data['Host'] begin ensure_ssh_config_structure write_include_file(ssh_config_data) add_include_directive @logger.info("Added SSH entry for host: #{ssh_config_data['Host']}") true rescue StandardError => e @logger.error("Failed to add SSH entry: #{e.message}") false end end |
#backup_include_file ⇒ Object
Backup include file before operations
135 136 137 138 139 140 141 142 143 144 145 146 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 135 def backup_include_file return nil unless File.exist?(@include_file_path) backup_path = "#{@include_file_path}.backup.#{Time.now.strftime('%Y%m%d_%H%M%S')}" FileUtils.cp(@include_file_path, backup_path) @logger.debug("Created backup of include file: #{backup_path}") backup_path rescue StandardError => e @logger.warn("Failed to create backup: #{e.message}") nil end |
#check_host_conflicts(host_name) ⇒ Object
Check for conflicts with existing SSH config
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 355 def check_host_conflicts(host_name) conflicts = [] return conflicts unless File.exist?(@ssh_config_file) # Check in main config file conflicts.concat(find_host_in_file(@ssh_config_file, host_name, 'main config')) # Check in other include files include_directives.each do |include_info| next if include_info[:is_ours] || !include_info[:exists] conflicts.concat(find_host_in_file( include_info[:absolute_path], host_name, "include file: #{include_info[:path]}" )) end conflicts end |
#cleanup_orphaned_include_files ⇒ Object
Clean up orphaned include files (for debugging/maintenance)
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 202 def cleanup_orphaned_include_files config_d_dir = File.dirname(@include_file_path) return 0 unless File.exist?(config_d_dir) cleaned_count = 0 Dir.glob(File.join(config_d_dir, 'vagrant-*')).each do |file_path| next unless File.file?(file_path) # Check if file is empty or only contains comments content = File.read(file_path).strip next unless content.empty? || content.lines.all? { |line| line.strip.empty? || line.strip.start_with?('#') } File.delete(file_path) cleaned_count += 1 @logger.debug("Cleaned up orphaned include file: #{file_path}") end cleaned_count rescue StandardError => e @logger.warn("Failed to cleanup orphaned files: #{e.message}") 0 end |
#cleanup_project_hosts ⇒ Object
Clean up all hosts for this project
423 424 425 426 427 428 429 430 431 432 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 423 def cleanup_project_hosts cleaned_count = 0 get_project_hosts.each do |host_name| cleaned_count += 1 if remove_ssh_entry(host_name) end @logger.info("Cleaned up #{cleaned_count} hosts for project: #{@project_name}") cleaned_count end |
#generate_isolated_host_name(machine_name) ⇒ Object
Generate host name with project isolation
393 394 395 396 397 398 399 400 401 402 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 393 def generate_isolated_host_name(machine_name) project_id = generate_project_identifier machine_name_clean = sanitize_name(machine_name.to_s) # Format: project-hash-machine host_name = "#{project_id}-#{machine_name_clean}" # Ensure host name is not too long (SSH has practical limits) truncate_host_name(host_name) end |
#generate_project_identifier ⇒ Object
Generate unique project identifier
379 380 381 382 383 384 385 386 387 388 389 390 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 379 def generate_project_identifier # Use multiple factors to ensure uniqueness project_path = @machine.env.root_path project_name = File.basename(project_path) # Create a hash of the full path for uniqueness path_hash = Digest::SHA256.hexdigest(project_path.to_s)[0..7] # Combine sanitized name with hash base_name = sanitize_name(project_name) "#{base_name}-#{path_hash}" end |
#include_directives ⇒ Object Also known as: get_include_directives
Fetch Include directives from the SSH include file
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 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 325 def include_directives return [] unless File.exist?(@include_file_path) directives = [] line_number = 0 File.readlines(@include_file_path).each do |line| line_number += 1 line_stripped = line.strip next unless line_stripped.start_with?('Include ') include_path = line_stripped.sub(/^Include\s+/, '') directives << { line_number: line_number, path: include_path, absolute_path: File.(include_path), exists: File.exist?(File.(include_path)), is_ours: include_path == @include_file_path } end directives rescue StandardError => e @logger.warn("Failed to get include directives: #{e.message}") [] end |
#include_file_info ⇒ Object
Get include file status and information
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 115 def include_file_info info = { path: @include_file_path, exists: File.exist?(@include_file_path), size: 0, entries_count: 0, last_modified: nil } if info[:exists] stat = File.stat(@include_file_path) info[:size] = stat.size info[:last_modified] = stat.mtime info[:entries_count] = count_entries_in_include_file end info end |
#list_vagrant_projects ⇒ Object
List all Vagrant projects detected in SSH config
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 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 486 def list_vagrant_projects projects = {} config_d_dir = File.dirname(@include_file_path) return projects unless File.exist?(config_d_dir) Dir.glob(File.join(config_d_dir, 'vagrant-*')).each do |file_path| next unless File.file?(file_path) # Extract project info from filename filename = File.basename(file_path) next unless filename.match(/^vagrant-(.+)$/) project_info = parse_project_from_filename(::Regexp.last_match(1)) next unless project_info hosts = extract_hosts_from_file(file_path) projects[project_info[:id]] = { name: project_info[:name], id: project_info[:id], include_file: file_path, hosts: hosts, hosts_count: hosts.count, last_modified: File.mtime(file_path) } end projects end |
#main_config_info ⇒ Object
Get information about main SSH config file
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 229 def main_config_info info = { path: @ssh_config_file, exists: File.exist?(@ssh_config_file), size: 0, writable: false, include_directive_exists: false, last_modified: nil } if info[:exists] stat = File.stat(@ssh_config_file) info[:size] = stat.size info[:last_modified] = stat.mtime info[:writable] = File.writable?(@ssh_config_file) info[:include_directive_exists] = include_directive_exists? end info end |
#migrate_to_project_naming?(old_host_names) ⇒ Boolean Also known as: migrate_to_project_naming
Migrate old naming scheme to new project-based scheme
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 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 450 def migrate_to_project_naming?(old_host_names) return false if old_host_names.nil? || old_host_names.empty? migrated_count = 0 old_host_names.each do |old_host_name| # Extract machine name from old host name machine_name = extract_machine_name_from_host(old_host_name) next unless machine_name # Generate new host name new_host_name = generate_isolated_host_name(machine_name) # Skip if names are the same next if old_host_name == new_host_name # Get SSH config for the old host ssh_config = find_ssh_config_for_host(old_host_name) next unless ssh_config # Update host name in config ssh_config['Host'] = new_host_name # Remove old entry and add new one if remove_ssh_entry(old_host_name) && add_ssh_entry(ssh_config) migrated_count += 1 @logger.info("Migrated host: #{old_host_name} -> #{new_host_name}") end end @logger.info("Migrated #{migrated_count} hosts to project-based naming") migrated_count.positive? end |
#project_hosts ⇒ Object Also known as: get_project_hosts
List project host names
405 406 407 408 409 410 411 412 413 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 405 def project_hosts hosts = [] project_id = generate_project_identifier # Search in our include file hosts.concat(extract_hosts_from_file(@include_file_path, project_id)) if File.exist?(@include_file_path) hosts end |
#project_owns_host?(host_name) ⇒ Boolean
Check if a host belongs to this project
417 418 419 420 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 417 def project_owns_host?(host_name) project_id = generate_project_identifier host_name.start_with?(project_id) end |
#project_ssh_entries ⇒ Object Also known as: get_project_ssh_entries
List all SSH entries managed by this project
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 86 def project_ssh_entries return [] unless File.exist?(@include_file_path) entries = [] current_entry = nil File.readlines(@include_file_path).each do |line| line = line.strip next if line.empty? || line.start_with?('#') if line.start_with?('Host ') entries << current_entry if current_entry current_entry = { 'Host' => line.sub(/^Host\s+/, '') } elsif current_entry && line.include?(' ') key, value = line.split(' ', 2) current_entry[key.strip] = value.strip end end entries << current_entry if current_entry entries rescue StandardError [] end |
#project_stats ⇒ Object Also known as: get_project_stats
Get project statistics Gather statistics about the project SSH entries
436 437 438 439 440 441 442 443 444 445 446 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 436 def project_stats { project_name: @project_name, project_id: generate_project_identifier, project_path: @machine.env.root_path.to_s, include_file: @include_file_path, hosts_count: project_hosts.count, include_file_exists: File.exist?(@include_file_path), include_file_size: File.exist?(@include_file_path) ? File.size(@include_file_path) : 0 } end |
#remove_include_directive_safe ⇒ Object
Remove include directive and clean up
271 272 273 274 275 276 277 278 279 280 281 282 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 271 def remove_include_directive_safe return true unless include_directive_exists? begin backup_main_config remove_include_directive_with_validation true rescue StandardError => e @logger.error("Failed to remove include directive safely: #{e.message}") false end end |
#remove_ssh_entry(host_name) ⇒ Object
Remove SSH configuration entry for a machine
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 42 def remove_ssh_entry(host_name) return false unless host_name begin removed = remove_from_include_file(host_name) cleanup_empty_include_file cleanup_include_directive_if_needed @logger.info("Removed SSH entry for host: #{host_name}") if removed removed rescue StandardError => e @logger.error("Failed to remove SSH entry: #{e.message}") false end end |
#restore_include_file(backup_path) ⇒ Object
Restore include file from backup
149 150 151 152 153 154 155 156 157 158 159 160 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 149 def restore_include_file(backup_path) return false unless File.exist?(backup_path) begin FileUtils.cp(backup_path, @include_file_path) @logger.info("Restored include file from backup: #{backup_path}") true rescue StandardError => e @logger.error("Failed to restore from backup: #{e.message}") false end end |
#ssh_entry_exists?(host_name) ⇒ Boolean
Check if SSH entry exists for a host
76 77 78 79 80 81 82 83 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 76 def ssh_entry_exists?(host_name) return false unless File.exist?(@include_file_path) content = File.read(@include_file_path) content.include?("Host #{host_name}") rescue StandardError false end |
#update_ssh_entry(ssh_config_data) ⇒ Object
Update SSH configuration entry for a machine
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 59 def update_ssh_entry(ssh_config_data) return false unless ssh_config_data && ssh_config_data['Host'] begin host_name = ssh_config_data['Host'] remove_ssh_entry(host_name) add_ssh_entry(ssh_config_data) @logger.info("Updated SSH entry for host: #{host_name}") true rescue StandardError => e @logger.error("Failed to update SSH entry: #{e.message}") false end end |
#validate_include_file ⇒ Object
Validate include file format and structure
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 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 163 def validate_include_file return { valid: true, errors: [] } unless File.exist?(@include_file_path) errors = [] line_number = 0 current_host = nil begin File.readlines(@include_file_path).each do |line| line_number += 1 line_stripped = line.strip next if line_stripped.empty? || line_stripped.start_with?('#') if line_stripped.start_with?('Host ') host_name = line_stripped.sub(/^Host\s+/, '') if host_name.empty? errors << "Line #{line_number}: Empty host name" else current_host = host_name end elsif current_host errors << "Line #{line_number}: Invalid SSH option format" unless line_stripped.include?(' ') else errors << "Line #{line_number}: SSH option without host declaration" end end rescue StandardError => e errors << "Failed to read include file: #{e.message}" end { valid: errors.empty?, errors: errors, path: @include_file_path } end |
#validate_main_config ⇒ Object
Validate main SSH config file structure
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 |
# File 'lib/vagrant_ssh_config_manager/ssh_config_manager.rb', line 285 def validate_main_config return { valid: true, errors: [], warnings: [] } unless File.exist?(@ssh_config_file) errors = [] warnings = [] line_number = 0 begin File.readlines(@ssh_config_file).each do |line| line_number += 1 line_stripped = line.strip next if line_stripped.empty? || line_stripped.start_with?('#') # Check for include directive syntax if line_stripped.start_with?('Include ') include_path = line_stripped.sub(/^Include\s+/, '') unless File.exist?(File.(include_path)) warnings << "Line #{line_number}: Include file does not exist: #{include_path}" end end # Check for potential conflicts with our include if line_stripped.start_with?('Host ') && line_stripped.include?(@project_name) warnings << "Line #{line_number}: Potential host name conflict detected" end end rescue StandardError => e errors << "Failed to read main config file: #{e.message}" end { valid: errors.empty?, errors: errors, warnings: warnings, path: @ssh_config_file } end |