Example #1
0
func GetAccountId(iamconn *iam.IAM, stsconn *sts.STS, authProviderName string) (string, error) {
	// If we have creds from instance profile, we can use metadata API
	if authProviderName == ec2rolecreds.ProviderName {
		log.Println("[DEBUG] Trying to get account ID via AWS Metadata API")

		cfg := &aws.Config{}
		setOptionalEndpoint(cfg)
		metadataClient := ec2metadata.New(session.New(cfg))
		info, err := metadataClient.IAMInfo()
		if err != nil {
			// This can be triggered when no IAM Role is assigned
			// or AWS just happens to return invalid response
			return "", fmt.Errorf("Failed getting EC2 IAM info: %s", err)
		}

		return parseAccountIdFromArn(info.InstanceProfileArn)
	}

	// Then try IAM GetUser
	log.Println("[DEBUG] Trying to get account ID via iam:GetUser")
	outUser, err := iamconn.GetUser(nil)
	if err == nil {
		return parseAccountIdFromArn(*outUser.User.Arn)
	}

	awsErr, ok := err.(awserr.Error)
	// AccessDenied and ValidationError can be raised
	// if credentials belong to federated profile, so we ignore these
	if !ok || (awsErr.Code() != "AccessDenied" && awsErr.Code() != "ValidationError") {
		return "", fmt.Errorf("Failed getting account ID via 'iam:GetUser': %s", err)
	}
	log.Printf("[DEBUG] Getting account ID via iam:GetUser failed: %s", err)

	// Then try STS GetCallerIdentity
	log.Println("[DEBUG] Trying to get account ID via sts:GetCallerIdentity")
	outCallerIdentity, err := stsconn.GetCallerIdentity(&sts.GetCallerIdentityInput{})
	if err == nil {
		return *outCallerIdentity.Account, nil
	}
	log.Printf("[DEBUG] Getting account ID via sts:GetCallerIdentity failed: %s", err)

	// Then try IAM ListRoles
	log.Println("[DEBUG] Trying to get account ID via iam:ListRoles")
	outRoles, err := iamconn.ListRoles(&iam.ListRolesInput{
		MaxItems: aws.Int64(int64(1)),
	})
	if err != nil {
		return "", fmt.Errorf("Failed getting account ID via 'iam:ListRoles': %s", err)
	}

	if len(outRoles.Roles) < 1 {
		return "", fmt.Errorf("Failed getting account ID via 'iam:ListRoles': No roles available")
	}

	return parseAccountIdFromArn(*outRoles.Roles[0].Arn)
}
Example #2
0
func (r *Role) ListRole(cli *iam.IAM) {
	req := &iam.ListRolesInput{}
	resp, err := cli.ListRoles(req)
	raiseError(err)

	if len(resp.Roles) < 1 {
		fmt.Println("not found")
		return
	}

	for i := 0; i < len(resp.Roles); i++ {
		fmt.Printf("%s %s\n",
			*resp.Roles[i].RoleId,
			*resp.Roles[i].RoleName,
		)

		r.ListRolePolicies(cli, *resp.Roles[i].RoleName)
	}
}