Terraform SDK - get keys from schema.Set

This page has an example of using TypeSet in a custom terraform provider to nest a substructure: Home - Plugin Development - Terraform by HashiCorp

Now I am trying to obtain the substructure values by key. But I am looking at set.go and the only way to get values out of the set seems to be List(), which provides values without keys.

From the sample in the doc link I mentioned, I would like to do this:

func resourceExampleCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
 . . .
    ingress := d.Get("ingress").(*schema.Set)
    from_port := ingress["from_port"]
 . . .

But schema.Set doesn’t support key lookup. How can I retrieve the set values by their names?

Hi @jimsnab,

There are no keys in a set, and the value contained in a set are not named, so you always need to iterate over the values to find what you are looking for. The *schema.Set type has a List() method which returns an []interface{} with the set values.

Ok so if I want only one substructure, I could limit with MaxItems like

"ingress": {
  Type:     schema.TypeSet,
  MaxItems: 1,
  Elem: &schema.Resource{
    Schema: map[string]*schema.Schema{
      "from_port": {
        Type:     schema.TypeInt,
        Required: true,
      },
. . .

And access with something similar to

func resourceExampleCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
 . . .
    ingress := d.Get("ingress").(*schema.Set)  // check for null/empty omitted    
    ingress_list = ingress.List()
    ingress_map = ingress_list[0].(map[string]interface{})
    from_port := ingress_map["from_port"]
 . . .

I hope. Maybe I could use TypeList for the same net result.