diff --git a/upup/pkg/fi/cloudup/alitasks/ramrole.go b/upup/pkg/fi/cloudup/alitasks/ramrole.go index 781622c01c..b8cd175fcc 100644 --- a/upup/pkg/fi/cloudup/alitasks/ramrole.go +++ b/upup/pkg/fi/cloudup/alitasks/ramrole.go @@ -18,7 +18,9 @@ package alitasks import ( "fmt" + "strings" + "github.com/denverdino/aliyungo/common" "github.com/denverdino/aliyungo/ram" "k8s.io/klog" @@ -42,37 +44,48 @@ func (r *RAMRole) CompareWithID() *string { return r.Name } +func compactPolicy(s string) string { + removedStrings := []string{"\n", "
", " ", "\r\n"} + for _, each := range removedStrings { + s = strings.Replace(s, each, "", -1) + } + return s +} + func (r *RAMRole) Find(c *fi.Context) (*RAMRole, error) { cloud := c.Cloud.(aliup.ALICloud) - roleList, err := cloud.RamClient().ListRoles() - if err != nil { - return nil, fmt.Errorf("error listing RamRoles: %v", err) + request := ram.RoleQueryRequest{ + RoleName: fi.StringValue(r.Name), } - // Don't exist RAMrole with specified User. - if len(roleList.Roles.Role) == 0 { + roleResp, err := cloud.RamClient().GetRole(request) + if err != nil { + if e, ok := err.(*common.Error); ok && e.StatusCode == 404 { + klog.V(2).Infof("no RamRole with name: %q", *r.Name) + return nil, nil + } + return nil, fmt.Errorf("error get RamRole %q: %v", *r.Name, err) + } + + role := roleResp.Role + if role.RoleId == "" { + klog.V(2).Infof("no RamRole with name: %q", *r.Name) return nil, nil } - // The same user's RAM resource name can not be repeated - for _, role := range roleList.Roles.Role { - if role.RoleName == fi.StringValue(r.Name) { - - klog.V(2).Infof("found matching RamRole with name: %q", *r.Name) - actual := &RAMRole{} - actual.Name = fi.String(role.RoleName) - actual.RAMRoleId = fi.String(role.RoleId) - actual.AssumeRolePolicyDocument = fi.String(role.AssumeRolePolicyDocument) - - // Ignore "system" fields - actual.Lifecycle = r.Lifecycle - r.RAMRoleId = actual.RAMRoleId - return actual, nil - } + klog.V(2).Infof("found matching RamRole with name: %q", *r.Name) + actual := &RAMRole{ + Name: fi.String(role.RoleName), + RAMRoleId: fi.String(role.RoleId), + AssumeRolePolicyDocument: fi.String(compactPolicy(role.AssumeRolePolicyDocument)), } - return nil, nil + // Ignore "system" fields + actual.Lifecycle = r.Lifecycle + r.RAMRoleId = actual.RAMRoleId + + return actual, nil } func (r *RAMRole) Run(c *fi.Context) error {