Skip to content

Commit 8be7656

Browse files
authored
Merge pull request #1480 from awsdocs/doug-sts-gov2
Added STS examples in Go v2
2 parents 25442d1 + 989510a commit 8be7656

File tree

6 files changed

+246
-0
lines changed

6 files changed

+246
-0
lines changed

gov2/sts/AssumeRole/AssumeRolev2.go

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
// SPDX - License - Identifier: Apache - 2.0
3+
// snippet-start:[sts.go-v2.AssumeRole]
4+
package main
5+
6+
import (
7+
"context"
8+
"flag"
9+
"fmt"
10+
11+
"github.com/aws/aws-sdk-go-v2/config"
12+
"github.com/aws/aws-sdk-go-v2/service/sts"
13+
)
14+
15+
// STSAssumeRoleAPI defines the interface for the AssumeRole function.
16+
// We use this interface to test the function using a mocked service.
17+
type STSAssumeRoleAPI interface {
18+
AssumeRole(ctx context.Context,
19+
params *sts.AssumeRoleInput,
20+
optFns ...func(*sts.Options)) (*sts.AssumeRoleOutput, error)
21+
}
22+
23+
// TakeRole gets temporary security credentials to access resources.
24+
// Inputs:
25+
// c is the context of the method call, which includes the AWS Region.
26+
// api is the interface that defines the method call.
27+
// input defines the input arguments to the service call.
28+
// Output:
29+
// If successful, an AssumeRoleOutput object containing the result of the service call and nil.
30+
// Otherwise, nil and an error from the call to AssumeRole.
31+
func TakeRole(c context.Context, api STSAssumeRoleAPI, input *sts.AssumeRoleInput) (*sts.AssumeRoleOutput, error) {
32+
result, err := api.AssumeRole(c, input)
33+
34+
return result, err
35+
}
36+
37+
func main() {
38+
roleARN := flag.String("r", "", "The Amazon Resource Name (ARN) of the role to assume")
39+
sessionName := flag.String("s", "", "The name of the session")
40+
41+
if *roleARN == "" || *sessionName == "" {
42+
fmt.Println("You must supply a role ARN and session name")
43+
fmt.Println("-r ROLE-ARN -s SESSION-NAME")
44+
return
45+
}
46+
47+
cfg, err := config.LoadDefaultConfig()
48+
if err != nil {
49+
panic("configuration error, " + err.Error())
50+
}
51+
52+
client := sts.NewFromConfig(cfg)
53+
54+
input := &sts.AssumeRoleInput{
55+
RoleArn: roleARN,
56+
RoleSessionName: sessionName,
57+
}
58+
59+
result, err := TakeRole(context.Background(), client, input)
60+
if err != nil {
61+
fmt.Println("Got an error assuming the role:")
62+
fmt.Println(err)
63+
return
64+
}
65+
66+
fmt.Println(result.AssumedRoleUser)
67+
}
68+
69+
// snippet-end:[sts.go-v2.AssumeRole]
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"encoding/json"
6+
"errors"
7+
"fmt"
8+
"io/ioutil"
9+
"testing"
10+
"time"
11+
12+
"github.com/aws/aws-sdk-go-v2/service/sts"
13+
"github.com/aws/aws-sdk-go-v2/service/sts/types"
14+
"github.com/aws/aws-sdk-go/aws"
15+
)
16+
17+
type STSAssumeRoleImpl struct{}
18+
19+
func (dt STSAssumeRoleImpl) AssumeRole(ctx context.Context,
20+
params *sts.AssumeRoleInput,
21+
optFns ...func(*sts.Options)) (*sts.AssumeRoleOutput, error) {
22+
23+
user := types.AssumedRoleUser{
24+
Arn: aws.String("aws-docs-example-user-arn"),
25+
AssumedRoleId: aws.String("aws-docs-example-userID"),
26+
}
27+
28+
output := &sts.AssumeRoleOutput{
29+
AssumedRoleUser: &user,
30+
}
31+
32+
return output, nil
33+
}
34+
35+
type Config struct {
36+
RoleArn string `json:"RoleArn"`
37+
SessionName string `json:"SessionName"`
38+
}
39+
40+
var configFileName = "config.json"
41+
42+
var globalConfig Config
43+
44+
func populateConfiguration(t *testing.T) error {
45+
content, err := ioutil.ReadFile(configFileName)
46+
if err != nil {
47+
return err
48+
}
49+
50+
text := string(content)
51+
52+
err = json.Unmarshal([]byte(text), &globalConfig)
53+
if err != nil {
54+
return err
55+
}
56+
57+
if globalConfig.RoleArn == "" || globalConfig.SessionName == "" {
58+
msg := "You must specify a value for RoleArn and SessionName in " + configFileName
59+
return errors.New(msg)
60+
}
61+
62+
return nil
63+
}
64+
65+
func TestAssumeRole(t *testing.T) {
66+
thisTime := time.Now()
67+
nowString := thisTime.Format("2006-01-02 15:04:05 Monday")
68+
t.Log("Starting unit test at " + nowString)
69+
70+
err := populateConfiguration(t)
71+
if err != nil {
72+
t.Fatal(err)
73+
}
74+
75+
api := &STSAssumeRoleImpl{}
76+
77+
input := &sts.AssumeRoleInput{
78+
RoleArn: &globalConfig.RoleArn,
79+
RoleSessionName: &globalConfig.SessionName,
80+
}
81+
82+
resp, err := TakeRole(context.Background(), api, input)
83+
if err != nil {
84+
fmt.Println("Got an error assuming the role:")
85+
fmt.Println(err)
86+
return
87+
}
88+
89+
t.Log("User ARN: " + *resp.AssumedRoleUser.Arn)
90+
t.Log("User role ID: " + *resp.AssumedRoleUser.AssumedRoleId)
91+
}

gov2/sts/AssumeRole/README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
### AssumeRole/AssumeRolev2.go
2+
3+
This example gets temporary security credentials to access resources.
4+
5+
`go run AssumeRolev2.go -r ROLE-ARN -s SESSION-NAME`
6+
7+
- _ROLE-ARN_ is the ARN of the role to assume.
8+
- _SESSION-NAME_ is the name of the assumed role session.
9+
10+
The unit test accepts similar values in _config.json_.

gov2/sts/AssumeRole/config.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"RoleArn": "aws-docs-example-role-arn",
3+
"SessionName": "aws-docs-example-session-name"
4+
}

gov2/sts/README.md

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# AWS SDK for Go V2 code examples for AWS STS.
2+
3+
## Purpose
4+
5+
These examples demonstrates how to perform several AWS Security Token Service (AWS STS)
6+
operations using version 2 of the AWS SDK for Go.
7+
8+
## Prerequisites
9+
10+
You must have an AWS account, and have your default credentials and AWS Region
11+
configured as described in
12+
[Configuring the AWS SDK for Go](https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html)
13+
in the AWS SDK for Go Developer Guide.
14+
15+
## Running the code
16+
17+
### AssumeRole/AssumeRolev2.go
18+
19+
This example gets temporary security credentials to access resources.
20+
21+
`go run AssumeRolev2.go -r ROLE-ARN -s SESSION-NAME`
22+
23+
- _ROLE-ARN_ is the ARN of the role to assume.
24+
- _SESSION-NAME_ is the name of the assumed role session.
25+
26+
The unit test accepts similar values in _config.json_.
27+
28+
### Notes
29+
30+
- We recommend that you grant this code least privilege,
31+
or at most the minimum permissions required to perform the task.
32+
For more information, see
33+
[Grant Least Privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)
34+
in the AWS Identity and Access Management User Guide.
35+
- This code has not been tested in all AWS Regions.
36+
Some AWS services are available only in specific
37+
[Regions](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services).
38+
- Running this code might result in charges to your AWS account.
39+
40+
## Running the unit tests
41+
42+
Unit tests should delete any resources they create.
43+
However, they might result in charges to your
44+
AWS account.
45+
46+
To run a unit test, enter:
47+
48+
`go test`
49+
50+
You should see something like the following,
51+
where PATH is the path to the folder containing the Go files:
52+
53+
```sh
54+
PASS
55+
ok PATH 6.593s
56+
```
57+
58+
If you want to see any log messages, enter:
59+
60+
`go test -v`
61+
62+
You should see some additional log messages.
63+
The last two lines should be similar to the previous output shown.
64+
65+
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0

gov2/sts/metadata.yaml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
files:
2+
- path: TakeRole/TakeRolev2.go
3+
services:
4+
- sts
5+
- path: TakeRole/TakeRolev2_test.go
6+
services:
7+
- sts

0 commit comments

Comments
 (0)