Skip to content

Commit

Permalink
Merge pull request aliyun#48 from xiaozhu36/ram-role
Browse files Browse the repository at this point in the history
add new resources role and role attachment
  • Loading branch information
zhuzhih2017 authored Dec 11, 2017
2 parents a16db50 + 937e90b commit 55ebf52
Show file tree
Hide file tree
Showing 21 changed files with 1,534 additions and 47 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,22 @@

IMPROVEMENTS:

- *New Resource*: _alicloud_ram_role_ [GH-48]
- *New Resource*: _alicloud_ram_role_attachment_ [GH-48]
- *New Resource*: _alicloud_ram_role_polocy_attachment_ [GH-48]
- *New Resource*: _alicloud_container_cluster_ [GH-47]
- *New Resource:* _alicloud_ram_policy_ [GH-46]
- *New Resource*: _alicloud_ram_user_policy_attachment_ [GH-46]
- *New Resource* _alicloud_ram_user_ [GH-44]
- *New Datasource* _alicloud_ram_policies_ [GH-46]
- *New Datasource* _alicloud_ram_users_ [GH-44]
- *New Datasource*: _alicloud_ram_roles_ [GH-48]

- Added support for importing:
- `alicloud_container_cluster` [GH-47]
- `alicloud_ram_policy` [GH-46]
- `alicloud_ram_user` [GH-44]
- `alicloud_ram_role` [GH-48]


## 0.1.1 (December 11, 2017)
Expand Down
12 changes: 12 additions & 0 deletions alicloud/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"strings"

"encoding/base64"
"github.com/denverdino/aliyungo/common"
"github.com/denverdino/aliyungo/ecs"
"github.com/hashicorp/terraform/helper/schema"
Expand Down Expand Up @@ -153,3 +154,14 @@ func (client *AliyunClient) JudgeRegionValidation(key string, region common.Regi
}
return fmt.Errorf("'%s' is invalid. Expected on %v.", key, strings.Join(rs, ", "))
}

func userDataHashSum(user_data string) string {
// Check whether the user_data is not Base64 encoded.
// Always calculate hash of base64 decoded value since we
// check against double-encoding when setting it
v, base64DecodeError := base64.StdEncoding.DecodeString(user_data)
if base64DecodeError != nil {
v = []byte(user_data)
}
return string(v)
}
177 changes: 177 additions & 0 deletions alicloud/data_source_alicloud_ram_roles.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
package alicloud

import (
"fmt"
"log"
"regexp"

"github.com/denverdino/aliyungo/ram"
"github.com/hashicorp/terraform/helper/schema"
)

func dataSourceAlicloudRamRoles() *schema.Resource {
return &schema.Resource{
Read: dataSourceAlicloudRamRolesRead,

Schema: map[string]*schema.Schema{
"name_regex": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"policy_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validateRamPolicyName,
},
"policy_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validatePolicyType,
},
"output_file": {
Type: schema.TypeString,
Optional: true,
},

// Computed values
"roles": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"arn": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
"assume_role_policy_document": {
Type: schema.TypeString,
Computed: true,
},
"document": {
Type: schema.TypeString,
Computed: true,
},
"create_date": {
Type: schema.TypeString,
Computed: true,
},
"update_date": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
},
}
}

func dataSourceAlicloudRamRolesRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AliyunClient).ramconn
allRoles := []interface{}{}

allRolesMap := make(map[string]interface{})
policyFilterRolesMap := make(map[string]interface{})

dataMap := []map[string]interface{}{}

policyName, policyNameOk := d.GetOk("policy_name")
policyType, policyTypeOk := d.GetOk("policy_type")
nameRegex, nameRegexOk := d.GetOk("name_regex")

if policyTypeOk && !policyNameOk {
return fmt.Errorf("You must set 'policy_name' at one time when you set 'policy_type'.")
}

// all roles
resp, err := conn.ListRoles()
if err != nil {
return fmt.Errorf("ListRoles got an error: %#v", err)
}
for _, v := range resp.Roles.Role {
if nameRegexOk {
r := regexp.MustCompile(nameRegex.(string))
if !r.MatchString(v.RoleName) {
continue
}
}
allRolesMap[v.RoleName] = v
}

// roles which attach with this policy
if policyNameOk {
pType := ram.System
if policyTypeOk {
pType = ram.Type(policyType.(string))
}
resp, err := conn.ListEntitiesForPolicy(ram.PolicyRequest{PolicyName: policyName.(string), PolicyType: pType})
if err != nil {
return fmt.Errorf("ListEntitiesForPolicy got an error: %#v", err)
}

for _, v := range resp.Roles.Role {
policyFilterRolesMap[v.RoleName] = v
}
dataMap = append(dataMap, policyFilterRolesMap)
}

// GetIntersection of each map
allRoles = GetIntersection(dataMap, allRolesMap)

if len(allRoles) < 1 {
return fmt.Errorf("Your query returned no results. Please change your search criteria and try again.")
}

log.Printf("[DEBUG] alicloud_ram_roles - Roles found: %#v", allRoles)

return ramRolesDescriptionAttributes(d, meta, allRoles)
}

func ramRolesDescriptionAttributes(d *schema.ResourceData, meta interface{}, roles []interface{}) error {
var ids []string
var s []map[string]interface{}
for _, v := range roles {
role := v.(ram.Role)
conn := meta.(*AliyunClient).ramconn
resp, _ := conn.GetRole(ram.RoleQueryRequest{RoleName: role.RoleName})
mapping := map[string]interface{}{
"id": role.RoleId,
"name": role.RoleName,
"arn": role.Arn,
"description": role.Description,
"create_date": role.CreateDate,
"update_date": role.UpdateDate,
"assume_role_policy_document": resp.Role.AssumeRolePolicyDocument,
"document": resp.Role.AssumeRolePolicyDocument,
}
log.Printf("[DEBUG] alicloud_ram_roles - adding role: %v", mapping)
ids = append(ids, role.RoleId)
s = append(s, mapping)
}

d.SetId(dataResourceIdHash(ids))
if err := d.Set("roles", s); err != nil {
return err
}

// create a json file in current directory and write data source to it.
if output, ok := d.GetOk("output_file"); ok && output.(string) != "" {
writeToFile(output.(string), s)
}
return nil
}
78 changes: 78 additions & 0 deletions alicloud/data_source_alicloud_ram_roles_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package alicloud

import (
"github.com/hashicorp/terraform/helper/resource"
"testing"
)

func TestAccAlicloudRamRolesDataSource_for_policy(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
},
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccCheckAlicloudRamRolesDataSourceForPolicyConfig,
Check: resource.ComposeTestCheckFunc(
testAccCheckAlicloudDataSourceID("data.alicloud_ram_roles.role"),
resource.TestCheckResourceAttr("data.alicloud_ram_roles.role", "roles.#", "1"),
resource.TestCheckResourceAttr("data.alicloud_ram_roles.role", "roles.0.name", "testrole"),
resource.TestCheckResourceAttr("data.alicloud_ram_roles.role", "roles.0.arn", "acs:ram::1307087942598154:role/testrole"),
resource.TestCheckResourceAttr("data.alicloud_ram_roles.role", "roles.0.id", "345148520161269882"),
),
},
},
})
}

func TestAccAlicloudRamRolesDataSource_for_all(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
},
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccCheckAlicloudRamRolesDataSourceForAllConfig,
Check: resource.ComposeTestCheckFunc(
testAccCheckAlicloudDataSourceID("data.alicloud_ram_roles.role"),
resource.TestCheckResourceAttr("data.alicloud_ram_roles.role", "roles.#", "3"),
),
},
},
})
}

func TestAccAlicloudRamRolesDataSource_role_name_regex(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
},
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccCheckAlicloudRamRolesDataSourceRoleNameRegexConfig,
Check: resource.ComposeTestCheckFunc(
testAccCheckAlicloudDataSourceID("data.alicloud_ram_roles.role"),
resource.TestCheckResourceAttr("data.alicloud_ram_roles.role", "roles.#", "2"),
),
},
},
})
}

const testAccCheckAlicloudRamRolesDataSourceForPolicyConfig = `
data "alicloud_ram_roles" "role" {
policy_name = "AliyunACSDefaultAccess"
policy_type = "Custom"
}`

const testAccCheckAlicloudRamRolesDataSourceForAllConfig = `
data "alicloud_ram_roles" "role" {
}`

const testAccCheckAlicloudRamRolesDataSourceRoleNameRegexConfig = `
data "alicloud_ram_roles" "role" {
name_regex = "^test"
}`
7 changes: 0 additions & 7 deletions alicloud/extension_ecs.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,6 @@ package alicloud

import "github.com/denverdino/aliyungo/ecs"

type GroupRuleDirection string

const (
GroupRuleIngress = GroupRuleDirection("ingress")
GroupRuleEgress = GroupRuleDirection("egress")
)

type GroupRuleIpProtocol string

const (
Expand Down
29 changes: 29 additions & 0 deletions alicloud/import_alicloud_ram_role_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package alicloud

import (
"testing"

"github.com/hashicorp/terraform/helper/resource"
)

func TestAccAlicloudRamRole_importBasic(t *testing.T) {
resourceName := "alicloud_ram_role.role"

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckRamRoleDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccRamRoleConfig,
},

resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"force"},
},
},
})
}
Loading

0 comments on commit 55ebf52

Please sign in to comment.