//snippet-sourcedescription:[AttachRolePolicy.java demonstrates how to attach a policy to an existing AWS Identity and Access Management (IAM) role.]
//snippet-keyword:[AWS SDK for Java v2]
//snippet-keyword:[Code Sample]
//snippet-service:[IAM]
//snippet-sourcetype:[full-example]
//snippet-sourcedate:[11/02/2020]
//snippet-sourceauthor:[scmacdon-aws]

/*
   Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   SPDX-License-Identifier: Apache-2.0
*/
package com.example.iam;

// snippet-start:[iam.java2.attach_role_policy.import]
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.services.iam.model.AttachRolePolicyRequest;
import software.amazon.awssdk.services.iam.model.AttachedPolicy;
import software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesRequest;
import software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
// snippet-end:[iam.java2.attach_role_policy.import]

public class AttachRolePolicy {

    public static void main(String[] args) {

        final String USAGE = "\n" +
                "Usage:\n" +
                "    AttachRolePolicy <roleName> <policyArn> \n\n" +
                "Where:\n" +
                "    roleName - a role name that you can obtain from the AWS Management Console. \n\n" +
                "    policyArn - a policy ARN that you can obtain from the AWS Management Console. \n\n" ;

        if (args.length != 2) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String roleName = args[0];
        String policyArn = args[1];

        // snippet-start:[iam.java2.attach_role_policy.client]
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();
        // snippet-end:[iam.java2.attach_role_policy.client]

        attachIAMRolePolicy(iam, roleName, policyArn);
        iam.close();
    }

    // snippet-start:[iam.java2.attach_role_policy.main]
    public static void attachIAMRolePolicy(IamClient iam,String roleName, String policyArn ) {

        try {

            List<AttachedPolicy> matchingPolicies = new ArrayList<>();

            boolean done = false;
            String newMarker = null;

            while(!done) {

                ListAttachedRolePoliciesResponse response;

                if (newMarker == null) {
                    ListAttachedRolePoliciesRequest request =
                        ListAttachedRolePoliciesRequest.builder()
                                .roleName(roleName).build();
                    response = iam.listAttachedRolePolicies(request);
                } else {
                    ListAttachedRolePoliciesRequest request =
                        ListAttachedRolePoliciesRequest.builder()
                                .roleName(roleName)
                                .marker(newMarker).build();
                    response = iam.listAttachedRolePolicies(request);
                }

                matchingPolicies.addAll(
                    response.attachedPolicies()
                            .stream()
                            .filter(p -> p.policyName().equals(roleName))
                            .collect(Collectors.toList()));

                if(!response.isTruncated()) {
                    done = true;

                } else {
                    newMarker = response.marker();
                }
            }

                if (matchingPolicies.size() > 0) {
                    System.out.println(roleName +
                        " policy is already attached to this role.");
                return;
            }

            // snippet-start:[iam.java2.attach_role_policy.attach]
            AttachRolePolicyRequest attachRequest =
                AttachRolePolicyRequest.builder()
                        .roleName(roleName)
                        .policyArn(policyArn).build();

            iam.attachRolePolicy(attachRequest);

            // snippet-end:[iam.java2.attach_role_policy.attach]
            System.out.println("Successfully attached policy " + policyArn +
                " to role " + roleName);

         } catch (IamException e) {
                System.err.println(e.awsErrorDetails().errorMessage());
                System.exit(1);
          }
        // snippet-end:[iam.java2.attach_role_policy.main]
     System.out.println("Done");
    }
}

@@ -1090,45 +1090,8 @@
 t;%0D%0A
-import java.util.stream.Collectors;%0D%0A
 // s
@@ -2277,16 +2277,17 @@
 ent iam,
+ 
 String r
@@ -2412,227 +2412,8 @@
 );%0D%0A
-%0D%0A            boolean done = false;%0D%0A            String newMarker = null;%0D%0A%0D%0A            while(!done) %7B%0D%0A%0D%0A                ListAttachedRolePoliciesResponse response;%0D%0A%0D%0A                if (newMarker == null) %7B%0D%0A        
     
@@ -2465,33 +2465,8 @@
 st =
-%0D%0A                       
  Lis
@@ -2521,36 +2521,24 @@
             
-            
 .roleName(ro
@@ -2544,25 +2544,16 @@
 oleName)
-.build();
 %0D%0A      
@@ -2570,482 +2570,169 @@
     
-response = iam.listAttachedRolePolicies(request);%0D%0A                %7D else %7B%0D%0A                    ListAttachedRolePoliciesRequest request =%0D%0A                        ListAttachedRolePoliciesRequest.builder()%0D%0A                                .roleName(roleName)%0D%0A                                .marker(newMarker).build();%0D%0A                    response = iam.listAttachedRolePolicies(request);%0D%0A                %7D%0D%0A%0D%0A                matchingPolicies.addAll(%0D%0A                   
+.build();%0D%0A%0D%0A            ListAttachedRolePoliciesResponse  response = iam.listAttachedRolePolicies(request);%0D%0A            List%3CAttachedPolicy%3E attachedPolicies =
  res
@@ -2755,16 +2755,19 @@
 licies()
+;%0D%0A
 %0D%0A      
@@ -2776,256 +2776,97 @@
     
-                .stream()%0D%0A                            .filter(p -%3E p.policyName().equals(roleName))%0D%0A                            .collect(Collectors.toList()));%0D%0A%0D%0A                if(!response.isTruncated()) %7B%0D%0A                    done = true
+// Ensure that the policy is not attached to this role%0D%0A            String polArn = %22%22
 ;%0D%0A
-%0D%0A
     
@@ -2877,163 +2877,160 @@
     
-    %7D else %7B%0D%0A                    newMarker = response.marker();%0D%0A                %7D%0D%0A            %7D%0D%0A%0D%0A                if (matchingPolicies.size() %3E 
+for (AttachedPolicy policy: attachedPolicies) %7B%0D%0A%0D%0A                polArn = policy.policyArn();%0D%0A                if (polArn.compareTo(policyArn)==
 0) %7B%0D%0A
- 
     
@@ -3071,24 +3071,28 @@
 roleName +%0D%0A
+    
             
@@ -3166,16 +3166,20 @@
         
+    
 return;%0D
@@ -3187,30 +3187,46 @@
             
+  
+  
 %7D%0D%0A
+          %7D%0D%0A
 %0D%0A
- 
            /
@@ -3474,16 +3474,42 @@
 licyArn)
+%0D%0A                        
 .build()

Update AttachRolePolicy.java