AWS SDK 또는 CLI로 PutUserPolicy 사용하기

AWS SDK 또는 CLI로 PutUserPolicy 사용하기

다음 코드 예시는 PutUserPolicy을(를) 사용하는 방법을 보여줘요.

액션 예시는 더 큰 프로그램에서 발췌한 코드 조각이라, 실제 프로그램 컨텍스트 안에서 실행돼야 해요.

출처: 문서

본문

AWS CLI

IAM 사용자에 정책을 연결하려면

다음 put-user-policy 명령은 Bob IAM 사용자에게 정책을 연결해요.

aws iam put-user-policy \
    --user-name
Bob
 \
    --policy-name
ExamplePolicy
 \
    --policy-document
file://AdminPolicy.json

이 명령은 출력이 없어요.

정책은 AdminPolicy.json 파일에 JSON 문서로 정의돼 있어요. (파일 이름과 확장자는 의미가 없어요.)

더 자세한 내용은 AWS IAM 사용자 가이드의 'IAM 자격 증명 권한 추가·제거' 문서를 참고하세요.

API 상세 내용은 AWS CLI Command Reference의 PutUserPolicy 문서를 참고하세요.

SDK for Go V2

참고: GitHub에 더 많은 내용이 있어요. AWS Code Examples Repository에서 전체 예시를 찾아 실행·설정 방법을 배울 수 있어요.

import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct
{

	IamClient *iam.Client
}



// CreateUserPolicy adds an inline policy to a user. This example creates a policy that
// grants a list of actions on a specified role.
// PolicyDocument shows how to work with a policy document as a data structure and
// serialize it to JSON by using Go's JSON marshaler.
func (wrapper UserWrapper) CreateUserPolicy(ctx context.Context, userName string, policyName string, actions []string,
	roleArn string) error
{

	policyDoc := PolicyDocument
{

		Version: "2012-10-17",
		Statement: []PolicyStatement
{
{

			Effect:   "Allow",
			Action:   actions,
			Resource: aws.String(roleArn),
		}},
	}
	policyBytes, err := json.Marshal(policyDoc)
	if err != nil
{

		log.Printf("Couldn't create policy document for %v. Here's why: %v\n", roleArn, err)
		return err
	}
	_, err = wrapper.IamClient.PutUserPolicy(ctx, &iam.PutUserPolicyInput
{

		PolicyDocument: aws.String(string(policyBytes)),
		PolicyName:     aws.String(policyName),
		UserName:       aws.String(userName),
	})
	if err != nil
{

		log.Printf("Couldn't create policy for user %v. Here's why: %v\n", userName, err)
	}
	return err
}

API 상세 내용은 AWS SDK for Go API Reference의 PutUserPolicy 문서를 참고하세요.

Tools for PowerShell V4

예시 1: 이 예시는 EC2AccessPolicy 인라인 정책을 만들고 Bob IAM 사용자에 포함해요. 같은 이름의 인라인 정책이 이미 있으면 덮어써요. JSON 정책 내용은 EC2AccessPolicy.json 파일에서 가져와요. JSON 파일 내용을 제대로 처리하려면 -Raw 파라미터를 꼭 사용해야 해요.

Write-IAMUserPolicy -UserName Bob -PolicyName EC2AccessPolicy -PolicyDocument (Get-Content -Raw EC2AccessPolicy.json)

API 상세 내용은 AWS Tools for PowerShell Cmdlet Reference (V4)의 PutUserPolicy 문서를 참고하세요.

Tools for PowerShell V5

예시 1: 이 예시는 EC2AccessPolicy 인라인 정책을 만들고 Bob IAM 사용자에 포함해요. 같은 이름의 인라인 정책이 이미 있으면 덮어써요. JSON 정책 내용은 EC2AccessPolicy.json 파일에서 가져와요. JSON 파일 내용을 제대로 처리하려면 -Raw 파라미터를 꼭 사용해야 해요.

Write-IAMUserPolicy -UserName Bob -PolicyName EC2AccessPolicy -PolicyDocument (Get-Content -Raw EC2AccessPolicy.json)

API 상세 내용은 AWS Tools for PowerShell Cmdlet Reference (V5)의 PutUserPolicy 문서를 참고하세요.

SDK for Ruby

참고: GitHub에 더 많은 내용이 있어요. AWS Code Examples Repository에서 전체 예시를 찾아 실행·설정 방법을 배울 수 있어요.

  # Creates an inline policy for a specified user.
  # @param username [String] The name of the IAM user.
  # @param policy_name [String] The name of the policy to create.
  # @param policy_document [String] The JSON policy document.
  # @return [Boolean]
  def create_user_policy(username, policy_name, policy_document)
    @iam_client.put_user_policy(
{

                                  user_name: username,
                                  policy_name: policy_name,
                                  policy_document: policy_document
                                })
    @logger.info("Policy #
{
policy_name} created for user #
{
username}.")
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Couldn't create policy #
{
policy_name} for user #
{
username}. Here's why:")
    @logger.error("\t#
{
e.code}: #
{
e.message}")
    false
  end

API 상세 내용은 AWS SDK for Ruby API Reference의 PutUserPolicy 문서를 참고하세요.

SDK for Swift

참고: GitHub에 더 많은 내용이 있어요. AWS Code Examples Repository에서 전체 예시를 찾아 실행·설정 방법을 배울 수 있어요.

import AWSIAM
import AWSS3


    func putUserPolicy(policyDocument: String, policyName: String, user: IAMClientTypes.User) async throws
{

        let input = PutUserPolicyInput(
            policyDocument: policyDocument,
            policyName: policyName,
            userName: user.userName
        )
        do
{

            _ = try await iamClient.putUserPolicy(input: input)
        } catch
{

            print("ERROR: putUserPolicy:", dump(error))
            throw error
        }
    }

API 상세 내용은 AWS SDK for Swift API reference의 PutUserPolicy 문서를 참고하세요.

더 알아보기 (Learn more)