Skip to content

Commit abd598c

Browse files
committed
New Data Source: alicloud_ram_system_policys.
1 parent 1d994ea commit abd598c

5 files changed

+384
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,191 @@
1+
// Package alicloud. This file is generated automatically. Please do not modify it manually, thank you!
2+
package alicloud
3+
4+
import (
5+
"fmt"
6+
"regexp"
7+
"time"
8+
9+
"github.com/PaesslerAG/jsonpath"
10+
util "github.com/alibabacloud-go/tea-utils/service"
11+
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
12+
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
13+
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
14+
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
15+
)
16+
17+
func dataSourceAliCloudRamSystemPolicys() *schema.Resource {
18+
return &schema.Resource{
19+
Read: dataSourceAliCloudRamSystemPolicyRead,
20+
Schema: map[string]*schema.Schema{
21+
"ids": {
22+
Type: schema.TypeList,
23+
Optional: true,
24+
ForceNew: true,
25+
Elem: &schema.Schema{Type: schema.TypeString},
26+
Computed: true,
27+
},
28+
"name_regex": {
29+
Type: schema.TypeString,
30+
Optional: true,
31+
ValidateFunc: validation.ValidateRegexp,
32+
ForceNew: true,
33+
},
34+
"names": {
35+
Type: schema.TypeList,
36+
Elem: &schema.Schema{Type: schema.TypeString},
37+
Computed: true,
38+
},
39+
"policys": {
40+
Type: schema.TypeList,
41+
Computed: true,
42+
Elem: &schema.Resource{
43+
Schema: map[string]*schema.Schema{
44+
"attachment_count": {
45+
Type: schema.TypeInt,
46+
Computed: true,
47+
},
48+
"create_time": {
49+
Type: schema.TypeString,
50+
Computed: true,
51+
},
52+
"description": {
53+
Type: schema.TypeString,
54+
Computed: true,
55+
},
56+
"policy_name": {
57+
Type: schema.TypeString,
58+
Computed: true,
59+
},
60+
"policy_type": {
61+
Type: schema.TypeString,
62+
Computed: true,
63+
},
64+
"update_date": {
65+
Type: schema.TypeString,
66+
Computed: true,
67+
},
68+
"id": {
69+
Type: schema.TypeString,
70+
Computed: true,
71+
},
72+
},
73+
},
74+
},
75+
"output_file": {
76+
Type: schema.TypeString,
77+
Optional: true,
78+
ForceNew: true,
79+
},
80+
},
81+
}
82+
}
83+
84+
func dataSourceAliCloudRamSystemPolicyRead(d *schema.ResourceData, meta interface{}) error {
85+
client := meta.(*connectivity.AliyunClient)
86+
87+
var objects []map[string]interface{}
88+
var nameRegex *regexp.Regexp
89+
if v, ok := d.GetOk("name_regex"); ok {
90+
r, err := regexp.Compile(v.(string))
91+
if err != nil {
92+
return WrapError(err)
93+
}
94+
nameRegex = r
95+
}
96+
97+
idsMap := make(map[string]string)
98+
if v, ok := d.GetOk("ids"); ok {
99+
for _, vv := range v.([]interface{}) {
100+
if vv == nil {
101+
continue
102+
}
103+
idsMap[vv.(string)] = vv.(string)
104+
}
105+
}
106+
107+
var request map[string]interface{}
108+
var response map[string]interface{}
109+
var query map[string]interface{}
110+
action := "ListPolicies"
111+
var err error
112+
request = make(map[string]interface{})
113+
query = make(map[string]interface{})
114+
request["PolicyType"] = "System"
115+
runtime := util.RuntimeOptions{}
116+
runtime.SetAutoretry(true)
117+
request["MaxResults"] = PageSizeLarge
118+
for {
119+
wait := incrementalWait(3*time.Second, 5*time.Second)
120+
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
121+
response, err = client.RpcPost("Ram", "2015-05-01", action, query, request, true)
122+
123+
if err != nil {
124+
if NeedRetry(err) {
125+
wait()
126+
return resource.RetryableError(err)
127+
}
128+
return resource.NonRetryableError(err)
129+
}
130+
addDebug(action, response, request)
131+
return nil
132+
})
133+
if err != nil {
134+
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
135+
}
136+
137+
resp, _ := jsonpath.Get("$.Policies.Policy[*]", response)
138+
139+
result, _ := resp.([]interface{})
140+
for _, v := range result {
141+
item := v.(map[string]interface{})
142+
if nameRegex != nil && !nameRegex.MatchString(fmt.Sprint(item["PolicyName"])) {
143+
continue
144+
}
145+
objects = append(objects, item)
146+
}
147+
148+
if nextToken, ok := response["Marker"].(string); ok && nextToken != "" {
149+
request["Marker"] = nextToken
150+
} else {
151+
break
152+
}
153+
}
154+
155+
ids := make([]string, 0)
156+
names := make([]interface{}, 0)
157+
s := make([]map[string]interface{}, 0)
158+
for _, objectRaw := range objects {
159+
mapping := map[string]interface{}{}
160+
161+
mapping["id"] = objectRaw[""]
162+
163+
mapping["attachment_count"] = objectRaw["AttachmentCount"]
164+
mapping["create_time"] = objectRaw["CreateDate"]
165+
mapping["description"] = objectRaw["Description"]
166+
mapping["policy_name"] = objectRaw["PolicyName"]
167+
mapping["policy_type"] = objectRaw["PolicyType"]
168+
mapping["update_date"] = objectRaw["UpdateDate"]
169+
170+
ids = append(ids, fmt.Sprint(mapping["id"]))
171+
names = append(names, objectRaw[""])
172+
s = append(s, mapping)
173+
}
174+
175+
d.SetId(dataResourceIdHash(ids))
176+
if err := d.Set("ids", ids); err != nil {
177+
return WrapError(err)
178+
}
179+
180+
if err := d.Set("names", names); err != nil {
181+
return WrapError(err)
182+
}
183+
if err := d.Set("policys", s); err != nil {
184+
return WrapError(err)
185+
}
186+
187+
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
188+
writeToFile(output.(string), s)
189+
}
190+
return nil
191+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package alicloud
2+
3+
import (
4+
"fmt"
5+
"strings"
6+
"testing"
7+
8+
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
9+
"github.com/hashicorp/terraform-plugin-sdk/helper/acctest"
10+
)
11+
12+
func TestAccAlicloudRamSystemPolicyDataSource(t *testing.T) {
13+
testAccPreCheckWithRegions(t, true, []connectivity.Region{"cn-hangzhou"})
14+
rand := acctest.RandIntRange(1000000, 9999999)
15+
16+
allConf := dataSourceTestAccConfig{
17+
existConfig: testAccCheckAlicloudRamSystemPolicySourceConfig(rand, map[string]string{
18+
"name_regex": `"^AdministratorAccess$"`,
19+
}),
20+
fakeConfig: testAccCheckAlicloudRamSystemPolicySourceConfig(rand, map[string]string{
21+
"name_regex": `"AdministratorAccessInvalid"`,
22+
}),
23+
}
24+
25+
RamSystemPolicyCheckInfo.dataSourceTestCheck(t, rand, allConf)
26+
}
27+
28+
var existRamSystemPolicyMapFunc = func(rand int) map[string]string {
29+
return map[string]string{
30+
"policys.#": "1",
31+
"policys.0.policy_type": "System",
32+
"policys.0.update_date": CHECKSET,
33+
"policys.0.description": CHECKSET,
34+
"policys.0.attachment_count": CHECKSET,
35+
"policys.0.policy_name": CHECKSET,
36+
"policys.0.create_time": CHECKSET,
37+
}
38+
}
39+
40+
var fakeRamSystemPolicyMapFunc = func(rand int) map[string]string {
41+
return map[string]string{
42+
"policys.#": "0",
43+
}
44+
}
45+
46+
var RamSystemPolicyCheckInfo = dataSourceAttr{
47+
resourceId: "data.alicloud_ram_system_policys.default",
48+
existMapFunc: existRamSystemPolicyMapFunc,
49+
fakeMapFunc: fakeRamSystemPolicyMapFunc,
50+
}
51+
52+
func testAccCheckAlicloudRamSystemPolicySourceConfig(rand int, attrMap map[string]string) string {
53+
var pairs []string
54+
for k, v := range attrMap {
55+
pairs = append(pairs, k+" = "+v)
56+
}
57+
config := fmt.Sprintf(`
58+
variable "name" {
59+
default = "tf-testAccRamSystemPolicy%d"
60+
}
61+
62+
data "alicloud_ram_system_policys" "default" {
63+
%s
64+
}
65+
`, rand, strings.Join(pairs, "\n "))
66+
return config
67+
}

alicloud/provider.go

+1
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,7 @@ func Provider() terraform.ResourceProvider {
174174
},
175175
},
176176
DataSourcesMap: map[string]*schema.Resource{
177+
"alicloud_ram_system_policys": dataSourceAliCloudRamSystemPolicys(),
177178
"alicloud_esa_sites": dataSourceAliCloudEsaSites(),
178179
"alicloud_cloud_firewall_nat_firewalls": dataSourceAliCloudCloudFirewallNatFirewalls(),
179180
"alicloud_cloud_firewall_vpc_cen_tr_firewalls": dataSourceAliCloudCloudFirewallVpcCenTrFirewalls(),

alicloud/service_alicloud_ram_v2.go

+69-1
Original file line numberDiff line numberDiff line change
@@ -414,4 +414,72 @@ func (s *RamServiceV2) RamRolePolicyAttachmentStateRefreshFunc(id string, field
414414
}
415415
}
416416

417-
// DescribeRamRolePolicyAttachment >>> Encapsulated.
417+
// DescribeRamRolePolicyAttachment >>> Encapsulated.
418+
419+
// DescribeRamSystemPolicy <<< Encapsulated get interface for Ram SystemPolicy.
420+
func (s *RamServiceV2) DescribeRamSystemPolicy(id string) (object map[string]interface{}, err error) {
421+
client := s.client
422+
var request map[string]interface{}
423+
var response map[string]interface{}
424+
var query map[string]interface{}
425+
request = make(map[string]interface{})
426+
query = make(map[string]interface{})
427+
request["PolicyName"] = id
428+
429+
request["PolicyType"] = "System"
430+
action := "GetPolicy"
431+
432+
wait := incrementalWait(3*time.Second, 5*time.Second)
433+
err = resource.Retry(1*time.Minute, func() *resource.RetryError {
434+
response, err = client.RpcPost("Ram", "2015-05-01", action, query, request, true)
435+
436+
if err != nil {
437+
if NeedRetry(err) {
438+
wait()
439+
return resource.RetryableError(err)
440+
}
441+
return resource.NonRetryableError(err)
442+
}
443+
return nil
444+
})
445+
addDebug(action, response, request)
446+
if err != nil {
447+
if IsExpectedErrors(err, []string{"EntityNotExist.Policy"}) {
448+
return object, WrapErrorf(Error(GetNotFoundMessage("SystemPolicy", id)), NotFoundMsg, response)
449+
}
450+
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
451+
}
452+
453+
return response, nil
454+
}
455+
456+
func (s *RamServiceV2) RamSystemPolicyStateRefreshFunc(id string, field string, failStates []string) resource.StateRefreshFunc {
457+
return func() (interface{}, string, error) {
458+
object, err := s.DescribeRamSystemPolicy(id)
459+
if err != nil {
460+
if NotFoundError(err) {
461+
return object, "", nil
462+
}
463+
return nil, "", WrapError(err)
464+
}
465+
466+
v, err := jsonpath.Get(field, object)
467+
currentStatus := fmt.Sprint(v)
468+
469+
if strings.HasPrefix(field, "#") {
470+
v, _ := jsonpath.Get(strings.TrimPrefix(field, "#"), object)
471+
if v != nil {
472+
currentStatus = "#CHECKSET"
473+
}
474+
}
475+
476+
for _, failState := range failStates {
477+
if currentStatus == failState {
478+
return object, currentStatus, WrapError(Error(FailedToReachTargetStatus, currentStatus))
479+
}
480+
}
481+
return object, currentStatus, nil
482+
}
483+
}
484+
485+
// DescribeRamSystemPolicy >>> Encapsulated.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
---
2+
subcategory: "RAM"
3+
layout: "alicloud"
4+
page_title: "Alicloud: alicloud_ram_system_policys"
5+
sidebar_current: "docs-alicloud-datasource-ram-system-policys"
6+
description: |-
7+
Provides a list of Ram System Policy owned by an Alibaba Cloud account.
8+
---
9+
10+
# alicloud_ram_system_policys
11+
12+
This data source provides Ram System Policy available to the user.[What is System Policy](https://next.api.alibabacloud.com/document/Ram/2015-05-01/GetPolicy)
13+
14+
-> **NOTE:** Available since v1.245.0.
15+
16+
## Example Usage
17+
18+
```terraform
19+
variable "name" {
20+
default = "terraform-example"
21+
}
22+
23+
provider "alicloud" {
24+
region = "cn-hangzhou"
25+
}
26+
27+
data "alicloud_ram_system_policys" "default" {
28+
name_regex = "^AdministratorAccess$"
29+
}
30+
31+
output "alicloud_ram_system_policy_example_id" {
32+
value = data.alicloud_ram_system_policys.default.policys.0.id
33+
}
34+
```
35+
36+
## Argument Reference
37+
38+
The following arguments are supported:
39+
* `ids` - (Optional, ForceNew, Computed) A list of System Policy IDs.
40+
* `name_regex` - (Optional, ForceNew) A regex string to filter results by Group Metric Rule name.
41+
* `output_file` - (Optional, ForceNew) File name where to save data source results (after running `terraform plan`).
42+
43+
44+
## Attributes Reference
45+
46+
The following attributes are exported in addition to the arguments listed above:
47+
* `ids` - A list of System Policy IDs.
48+
* `names` - A list of name of System Policys.
49+
* `policys` - A list of System Policy Entries. Each element contains the following attributes:
50+
* `attachment_count` - Number of references.
51+
* `create_time` - Creation time.
52+
* `description` - The permission policy description.
53+
* `policy_name` - The permission policy name.
54+
* `policy_type` - Permission policy type.
55+
* `update_date` - Modification time.
56+
* `id` - The ID of the resource supplied above.

0 commit comments

Comments
 (0)