Creating an IAM policy manually via string manipulation is error-prone. Create IAM policies using the Policy
class in the AWS IAM SDK.
1public void iamPolicyNoncompliant(final String roleName, String userArn) {
2 final AmazonIdentityManagement iamClient = AmazonIdentityManagementClientBuilder.standard().withRegion(Regions.US_EAST_1).build();
3 String policyDocument = "{\n" +
4 " \"Version\": \"2012-10-17\",\n" +
5 " \"Statement\": [\n" +
6 " {\n" +
7 " \"Effect\": \"Allow\",\n" +
8 " \"Principal\": {\n" +
9 " \"AWS\": \"" + userArn + "\"\n" +
10 " },\n" +
11 " \"Action\": \"sts:AssumeRole\"\n" +
12 " }\n" +
13 " ]\n" +
14 "}";
15 final CreateRoleRequest createRoleRequest = new CreateRoleRequest();
16 // Noncompliant: creates an IAM role/policy manually.
17 createRoleRequest.withPath("path").withRoleName(roleName).withAssumeRolePolicyDocument(policyDocument);
18 iamClient.createRole(createRoleRequest);
19}
1public void iamPolicyCompliant(final String roleName) throws UnsupportedEncodingException {
2 final AmazonIdentityManagement iamClient = AmazonIdentityManagementClientBuilder.standard().withRegion(Regions.US_EAST_1).build();
3 final String policyDocument = URLDecoder.decode(iamClient.getRolePolicy(new GetRolePolicyRequest()).getPolicyDocument(), "UTF-8");
4 final CreateRoleRequest createRoleRequest = new CreateRoleRequest()
5 .withRoleName(roleName)
6 .withAssumeRolePolicyDocument(policyDocument);
7 // Compliant: creates an IAM role/policy automatically.
8 final String policyArn = iamClient.createRole(createRoleRequest).getRole().getArn();
9}