Search in sources :

Example 1 with AttachRolePolicyRequest

use of com.amazonaws.services.identitymanagement.model.AttachRolePolicyRequest in project aws-doc-sdk-examples by awsdocs.

the class AttachRolePolicy method main.

public static void main(String[] args) {
    final String USAGE = "To run this example, supply a role name\n" + "Ex: AttachRolePolicy <role-name>\n";
    if (args.length != 1) {
        System.out.println(USAGE);
        System.exit(1);
    }
    String role_name = args[0];
    final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient();
    ListAttachedRolePoliciesRequest request = new ListAttachedRolePoliciesRequest().withRoleName(role_name);
    List<AttachedPolicy> matching_policies = new ArrayList<>();
    boolean done = false;
    while (!done) {
        ListAttachedRolePoliciesResult response = iam.listAttachedRolePolicies(request);
        matching_policies.addAll(response.getAttachedPolicies().stream().filter(p -> p.getPolicyName().equals(role_name)).collect(Collectors.toList()));
        if (!response.getIsTruncated()) {
            done = true;
        }
        request.setMarker(response.getMarker());
    }
    if (matching_policies.size() > 0) {
        System.out.println(role_name + " policy is already attached to this role.");
        return;
    }
    AttachRolePolicyRequest attach_request = new AttachRolePolicyRequest().withRoleName(role_name).withPolicyArn(POLICY_ARN);
    iam.attachRolePolicy(attach_request);
    System.out.println("Successfully attached policy " + POLICY_ARN + " to role " + role_name);
}
Also used : ListAttachedRolePoliciesResult(com.amazonaws.services.identitymanagement.model.ListAttachedRolePoliciesResult) AttachRolePolicyRequest(com.amazonaws.services.identitymanagement.model.AttachRolePolicyRequest) AttachedPolicy(com.amazonaws.services.identitymanagement.model.AttachedPolicy) ArrayList(java.util.ArrayList) ListAttachedRolePoliciesRequest(com.amazonaws.services.identitymanagement.model.ListAttachedRolePoliciesRequest) AmazonIdentityManagement(com.amazonaws.services.identitymanagement.AmazonIdentityManagement)

Aggregations

AmazonIdentityManagement (com.amazonaws.services.identitymanagement.AmazonIdentityManagement)1 AttachRolePolicyRequest (com.amazonaws.services.identitymanagement.model.AttachRolePolicyRequest)1 AttachedPolicy (com.amazonaws.services.identitymanagement.model.AttachedPolicy)1 ListAttachedRolePoliciesRequest (com.amazonaws.services.identitymanagement.model.ListAttachedRolePoliciesRequest)1 ListAttachedRolePoliciesResult (com.amazonaws.services.identitymanagement.model.ListAttachedRolePoliciesResult)1 ArrayList (java.util.ArrayList)1