

# AWS SDK または CLI で `PutUserPolicy` を使用する
<a name="iam_example_iam_PutUserPolicy_section"></a>

次のサンプルコードは、`PutUserPolicy` を使用する方法を説明しています。

アクション例は、より大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。次のコード例で、このアクションのコンテキストを確認できます。
+  [基本を学ぶ](iam_example_iam_Scenario_CreateUserAssumeRole_section.md) 

------
#### [ CLI ]

**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 ID アクセス許可の追加および削除](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[PutUserPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/put-user-policy.html)」を参照してください。

------
#### [ Go ]

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
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 リファレンス*」の「[PutUserPolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.PutUserPolicy)」を参照してください。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**例 1: この例では、`EC2AccessPolicy` という名前のインラインポリシーを作成し、IAM ユーザー `Bob` に埋め込みます。同じ名前のインラインポリシーが既に存在する場合、上書きされます。JSON ポリシーの内容は、ファイル `EC2AccessPolicy.json` から取得されます。JSON ファイルの内容を正常に処理するには、`-Raw` パラメータを使用する必要があることに注意してください。**  

```
Write-IAMUserPolicy -UserName Bob -PolicyName EC2AccessPolicy -PolicyDocument (Get-Content -Raw EC2AccessPolicy.json)
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutUserPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、`EC2AccessPolicy` という名前のインラインポリシーを作成し、IAM ユーザー `Bob` に埋め込みます。同じ名前のインラインポリシーが既に存在する場合、上書きされます。JSON ポリシーの内容は、ファイル `EC2AccessPolicy.json` から取得されます。JSON ファイルの内容を正常に処理するには、`-Raw` パラメータを使用する必要があることに注意してください。**  

```
Write-IAMUserPolicy -UserName Bob -PolicyName EC2AccessPolicy -PolicyDocument (Get-Content -Raw EC2AccessPolicy.json)
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet リファレンス (V5)*」の「[PutUserPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
  # 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 リファレンス*」の「[PutUserPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/PutUserPolicy)」を参照してください。

------
#### [ Swift ]

**SDK for Swift**  
 GitHub には、その他のリソースもあります。[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)で完全な例を見つけて、設定と実行の方法を確認してください。

```
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 リファレンス」の「[PutUserPolicy](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/putuserpolicy(input:))」を参照してください。

------

AWS SDK デベロッパーガイドとコード例の詳細なリストについては、[このサービスを AWS SDK で使用する](sdk-general-information-section.md) を参照してください。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。