3

I am using client-go to create resource by parsing yaml files, click code.

But setting labels to resources not work via unstructed interface, how to do that?

    func (u *Unstructured) SetLabels(labels map[string]string) {
        if labels == nil {
            RemoveNestedField(u.Object, "metadata", "labels")
            return
        }
        u.setNestedMap(labels, "metadata", "labels")
    }

My code is like:

    func ApplyUnstructured(ctx context.Context, dynamicClient dynamic.Interface, restMapper meta.RESTMapper, unstructuredObj unstructured.Unstructured, serverSide bool) (*unstructured.Unstructured, error) {
        if len(unstructuredObj.GetName()) == 0 {           
            metadata, _ := meta.Accessor(unstructuredObj)      
            generateName := metadata.GetGenerateName()      
            if len(generateName) > 0 {       
                return nil, fmt.Errorf("from %s: cannot use generate name with >apply", generateName)      
            }      
        }         
    ....
    // !!!! set labels not work !!!!!!!        
                unstructuredObj.SetLabels(map[string]string {        
         "jobid":"test",          
    } )
Jonas
  • 121,568
  • 97
  • 310
  • 388
Wallace
  • 561
  • 2
  • 21
  • 54
  • Do you have some specific error that is happening? SetLabels is supported on everything that implements metav1.Object, which includes Unstructured. – coderanger Jun 02 '21 at 07:48
  • no, the function doesn't have anything returned. the target resource was created successfully, only the labels wasn't there. The resource was the same as yaml describes @coderanger – Wallace Jun 02 '21 at 08:48
  • Just a thought, a missing `)` in `unstructuredObj.SetLabels(map[string]string`? –  Jun 04 '21 at 13:38
  • Where do you call `SetLabel` ? Is the case that you call `SetLabels` and then `Create` and there is no labels _or_ there is already a resource in API Server but patching labels doesn't work? If it's the latter case is it server side apply or just patch? If it's server side apply what are managed fields in existing object? Which version of Kubernetes are you using? – reith Jun 09 '21 at 09:25
  • And I'm dubious if [this line](https://github.com/pytimer/k8sutil/blob/main/apply/apply.go#L162) works. I don't beleive you can change manager fields in server side apply request. – reith Jun 09 '21 at 09:36

0 Answers0