forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
buildsecret.go
334 lines (284 loc) · 9.28 KB
/
buildsecret.go
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
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
176
177
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
package set
import (
"fmt"
"io"
"os"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/errors"
kapi "k8s.io/kubernetes/pkg/apis/core"
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/resource"
buildapi "github.com/openshift/origin/pkg/build/apis/build"
"github.com/openshift/origin/pkg/oc/cli/util/clientcmd"
)
var (
buildSecretLong = templates.LongDesc(`
Set or remove a build secret on a build config
A build config can reference a secret to push or pull images from private registries or
to access private source repositories.
Specify the type of secret being set by using the --push, --pull, or --source flags.
A secret reference can be removed by using --remove flag.
A label selector may be specified with the --selector flag to select the build configs
on which to set or remove secrets. Alternatively, all build configs in the namespace can
be selected with the --all flag.`)
buildSecretExample = templates.Examples(`
# Clear push secret on a build config
%[1]s build-secret --push --remove bc/mybuild
# Set the pull secret on a build config
%[1]s build-secret --pull bc/mybuild mysecret
# Set the push and pull secret on a build config
%[1]s build-secret --push --pull bc/mybuild mysecret
# Set the source secret on a set of build configs matching a selector
%[1]s build-secret --source -l app=myapp gitsecret`)
)
type BuildSecretOptions struct {
Out io.Writer
Err io.Writer
Builder *resource.Builder
Infos []*resource.Info
Encoder runtime.Encoder
Filenames []string
Selector string
All bool
Cmd *cobra.Command
ShortOutput bool
Local bool
Mapper meta.RESTMapper
Output string
PrintObject func([]*resource.Info) error
Secret string
Push bool
Pull bool
Source bool
Remove bool
}
// NewCmdBuildSecret implements the set build-secret command
func NewCmdBuildSecret(fullName string, f *clientcmd.Factory, out, errOut io.Writer) *cobra.Command {
options := &BuildSecretOptions{
Out: out,
Err: errOut,
}
cmd := &cobra.Command{
Use: "build-secret BUILDCONFIG SECRETNAME",
Short: "Update a build secret on a build config",
Long: buildSecretLong,
Example: fmt.Sprintf(buildSecretExample, fullName),
Run: func(cmd *cobra.Command, args []string) {
kcmdutil.CheckErr(options.Complete(f, cmd, args))
kcmdutil.CheckErr(options.Validate())
if err := options.Run(); err != nil {
// TODO: move me to kcmdutil
if err == kcmdutil.ErrExit {
os.Exit(1)
}
kcmdutil.CheckErr(err)
}
},
}
kcmdutil.AddPrinterFlags(cmd)
cmd.Flags().StringVarP(&options.Selector, "selector", "l", options.Selector, "Selector (label query) to filter build configs")
cmd.Flags().BoolVar(&options.All, "all", options.All, "If true, select all build configs in the namespace")
cmd.Flags().StringSliceVarP(&options.Filenames, "filename", "f", options.Filenames, "Filename, directory, or URL to file to use to edit the resource.")
cmd.Flags().BoolVar(&options.Push, "push", options.Push, "If true, set the push secret on a build config")
cmd.Flags().BoolVar(&options.Pull, "pull", options.Pull, "If true, set the pull secret on a build config")
cmd.Flags().BoolVar(&options.Source, "source", options.Source, "If true, set the source secret on a build config")
cmd.Flags().BoolVar(&options.Remove, "remove", options.Remove, "If true, remove the build secret.")
cmd.Flags().BoolVar(&options.Local, "local", false, "If true, set build-secret will NOT contact api-server but run locally.")
cmd.MarkFlagFilename("filename", "yaml", "yml", "json")
kcmdutil.AddDryRunFlag(cmd)
return cmd
}
var supportedBuildTypes = []string{"buildconfigs"}
func (o *BuildSecretOptions) secretFromArg(f *clientcmd.Factory, mapper meta.RESTMapper, typer runtime.ObjectTyper, namespace, arg string) (string, error) {
builder := f.NewBuilder().
Internal().
LocalParam(o.Local).
NamespaceParam(namespace).DefaultNamespace().
RequireObject(false).
ContinueOnError().
ResourceNames("secrets", arg).
Flatten()
var secretName string
err := builder.Do().Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
if info.Mapping.Resource != "secrets" {
return fmt.Errorf("please specify a secret")
}
secretName = info.Name
return nil
})
if err != nil {
return "", err
}
return secretName, nil
}
func (o *BuildSecretOptions) Complete(f *clientcmd.Factory, cmd *cobra.Command, args []string) error {
var secretArg string
if !o.Remove {
if len(args) < 1 {
return kcmdutil.UsageErrorf(cmd, "a secret name must be specified")
}
secretArg = args[len(args)-1]
args = args[:len(args)-1]
}
resources := args
if len(resources) == 0 && len(o.Selector) == 0 && len(o.Filenames) == 0 && !o.All {
return kcmdutil.UsageErrorf(cmd, "one or more build configs must be specified as <name> or <resource>/<name>")
}
cmdNamespace, explicit, err := f.DefaultNamespace()
if err != nil {
return err
}
o.Cmd = cmd
mapper, typer := f.Object()
if len(secretArg) > 0 {
o.Secret, err = o.secretFromArg(f, mapper, typer, cmdNamespace, secretArg)
if err != nil {
return err
}
}
o.Builder = f.NewBuilder().
Internal().
LocalParam(o.Local).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
FilenameParam(explicit, &resource.FilenameOptions{Recursive: false, Filenames: o.Filenames}).
Flatten()
if !o.Local {
o.Builder = o.Builder.
ResourceNames("buildconfigs", resources...).
LabelSelectorParam(o.Selector).
Latest()
if o.All {
o.Builder.ResourceTypes(supportedBuildTypes...).SelectAllParam(o.All)
}
}
o.Output = kcmdutil.GetFlagString(cmd, "output")
o.PrintObject = func(infos []*resource.Info) error {
return f.PrintResourceInfos(cmd, o.Local, infos, o.Out)
}
o.Encoder = kcmdutil.InternalVersionJSONEncoder()
o.ShortOutput = kcmdutil.GetFlagString(cmd, "output") == "name"
o.Mapper = mapper
return nil
}
func (o *BuildSecretOptions) Validate() error {
if !o.Pull && !o.Push && !o.Source {
return fmt.Errorf("specify the type of secret to set (--push, --pull, or --source)")
}
if !o.Remove && len(o.Secret) == 0 {
return fmt.Errorf("specify a secret to set")
}
if o.Remove && len(o.Secret) > 0 {
return fmt.Errorf("a secret cannot be specified when using the --remove flag")
}
return nil
}
func (o *BuildSecretOptions) Run() error {
infos := o.Infos
singleItemImplied := len(o.Infos) <= 1
if o.Builder != nil {
loaded, err := o.Builder.Do().IntoSingleItemImplied(&singleItemImplied).Infos()
if err != nil {
return err
}
infos = loaded
}
patches := CalculatePatches(infos, o.Encoder, func(info *resource.Info) (bool, error) {
return o.setBuildSecret(info.Object)
})
if singleItemImplied && len(patches) == 0 {
return fmt.Errorf("cannot set a build secret on %s/%s", infos[0].Mapping.Resource, infos[0].Name)
}
if len(o.Output) > 0 || o.Local || kcmdutil.GetDryRunFlag(o.Cmd) {
return o.PrintObject(infos)
}
errs := []error{}
for _, patch := range patches {
info := patch.Info
if patch.Err != nil {
errs = append(errs, fmt.Errorf("%s/%s %v", info.Mapping.Resource, info.Name, patch.Err))
continue
}
if string(patch.Patch) == "{}" || len(patch.Patch) == 0 {
fmt.Fprintf(o.Err, "info: %s %q was not changed\n", info.Mapping.Resource, info.Name)
continue
}
obj, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, types.StrategicMergePatchType, patch.Patch)
if err != nil {
errs = append(errs, fmt.Errorf("%s/%s %v", info.Mapping.Resource, info.Name, err))
continue
}
info.Refresh(obj, true)
kcmdutil.PrintSuccess(o.ShortOutput, o.Out, info.Object, false, "updated")
}
if len(errs) > 0 {
return errors.NewAggregate(errs)
}
return nil
}
// setBuildSecret will set a secret on an object. For now the only supported
// object type is BuildConfig.
func (o *BuildSecretOptions) setBuildSecret(obj runtime.Object) (bool, error) {
switch buildObj := obj.(type) {
case *buildapi.BuildConfig:
o.updateBuildConfig(buildObj)
return true, nil
default:
return false, nil
}
}
func (o *BuildSecretOptions) updateBuildConfig(bc *buildapi.BuildConfig) {
if o.Push {
if o.Remove {
bc.Spec.Output.PushSecret = nil
} else {
bc.Spec.Output.PushSecret = &kapi.LocalObjectReference{
Name: o.Secret,
}
}
}
if o.Pull {
switch {
case bc.Spec.Strategy.DockerStrategy != nil:
if o.Remove {
bc.Spec.Strategy.DockerStrategy.PullSecret = nil
} else {
bc.Spec.Strategy.DockerStrategy.PullSecret = &kapi.LocalObjectReference{
Name: o.Secret,
}
}
case bc.Spec.Strategy.SourceStrategy != nil:
if o.Remove {
bc.Spec.Strategy.SourceStrategy.PullSecret = nil
} else {
bc.Spec.Strategy.SourceStrategy.PullSecret = &kapi.LocalObjectReference{
Name: o.Secret,
}
}
case bc.Spec.Strategy.CustomStrategy != nil:
if o.Remove {
bc.Spec.Strategy.CustomStrategy.PullSecret = nil
} else {
bc.Spec.Strategy.CustomStrategy.PullSecret = &kapi.LocalObjectReference{
Name: o.Secret,
}
}
}
}
if o.Source {
if o.Remove {
bc.Spec.Source.SourceSecret = nil
} else {
bc.Spec.Source.SourceSecret = &kapi.LocalObjectReference{
Name: o.Secret,
}
}
}
}