use of software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesResponse in project aws-doc-sdk-examples by awsdocs.
the class DemoUtils method attachIamPolicyToRole.
public static void attachIamPolicyToRole(IamClient iam, String roleName, String policyArn) {
String policyName = policyArn.substring(policyArn.indexOf("/") + 1);
try {
ListAttachedRolePoliciesRequest request = ListAttachedRolePoliciesRequest.builder().roleName(roleName).build();
ListAttachedRolePoliciesResponse response = iam.listAttachedRolePolicies(request);
List<AttachedPolicy> attachedPolicies = response.attachedPolicies();
// Ensure that the policy is not attached to this role
String polArn;
for (AttachedPolicy policy : attachedPolicies) {
polArn = policy.policyArn();
if (polArn.compareTo(policyArn) == 0) {
System.out.println("The " + policyName + " policy is already attached to this role.");
return;
}
}
AttachRolePolicyRequest attachRequest = AttachRolePolicyRequest.builder().roleName(roleName).policyArn(policyArn).build();
iam.attachRolePolicy(attachRequest);
System.out.println("Successfully attached policy " + policyArn + " to role " + roleName);
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.println("Done");
}
use of software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesResponse in project aws-doc-sdk-examples by awsdocs.
the class AttachRolePolicy method attachIAMRolePolicy.
// snippet-start:[iam.java2.attach_role_policy.main]
public static void attachIAMRolePolicy(IamClient iam, String roleName, String policyArn) {
try {
ListAttachedRolePoliciesRequest request = ListAttachedRolePoliciesRequest.builder().roleName(roleName).build();
ListAttachedRolePoliciesResponse response = iam.listAttachedRolePolicies(request);
List<AttachedPolicy> attachedPolicies = response.attachedPolicies();
// Ensure that the policy is not attached to this role
String polArn = "";
for (AttachedPolicy policy : attachedPolicies) {
polArn = policy.policyArn();
if (polArn.compareTo(policyArn) == 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);
}
System.out.println("Done");
}
Aggregations