Creating IAM Policies with Ease:  ChatGPT vs. GitHub Copilot vs. AWS Policy Generator

Creating IAM Policies with Ease: ChatGPT vs. GitHub Copilot vs. AWS Policy Generator

IAM policies are utilized for regulating entry to AWS resources and services. Manual creation of these policies can be tedious and susceptible to errors. Nevertheless, numerous tools are available to simplify the procedure of crafting custom policies.

In this article, we will cover the basics of IAM policies. This includes understanding what a policy is and the various types of policies that are offered. Furthermore, we will explore the steps involved in creating and managing policies using GitHub Copilot, ChatGPT, and the AWS Policy Generator, while also comparing their practicality for everyday use. Lastly, we will provide some recommended best practices for IAM policies.

AWS IAM Policy Generation - Fundamentals of IAM Policies and how to leverage tools like GitHub Copilot, ChatGPT, or AWS Policy Generator to create IAM Policies.

IAM Policy Fundamentals

Before we delve into policy generation, let's briefly review the basics of IAM policies. If you're already well-versed in IAM, feel free to skip this section.

Semantics of a Policy

Every time a request is made to AWS, it undergoes an enforcement check to verify if the requesting entity is authenticated and authorized to perform the intended action. The determination is based on the policies assigned either directly to the IAM user or the currently assumed role.

In AWS, a policy is an entity that decides whether to grant (allow) or prohibit actions (deny) on services and resources. Policies are primarily saved as organized JSON files and have varying categories.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DenyIPRange",
      "Action": "*",
      "Effect": "Deny",
      "Resource": "*",
      "Condition": {
        "NotIpAddress": {
          "aws:SourceIp": ["192.0.2.0/24", "203.0.113.0/24"]
        }
      }
    }
  ]
}

Every policy includes one or more statements that specify which actions are authorized for a particular resource based on the circumstances.

  • Version: specifying the version of the policy language you want to use. The latest one is 2012-10-17 ****and you shouldn’t use a previous version.

  • Statement: a container holding one or several items that define the permissions.

  • Effect: stating whether actions are granted (allow) or denied (deny). A deny statement always overwrites allow statements.

  • Principal: missing in our example, but for example used with resource-based policies to determine the account, user, or role for which the statement applies or with trust policies to determine the trust relationship for a role.

  • Action: a list of API actions for the target service that are either allowed or denied.

  • Resource: the resources for which the statement should allow or deny the given actions. This is not required for resource-based policies, as it’s implicitly applied to the resource to which the policy is attached.

  • Condition: specifying under which circumstances the statement should be applied. This is optional but can be used to further drill-down permissions.

We will discuss various types of policies in the following paragraphs.

Trust Policies

AWS IAM roles have trust policies that determine which entities (such as users, groups, or AWS services) are authorized to assume the role. The trust policy is a JSON document that includes the principal element, which identifies the trusted entities. When an entity assumes a role, it temporarily gains the permissions associated with it.

Trust policies define the trust relationship to principals.

Example: Enabling a Lambda function to take on a role.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

Resource-based Policies

Resource-based policies are linked directly to AWS resources like Amazon S3 buckets and AWS Key Management Service (KMS) keys. They authorize specific principals (e.g., AWS accounts, users, or roles) to carry out actions on the related resource.

Most AWS Services do not support resource-based policies.

Example: a resource-based policy attached to an Amazon S3 bucket, allowing an IAM user from a specific AWS account to list the bucket contents.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::123456789012:user/UserA"
      },
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::example-bucket"
    }
  ]
}

Identity-based Policies

IAM identities, including users, groups, and roles, are associated with identity-based policies that dictate their access to AWS resources.

IAM Roles can have an inline policy and one or multiple attached policies.

There are three different sub-types of identity-based policies:

  • Inline - as part of a role definition and not a distinct resource.

  • AWS-managed - created and maintained by AWS.

  • custom - self-defined policies.

Example: an identity-based policy that is directly attached to an IAM user, granting permissions for EC2 instances.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeInstances",
        "ec2:StartInstances",
        "ec2:StopInstances",
        "ec2:TerminateInstances"
      ],
      "Resource": "*"
    }
  ]
}

If you're interested in gaining a better understanding of policies and how to utilize them effectively, we recommend checking out our in-depth article on the subject.

Creating Policies with Github Copilot

GitHub Copilot is a tool for code completion that utilizes artificial intelligence, which was created by the collaborative efforts of OpenAI and GitHub.

It is an excellent tool for creating IAM policies directly within your IDE. If we're looking at a Terraform example, we can create new policies easily via two approaches:

  1. Leveraging code suggestions - starting with a new resource type and giving it a detailed name.

  2. Descriptive comments - writing a comment in which we'll include our intentions for the policy.

Both variants work out, even though the second option will result in better results. Both options can be easily iterated with additional comments within the sections.

One of the primary benefits of using GitHub Copilot is that it allows you to stay within your IDE. While there are ChatGPT integrations available, they typically require you to open an additional tab to view the response from OpenAI. Furthermore, these responses often include explanations that may not be necessary for the task at hand, although they can be removed with appropriate prompts.

Using Descriptive Comments

To begin, provide a detailed comment that outlines the specifics of the IAM policy you wish to establish. Be explicit about the actions, resources, and conditions involved. By doing so, GitHub Copilot can generate accurate code suggestions that meet your needs.

Creating IAM policies with GitHub Copilot through descriptive Comments.

In the above example, we are setting up a lambda execution role. Thanks to GitHub Copilot's automatic assistance, we don't have to worry about including the trust policy for AWS Lambda - it's already taken care of. Once that's done, we proceed to add the basic execution policy that grants Lambda the necessary permissions to create a log group, log streams, and write log data.

Leveraging Code Suggestions and Iterating

Starting with comments is unnecessary since Copilot has access to the surrounding code, allowing it to understand what we are currently developing. Nevertheless, it mostly comes with the best results as we're giving additional context.

The initial proposal may not precisely align with our needs, but we can easily improve our approach through iterative refinement.

Iterating through IAM policies with GitHub Copilot to improve the results.

While GitHub Copilot is a fast and effective tool for crafting IAM policies ranging from basic to advanced, it may fall short of achieving the ultimate objective if the complexity of the policy is too great.

Creating Policies with ChatGPT

With ChatGPT, there are no rules to follow when inputting our requirements. We have the freedom to describe our needs in any way we wish - whether it be in a single sentence, broken down into multiple statements, listed out, or simply a few keywords. ChatGPT will take care of the rest.

However, we can adjust our prompt to optimize the outcome.

Using ChatGPT to generate IAM Policies.

We're not restricted to using only one resource per prompt. We can generate multiple resources from one prompt.

Improving IAM Policies Generation results at ChatGPT by fine-tuning the prompts.

ChatGPT is also context-aware, so we can write more prompts the fine-tune our previous results.

Extending, Restricting, or Debugging Existing Policies

We can also incorporate pre-existing policies to expand or modify them.

Using ChatGPT to extend existing policies.

We're limiting DynamoDB permissions in this example.

Getting Explanations for Existing Policies

ChatGPT can explain policies in-depth. This is powerful, especially when just starting with IAM.

Creating explanations of existing policies via ChatGPT.

GPT-4 has significantly increased the number of tokens (or characters) that can be included in a single prompt, allowing for the pasting of large code files and the provision of comprehensive explanations.

Creating Policies with the AWS Policy Generator

With the AWS Policy Generator, you can also easily create IAM policies in a wizard-like interface.

It will guide us through multiple steps:

  • Selecting the policy type - choosing between a generic identity-based policy or a specific resource-based policy.

  • Adding the statements - adding the permissions we need.

AWS Policy Generator for easily creating fitting IAM Policies.

Let's dive right into it and run through an example.

Selecting the Policy Type

AWS makes a distinction between identity-based policies and resource-based policies. Resource-based policies can be utilized on resources, rather than on identities such as users, groups, and roles. Only a select few AWS services are capable of supporting resource-based policies, including SQS, SNS, S3, and VPC endpoints.

Selecting the policy type in the AWS Policy Generator.

Choosing a policy type will affect the appearance of the subsequent step in the generator, as each type has distinct mandatory and discretionary fields.

Adding Statements

Once we've chosen our policy type, we can proceed to define one or more statements. For this particular example, we've opted for an identity-based policy, specifically an IAM Policy, to grant access to an S3 bucket.

Defining statements in the AWS Policy Generator.

The policy generator will display the potential actions for the selected service, but it does not provide comprehensive explanations for them. Several of these actions may not be immediately clear. You can also have a quick look at the AWS documentation, as there's a complete list of all actions, resources, and condition keys for AWS services.

We also have the option to add conditions, which can further refine the application of our policy.

Adding conditions via the AWS Policy Generator.

When we finished our statement, we can add it via a click on the "Add statement" button.

Generating the Policy

We can choose to add further statements or generate the final policy. When generating, it will appear in a small modal.

Viewing the final results of the AWS Policy Generator.

Comparison of the three approaches

GitHub Copilot, ChatGPT, and AWS Policy Generator are three distinct tools with different purposes and functionalities.

  1. GitHub Copilot - Although GitHub Copilot wasn't designed specifically for creating IAM policies, it could still offer code suggestions for JSON-based IAM policies if you begin writing one. However, its main purpose is to aid with general programming tasks, so its ability to generate IAM policies may be restricted compared to specialized tools.

  2. ChatGPT - Like GitHub Copilot, ChatGPT is not solely designed for creating IAM Policies. However, it can generate relevant policies or offer assistance in creating, comprehending, or modifying them. Nevertheless, it may not be as precise or effective as utilizing a specialized IAM policy generation tool. Thus, you should meticulously examine any policy generated for accuracy and compliance with best practices.

  3. AWS Policy Generator - The AWS Policy Generator is a specialized tool designed for creating IAM policies, offering a more focused approach to policy crafting. The user-friendly interface and added functionalities like policy templates and real-time validation could potentially surpass the quality of output from Copilot and ChatGPT. However, it may require more time and effort to utilize.

To put it simply, the most efficient tool is the ideal choice for the task at hand. Personally, GitHub Copilot's smooth integration makes it an outstanding asset for composing accurate IAM policies, regardless of the IaC tool I opt to utilize.

On the other hand, ChatGPT impresses with its ability to generate sophisticated policies simply by accurately specifying the requirements for permissions.

AWS Management Console's Policy Editor

To make this article complete, you're also able to create and adapt policies in the console editor. As we don't want to maintain production policies without infrastructure as code, this should not be the way to go.

Visual Editor for IAM Policies.

Nevertheless, the visual policy editor comes with many advantages:

  • Simplified creation - You don't have to write JSON to make it more accessible initially. Generating new statements is just as straightforward as it is with the AWS Policy Generator.

  • Less error-prone - The graphical interface of the visual policy editor helps users create policies with fewer errors. It guides them through the process and prevents common mistakes such as typos, incorrect resource ARNs, or missing elements.

  • Real-time validation - The policy editor with visual aids checks the syntax and structure of policies in real-time as they are created or modified, minimizing the likelihood of producing an invalid policy.

  • Previewing policy effects - You can preview the effects of your policy before implementation, guaranteeing comprehension of the outcomes of your modifications before they become active.

While it's not as simple as using Copilot or ChatGPT to generate blueprints, the visual editor is an excellent resource for managing IAM policies.

Best Practices for IAM Policies

The backbone of your cloud infrastructure's security lies in IAM policies. By adhering to best practices, you can minimize potential risks.

Aiming for the Least Privilege

The least privilege principle dictates that every user, group, or role that is assumable ought to possess only the essential permissions required to carry out their specific tasks.

The benefits of aiming for this goal are manifold, including amongst others:

  1. Reduced risk of unauthorized access.

  2. Minimizing the impact of compromised credentials.

  3. Encouraging role segregation.

  4. Improved data security.

  5. There is a lower chance of unintentional actions.

  6. Improved management of resource consumption.

Utilizing Managed Policies

AWS creates and maintains predefined IAM policies called managed policies, which provide specific permissions for different AWS services. These policies can be assigned to IAM users, groups, or roles.

There are several reasons why utilizing managed policies can be a beneficial practice, including less room for human error and simplified policy management.

However, utilizing managed policies carries the potential for overlooked ownership. AWS retains the ability to modify policies at its discretion, which may result in a significant impact on any production environment utilizing said policies.

Implementing Policy Versioning

This happens automatically. If you're updating a policy, AWS will keep the previous versions.

If you go straight to the policy overview, you'll see the tab for Policy Revisions. This tab will show you the most recent 5 versions. With this feature, you can easily track previous changes and revert them in case of permission errors.

Conclusion

In conclusion, crafting and managing IAM policies can be a tedious and error-prone task, but there are various tools available to simplify the process.

In this article, we have discussed the fundamentals of IAM policies and the different categories of policies available. We have also explored the process of using GitHub Copilot, ChatGPT, and the AWS Policy Generator to create and maintain policies while highlighting the most effective techniques for managing AWS IAM policies.

In addition, we have discussed the most effective approaches for IAM policies, including the principle of least privilege, the use of managed policies, and the implementation of policy versioning. By adhering to these guidelines and utilizing the appropriate resources, you can guarantee the safety and efficiency of your cloud infrastructure.