Class: MuxTf::PlanFormatter
- Inherits:
-
Object
- Object
- MuxTf::PlanFormatter
- Extended by:
- TerraformHelpers, PiotrbCliUtils::Util
- Includes:
- Coloring
- Defined in:
- lib/mux_tf/plan_formatter.rb
Overview
rubocop:disable Metrics/ClassLength
Class Method Summary collapse
-
.handle_error_states(meta, state, line) ⇒ Object
rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity.
- .init_status_to_remedies(status, meta) ⇒ Object
- .log_unhandled_line(state, line, reason: nil) ⇒ Object
-
.parse_lock_info(detail) ⇒ Object
rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity.
- .parse_non_json_plan_line(raw_line) ⇒ Object
- .pretty_plan(filename, targets: []) ⇒ Object
-
.pretty_plan_v1(filename, targets: []) ⇒ Object
rubocop:enable Metrics/AbcSize, Metrics/MethodLength, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity.
-
.pretty_plan_v2(filename, targets: []) ⇒ Object
rubocop:disable Metrics/AbcSize, Metrics/MethodLength, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity.
- .print_plan_line(parsed_line, without: []) ⇒ Object
- .print_validation_errors(info) ⇒ Object
-
.process_validation(info) ⇒ Object
rubocop:disable Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity.
-
.run_tf_init(upgrade: nil, reconfigure: nil) ⇒ Object
rubocop:disable Metrics/MethodLength.
- .setup_error_handling(parser, from_states:) ⇒ Object
-
.tf_plan_json(out:, targets: [], &block) ⇒ Object
rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity.
Methods included from TerraformHelpers
tf_apply, tf_force_unlock, tf_init, tf_plan, tf_show, tf_validate
Methods included from Coloring
Class Method Details
.handle_error_states(meta, state, line) ⇒ Object
rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
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 |
# File 'lib/mux_tf/plan_formatter.rb', line 501 def handle_error_states(, state, line) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity case state when :error_block [:current_error] = { type: :unknown, body: [] } when :error_block_error, :error_block_warning clean_line = pastel.strip(line).gsub(/^│ /, "") if clean_line =~ /^(Warning|Error): (.+)$/ [:current_error][:type] = $LAST_MATCH_INFO[1].downcase.to_sym [:current_error][:message] = $LAST_MATCH_INFO[2] elsif clean_line == "" # skip double empty lines [:current_error][:body] << clean_line if [:current_error][:body].last != "" else [:current_error][:body] ||= [] [:current_error][:body] << clean_line end when :after_error case pastel.strip(line) when "╵" # closing of an error block if [:current_error][:type] == :error [:errors] ||= [] [:errors] << [:current_error] end if [:current_error][:type] == :warning [:warnings] ||= [] [:warnings] << [:current_error] end .delete(:current_error) end else return false end true end |
.init_status_to_remedies(status, meta) ⇒ Object
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 |
# File 'lib/mux_tf/plan_formatter.rb', line 472 def init_status_to_remedies(status, ) remedies = Set.new if status != 0 remedies << :reconfigure if [:need_reconfigure] remedies << :auth if [:need_auth] log "!! expected meta[:errors] to be set, how did we get here?" unless [:errors] if [:errors] [:errors].each do |error| remedies << :add_provider_constraint if error[:body].grep(/Could not retrieve the list of available versions for provider/) end end if remedies.empty? log "!! don't know how to generate init remedies for this" log "!! Status: #{status}" log "!! Meta:" log .to_yaml.split("\n").map { |l| "!! #{l}" }.join("\n") remedies << :unknown end end remedies end |
.log_unhandled_line(state, line, reason: nil) ⇒ Object
10 11 12 |
# File 'lib/mux_tf/plan_formatter.rb', line 10 def log_unhandled_line(state, line, reason: nil) p [state, pastel.strip(line), reason] end |
.parse_lock_info(detail) ⇒ Object
rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 |
# File 'lib/mux_tf/plan_formatter.rb', line 134 def parse_lock_info(detail) # Lock Info: # ID: 4cc9c775-f0b7-3da7-25a4-94131afcef4d # Path: jane-terraform-eks-dev/admin/apps/kube-system-event-bus/terraform.tfstate # Operation: OperationTypePlan # Who: [email protected] # Version: 1.5.4 # Created: 2023-08-25 19:03:38.821597 +0000 UTC # Info: result = {} keys = %w[ID Path Operation Who Version Created] keys.each do |key| result[key] = detail.match(/^\s*#{key}:\s+(.+)$/)&.captures&.first end result end |
.parse_non_json_plan_line(raw_line) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/mux_tf/plan_formatter.rb', line 22 def parse_non_json_plan_line(raw_line) result = {} if raw_line.match(/^time=(?<timestamp>[^ ]+) level=(?<level>[^ ]+) msg=(?<message>.+?)(?: prefix=\[(?<prefix>.+?)\])?\s*$/) result.merge!($LAST_MATCH_INFO.named_captures.symbolize_keys) result[:module] = "terragrunt" result.delete(:prefix) unless result[:prefix] result[:prefix] = Pathname.new(result[:prefix]).relative_path_from(Dir.getwd).to_s if result[:prefix] result[:merge_up] = true if result[:message].match(/^\d+ errors? occurred:$/) elsif raw_line.strip == "" result[:blank] = true else result[:message] = raw_line result[:merge_up] = true end # time=2023-08-25T11:44:41-07:00 level=error msg=Terraform invocation failed in /Users/piotr/Work/janepods/.terragrunt-cache/BM86IAj5tW4bZga2lXeYT8tdOKI/V0IEypKSfyl-kHfCnRNAqyX02V8/modules/event-bus prefix=[/Users/piotr/Work/janepods/accounts/eks-dev/admin/apps/kube-system-event-bus] # time=2023-08-25T11:44:41-07:00 level=error msg=1 error occurred: # * [/Users/piotr/Work/janepods/.terragrunt-cache/BM86IAj5tW4bZga2lXeYT8tdOKI/V0IEypKSfyl-kHfCnRNAqyX02V8/modules/event-bus] exit status 2 # # result end |
.pretty_plan(filename, targets: []) ⇒ Object
14 15 16 17 18 19 20 |
# File 'lib/mux_tf/plan_formatter.rb', line 14 def pretty_plan(filename, targets: []) if ENV["JSON_PLAN"] pretty_plan_v2(filename, targets: targets) else pretty_plan_v1(filename, targets: targets) end end |
.pretty_plan_v1(filename, targets: []) ⇒ Object
rubocop:enable Metrics/AbcSize, Metrics/MethodLength, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
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 |
# File 'lib/mux_tf/plan_formatter.rb', line 355 def pretty_plan_v1(filename, targets: []) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity = {} parser = StatefulParser.new(normalizer: pastel.method(:strip)) parser.state(:info, /^Acquiring state lock/) parser.state(:error, /(Error locking state|Error:)/, [:none, :blank, :info, :reading]) parser.state(:reading, /: (Reading...|Read complete after)/, [:none, :info, :reading]) parser.state(:none, /^$/, [:reading]) parser.state(:refreshing, /^.+: Refreshing state... \[id=/, [:none, :info, :reading]) parser.state(:refreshing, /Refreshing Terraform state in-memory prior to plan.../, [:none, :blank, :info, :reading]) parser.state(:none, /^----------+$/, [:refreshing]) parser.state(:none, /^$/, [:refreshing]) parser.state(:output_info, /^Changes to Outputs:$/, [:none]) parser.state(:none, /^$/, [:output_info]) parser.state(:plan_info, /Terraform will perform the following actions:/, [:none]) parser.state(:plan_summary, /^Plan:/, [:plan_info]) parser.state(:plan_legend, /^Terraform used the selected providers to generate the following execution$/) parser.state(:none, /^$/, [:plan_legend]) parser.state(:plan_info, /Terraform planned the following actions, but then encountered a problem:/, [:none]) parser.state(:plan_info, /No changes. Your infrastructure matches the configuration./, [:none]) parser.state(:plan_error, /Planning failed. Terraform encountered an error while generating this plan./, [:refreshing]) # this extends the error block to include the lock info parser.state(:error_lock_info, /Lock Info/, [:error_block_error]) parser.state(:after_error, /^╵/, [:error_lock_info]) setup_error_handling(parser, from_states: [:plan_error, :none, :blank, :info, :reading, :plan_summary, :refreshing]) last_state = nil status = tf_plan(out: filename, detailed_exitcode: true, compact_warnings: true, targets: targets) { |raw_line| parser.parse(raw_line.rstrip) do |state, line| first_in_state = last_state != state case state when :none if line.blank? # nothing elsif raw_line.match(/Error when retrieving token from sso/) || raw_line.match(/Error loading SSO Token/) [:need_auth] = true log pastel.red("authentication problem"), depth: 2 else log_unhandled_line(state, line, reason: "unexpected non blank line in :none state") end when :reading clean_line = pastel.strip(line) if clean_line.match(/^(.+): Reading...$/) log "Reading: #{$LAST_MATCH_INFO[1]} ...", depth: 2 elsif clean_line.match(/^(.+): Read complete after ([^\[]+)(?: \[(.+)\])?$/) if $LAST_MATCH_INFO[3] log "Reading Complete: #{$LAST_MATCH_INFO[1]} after #{$LAST_MATCH_INFO[2]} [#{$LAST_MATCH_INFO[3]}]", depth: 3 else log "Reading Complete: #{$LAST_MATCH_INFO[1]} after #{$LAST_MATCH_INFO[2]}", depth: 3 end else log_unhandled_line(state, line, reason: "unexpected line in :reading state") end when :info if /Acquiring state lock. This may take a few moments.../.match?(line) log "Acquiring state lock ...", depth: 2 else log_unhandled_line(state, line, reason: "unexpected line in :info state") end when :plan_error case pastel.strip(line) when "" # skip empty line when /Releasing state lock. This may take a few moments"/ log line, depth: 2 when /Planning failed./ # rubocop:disable Lint/DuplicateBranch log line, depth: 2 else log_unhandled_line(state, line, reason: "unexpected line in :plan_error state") end when :error_lock_info ["error"] = "lock" [$LAST_MATCH_INFO[1]] = $LAST_MATCH_INFO[2] if line =~ /([A-Z]+\S+)+:\s+(.+)$/ clean_line = pastel.strip(line).gsub(/^│ /, "") if clean_line == "" [:current_error][:body] << clean_line if [:current_error][:body].last != "" else [:current_error][:body] << clean_line end when :refreshing if first_in_state log "Refreshing state ", depth: 2, newline: false else print "." end when :plan_legend puts if first_in_state log line, depth: 2 when :refresh_done puts if first_in_state when :plan_info # rubocop:disable Lint/DuplicateBranch puts if first_in_state log line, depth: 2 when :output_info # rubocop:disable Lint/DuplicateBranch puts if first_in_state log line, depth: 2 when :plan_summary log line, depth: 2 else log_unhandled_line(state, line, reason: "unexpected state") unless handle_error_states(, state, line) end last_state = state end } [status.status, ] end |
.pretty_plan_v2(filename, targets: []) ⇒ Object
rubocop:disable Metrics/AbcSize, Metrics/MethodLength, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
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 |
# File 'lib/mux_tf/plan_formatter.rb', line 178 def pretty_plan_v2(filename, targets: []) = {} [:seen] = { module_and_type: Set.new } status = tf_plan_json(out: filename, targets: targets) { |(parsed_line)| seen = proc { |module_arg, type_arg| [:seen][:module_and_type].include?([module_arg, type_arg]) } # first_in_state = !seen.call(parsed_line[:module], parsed_line[:type]) case parsed_line[:level] when "info" case parsed_line[:module] when "terraform.ui" case parsed_line[:type] when "version" [:terraform_version] = parsed_line[:terraform] [:terraform_ui_version] = parsed_line[:ui] when "apply_start", "refresh_start" first_in_group = !seen.call(parsed_line[:module], "apply_start") && !seen.call(parsed_line[:module], "refresh_start") log "Refreshing ", depth: 1, newline: false if first_in_group # { # :hook=>{ # "resource"=>{ # "addr"=>"data.aws_eks_cluster_auth.this", # "module"=>"", # "resource"=>"data.aws_eks_cluster_auth.this", # "implied_provider"=>"aws", # "resource_type"=>"aws_eks_cluster_auth", # "resource_name"=>"this", # "resource_key"=>nil # }, # "action"=>"read" # } # } log ".", newline: false when "apply_complete", "refresh_complete" # { # :hook=>{ # "resource"=>{ # "addr"=>"data.aws_eks_cluster_auth.this", # "module"=>"", # "resource"=>"data.aws_eks_cluster_auth.this", # "implied_provider"=>"aws", # "resource_type"=>"aws_eks_cluster_auth", # "resource_name"=>"this", # "resource_key"=>nil # }, # "action"=>"read", # "id_key"=>"id", # "id_value"=>"admin", # "elapsed_seconds"=>0 # } # } # noop when "resource_drift" first_in_group = !seen.call(parsed_line[:module], "resource_drift") && !seen.call(parsed_line[:module], "planned_change") # { # :change=>{ # "resource"=>{"addr"=>"module.application.kubectl_manifest.application", "module"=>"module.application", "resource"=>"kubectl_manifest.application", "implied_provider"=>"kubectl", "resource_type"=>"kubectl_manifest", "resource_name"=>"application", "resource_key"=>nil}, # "action"=>"update" # } # } if first_in_group log "" log "" log "Planned Changes:" end # { # :change=>{ # "resource"=>{"addr"=>"aws_iam_policy.crossplane_aws_ecr[0]", "module"=>"", "resource"=>"aws_iam_policy.crossplane_aws_ecr[0]", "implied_provider"=>"aws", "resource_type"=>"aws_iam_policy", "resource_name"=>"crossplane_aws_ecr", "resource_key"=>0}, # "action"=>"update" # }, # :type=>"resource_drift", # :level=>"info", # :message=>"aws_iam_policy.crossplane_aws_ecr[0]: Drift detected (update)", # :module=>"terraform.ui", # :timestamp=>"2023-09-26T17:11:46.340117-07:00", # :stream=>:stdout # } log format("[%<action>s] %<addr>s - Drift Detected (%<change_action>s)", action: PlanSummaryHandler.format_action(parsed_line[:change]["action"]), addr: PlanSummaryHandler.format_address(parsed_line[:change]["resource"]["addr"]), change_action: parsed_line[:change]["action"]), depth: 1 when "planned_change" first_in_group = !seen.call(parsed_line[:module], "resource_drift") && !seen.call(parsed_line[:module], "planned_change") # { # :change=> # {"resource"=> # {"addr"=>"module.application.kubectl_manifest.application", # "module"=>"module.application", # "resource"=>"kubectl_manifest.application", # "implied_provider"=>"kubectl", # "resource_type"=>"kubectl_manifest", # "resource_name"=>"application", # "resource_key"=>nil}, # "action"=>"create"}, # :type=>"planned_change", # :level=>"info", # :message=>"module.application.kubectl_manifest.application: Plan to create", # :module=>"terraform.ui", # :timestamp=>"2023-08-25T14:48:46.005185-07:00", # } if first_in_group log "" log "" log "Planned Changes:" end log format("[%<action>s] %<addr>s", action: PlanSummaryHandler.format_action(parsed_line[:change]["action"]), addr: PlanSummaryHandler.format_address(parsed_line[:change]["resource"]["addr"])), depth: 1 when "change_summary" # { # :changes=>{"add"=>1, "change"=>0, "import"=>0, "remove"=>0, "operation"=>"plan"}, # :type=>"change_summary", # :level=>"info", # :message=>"Plan: 1 to add, 0 to change, 0 to destroy.", # :module=>"terraform.ui", # :timestamp=>"2023-08-25T14:48:46.005211-07:00", # :stream=>:stdout # } log "" # puts parsed_line[:message] log "#{parsed_line[:changes]['operation'].capitalize} summary: " + parsed_line[:changes].without("operation").map { |k, v| color = PlanSummaryHandler.color_for_action(k) "#{pastel.yellow(v)} to #{pastel.decorate(k, color)}" if v.positive? }.compact.join(" ") else print_plan_line(parsed_line) end else print_plan_line(parsed_line) end when "error" if parsed_line[:diagnostic] handled_error = false muted_error = false unless parsed_line[:module] == "terragrunt" && parsed_line[:type] == "tf_failed" [:errors] ||= [] [:errors] << { type: :error, message: parsed_line[:diagnostic]["summary"], body: parsed_line[:diagnostic]["detail"].split("\n") } end if parsed_line[:diagnostic]["summary"] == "Error acquiring the state lock" ["error"] = "lock" .merge!(parse_lock_info(parsed_line[:diagnostic]["detail"])) handled_error = true elsif parsed_line[:module] == "terragrunt" && parsed_line[:type] == "tf_failed" muted_error = true end unless muted_error if handled_error print_plan_line(parsed_line, without: [:diagnostic]) else print_plan_line(parsed_line) end end else print_plan_line(parsed_line) end end [:seen][:module_and_type] << [parsed_line[:module], parsed_line[:type]] } [status.status, ] end |
.print_plan_line(parsed_line, without: []) ⇒ Object
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 |
# File 'lib/mux_tf/plan_formatter.rb', line 151 def print_plan_line(parsed_line, without: []) default_without = [ :level, :module, :type, :stream, :message, :timestamp, :terraform, :ui ] extra = parsed_line.without(*default_without, *without) data = parsed_line.merge(extra: extra) log_line = [ "%<level>-6s", "%<module>-12s", "%<type>-10s", "%<message>s", "%<extra>s" ].map { |format_string| field = format_string.match(/%<([^>]+)>/)[1].to_sym data[field].present? ? format(format_string, data) : nil }.compact.join(" | ") log log_line end |
.print_validation_errors(info) ⇒ Object
684 685 686 687 688 689 690 691 692 693 694 |
# File 'lib/mux_tf/plan_formatter.rb', line 684 def print_validation_errors(info) return unless (info["error_count"]).positive? || (info["warning_count"]).positive? log "Encountered #{pastel.red(info['error_count'])} Errors and #{pastel.yellow(info['warning_count'])} Warnings!", depth: 2 info["diagnostics"].each do |dinfo| color = dinfo["severity"] == "error" ? :red : :yellow log "#{pastel.decorate(dinfo['severity'].capitalize, color)}: #{dinfo['summary']}", depth: 3 log dinfo["detail"].split("\n"), depth: 4 if dinfo["detail"] log format_validation_range(dinfo, color), depth: 4 if dinfo["range"] end end |
.process_validation(info) ⇒ Object
rubocop:disable Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
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 |
# File 'lib/mux_tf/plan_formatter.rb', line 697 def process_validation(info) # rubocop:disable Metrics/CyclomaticComplexity remedies = Set.new if (info["error_count"]).positive? || (info["warning_count"]).positive? info["diagnostics"].each do |dinfo| # rubocop:disable Metrics/BlockLength item_handled = false case dinfo["summary"] when /there is no package for .+ cached in/, /Missing required provider/, /Module not installed/, /Module source has changed/, /Required plugins are not installed/, /Module version requirements have changed/ remedies << :init item_handled = true when /Missing required argument/, /Error in function call/, /Invalid value for input variable/, /Unsupported block type/, /Reference to undeclared input variable/, /Invalid reference/, /Unsupported attribute/, /Invalid depends_on reference/ remedies << :user_error item_handled = true end if dinfo["severity"] == "error" && dinfo["snippet"] # trying something new .. assuming anything with a snippet is a user error remedies << :user_error item_handled = true end case dinfo["detail"] when /timeout while waiting for plugin to start/ remedies << :init item_handled = true end if dinfo["severity"] == "warning" remedies << :user_warning item_handled = true end next if item_handled puts "!! don't know how to handle this validation error" puts dinfo.inspect remedies << :unknown if dinfo["severity"] == "error" end end remedies end |
.run_tf_init(upgrade: nil, reconfigure: nil) ⇒ Object
rubocop:disable Metrics/MethodLength
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 |
# File 'lib/mux_tf/plan_formatter.rb', line 539 def run_tf_init(upgrade: nil, reconfigure: nil) # rubocop:disable Metrics/MethodLength phase = :init = {} parser = StatefulParser.new(normalizer: pastel.method(:strip)) parser.state(:modules_init, /^Initializing modules\.\.\./, [:none, :backend]) parser.state(:modules_upgrade, /^Upgrading modules\.\.\./) parser.state(:backend, /^Initializing the backend\.\.\./, [:none, :modules_init, :modules_upgrade]) parser.state(:plugins, /^Initializing provider plugins\.\.\./, [:backend, :modules_init]) parser.state(:backend_error, /Error when retrieving token from sso/, [:backend]) parser.state(:plugin_warnings, /^$/, [:plugins]) parser.state(:backend_error, /Error:/, [:backend]) setup_error_handling(parser, from_states: [:plugins, :modules_init]) status = tf_init(upgrade: upgrade, reconfigure: reconfigure) { |raw_line| stripped_line = pastel.strip(raw_line.rstrip) parser.parse(raw_line.rstrip) do |state, line| case state when :modules_init if phase != state phase = state log "Initializing modules ", depth: 1 next end case stripped_line when /^Downloading (?<repo>[^ ]+) (?<version>[^ ]+) for (?<module>[^ ]+)\.\.\./ print "D" when /^Downloading (?<repo>[^ ]+) for (?<module>[^ ]+)\.\.\./ # rubocop:disable Lint/DuplicateBranch print "D" when /^- (?<module>[^ ]+) in (?<path>.+)$/ print "." when "" puts else log_unhandled_line(state, line, reason: "unexpected line in :modules_init state") end when :modules_upgrade if phase != state # first line phase = state log "Upgrding modules ", depth: 1, newline: false next end case stripped_line when /^- (?<module>[^ ]+) in (?<path>.+)$/ print "." when /^Downloading (?<repo>[^ ]+) (?<version>[^ ]+) for (?<module>[^ ]+)\.\.\./ print "D" when /^Downloading (?<repo>[^ ]+) for (?<module>[^ ]+)\.\.\./ # rubocop:disable Lint/DuplicateBranch print "D" when "" puts else log_unhandled_line(state, line, reason: "unexpected line in :modules_upgrade state") end when :backend if phase != state # first line phase = state log "Initializing the backend ", depth: 1 # , newline: false next end case stripped_line when /^Successfully configured/ log line, depth: 2 when /unless the backend/ # rubocop:disable Lint/DuplicateBranch log line, depth: 2 when "" puts else log_unhandled_line(state, line, reason: "unexpected line in :backend state") end when :backend_error if raw_line.match "terraform init -reconfigure" [:need_reconfigure] = true log pastel.red("module needs to be reconfigured"), depth: 2 end if raw_line.match "Error when retrieving token from sso" [:need_auth] = true log pastel.red("authentication problem"), depth: 2 end when :plugins if phase != state # first line phase = state log "Initializing provider plugins ...", depth: 1 next end case stripped_line when /^- Reusing previous version of (?<module>.+) from the dependency lock file$/ info = $LAST_MATCH_INFO.named_captures log "- [FROM-LOCK] #{info['module']}", depth: 2 when /^- (?<module>.+) is built in to Terraform$/ info = $LAST_MATCH_INFO.named_captures log "- [BUILTIN] #{info['module']}", depth: 2 when /^- Finding (?<module>[^ ]+) versions matching "(?<version>.+)"\.\.\./ info = $LAST_MATCH_INFO.named_captures log "- [FIND] #{info['module']} matching #{info['version'].inspect}", depth: 2 when /^- Finding latest version of (?<module>.+)\.\.\.$/ info = $LAST_MATCH_INFO.named_captures log "- [FIND] #{info['module']}", depth: 2 when /^- Installing (?<module>[^ ]+) v(?<version>.+)\.\.\.$/ info = $LAST_MATCH_INFO.named_captures log "- [INSTALLING] #{info['module']} v#{info['version']}", depth: 2 when /^- Installed (?<module>[^ ]+) v(?<version>.+) \(signed by(?: a)? (?<signed>.+)\)$/ info = $LAST_MATCH_INFO.named_captures log "- [INSTALLED] #{info['module']} v#{info['version']} (#{info['signed']})", depth: 2 when /^- Using previously-installed (?<module>[^ ]+) v(?<version>.+)$/ info = $LAST_MATCH_INFO.named_captures log "- [USING] #{info['module']} v#{info['version']}", depth: 2 when /^- Downloading plugin for provider "(?<provider>[^"]+)" \((?<provider_path>[^)]+)\) (?<version>.+)\.\.\.$/ info = $LAST_MATCH_INFO.named_captures log "- #{info['provider']} #{info['version']}", depth: 2 when "- Checking for available provider plugins..." # noop else log_unhandled_line(state, line, reason: "unexpected line in :plugins state") end when :plugin_warnings if phase != state # first line phase = state next end log pastel.yellow(line), depth: 1 when :none next if line == "" log_unhandled_line(state, line, reason: "unexpected line in :none state") else log_unhandled_line(state, line, reason: "unexpected state") unless handle_error_states(, state, line) end end } [status.status, ] end |
.setup_error_handling(parser, from_states:) ⇒ Object
494 495 496 497 498 499 |
# File 'lib/mux_tf/plan_formatter.rb', line 494 def setup_error_handling(parser, from_states:) parser.state(:error_block, /^╷/, from_states | [:after_error]) parser.state(:error_block_error, /^│ Error: /, [:error_block]) parser.state(:error_block_warning, /^│ Warning: /, [:error_block]) parser.state(:after_error, /^╵/, [:error_block, :error_block_error, :error_block_warning]) end |
.tf_plan_json(out:, targets: [], &block) ⇒ Object
rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
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 |
# File 'lib/mux_tf/plan_formatter.rb', line 48 def tf_plan_json(out:, targets: [], &block) emit_line = proc { |result| result[:level] ||= result[:stream] == :stderr ? "error" : "info" result[:module] ||= result[:stream] result[:type] ||= "unknown" if result[:message].match(/^Terraform invocation failed in (.+)/) result[:type] = "tf_failed" lines = result[:message].split("\n") result[:diagnostic] = { "summary" => "Terraform invocation failed", "detail" => result[:message], roots: [], extra: [] } lines.each do |line| if line.match(/^\s+\* \[(.+)\] exit status (\d+)$/) result[:diagnostic][:roots] << { path: $LAST_MATCH_INFO[1], status: $LAST_MATCH_INFO[2].to_i } elsif line.match(/^\d+ errors? occurred$/) # noop else result[:diagnostic][:extra] << line end end result[:message] = "Terraform invocation failed" end block.call(result) } last_stderr_line = nil status = tf_plan(out: out, detailed_exitcode: true, color: true, compact_warnings: false, json: true, input: false, targets: targets) { |(stream, raw_line)| case stream # when :command # puts raw_line when :stdout parsed_line = JSON.parse(raw_line) parsed_line.keys.each do |key| # rubocop:disable Style/HashEachMethods -- intentional, allow adding keys to hash while iterating if key[0] == "@" parsed_line[key[1..]] = parsed_line[key] parsed_line.delete(key) end end parsed_line.symbolize_keys! parsed_line[:stream] = stream if last_stderr_line emit_line.call(last_stderr_line) last_stderr_line = nil end emit_line.call(parsed_line) when :stderr parsed_line = parse_non_json_plan_line(raw_line) parsed_line[:stream] = stream if parsed_line[:blank] if last_stderr_line emit_line.call(last_stderr_line) last_stderr_line = nil end elsif parsed_line[:merge_up] if last_stderr_line last_stderr_line[:message] += "\n#{parsed_line[:message]}" else # this is just a standalone message then parsed_line.delete(:merge_up) last_stderr_line = parsed_line end elsif last_stderr_line emit_line.call(last_stderr_line) last_stderr_line = parsed_line else last_stderr_line = parsed_line end end } emit_line.call(last_stderr_line) if last_stderr_line status end |