-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathTagPlugin.groovy
108 lines (90 loc) · 2.61 KB
/
TagPlugin.groovy
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
class TagPlugin implements TerraformPlanCommandPlugin,
TerraformApplyCommandPlugin,
Resettable {
private static variableName
private static disableOnApply = false
private static writeToFile = false
private static List tagClosures = []
public static init() {
def plugin = new TagPlugin()
TerraformPlanCommand.addPlugin(plugin)
TerraformApplyCommand.addPlugin(plugin)
}
@Override
public void apply(TerraformPlanCommand command) {
applyToCommand(command)
}
@Override
public void apply(TerraformApplyCommand command) {
if (disableOnApply) {
return
}
applyToCommand(command)
}
private void applyToCommand(command) {
String variableName = getVariableName()
Map tags = getTags(command)
if (writeToFile) {
command.withVariableFile(variableName, tags)
} else {
command.withVariable(variableName, tags)
}
}
public static withVariableName(String variableName) {
this.variableName = variableName
}
public static withEnvironmentTag(String tagKey = 'environment') {
tagClosures << { command ->
Map tag = [:]
tag[tagKey] = command.getEnvironment()
tag
}
return this
}
public static withTag(String key, String value) {
tagClosures << { command ->
Map tag = [:]
tag[key] = value
tag
}
return this
}
public static withTagFromFile(String key, String filename) {
tagClosures << { command ->
Map tag = [:]
tag[key] = Jenkinsfile.readFile(filename)
tag
}
return this
}
public static withTagFromEnvironmentVariable(String key, String variable) {
tagClosures << { command ->
Map tag = [:]
tag[key] = Jenkinsfile.getEnvironmentVariable(variable)
tag
}
return this
}
public static disableOnApply() {
disableOnApply = true
return this
}
public static writeToFile() {
writeToFile = true
return this
}
private static getVariableName() {
return variableName ?: 'tags'
}
public Map getTags(TerraformCommand command) {
return tagClosures.inject([:]) { memo, tagClosure ->
memo + tagClosure.call(command)
}
}
public static reset() {
tagClosures = []
variableName = null
disableOnApply = false
writeToFile = false
}
}