-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinfermv
executable file
·98 lines (81 loc) · 2.48 KB
/
infermv
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
#!/usr/bin/env ruby
require 'json'
# terraform plan -out=./plan-result
# terraform show -json plan-result > plan-result.json
$plan_file = ARGV.shift
unless $plan_file
puts 'select plan file'
abort
end
$similarity_threashold = (ARGV.shift || '1.0').to_f
# Refer address in https://www.terraform.io/docs/internals/json-format.html#plan-representation
class Resource
def initialize(tree)
@address = tree['address']
@type = tree['type']
@name = tree['name']
@change = tree['change']
@actions = tree['change']['actions'].join('-')
@before = tree['change']['before']
@after = tree['change']['after']
end
attr_reader 'type'
attr_reader 'name'
# https://github.com/hashicorp/terraform-json/blob/7bf4a174/action.go#L11-L26
attr_reader 'actions'
attr_reader 'before'
attr_reader 'after'
def to_s
@address
end
# self must be 'delete' resource and another must be 'create' it
def similarity(another)
return 0.0 if @type != another.type
similarity = Resource.compare(before, another.after) * 0.8
similarity += @name == another.name ? 0.2 : 0
similarity
end
private
# terraform cannot distinguish nil, blank hash and blank string
def self.is_blank?(obj)
obj == nil || obj == {} || obj == ''
end
def self.compare(lhs, rhs)
if self.is_blank?(lhs) && self.is_blank?(rhs)
1.0
elsif lhs.instance_of?(Hash) && rhs.instance_of?(Hash)
compare_results = (lhs.keys & rhs.keys).
map { |key| compare(lhs[key], rhs[key]) }
return 0.0 if compare_results.length == 0
compare_results.sum / compare_results.length
else
lhs == rhs ? 1.0 : 0.0
end
end
end
$tree = File.open($plan_file) { |file| JSON.load(file) }
resources = $tree['resource_changes'].map { |rc| Resource.new(rc) }
$creating_resources = resources.select { |r| r.actions == 'create' }
$deleting_resources = resources.select { |r| r.actions == 'delete' }
def infer_move()
infered_moves = $deleting_resources.map { |dr|
similarities = $creating_resources.map { |cr| dr.similarity(cr) }
max_similarity = similarities.max
if $similarity_threashold <= max_similarity
[dr, $creating_resources.delete_at(similarities.index(max_similarity))]
else
nil
end
}
infered_moves.compact
end
print infer_move().group_by { |dr, _| dr.type }.map { |type, moves|
moved_block_of_type = "# #{type}
"
moved_block_of_type << moves.map { |dr, cr|
"moved {
from = #{dr}
to = #{cr}
}"
}.join("\n\n")
}.join("\n\n\n")