General

How to Use Amazon CodeWhisperer (AI Code Generator)

amazon codewhisperer

In the fast-paced landscape of software development and cloud infrastructure, the emergence of generative AI code companions represents an excellent opportunity for productivity gains. These tools, backed by cutting-edge artificial intelligence, are reshaping and fast-tracking how developers write and debug code. Even more, these tools get better day by day, and their ability to learn from your own code bases, adapt to your coding style, and leverage your internal libraries has made them valuable assets for developers over the past year.

In this blog post, we will deep dive into Amazon CodeWhisperer, an AI-powered code generation tool that helps improve developer productivity.

  1. What is Amazon CodeWhisperer?
  2. Amazon CodeWhisperer additional features
  3. How to use CodeWhisperer with AWS Builder ID
  4. Getting Started with CodeWhisperer
  5. Demo: Write Terraform code with CodeWhisperer

What is Amazon CodeWhisperer?

CodeWhisperer is a general-purpose, machine-learning-powered code companion that provides recommendations and generates code blocks in real time as developers work on their favorite integrated development environment (IDE). To trigger CodeWhisperer, users write comments in natural language describing the task they want to accomplish. These suggestions vary from single-line to fully formed code functions and classes. CodeWhisperer takes into account the existing code context and provides tailored recommendations. 

How can you use CodeWhisperer?

You can interact with CodeWhisperer from various places such as popular IDEs (VS Code, JetBrains, Visual Studio, AWS Cloud9), the command line, Jupyterlab, and various AWS services such as AWS Lambda, AWS Glue Studio, and AWS EMR Studio. 

Is CodeWhisperer free?

CodeWhisperer comes in two different tiers. The Individual developer tier is currently free with an AWS Builder ID and provides code suggestions, reference tracking, and security scans. The Professional tier offers additional capabilities, such as administrative functions for organizations that want to adopt it and customization capabilities that allow CodeWhisperer to provide more targeted and relevant suggestions by integrating the organization’s internal codebases. Find more details on the official pricing page.

Which languages are currently supported by CodeWhisperer?

CodeWhisperer offers code recommendations for multiple programming languages, and the list is growing as time progresses. Currently, it supports Java, Python, JavaScript, TypeScript, C#, Go, PHP, Rust, Kotlin, SQL, JSON (AWS CloudFormation), YAML (AWS CloudFormation), HCL (Terraform), CDK (Typescript, Python), Ruby, C++, C, Shell, and Scala.

Check out another AWS AI tool: What is Amazon Bedrock?.

Amazon CodeWhisperer additional features

Security scans and remediation suggestions

CodeWhisperer integrates with Amazon CodeGuru to enable security scans of your code and highlights security findings along with suggested AI-powered code remediations to solve them. Built-in security scanning detects issues such as exposed credentials and log injection. 

Reference tracker for open source code

CodeWhisperer identifies code suggestions that may bear similarities to publicly available code and accordingly flags them. This allows developers to check the open-source project repository URL and its license and ensure they responsibly incorporate open-source code by properly adding license attribution. 

Optimization for AWS services

CodeWhisperer offers optimized recommendations for interacting with AWS services and APIs. It actively examines your code and comments and offers suggestions that utilize cloud services and public software libraries in line with AWS best practices, ensuring that the recommendations are relevant and adhere to high coding standards.

How to use CodeWhisperer with AWS Builder ID

To set up CodeWhisperer for the first time as an individual developer, you must create your personal AWS Builder ID. AWS Builder ID is a free and personal profile, independent from any credentials and data you may have in existing AWS accounts, that provides access to select tools and services, including Amazon CodeCatalyst, Amazon CodeWhisperer, and AWS Training and Certification

If you are an administrator setting up CodeWhisperer Professional for your organization, see the official docs Setting up Amazon CodeWhisperer for administrators.

Next, after you have your AWS Builder ID, you have to prepare your favorite environment or IDE for CodeWhisperer. You can check the full list of supported IDEs.

I usually use Visual Studio Code, so I have to install the AWS Toolkit for Visual Studio Code. Basically, an open-source plug-in for Visual Studio Code that makes it easier to create, debug, and deploy applications on Amazon Web Services. In order to install the plugin and configure it for use, check out Getting Started with the AWS Toolkit for Visual Studio Code.

If you prefer following video instructions, here’s a 2-minute Getting Started with CodeWhisperer video.

Getting Started with CodeWhisperer

Assuming everything is set up, we can start using Amazon CodeWhisperer to fast-track our development experience. 

How to interact with CodeWhisperer?

You can trigger CodeWhisperer either by using comments to initiate suggestions or allowing it to auto-suggest code while you type. If you need to explicitly trigger a suggestion, press Option + C on MacOS or Alt + C on Windows. When you get a recommendation, you can navigate through a maximum of five recommendations using the Forward (→) and Backward (←) keys and accept your preferred one with Tab.

Next, let’s look into some examples of using and triggering CodeWhisperer.

Trigger CodeWhisperer based on a function name

CodeWhisperer understands your intent and tries to offer suggestions tailored to the names of your functions. As a best practice, try to use clear and descriptive function names for better suggestions.

I will be using Python and HCL for Terraform languages to showcase CodeWhisperer in the next examples. To follow along, create a test.py file in your IDE and start typing:

def upload_to_s3(

You will notice that CodeWhisperer is triggered automatically, and you will get the code completion suggestion in gray:

codewhisperer example

As mentioned, to circle through different recommendations, use the Forward (→) and Backward (←) keys and accept your preferred one with Tab.

Let’s use this one that provides some comments and documents the function parameters as well:

amazon codewhisperer example

After pressing tab, notice that your function has been code-completed and any necessary package has been imported.

codewhisperer code

Two important things to note before we proceed. 

First, it is important to validate that the code recommendation effectively fulfills its intended purpose. At times, you might not get relevant or fully working recommendations. Treat code suggestions as a basis to start with and adjust and tweak according to your needs. As a best practice, never accept code suggestions blindly, and make sure to test them properly. Validating and testing the code recommendations shown in this blog post is outside this demo’s scope.

CodeWhisperer is a Generative AI tool, meaning you won’t always get the same recommendations even if you trigger it with the same input. Note that CodeWhisperer considers function names, variable names, comments, and content of the file you are currently using.

Trigger CodeWhisperer based on comments

Another way to trigger CodeWhisperer is to write your intent in comments. You can use a single-line comment: 

codewhisperer comment

You can also use multi-line comments:

amazon codewhisperer multi line comments

Trigger CodeWhisperer to auto-complete fake data and unit tests

You can easily generate fake data with CodeWhisperer for testing:

codewhisperer

In the above example, keep pressing the tab button to generate more fake users:

codewhisperer test

Another area where CodeWhisperer can be extremely helpful is generating unit tests for your code:

amazon codewhisperer test case

Keep triggering CodeWhisperer to generate more test cases:

aws codewhisperer

Context matters

As discussed, your existing code, names, and context are taken into account in the provided suggestions. Let’s see an example to validate this behavior. We will trigger CodeWhisperer to suggest a function to validate an email address two times, each time while we have imported a different Python package:

amazon codewhisperer trigger

Now, if we import the boto3 Python package instead in our existing code, we get a suggestion that leverages this package instead:

aws codewhisperer context

Demo: Write Terraform code with CodeWhisperer

In this example, let’s try to create a VPC and an EC2 instance on AWS with the help of CodeWhisperer.

Create an empty Terraform file and start typing in our IDE. Note that for this simplistic demo, we won’t consider different best practices for structuring Terraform code, but we will focus on writing functional Terraform code utilizing CodeWhisperer’s suggestions as much as possible. Always treat these code recommendations as the basis, and adjust and refactor according to your needs.

In order to connect to AWS, we must first define the aws provider. Let’s write a comment to generate the required provider block with CodeWhisperer:

codewhisperer aws provider

That looks correct, although the version looks old. Let’s accept the recommendation but update the version to a more recent one.

Next, let’s use this provider and define an alias:

amazon codewhisperer terraform

That’s perfect. Next, let’s write a comment to define a few variables:

amazon codewhisperer how to use

CodeWhisperer adds automatically one by one the variables I have described in the comment:

codewhisperer iac

After I kept accepting its recommendations, my variables looked like this:

terraform variables with ai

It’s not bad at all, although my code isn’t formatted correctly. I’ll use CodeWhisperer’s suggestions for the default region, VPC CIDR, private, and public subnets.

Next, we need to create the VPC. You know the drill by now: write a comment to describe what we need.

codewhisperer vpc

Again, the code looks functional, although the version is quite old. Let’s accept the recommendation but use a more recent version. Even more, defining the Availability Zones based on the region name and letters `a`, `b`, and `c` isn’t the most optimal way, but I will go ahead with this implementation for this demo. Let’s add an EC2 instance on top of our VPC.

This time, CodeWhisperer suggests even the comment as the next step:

terraform with ai

Let’s accept this comment and see the code suggestion:

iac ai

We have to adjust a few things here. We don’t have an SSH key, so this code will fail. Let’s remove this line. We get a hardcoded AMI, but AMI IDs are tied to specific regions. We might need to change that since we aren’t sure if it’s from the region we are using. We get some suggested tags that might also be irrelevant and possibly need adjustment. 

For the sake of this demo, I just removed the key_name variable and went ahead and tried to provision this infrastructure on AWS:

terraform init
terraform apply

After a while, Terraform was able to spin up the resources successfully:

codewhisperer terraform variables

This is far from a production-ready setup, but we managed to get a functional code mostly using CodeWhisperer to do the heavy lifting with just a few code tweaks. 

Key points

In this blog post, we deep-dived into Amazon CodeWhisperer, a GitHub Copilot alternative, its features, characteristics, and capabilities. We explored supported languages and environments and reviewed detailed information on getting started. Lastly, we saw practical examples of leveraging CodeWhisperer in action and used it to generate Terraform code to provision a VPC and an EC2 instance from scratch in minutes.

We encourage you also to explore how Spacelift makes it easy to work with Terraform. If you need any help managing your Terraform infrastructure, building more complex workflows based on Terraform, and managing AWS credentials per run, instead of using a static pair on your local machine, Spacelift is a fantastic tool for this. It supports Git workflows, policy as code, programmatic configuration, context sharing, drift detection, and many more great features right out of the box. You can also see Spacelift integration with AWS, with our Cloud Integrations section and our update to support account-level AWS integrations. Try it for free or book a demo with one of our engineers.

Thank you for reading, and I hope you enjoyed this as much as I did!

The Most Flexible CI/CD Automation Tool

Spacelift is an alternative to using homegrown solutions on top of a generic CI. It helps overcome common state management issues and adds several must-have capabilities for infrastructure management.

Start free trial