Skip to content

Commit 1e67c83

Browse files
committed
Add server side dry-run before create fix #24
* requires namespace to exist for namespaced resources * requires CRD to exist for custom objects If namespace or CRD does not exist, the server side dry-run result is ignored for the respective resource.
1 parent d79188b commit 1e67c83

File tree

1 file changed

+37
-10
lines changed

1 file changed

+37
-10
lines changed

kustomize/resource_kustomization.go

+37-10
Original file line numberDiff line numberDiff line change
@@ -167,31 +167,58 @@ func kustomizationResourceDiff(ctx context.Context, d *schema.ResourceDiff, m in
167167

168168
do, dm := d.GetChange("manifest")
169169

170+
kmm := newKManifest(mapper, client)
171+
err := kmm.load([]byte(dm.(string)))
172+
if err != nil {
173+
return err
174+
}
175+
setLastAppliedConfig(kmm, gzipLastAppliedConfig)
176+
170177
if do.(string) == "" {
178+
// diffing for create
179+
_, err := kmm.mappings()
180+
if err != nil {
181+
// if there are no mappings we can't dry-run
182+
// this is always the case for CRDs
183+
return nil
184+
}
185+
186+
_, err = kmm.apiCreate(k8smetav1.CreateOptions{DryRun: []string{k8smetav1.DryRunAll}})
187+
if err != nil {
188+
if k8serrors.IsAlreadyExists(err) {
189+
// this is an edge case during tests
190+
// get change above has empty original
191+
// yet the create request fails with
192+
// Error running pre-apply refresh
193+
return nil
194+
}
195+
196+
if k8serrors.IsNotFound(err) {
197+
// we're dry-running a create
198+
// the notfound seems mostly the namespace
199+
return nil
200+
}
201+
202+
return kmm.fmtErr(err)
203+
}
204+
171205
return nil
172206
}
173207

208+
// diffing for update
174209
kmo := newKManifest(mapper, client)
175-
err := kmo.load([]byte(do.(string)))
176-
if err != nil {
177-
return err
178-
}
179-
180-
kmm := newKManifest(mapper, client)
181-
err = kmm.load([]byte(dm.(string)))
210+
err = kmo.load([]byte(do.(string)))
182211
if err != nil {
183212
return err
184213
}
214+
setLastAppliedConfig(kmo, gzipLastAppliedConfig)
185215

186216
if kmo.name() != kmm.name() || kmo.namespace() != kmm.namespace() {
187217
// if the resource name or namespace changes, we can't patch but have to destroy and re-create
188218
d.ForceNew("manifest")
189219
return nil
190220
}
191221

192-
setLastAppliedConfig(kmo, gzipLastAppliedConfig)
193-
setLastAppliedConfig(kmm, gzipLastAppliedConfig)
194-
195222
pt, p, err := kmm.apiPreparePatch(kmo, true)
196223
if err != nil {
197224
return err

0 commit comments

Comments
 (0)