Stack Exchange
MalformedPolicyDocumentException while creating IAM policy using Boto
I am working on a boto script to create an IAM policy using a python function. The policy has been converted to JSON format using "json.dumps()", but AWS would still not consider it as a valid format.
The function is:
##### Global variables ####
region="us-east-2"
instance_type="t2.micro"
ebs_volume_size="20"
meta_template_name="ec2_policy_meta_template"
###############################

start_time_1 = input("What's the start time")
end_time1 = input("What's the end time")
def create_aws_iam_policy_template(**kwargs):
  template_data = {}
  template_data["region"] = kwargs.get('region')
  template_data["start_time"] = kwargs.get('end_time')
  template_data["end_time"] = kwargs.get('start_time')
  template_data["instance_type"] = kwargs.get('instance_type')
  template_data["ebs_volume_size"] = kwargs.get('ebs_volume_size')
  template_data["meta_template_name"] = kwargs.get('meta_template_name')

  meta_template_dict = getattr(meta_templates, template_data["meta_template_name"])
  meta_template_json = json.dumps(meta_template_dict)
  template_json = Template(meta_template_json).render(template_data)
  return template_json  


template_json = create_aws_iam_policy_template(
  region=region,
  instance_type=instance_type,
  ebs_volume_size=ebs_volume_size,
  meta_template_name=meta_template_name,
  start_time = start_time_1,
  end_time = end_time1
)

This is what I am using to convert dict to JSON:
app_json = json.dumps(template_json)
print(app_json)

This is the output of the IAM policy:
"{"Version": "2012-10-17", "Statement": [{"Sid": "VisualEditor0", "Effect": "Allow", "Action": "ec2:RunInstances", "Resource": ["arn:aws:ec2:us-east-2::instance/", "arn:aws:ec2:us-east-2::network-interface/", "arn:aws:ec2:us-east-2::key-pair/", "arn:aws:ec2:us-east-2::security-group/", "arn:aws:ec2:us-east-2::subnet/", "arn:aws:ec2:us-east-2::volume/", "arn:aws:ec2:us-east-2::image/ami-"], "Condition": {"ForAllValues:NumericLessThanEquals": {"ec2:VolumeSize": "20"}, "ForAllValues:StringEquals": {"ec2:InstanceType": "t2.micro"}}}, {"Sid": "VisualEditor1", "Effect": "Allow", "Action": ["ec2:TerminateInstances", "ec2:StartInstances", "ec2:StopInstances"], "Resource": "arn:aws:ec2:us-east-2::instance/", "Condition": {"ForAllValues:StringEquals": {"ec2:InstanceType": "t2.micro"}}}, {"Sid": "VisualEditor2", "Effect": "Allow", "Action": ["ec2:Describe*", "ec2:GetConsole*", "cloudwatch:DescribeAlarms", "iam:ListInstanceProfiles", "cloudwatch:GetMetricStatistics", "ec2:DescribeKeyPairs", "ec2:CreateKeyPair"], "Resource": "*", "Condition": {"DateGreaterThan": {"aws:CurrentTime": "2020-06-30T23:59:59Z"}, "DateLessThanEquals": {"aws:CurrentTime": "2020-04-01T00:00:00Z"}}}]}"
This is the error I am getting while trying to create an IAM policy:
botocore.errorfactory.MalformedPolicyDocumentException: An error occurred (MalformedPolicyDocument) when calling the CreatePolicy operation: Syntax errors in policy.


Can you provide more complete example code? Where and how do you generate template_json and call CreatePolicy?

I have made the changes in the question. Do check it out.

The policy overall has too many warnings, even though I was able to create it via the console.
For example, aws:CurrentTime should be somethink like below:
                "DateGreaterThan": {"aws:CurrentTime": "2020-04-01T00:00:00Z"},
                "DateLessThan": {"aws:CurrentTime": "2020-06-30T23:59:59Z"}

ec2:InstanceType condition doesnt have the corresponding condition's value specified.
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "VisualEditor0",
      "Effect": "Allow",
      "Action": "ec2:RunInstances",
      "Resource": [
        "arn:aws:ec2:us-east-2::instance/",
        "arn:aws:ec2:us-east-2::network-interface/",
        "arn:aws:ec2:us-east-2::key-pair/",
        "arn:aws:ec2:us-east-2::security-group/",
        "arn:aws:ec2:us-east-2::subnet/",
        "arn:aws:ec2:us-east-2::volume/",
        "arn:aws:ec2:us-east-2::image/ami-"
      ],
      "Condition": {
        "ForAllValues:NumericLessThanEquals": {
          "ec2:VolumeSize": "20"
        },
        "ForAllValues:StringEquals": {
          "ec2:InstanceType": ""
        }
      }
    },
    {
      "Sid": "VisualEditor1",
      "Effect": "Allow",
      "Action": [
        "ec2:TerminateInstances",
        "ec2:StartInstances",
        "ec2:StopInstances"
      ],
      "Resource": "arn:aws:ec2:us-east-2::instance/",
      "Condition": {
        "ForAllValues:StringEquals": {
          "ec2:InstanceType": ""
        }
      }
    },
    {
      "Sid": "VisualEditor2",
      "Effect": "Allow",
      "Action": [
        "ec2:Describe*",
        "ec2:GetConsole*",
        "cloudwatch:DescribeAlarms",
        "iam:ListInstanceProfiles",
        "cloudwatch:GetMetricStatistics",
        "ec2:DescribeKeyPairs",
        "ec2:CreateKeyPair"
      ],
      "Resource": "*",
      "Condition": {
        "DateGreaterThan": {
          "aws:CurrentTime": "30"
        },
        "DateLessThanEquals": {
          "aws:CurrentTime": "20"
        }
      }
    }
  ]
}


Thanks for replying, I have updated both the issues, yet I am getting the same error, I have rechecked not sure what might be wrong now.

@PranaySinghParihar I would suggest giving the policy test in IAM Policy Simulator. Once you are sure, that's the policy you need, then you can easily generate it via the code.

Yeah, I think the attributes are fine but the output has these backward slashes '' which does not comply with the IAM policy format, but I don't know how to get rid of it.

@PranaySinghParihar the policy which you shared in the post, is valid, just that the conditions you are placing have troubles. As I confirmed in my answer as well.  I was able to create the policy via the console

In the simulator I seem to be getting a parcing error.

@PranaySinghParihar can you share the error and the corresponding policy via gist?

Parse error on line 1: "{"Version": "2012-10-1 ---^ Expecting 'EOF', '}', ':', ',', ']', got 'undefined'
This is the error.

Let us continue this discussion in chat.
