Go以Google API Client Libraries來建立IAM Policy。
事前要求
參考「Golang 建立AWS IAM API client」建立IAM API client。
建立Policy
呼叫iam.Client.CreatePolicy
,傳入iam.CreatePolicyInput
參數建立policy。
iam.CreatePolicyInput
欄位如下:
PolicyName
- Policy的名稱。PolicyDocument
- JSON格式的Policy文件。
main.go
package main
import (
"context"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/iam"
)
func main() {
ctx := context.TODO()
client := NewIamClient(ctx)
input := &iam.CreatePolicyInput{
PolicyName: aws.String("S3Access"),
PolicyDocument: aws.String(
`{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "S3Access",
"Effect": "Allow",
"Action": [
"s3:*"
],
"Resource": "*"
}
]
}`,
),
}
output, err := client.CreatePolicy(ctx, input)
if err != nil {
panic(err)
}
fmt.Println(*output.Policy.Arn) // arn:aws:iam::[ACCOUNT_ID]:policy/S3Access
}
func NewIamClient(ctx context.Context) *iam.Client {
cfg, err := config.LoadDefaultConfig(
ctx,
config.WithRegion("ap-northeast-1"),
)
if err != nil {
panic(err)
}
return iam.NewFromConfig(cfg)
}
測試
執行印出以下:
arn:aws:iam::[ACCOUNT_ID]:policy/S3Access
在AWS console IAM服務檢視建立的Policy。
沒有留言:
張貼留言