Skip to content

Commit 1dd9a29

Browse files
committed
Add search option exact_match for data source rancher2_principal
1 parent c0f5eca commit 1dd9a29

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

docs/data-sources/principal.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ The following arguments are supported:
2020

2121
* `name` - (Required) The full name of the principal (string)
2222
* `type` - (Optional) The type of the identity (string). Defaults to `user`. Only `user` and `group` values are supported (string)
23+
* `exact_match` - (Optional) If set to `true`, only the exactly matched result is returned. Defaults to `false`, which means a partially matched result can be returned (for example: `foo2` also matches for `foo` search input) (bool)
2324

2425

2526
## Attributes Reference

rancher2/data_source_rancher2_principal.go

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,11 @@ func dataSourceRancher2Principal() *schema.Resource {
3232
Default: principalTypeUser,
3333
ValidateFunc: validation.StringInSlice(principalTypes, true),
3434
},
35+
"exact_match": {
36+
Type: schema.TypeBool,
37+
Optional: true,
38+
Default: false,
39+
},
3540
},
3641
}
3742
}
@@ -44,8 +49,9 @@ func dataSourceRancher2PrincipalRead(d *schema.ResourceData, meta interface{}) e
4449

4550
name := d.Get("name").(string)
4651
principalType := d.Get("type").(string)
52+
exactMatch := d.Get("exact_match").(bool)
4753

48-
collection, err := client.Principal.List(nil)
54+
collection, err := client.Principal.ListAll(nil)
4955
if err != nil {
5056
return err
5157
}
@@ -63,6 +69,19 @@ func dataSourceRancher2PrincipalRead(d *schema.ResourceData, meta interface{}) e
6369
return fmt.Errorf("[ERROR] principal \"%s\" of type \"%s\" not found", name, principalType)
6470
}
6571

72+
// We always had at least one result here, let's find which can match exactly with the inputted name
73+
if exactMatch {
74+
for _, v := range principals.Data {
75+
if v.Name == name {
76+
return flattenDataSourcePrincipal(d, &v)
77+
}
78+
}
79+
// This situation will be almost never happened, but we still ensure for the special case
80+
return fmt.Errorf(
81+
"[ERROR] principal \"%s\" of type \"%s\" not found. Try again with \"exact_match=false\" for partially matched result",
82+
name, principalType)
83+
}
84+
6685
return flattenDataSourcePrincipal(d, &principals.Data[0])
6786
}
6887

0 commit comments

Comments
 (0)