

AWS SDK for Go V1 has reached end-of-support. We recommend that you migrate to [AWS SDK for Go V2](https://docs.aws.amazon.com/sdk-for-go/v2/developer-guide/). For additional details and information on how to migrate, please refer to this [announcement](https://aws.amazon.com/blogs//developer/announcing-end-of-support-for-aws-sdk-for-go-v1-on-july-31-2025/).

# IAM Examples Using the AWS SDK for Go
IAM Examples

AWS Identity and Access Management (IAM) is a web service that enables AWS customers to manage users and user permissions in AWS. The service is targeted at organizations with multiple users or systems in the cloud that use AWS products. With IAM, you can centrally manage users, security credentials such as access keys, and permissions that control which AWS resources users can access.

The examples assume you have already set up and configured the SDK (that is, you’ve imported all required packages and set your credentials and region). For more information, see [Getting Started with the AWS SDK for Go](setting-up.md) and [Configuring the AWS SDK for Go](configuring-sdk.md).

You can download complete versions of these example files from the [aws-doc-sdk-examples](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/go/example_code/s3) repository on GitHub.

**Topics**
+ [

# Managing IAM Users
](iam-example-managing-users.md)
+ [

# Managing IAM Access Keys
](iam-example-managing-access-keys.md)
+ [

# Managing IAM Account Aliases
](iam-example-account-aliases.md)
+ [

# Working with IAM Policies
](iam-example-policies.md)
+ [

# Working with IAM Server Certificates
](iam-example-server-certificates.md)

# Managing IAM Users


This Go example shows you how to create, update, view, and delete IAM users. You can download complete versions of these example files from the [aws-doc-sdk-examples](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/go/example_code/iam) repository on GitHub.

## Scenario


In this example, you use a series of Go routines to manage users in IAM. The routines use the AWS SDK for Go IAM client methods that follow:
+  [CreateUser](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.CreateUser) 
+  [ListUsers](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.ListUsers) 
+  [UpdateUser](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.UpdateUser) 
+  [GetUser](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.GetUser) 
+  [DeleteUser](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.DeleteUser) 
+  [GetAccountAuthorizationDetails](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.GetAccountAuthorizationDetails) 

## Prerequisites

+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with IAM users. To learn more, see [IAM Users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html) in the IAM User Guide.

## Create a New IAM User


This code creates a new IAM user.

Create a new Go file named `iam_createuser.go`. You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
import (
    "fmt"
    "os"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/awserr"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"
)
```

The code takes the new user name as an argument, and then calls `GetUser` with the user name.

```
// Initialize a session in us-west-2 that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
    Region: aws.String("us-west-2")},
)

// Create a IAM service client.
svc := iam.New(sess)

_, err = svc.GetUser(&iam.GetUserInput{
    UserName: &os.Args[1],
})
```

If you receive a `NoSuchEntity` error, call `CreateUser` because the user doesn’t exist.

```
if awserr, ok := err.(awserr.Error); ok && awserr.Code() == iam.ErrCodeNoSuchEntityException {
    result, err := svc.CreateUser(&iam.CreateUserInput{
        UserName: &os.Args[1],
    })

    if err != nil {
        fmt.Println("CreateUser Error", err)
        return
    }

    fmt.Println("Success", result)
} else {
    fmt.Println("GetUser Error", err)
}
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/iam/iam_createuser.go) on GitHub.

## List IAM Users in Your Account


You can get a list of the users in your account and print the list to the console.

Create a new Go file named `iam_listusers.go`. You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
import (
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"
)
```

Set up a new IAM client.

```
// Initialize a session in us-west-2 that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
    Region: aws.String("us-west-2")},
)

// Create a IAM service client.
svc := iam.New(sess)
```

Call `ListUsers` and print the results.

```
result, err := svc.ListUsers(&iam.ListUsersInput{
    MaxItems: aws.Int64(10),
})

if err != nil {
    fmt.Println("Error", err)
    return
}

for i, user := range result.Users {
    if user == nil {
        continue
    }
    fmt.Printf("%d user %s created %v\n", i, *user.UserName, user.CreateDate)
}
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/iam/iam_listusers.go) on GitHub.

## Update a User’s Name


In this example, you change the name of an IAM user to a new value.

Create a new Go file named `iam_updateuser.go`. You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
import (
    "fmt"
    "os"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"
)
```

Set up a new IAM client.

```
// Initialize a session in us-west-2 that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
    Region: aws.String("us-west-2")},
)

// Create a IAM service client.
svc := iam.New(sess)
```

Call `UpdateUser`, passing in the original user name and the new name, and print the results.

```
result, err := svc.UpdateUser(&iam.UpdateUserInput{
    UserName:    &os.Args[1],
    NewUserName: &os.Args[2],
})

if err != nil {
    fmt.Println("Error", err)
    return
}

fmt.Println("Success", result)
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/iam/iam_updateuser.go) on GitHub.

## Delete an IAM User


In this example, you delete an IAM user.

Create a new Go file named `iam_deleteuser.go`. You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
import (
    "fmt"
    "os"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/awserr"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"
)
```

Set up a new IAM client.

```
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )
    svc := iam.New(sess)
```

Call `DeleteUser`, passing in the user name, and print the results. If the user doesn’t exist, display an error.

```
    _, err = svc.DeleteUser(&iam.DeleteUserInput{
        UserName: &os.Args[1],
    })

    // If the user does not exist than we will log an error.
    if awserr, ok := err.(awserr.Error); ok && awserr.Code() == iam.ErrCodeNoSuchEntityException {
        fmt.Printf("User %s does not exist\n", os.Args[1])
        return
    } else if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Printf("User %s has been deleted\n", os.Args[1])
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/iam/iam_deleteuser.go) on GitHub.

## List the IAM Users who have Administrator Privileges


In this example, you list the IAM users who have administrator privileges (a policy or attached policy of the user or a group to which the user belongs has the name **AdministratorAccess**.

Create a new Go file named `IamGetAdmins.go`. Import the following packages.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"

    "fmt"
    "os"
)
```

Create a method to determine whether a user has a policy that has administrator privileges.

```
func UserPolicyHasAdmin(user *iam.UserDetail, admin string) bool {
    for _, policy := range user.UserPolicyList {
        if *policy.PolicyName == admin {
            return true
        }
    }

    return false
}
```

Create a method to determine whether a user has an attached policy that has administrator privileges.

```
func AttachedUserPolicyHasAdmin(user *iam.UserDetail, admin string) bool {
    for _, policy := range user.AttachedManagedPolicies {
        if *policy.PolicyName == admin {
            return true
        }
    }

    return false
}
```

Create a method that determines whether a group has a policy that has adminstrator privileges.

```
func GroupPolicyHasAdmin(svc *iam.IAM, group *iam.Group, admin string) bool {
    input := &iam.ListGroupPoliciesInput{
        GroupName: group.GroupName,
    }

    result, err := svc.ListGroupPolicies(input)
    if err != nil {
        fmt.Println("Got error calling ListGroupPolicies for group", group.GroupName)
    }

    // Wade through policies
    for _, policyName := range result.PolicyNames {
        if
        *policyName == admin {
            return true
        }
    }

    return false
}
```

Create a method that determines whether a group has an attached policy that has administrator privileges.

```
func AttachedGroupPolicyHasAdmin(svc *iam.IAM, group *iam.Group, admin string) bool {
    input := &iam.ListAttachedGroupPoliciesInput{GroupName: group.GroupName}
    result, err := svc.ListAttachedGroupPolicies(input)
    if err != nil {
        fmt.Println("Got error getting attached group policies:")
        fmt.Println(err.Error())
        os.Exit(1)
    }

    for _, policy := range result.AttachedPolicies {
        if *policy.PolicyName == admin {
            return true
        }
    }

    return false
}
```

Create a method that determines whether any group to which the user belongs has administrator privileges.

```
func UsersGroupsHaveAdmin(svc *iam.IAM, user *iam.UserDetail, admin string) bool {
    input := &iam.ListGroupsForUserInput{UserName: user.UserName}
    result, err := svc.ListGroupsForUser(input)
    if err != nil {
        fmt.Println("Got error getting groups for user:")
        fmt.Println(err.Error())
        os.Exit(1)
    }

    for _, group := range result.Groups {
        groupPolicyHasAdmin := GroupPolicyHasAdmin(svc, group, admin)

        if groupPolicyHasAdmin {
            return true
        }

        attachedGroupPolicyHasAdmin := AttachedGroupPolicyHasAdmin(svc, group, admin)

        if attachedGroupPolicyHasAdmin {
            return true
        }
    }

    return false
}
```

Create a method that determines whether a user has administrator privileges.

```
func IsUserAdmin(svc *iam.IAM, user *iam.UserDetail, admin string) bool {
    // Check policy, attached policy, and groups (policy and attached policy)
    policyHasAdmin := UserPolicyHasAdmin(user, admin)
    if policyHasAdmin {
        return true
    }

    attachedPolicyHasAdmin := AttachedUserPolicyHasAdmin(user, admin)
    if attachedPolicyHasAdmin {
        return true
    }

    userGroupsHaveAdmin := UsersGroupsHaveAdmin(svc, user, admin)
    if userGroupsHaveAdmin {
        return true
    }

    return false
}
```

Create a main method with an IAM client in `us-west-2`. Create variables to keep track of how many users we have and how many of those have administrator privileges.

```
sess, err := session.NewSession()
if err != nil {
    fmt.Println("Got error creating new session")
    fmt.Println(err.Error())
    os.Exit(1)
}

svc := iam.New(sess, &aws.Config{Region: aws.String("us-west-2")})

numUsers := 0
numAdmins := 0
```

Create the input for and call `GetAccountAuthorizationDetails`. If there is an error, print an error message and quit.

```
user := "User"
input := &iam.GetAccountAuthorizationDetailsInput{Filter: []*string{&user}}
resp, err := svc.GetAccountAuthorizationDetails(input)
if err != nil {
    fmt.Println("Got error getting account details")
    fmt.Println(err.Error())
    os.Exit(1)
}
```

Loop through the users. If a user has adminstrator privileges, print their name and increment the number of users who have adminstrator privileges.

```
adminName := "AdministratorAccess"

// Wade through resulting users
for _, user := range resp.UserDetailList {
    numUsers += 1

    isAdmin := IsUserAdmin(svc, user, adminName)

    if isAdmin {
        fmt.Println(*user.UserName)
        numAdmins += 1
    }
}
```

If we did not get all of the users in the first call to `GetAccountAuthorizationDetails`, loop through the next set of users and determine which of those have adminstrator privileges.

```
for *resp.IsTruncated {
    input := &iam.GetAccountAuthorizationDetailsInput{Filter: []*string{&user}, Marker: resp.Marker}
    resp, err = svc.GetAccountAuthorizationDetails(input)
    if err != nil {
        fmt.Println("Got error getting account details")
        fmt.Println(err.Error())
        os.Exit(1)
    }

    // Wade through resulting users
    for _, user := range resp.UserDetailList {
        numUsers += 1

        isAdmin := IsUserAdmin(svc, user, adminName)

        if isAdmin {
            fmt.Println(*user.UserName)
            numAdmins += 1
        }
    }
}
```

Finally, display the number of users who have administrator access.

```
fmt.Println("")
fmt.Println("Found", numAdmins, "admin(s) out of", numUsers, "user(s).")
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/iam/IamListAdmins.go) on GitHub.

# Managing IAM Access Keys


This Go example shows you how to create, modify, view, or rotate IAM access keys. You can download complete versions of these example files from the [aws-doc-sdk-examples](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/go/example_code/iam) repository on GitHub.

## Scenario


Users need their own access keys to make programmatic calls to the AWS SDK for Go. To fill this need, you can create, modify, view, or rotate access keys (access key IDs and secret access keys) for IAM users. By default, when you create an access key its status is Active, which means the user can use the access key for API calls.

In this example, you use a series of Go routines to manage access keys in IAM. The routines use the AWS SDK for Go IAM client methods that follow:
+  [CreateAccessKey](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.CreateAccessKey) 
+  [ListAccessKeys](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.ListAccessKeys) 
+  [GetAccessKeyLastUsed](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.GetAccessKeyLastUsed) 
+  [UpdateAccessKey](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.UpdateAccessKey) 
+  [DeleteAccessKey](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.DeleteAccessKey) 

## Prerequisites

+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with IAM access keys. To learn more, see [Managing Access Keys for IAM Users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html) in the IAM User Guide.

## Create a New IAM Access Key


This code creates a new IAM access key for the IAM user named IAM\$1USER\$1NAME.

Create a new Go file named `iam_createaccesskey.go`. You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
package main

import (
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"
)
```

Set up the session.

```
func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Call `CreateAccessKey` and print the results.

```
    result, err := svc.CreateAccessKey(&iam.CreateAccessKeyInput{
        UserName: aws.String("IAM_USER_NAME"),
    })

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Println("Success", *result.AccessKey)
}
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/iam/iam_createaccesskey.go) on GitHub.

## List a User’s Access Keys


In this example, you get a list of the access keys for a user and print the list to the console.

Create a new Go file named `iam_listaccesskeys.go`. You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
package main

import (
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"
)
```

Set up a new IAM client.

```
func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Call `ListAccessKeys` and print the results.

```
    result, err := svc.ListAccessKeys(&iam.ListAccessKeysInput{
        MaxItems: aws.Int64(5),
        UserName: aws.String("IAM_USER_NAME"),
    })

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Println("Success", result)
}
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/iam/iam_listaccesskeys.go) on GitHub.

## Get the Last Use for an Access Key


In this example, you find out when an access key was last used.

Create a new Go file named `iam_accesskeylastused.go`. You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
package main

import (
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"
)
```

Set up a new IAM client.

```
func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Call `GetAccessKeyLastUsed`, passing in the access key ID, and print the results.

```
    result, err := svc.GetAccessKeyLastUsed(&iam.GetAccessKeyLastUsedInput{
        AccessKeyId: aws.String("ACCESS_KEY_ID"),
    })

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Println("Success", *result.AccessKeyLastUsed)
}
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/iam/iam_accesskeylastused.go) on GitHub.

## Update Access Key Status


In this example, you delete an IAM user.

Create a new Go file with the name `iam_updateaccesskey.go`. You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
package main

import (
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"
)
```

Set up a new IAM client.

```
func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Call `UpdateAccessKey`, passing in the access key ID, status (making it active in this case), and user name.

```
    _, err = svc.UpdateAccessKey(&iam.UpdateAccessKeyInput{
        AccessKeyId: aws.String("ACCESS_KEY_ID"),
        Status:      aws.String(iam.StatusTypeActive),
        UserName:    aws.String("USER_NAME"),
    })

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Println("Access Key updated")
}
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/iam/iam_updateaccesskey.go) on GitHub.

## Delete an Access Key


In this example, you delete an access key.

Create a new Go file named `iam_deleteaccesskey.go`. You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
package main

import (
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"
)
```

Set up a new IAM client.

```
func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Call `DeleteAccessKey`, passing in the access key ID and user name.

```
    result, err := svc.DeleteAccessKey(&iam.DeleteAccessKeyInput{
        AccessKeyId: aws.String("ACCESS_KEY_ID"),
        UserName:    aws.String("USER_NAME"),
    })

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Println("Success", result)
}
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/iam/iam_deleteaccesskey.go) on GitHub.

# Managing IAM Account Aliases


This Go example shows you how to create, list, and delete IAM account aliases. You can download complete versions of these example files from the [aws-doc-sdk-examples](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/go/example_code/iam) repository on GitHub.

## Scenario


You can use a series of Go routines to manage aliases in IAM. The routines use the AWS SDK for Go IAM client methods that follow:
+  [CreateAccountAlias](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.CreateAccountAlias) 
+  [ListAccountAliases](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.ListAccountAliases) 
+  [DeleteAccountAlias](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.DeleteAccountAlias) 

## Prerequisites

+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with IAM account aliases. To learn more, see [Your AWS account ID and Its Alias](https://docs.aws.amazon.com/IAM/latest/UserGuide/console_account-alias.html) in the IAM User Guide.

## Create a New IAM Account Alias


This code creates a new IAM user.

Create a new Go file named `iam_createaccountalias.go`. You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
package main

import (
    "fmt"
    "os"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"
)
```

Set up a session and an IAM client.

```
func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

The code takes the new alias as an argument, and then calls `CreateAccountAlias` with the alias name.

```
    _, err = svc.CreateAccountAlias(&iam.CreateAccountAliasInput{
        AccountAlias: &os.Args[1],
    })

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Printf("Account alias %s has been created\n", os.Args[1])
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/iam/iam_createaccountalias.go) on GitHub.

## List IAM Account Aliases


This code lists the aliases for your IAM account.

Create a new Go file named `iam_listaccountaliases.go`. You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
package main

import (
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"
)
```

Set up a session and an IAM client.

```
func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

The code calls `ListAccountAliases`, specifying to return a maximum of 10 items.

```
    result, err := svc.ListAccountAliases(&iam.ListAccountAliasesInput{
        MaxItems: aws.Int64(10),
    })

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    for i, alias := range result.AccountAliases {
        if alias == nil {
            continue
        }
        fmt.Printf("Alias %d: %s\n", i, *alias)
    }
}
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/iam/iam_listaccountaliases.go) on GitHub.

## Delete an IAM Account Alias


This code deletes a specified IAM account alias.

Create a new Go file with the name `iam_deleteaccountalias.go`. You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
package main

import (
    "fmt"
    "os"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"
)
```

Set up a session and an IAM client.

```
func main() {
    // Initialize a session in us-west-2 that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials.
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

The code calls `ListAccountAliases`, specifying to return a maximum of 10 items.

```
    _, err = svc.DeleteAccountAlias(&iam.DeleteAccountAliasInput{
        AccountAlias: &os.Args[1],
    })

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Printf("Alias %s has been deleted\n", os.Args[1])
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/iam/iam_deleteaccountalias.go) on GitHub.

# Working with IAM Policies


This Go example shows you how to create, get, attach, and detach IAM policies. You can download complete versions of these example files from the [aws-doc-sdk-examples](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/go/example_code/iam) repository on GitHub.

## Scenario


You grant permissions to a user by creating a policy, which is a document that lists the actions that a user can perform and the resources those actions can affect. Any actions or resources that are not explicitly allowed are denied by default. Policies can be created and attached to users, groups of users, roles assumed by users, and resources.

In this example, you use a series of Go routines to manage policies in IAM. The routines use the AWS SDK for Go IAM client methods that follow:
+  [CreatePolicy](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.CreatePolicy) 
+  [GetPolicy](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.GetPolicy) 
+  [ListAttachedRolePolicies](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.ListAttachedRolePolicies) 
+  [AttachRolePolicy](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.AttachRolePolicy) 
+  [DetachRolePolicy](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.DetachRolePolicy) 

## Prerequisites

+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with IAM policies. To learn more, see [Overview of Access Management: Permissions and Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction_access-management.html) in the IAM User Guide.

## Create an IAM Policy


This code creates a new IAM Policy. Create a new Go file named `iam_createpolicy.go`.

You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
package main

import (
    "encoding/json"
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"
)
```

Define two structs. The first is the definition of the policies to upload to IAM.

```
type PolicyDocument struct {
    Version   string
    Statement []StatementEntry
}
```

The second dictates what this policy will allow or disallow.

```
type StatementEntry struct {
    Effect   string
    Action   []string
    Resource string
}
```

Set up the session and IAM client.

```
func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Build the policy document using the structures defined earlier.

```
    policy := PolicyDocument{
        Version: "2012-10-17",		 	 	 
        Statement: []StatementEntry{
            StatementEntry{
                Effect: "Allow",
                Action: []string{
                    "logs:CreateLogGroup", // Allow for creating log groups
                },
                Resource: "RESOURCE ARN FOR logs:*",
            },
            StatementEntry{
                Effect: "Allow",
                // Allows for DeleteItem, GetItem, PutItem, Scan, and UpdateItem
                Action: []string{
                    "dynamodb:DeleteItem",
                    "dynamodb:GetItem",
                    "dynamodb:PutItem",
                    "dynamodb:Scan",
                    "dynamodb:UpdateItem",
                },
                Resource: "RESOURCE ARN FOR dynamodb:*",
            },
        },
    }
```

Marshal the policy to JSON and pass to `CreatePolicy`.

```
    b, err := json.Marshal(&policy)
    if err != nil {
        fmt.Println("Error marshaling policy", err)
        return
    }

    result, err := svc.CreatePolicy(&iam.CreatePolicyInput{
        PolicyDocument: aws.String(string(b)),
        PolicyName:     aws.String("myDynamodbPolicy"),
    })

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Println("New policy", result)
}
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/iam/iam_createpolicy.go) on GitHub.

## Get an IAM Policy


In this example, you retrieve an existing policy from IAM. Create a new Go file named `iam_getpolicy.go`.

You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
package main

import (
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"
)
```

Set up a new IAM client.

```
func main() {
    // Initialize a session in us-west-2 that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials.
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Call `GetPolicy`, passing in the ARN for the policy (which is hard coded in this example), and print the results.

```
    arn := "arn:aws:iam::aws:policy/AWSLambdaExecute"
    result, err := svc.GetPolicy(&iam.GetPolicyInput{
        PolicyArn: &arn,
    })

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Printf("%s - %s\n", arn, *result.Policy.Description)
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/iam/iam_getpolicy.go) on GitHub.

## Attach a Managed Role Policy


In this example, you attach an IAM managed role policy. Create a new Go file named `iam_attachuserpolicy.go`. You’ll call the `ListAttachedRolePolicies` method of the IAM service object, which returns an array of managed policies.

Then, you’ll check the array members to see if the policy you want to attach to the role is already attached. If the policy isn’t attached, you’ll call the `AttachRolePolicy` method to attach it.

You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
package main

import (
    "fmt"
    "os"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"
)
```

Set up a new IAM client.

```
func main() {
    // Initialize a session in us-west-2 that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials.
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Declare variables to hold the name and ARN of the policy.

```
    var pageErr error
    policyName := "AmazonDynamoDBFullAccess"
    policyArn := "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess"
```

Paginate through all the role policies. If your role exists on any role policy, you set the `pageErr` and return `false`, stopping the pagination.

```
    err = svc.ListAttachedRolePoliciesPages(
        &iam.ListAttachedRolePoliciesInput{
            RoleName: &os.Args[1],
        },
        func(page *iam.ListAttachedRolePoliciesOutput, lastPage bool) bool {
            if page != nil && len(page.AttachedPolicies) > 0 {
                for _, policy := range page.AttachedPolicies {
                    if *policy.PolicyName == policyName {
                        pageErr = fmt.Errorf("%s is already attached to this role", policyName)
                        return false
                    }
                }
                // We should keep paginating because we did not find our role
                return true
            }
            return false
        },
    )
```

If your role policy is not attached already, call `AttachRolePolicy`.

```
    if pageErr != nil {
        fmt.Println("Error", pageErr)
        return
    }

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    _, err = svc.AttachRolePolicy(&iam.AttachRolePolicyInput{
        PolicyArn: &policyArn,
        RoleName:  &os.Args[1],
    })

    if err != nil {
        fmt.Println("Unable to attach role policy to role")
        return
    }
    fmt.Println("Role attached successfully")
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/iam/iam_attachuserpolicy.go) on GitHub.

## Detach a Managed Role Policy


In this example, you detach a role policy. Once again, you call the `ListAttachedRolePolicies` method of the IAM service object, which returns an array of managed policies.

Then, check the array members to see if the policy you want to detach from the role is attached. If the policy is attached, call the `DetachRolePolicy` method to detach it.

Create a new Go file named `iam_detachuserpolicy.go`. You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
package main

import (
    "fmt"
    "os"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"
)
```

Set up a new IAM client.

```
func main() {
    // Initialize a session in us-west-2 that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials.
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Declare variables to hold the name and ARN of the policy.

```
    foundPolicy := false
    policyName := "AmazonDynamoDBFullAccess"
    policyArn := "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess"
```

Paginate through all the role policies. If the role exists on any role policy, you stop iterating and detach the role.

```
    err = svc.ListAttachedRolePoliciesPages(
        &iam.ListAttachedRolePoliciesInput{
            RoleName: &os.Args[1],
        },
        func(page *iam.ListAttachedRolePoliciesOutput, lastPage bool) bool {
            if page != nil && len(page.AttachedPolicies) > 0 {
                for _, policy := range page.AttachedPolicies {
                    if *policy.PolicyName == policyName {
                        foundPolicy = true
                        return false
                    }
                }
                return true
            }
            return false
        },
    )

    if err != nil {
        fmt.Println("Error", err)
        return
    }

    if !foundPolicy {
        fmt.Println("Policy was not attached to role")
        return
    }

    _, err = svc.DetachRolePolicy(&iam.DetachRolePolicyInput{
        PolicyArn: &policyArn,
        RoleName:  &os.Args[1],
    })

    if err != nil {
        fmt.Println("Unable to detach role policy to role")
        return
    }
    fmt.Println("Role detached successfully")
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/iam/iam_detachuserpolicy.go) on GitHub.

# Working with IAM Server Certificates


This Go example shows you how to carry out basic tasks for managing server certificate HTTPS connections with the AWS SDK for Go.

You can download complete versions of these example files from the [aws-doc-sdk-examples](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/go/example_code/iam) repository on GitHub.

## Scenario


To enable HTTPS connections to your website or application on AWS, you need an SSL/TLS server certificate. To use a certificate that you obtained from an external provider with your website or application on AWS, you must upload the certificate to IAM or import it into AWS Certificate Manager.

In this example, you use a series of Go routines to manage policies in IAM. The routines use the AWS SDK for GoIAM client methods that follow:
+  [ListServerCertificates](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.ListServerCertificates) 
+  [GetServerCertificate](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.GetServerCertificate) 
+  [UpdateServerCertificate](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.UpdateServerCertificate) 
+  [DeleteServerCertificate](https://docs.aws.amazon.com/sdk-for-go/api/service/iam/#IAM.DeleteServerCertificate) 

## Prerequisites

+ You have [set up](setting-up.md) and [configured](configuring-sdk.md) the AWS SDK for Go.
+ You are familiar with server certificates. To learn more, see [Working with Server Certificates](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html) in the IAM User Guide.

## List Your Server Certificates


This code lists your certificates. Create a new Go file named `iam_listservercerts.go`.

You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
import (
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"
)
```

Set up the session and IAM client.

```
func main() {
    // Initialize a session in us-west-2 that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials.
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Call `ListServerCertificates` and print the details.

```
    result, err := svc.ListServerCertificates(nil)
    if err != nil {
        fmt.Println("Error", err)
        return
    }

    for i, metadata := range result.ServerCertificateMetadataList {
        if metadata == nil {
            continue
        }

        fmt.Printf("Metadata %d: %v\n", i, metadata)
    }
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/iam/iam_listservercerts.go) on GitHub.

## Get a Server Certificate


In this example, you retrieve an existing server certificate.

Create a new Go file named `iam_getservercert.go`. You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
package main

import (
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"
)
```

Set up a new IAM client.

```
func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Call `GetServerCertificate`, passing the name of the certificate, and print the results.

```
    result, err := svc.GetServerCertificate(&iam.GetServerCertificateInput{
        ServerCertificateName: aws.String("CERTIFICATE_NAME"),
    })
    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Println("ServerCertificate:", result)
}
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/iam/iam_getservercert.go) on GitHub.

## Update a Server Certificate


In this example, you update an existing server certificate.

Create a new Go file named `iam_updateservercert.go`. You call the `UpdateServerCertificate` method of the IAM service object to change the name of the certificate.

You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
package main

import (
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"
)
```

Set up a new IAM client.

```
func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Update the certificate name.

```
    _, err = svc.UpdateServerCertificate(&iam.UpdateServerCertificateInput{
        ServerCertificateName:    aws.String("CERTIFICATE_NAME"),
        NewServerCertificateName: aws.String("NEW_CERTIFICATE_NAME"),
    })
    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Println("Server certificate updated")
}
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/iam/iam_updateservercert.go) on GitHub.

## Delete a Server Certificate


In this example, you delete an existing server certificate.

Create a new Go file named `iam_deleteservercert.go`. You call the `DeleteServerCertificate` method of the IAM service object to change the name of the certificate.

You must import the relevant Go and AWS SDK for Go packages by adding the following lines.

```
package main

import (
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/iam"
)
```

Set up a new IAM client.

```
func main() {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-west-2")},
    )

    // Create a IAM service client.
    svc := iam.New(sess)
```

Call the method to delete the certificate, specifying the name of certificate.

```
    _, err = svc.DeleteServerCertificate(&iam.DeleteServerCertificateInput{
        ServerCertificateName: aws.String("CERTIFICATE_NAME"),
    })
    if err != nil {
        fmt.Println("Error", err)
        return
    }

    fmt.Println("Server certificate deleted")
}
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/iam/iam_deleteservercert.go) on GitHub.