• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang iam.New函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/aws/aws-sdk-go/service/iam.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了New函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: New

func New(config Config) (*Client, error) {
	credentials := credentials.NewStaticCredentials(config.AccessKey, config.SecretKey, "")
	sdkConfig := &aws.Config{
		Credentials: credentials,
		Region:      aws.String(config.Region),
	}

	session := session.New(sdkConfig)

	if config.CloudFormationWaitTimeout == 0 {
		return nil, fmt.Errorf("AWS config CloudFormationWaitTimeout must be a positive timeout")
	}

	ec2EndpointConfig, err := config.getEndpoint("ec2")
	if err != nil {
		return nil, err
	}
	cloudformationEndpointConfig, err := config.getEndpoint("cloudformation")
	if err != nil {
		return nil, err
	}
	iamEndpointConfig, err := config.getEndpoint("iam")
	if err != nil {
		return nil, err
	}

	return &Client{
		EC2:            ec2.New(session, ec2EndpointConfig),
		CloudFormation: cloudformation.New(session, cloudformationEndpointConfig),
		IAM:            iam.New(session, iamEndpointConfig),
		Clock:          clockImpl{},
		CloudFormationWaitTimeout: config.CloudFormationWaitTimeout,
	}, nil
}
开发者ID:rosenhouse,项目名称:tubes,代码行数:34,代码来源:client.go


示例2: validateUserAccess

/// validateUserAccess checks for the "AdministratorAccess" policy needed to create a rack.
func validateUserAccess(region string, creds *AwsCredentials) error {

	// this validation need to check for actual permissions somehow and not
	// just a policy name
	return nil

	Iam := iam.New(session.New(), awsConfig(region, creds))

	userOutput, err := Iam.GetUser(&iam.GetUserInput{})
	if err != nil {
		if ae, ok := err.(awserr.Error); ok {
			return fmt.Errorf("%s. See %s", ae.Code(), iamUserURL)
		}
		return fmt.Errorf("%s. See %s", err, iamUserURL)
	}

	policies, err := Iam.ListAttachedUserPolicies(&iam.ListAttachedUserPoliciesInput{
		UserName: userOutput.User.UserName,
	})
	if err != nil {
		if ae, ok := err.(awserr.Error); ok {
			return fmt.Errorf("%s. See %s", ae.Code(), iamUserURL)
		}
	}

	for _, policy := range policies.AttachedPolicies {
		if "AdministratorAccess" == *policy.PolicyName {
			return nil
		}
	}

	msg := fmt.Errorf("Administrator access needed. See %s", iamUserURL)
	stdcli.QOSEventSend("cli-install", distinctID, stdcli.QOSEventProperties{Error: msg})
	return stdcli.Error(msg)
}
开发者ID:convox,项目名称:rack,代码行数:36,代码来源:install.go


示例3: createIAMLambdaRolePolicy

func (infra *Infrastructure) createIAMLambdaRolePolicy(roleName string) error {
	svc := iam.New(session.New(), infra.config)

	_, err := svc.PutRolePolicy(&iam.PutRolePolicyInput{
		PolicyDocument: aws.String(`{
          "Version": "2012-10-17",
          "Statement": [
            {
              "Action": [
                "sqs:SendMessage"
              ],
              "Effect": "Allow",
              "Resource": "arn:aws:sqs:*:*:goad-*"
		  	},
			{
              "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
              ],
              "Effect": "Allow",
              "Resource": "arn:aws:logs:*:*:*"
	        }
          ]
        }`),
		PolicyName: aws.String("goad-lambda-role-policy"),
		RoleName:   aws.String(roleName),
	})
	return err
}
开发者ID:goadapp,项目名称:goad,代码行数:30,代码来源:infrastructure.go


示例4: createIAMLambdaRole

func (infra *Infrastructure) createIAMLambdaRole(roleName string) (arn string, err error) {
	svc := iam.New(session.New(), infra.config)

	resp, err := svc.GetRole(&iam.GetRoleInput{
		RoleName: aws.String(roleName),
	})
	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			if awsErr.Code() == "NoSuchEntity" {
				res, err := svc.CreateRole(&iam.CreateRoleInput{
					AssumeRolePolicyDocument: aws.String(`{
        	          "Version": "2012-10-17",
        	          "Statement": {
        	            "Effect": "Allow",
        	            "Principal": {"Service": "lambda.amazonaws.com"},
        	            "Action": "sts:AssumeRole"
        	          }
            	    }`),
					RoleName: aws.String(roleName),
					Path:     aws.String("/"),
				})
				if err != nil {
					return "", err
				}
				if err := infra.createIAMLambdaRolePolicy(*res.Role.RoleName); err != nil {
					return "", err
				}
				return *res.Role.Arn, nil
			}
		}
		return "", err
	}

	return *resp.Role.Arn, nil
}
开发者ID:goadapp,项目名称:goad,代码行数:35,代码来源:infrastructure.go


示例5: main

func main() {
	flag.Parse()

	config, err := LoadConfig(configFilePath)
	if err != nil {
		log.Fatalf("Error loading config file: %s", err)
	}

	logger := buildLogger(config.LogLevel)

	awsConfig := aws.NewConfig().WithRegion(config.SQSConfig.Region)
	awsSession := session.New(awsConfig)

	sqssvc := sqs.New(awsSession)
	queue := awssqs.NewSQSQueue(sqssvc, logger)

	iamsvc := iam.New(awsSession)
	user := awsiam.NewIAMUser(iamsvc, logger)

	serviceBroker := sqsbroker.New(config.SQSConfig, queue, user, logger)

	credentials := brokerapi.BrokerCredentials{
		Username: config.Username,
		Password: config.Password,
	}

	brokerAPI := brokerapi.New(serviceBroker, logger, credentials)
	http.Handle("/", brokerAPI)

	fmt.Println("SQS Service Broker started on port " + port + "...")
	http.ListenAndServe(":"+port, nil)
}
开发者ID:cf-platform-eng,项目名称:sqs-broker,代码行数:32,代码来源:main.go


示例6: Run

func (u *User) Run(args []string) int {
	cli := iam.New(session.New(aws.NewConfig().WithRegion(u.config.Region)))

	u.ListUsers(cli)

	return 0
}
开发者ID:honeybe,项目名称:code-sample,代码行数:7,代码来源:user.go


示例7: teardown

func teardown() error {
	creds := credentials.NewStaticCredentials(os.Getenv("AWS_ACCESS_KEY_ID"), os.Getenv("AWS_SECRET_ACCESS_KEY"), "")

	awsConfig := &aws.Config{
		Credentials: creds,
		Region:      aws.String("us-east-1"),
		HTTPClient:  cleanhttp.DefaultClient(),
	}
	svc := iam.New(session.New(awsConfig))

	attachment := &iam.DetachRolePolicyInput{
		PolicyArn: aws.String(testPolicyArn),
		RoleName:  aws.String(testRoleName), // Required
	}
	_, err := svc.DetachRolePolicy(attachment)

	params := &iam.DeleteRoleInput{
		RoleName: aws.String(testRoleName),
	}

	log.Printf("[INFO] AWS DeleteRole: %s", testRoleName)
	_, err = svc.DeleteRole(params)

	if err != nil {
		log.Printf("[WARN] AWS DeleteRole failed: %v", err)
	}

	return err
}
开发者ID:GauntletWizard,项目名称:vault,代码行数:29,代码来源:backend_test.go


示例8: main

func main() {
	flag.Parse()

	config, err := LoadConfig(configFilePath)
	if err != nil {
		log.Fatalf("Error loading config file: %s", err)
	}

	logger := buildLogger(config.LogLevel)

	awsConfig := aws.NewConfig().WithRegion(config.RDSConfig.Region)
	awsSession := session.New(awsConfig)

	iamsvc := iam.New(awsSession)
	rdssvc := rds.New(awsSession)
	dbInstance := awsrds.NewRDSDBInstance(config.RDSConfig.Region, iamsvc, rdssvc, logger)
	dbCluster := awsrds.NewRDSDBCluster(config.RDSConfig.Region, iamsvc, rdssvc, logger)

	sqlProvider := sqlengine.NewProviderService(logger)

	serviceBroker := rdsbroker.New(config.RDSConfig, dbInstance, dbCluster, sqlProvider, logger)

	credentials := brokerapi.BrokerCredentials{
		Username: config.Username,
		Password: config.Password,
	}

	brokerAPI := brokerapi.New(serviceBroker, logger, credentials)
	http.Handle("/", brokerAPI)

	fmt.Println("RDS Service Broker started on port " + port + "...")
	http.ListenAndServe(":"+port, nil)
}
开发者ID:x6j8x,项目名称:rds-broker,代码行数:33,代码来源:main.go


示例9: AccountID

// AccountID parses an AWS arn string to get the Account ID.
func (c *Cred) AccountID() (string, error) {
	user, err := iam.New(c.session()).GetUser(nil)
	if err == nil {
		return parseAccountID(aws.StringValue(user.User.Arn))
	}

	for msg := err.Error(); msg != ""; {
		i := strings.Index(msg, arnPrefix)

		if i == -1 {
			break
		}

		msg = msg[i:]

		accountID, e := parseAccountID(msg)
		if e != nil {
			continue
		}

		return accountID, nil
	}

	return "", err
}
开发者ID:koding,项目名称:koding,代码行数:26,代码来源:aws.go


示例10: Run

func (r *Role) Run(args []string) int {
	cli := iam.New(session.New(aws.NewConfig().WithRegion(r.config.Region)))

	r.ListRole(cli)

	return 0
}
开发者ID:honeybe,项目名称:code-sample,代码行数:7,代码来源:role.go


示例11: clientIAM

// clientIAM creates a client to interact with AWS IAM API
func (b *backend) clientIAM(s logical.Storage, region string) (*iam.IAM, error) {
	b.configMutex.RLock()
	if b.IAMClientsMap[region] != nil {
		defer b.configMutex.RUnlock()
		// If the client object was already created, return it
		return b.IAMClientsMap[region], nil
	}

	// Release the read lock and acquire the write lock
	b.configMutex.RUnlock()
	b.configMutex.Lock()
	defer b.configMutex.Unlock()

	// If the client gets created while switching the locks, return it
	if b.IAMClientsMap[region] != nil {
		return b.IAMClientsMap[region], nil
	}

	// Create an AWS config object using a chain of providers
	awsConfig, err := b.getClientConfig(s, region)
	if err != nil {
		return nil, err
	}

	// Create a new IAM client object, cache it and return the same
	b.IAMClientsMap[region] = iam.New(session.New(awsConfig))
	return b.IAMClientsMap[region], nil
}
开发者ID:quixoten,项目名称:vault,代码行数:29,代码来源:client.go


示例12: clientIAM

func clientIAM(s logical.Storage) (*iam.IAM, error) {
	entry, err := s.Get("config/root")
	if err != nil {
		return nil, err
	}
	if entry == nil {
		return nil, fmt.Errorf(
			"root credentials haven't been configured. Please configure\n" +
				"them at the 'config/root' endpoint")
	}

	var config rootConfig
	if err := entry.DecodeJSON(&config); err != nil {
		return nil, fmt.Errorf("error reading root configuration: %s", err)
	}

	creds := credentials.NewStaticCredentials(config.AccessKey, config.SecretKey, "")
	awsConfig := &aws.Config{
		Credentials: creds,
		Region:      aws.String(config.Region),
		HTTPClient:  cleanhttp.DefaultClient(),
	}

	return iam.New(session.New(awsConfig)), nil
}
开发者ID:vincentaubert,项目名称:vault,代码行数:25,代码来源:client.go


示例13: initIamClient

func (r *run) initIamClient() *iam.IAM {
	var awsconf aws.Config
	if r.c.AccessKey != "" && r.c.SecretKey != "" {
		awscreds := awscred.NewStaticCredentials(r.c.AccessKey, r.c.SecretKey, "")
		awsconf.Credentials = awscreds
	}
	return iam.New(session.New(), &awsconf)
}
开发者ID:yonglehou,项目名称:userplex,代码行数:8,代码来源:aws.go


示例14: initIamClient

func (r *run) initIamClient() *iam.IAM {
	awsconf := aws.NewConfig()
	if r.c.AccessKey != "" && r.c.SecretKey != "" {
		creds := awscred.NewStaticCredentials(r.c.AccessKey, r.c.SecretKey, "")
		awsconf = awsconf.WithCredentials(creds)
	}
	return iam.New(session.New(), awsconf)
}
开发者ID:mozilla-services,项目名称:userplex,代码行数:8,代码来源:aws.go


示例15: determineAccountIdViaGetUser

// see http://stackoverflow.com/a/18124234
func determineAccountIdViaGetUser(sess *session.Session) (string, error) {
	getUserResp, err := iam.New(sess).GetUser(&iam.GetUserInput{})
	if err != nil {
		return "", err
	}

	return getAccountIdFromArn(*getUserResp.User.Arn), nil
}
开发者ID:99designs,项目名称:iamy,代码行数:9,代码来源:awsaccountid.go


示例16: testDecryptPasswordAndTest

func testDecryptPasswordAndTest(nProfile, nAccessKey, key string) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		profileResource, ok := s.RootModule().Resources[nProfile]
		if !ok {
			return fmt.Errorf("Not found: %s", nProfile)
		}

		password, ok := profileResource.Primary.Attributes["encrypted_password"]
		if !ok {
			return errors.New("No password in state")
		}

		accessKeyResource, ok := s.RootModule().Resources[nAccessKey]
		if !ok {
			return fmt.Errorf("Not found: %s", nAccessKey)
		}

		accessKeyId := accessKeyResource.Primary.ID
		secretAccessKey, ok := accessKeyResource.Primary.Attributes["secret"]
		if !ok {
			return errors.New("No secret access key in state")
		}

		decryptedPassword, err := pgpkeys.DecryptBytes(password, key)
		if err != nil {
			return fmt.Errorf("Error decrypting password: %s", err)
		}

		iamAsCreatedUserSession := session.New(&aws.Config{
			Region:      aws.String("us-west-2"),
			Credentials: credentials.NewStaticCredentials(accessKeyId, secretAccessKey, ""),
		})
		_, err = iamAsCreatedUserSession.Config.Credentials.Get()
		if err != nil {
			return fmt.Errorf("Error getting session credentials: %s", err)
		}

		return resource.Retry(2*time.Minute, func() *resource.RetryError {
			iamAsCreatedUser := iam.New(iamAsCreatedUserSession)
			_, err = iamAsCreatedUser.ChangePassword(&iam.ChangePasswordInput{
				OldPassword: aws.String(decryptedPassword.String()),
				NewPassword: aws.String(generatePassword(20)),
			})
			if err != nil {
				if awserr, ok := err.(awserr.Error); ok && awserr.Code() == "InvalidClientTokenId" {
					return resource.RetryableError(err)
				}

				return resource.NonRetryableError(fmt.Errorf("Error changing decrypted password: %s", err))
			}

			return nil
		})
	}
}
开发者ID:hashicorp,项目名称:terraform,代码行数:55,代码来源:resource_aws_iam_user_login_profile_test.go


示例17: GetConsoleLoginURL

// GetConsoleLoginURL works with the AWS API to create a federation login URL to
// the web console for the given environment which will expire after timeout
func (a *AWSCredentialStore) GetConsoleLoginURL(env string, timeout int, subconsole string) (string, error) {
	e, ok := a.Credentials[env]
	if !ok {
		return "", fmt.Errorf("Environment '%s' was not found.", env)
	}

	c := credentials.NewStaticCredentials(e.AWSAccessKeyID, e.AWSSecretAccessKey, "")

	// Get the username of the current user
	iam := iam.New(&aws.Config{Credentials: c})
	usr, err := iam.GetUser(nil)
	if err != nil {
		return "", err
	}

	username := "root"
	if usr.User.UserName != nil {
		username = *usr.User.UserName
	}

	// Create STS url for current user
	svc := sts.New(&aws.Config{Credentials: c})

	resp, err := svc.GetFederationToken(&sts.GetFederationTokenInput{
		Name:            aws.String(fmt.Sprintf("awsenv-%s", username)),
		DurationSeconds: aws.Int64(int64(timeout)),
		Policy:          aws.String(iamPolicy),
	})

	if err != nil {
		return "", err
	}

	signinToken, err := a.getFederatedSigninToken(resp)
	if err != nil {
		return "", err
	}

	p := url.Values{
		"Action":      []string{"login"},
		"Issuer":      []string{"https://github.com/Luzifer/awsenv"},
		"Destination": []string{fmt.Sprintf("https://console.aws.amazon.com/%s/home?region=%s", subconsole, e.AWSRegion)},
		"SigninToken": []string{signinToken},
	}
	out := url.URL{
		Scheme:   "https",
		Host:     "signin.aws.amazon.com",
		Path:     "federation",
		RawQuery: p.Encode(),
	}

	return out.String(), nil

}
开发者ID:rhoml,项目名称:awsenv,代码行数:56,代码来源:federatedLogin.go


示例18: determineAccountIdViaListUsers

func determineAccountIdViaListUsers(sess *session.Session) (string, error) {
	listUsersResp, err := iam.New(sess).ListUsers(&iam.ListUsersInput{})
	if err != nil {
		return "", err
	}
	if len(listUsersResp.Users) == 0 {
		return "", errors.New("No users found")
	}

	return getAccountIdFromArn(*listUsersResp.Users[0].Arn), nil
}
开发者ID:99designs,项目名称:iamy,代码行数:11,代码来源:awsaccountid.go


示例19: findAcccountID

// findAcccountID returns the AWS account ID
func (c *config) findAcccountID() (string, error) {
	i := iam.New(session.New(), &aws.Config{Region: aws.String(c.src)})
	u, err := i.GetUser(nil)
	if err != nil {
		return "", err
	}
	parts := strings.Split(*u.User.Arn, ":")
	if len(parts) != 6 {
		return "", fmt.Errorf("Error parsing user ARN")
	}
	return parts[4], nil
}
开发者ID:rhartkopf,项目名称:rdsbackup,代码行数:13,代码来源:rdsbackup.go


示例20: verifyIAMRoles

// Verify & cache the IAM rolename to ARN mapping
func verifyIAMRoles(ctx *workflowContext) (workflowStep, error) {
	// The map is either a literal Arn from a pre-existing role name
	// or a ArbitraryJSONObject{
	// 	"Fn::GetAtt": []string{iamRoleDefinitionName, "Arn"},
	// }
	// Don't verify them, just create them...
	ctx.logger.Info("Verifying IAM Lambda execution roles")
	ctx.lambdaIAMRoleNameMap = make(map[string]interface{}, 0)
	svc := iam.New(ctx.awsSession)

	for _, eachLambda := range ctx.lambdaAWSInfos {
		if "" != eachLambda.RoleName && nil != eachLambda.RoleDefinition {
			return nil, fmt.Errorf("Both RoleName and RoleDefinition defined for lambda: %s", eachLambda.lambdaFnName)
		}

		// Get the IAM role name
		if "" != eachLambda.RoleName {
			_, exists := ctx.lambdaIAMRoleNameMap[eachLambda.RoleName]
			if !exists {
				// Check the role
				params := &iam.GetRoleInput{
					RoleName: aws.String(eachLambda.RoleName),
				}
				ctx.logger.Debug("Checking IAM RoleName: ", eachLambda.RoleName)
				resp, err := svc.GetRole(params)
				if err != nil {
					ctx.logger.Error(err.Error())
					return nil, err
				}
				// Cache it - we'll need it later when we create the
				// CloudFormation template which needs the execution Arn (not role)
				ctx.lambdaIAMRoleNameMap[eachLambda.RoleName] = *resp.Role.Arn
			}
		} else {
			logicalName := eachLambda.RoleDefinition.logicalName()
			_, exists := ctx.lambdaIAMRoleNameMap[logicalName]
			if !exists {
				// Insert it into the resource creation map and add
				// the "Ref" entry to the hashmap
				ctx.cloudformationResources[logicalName] = eachLambda.RoleDefinition.rolePolicy(eachLambda.EventSourceMappings, ctx.logger)

				ctx.lambdaIAMRoleNameMap[logicalName] = ArbitraryJSONObject{
					"Fn::GetAtt": []string{logicalName, "Arn"},
				}
			}
		}
	}
	ctx.logger.WithFields(logrus.Fields{
		"Count": len(ctx.lambdaIAMRoleNameMap),
	}).Info("IAM roles verified")

	return createPackageStep(), nil
}
开发者ID:dmreiland,项目名称:Sparta,代码行数:54,代码来源:provision.go



注:本文中的github.com/aws/aws-sdk-go/service/iam.New函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang iam.IAM类代码示例发布时间:2022-05-24
下一篇:
Golang glacier.Glacier类代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap