Use VSCode to write Terraform? AWS AI can now help you write your code!
Tags: vscode, terraform, codewhisperer, reinvent2023
Published: 2023-11-27 18:37:52

As I sit here writing this article, AWS's annual re:Invent is just starting in Las Vegas. This huge event pulls together cloud enthusiasts from around the world to learn about the largest cloud providers offerings.

Not surprisingly, AWS use this time to announce new and improved services, and we'll see hundreds of articles over the next week - in fact, there are so many announcements, they have to start drip-feeding them out in advance of the main event.

One of the announcements released in advance of re:Invent this year, was that [new capabilities had been added to AWS CodeWhisperer](https://aws.amazon.com/about-aws/whats-new/2023/11/amazon-codewhisperer-new-enhancements/), AWS's AI powered coding bot - including the ability to generate Terraform code. In this article, I'll show how you can configure VSCode to use CodeWhisperer and how you can start to use CodeWhisperer to produce Terraform.

## Getting started
Assuming you have VSCode installed, we'll need to go through a few steps to let us use CodeWhisperer.

### Installing the AWS Toolkit extension for VSCode
If you're a regular user, you'll not be surprised to learn that the integration between VSCode and CodeWhisperer is via an extension. Extensions are VSCode's plugins that are used to add additional functionality, such as check code formats, linting, syntax checks etc.

To install an extension, click on the extensions icon in the taskbar on the left-hand side of VSCode which is shown below


![Extension bar of VSCode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jmwjlt6eu67b2v5g2ed2.png)

In the search bar that appears, enter the name ` amazonwebservices.aws-toolkit-vscode` or `AWS Toolkit`and you'll see an icon appear along with a brief description. Click on this to show information about the extension, and you can then click on the blue `Install` button. After installation, you may be asked to reload VSCode to activate the extension.


![AWS Toolkit extension screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kdii4du3ght45938t4y7.png)

After the extension is properly installed, you will see a new AWS icon in the task-bar.

![VSCode taskbar with new AWS Icon](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ckypansye0v2xv1hytb9.png)

### Who goes there?

With the extension in place, we need to authenticate our VSCode session to AWS. If your organisation is paying for the CodeWhisperer Professional tier, you might have access to it through IAM's SSO Identity Center. However, for most of us the easiest option is to sign up for an AWS Builder Id via https://profile.aws.amazon.com/.

Builder Ids are a relatively new way of authenticating with AWS, and they are not associated with a particular AWS account, so these identities are free.


### You're not coming in, if your name's not on the list.

Once you have have a builder Id, signing into the extension is fairly pain-free. Click on the new AWS icon in the VSCode taskbar, and you'll be asked to `Select a connection`. Click on this and you'll get a popup, giving you the change to `Add New Connection`.


![Asking to add new connection](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eaape9iu8875yxza7x9i.png)

Select the `Add new connection`, and you'll be shown a screen showing the different ways you can connect with the AWS Toolkit. Scroll down under CodeWhisperer and you'll see a button, asking you to sign up or sign in for an AWS Builder Id. Click on this and you'll be prompted through a series of popups asking you to connect via your browser. Confirm these connections and you'll be taken through the sign-in process before being prompted to confirm you allow the extension to access your builder Id and associated data. Confirm this and you'll get confirmation in the browser that you have allowed this, and in VSCode the screen will change to show you're connected with your builder Id.


![Confirmed Connection](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sqba1u6ppf1x9f1j47jk.png)

## Let's get the party started.

With the confirmed connection we can finally get down to using CodeWhisperer to create some code.

After closing down any open windows in VSCode, create a new text file. You should be prompted to `Select a language` - click on this and choose `Terraform`. (If you don't see Terraform in the list of options, you may need to install the official Hashicorp Terraform extension.)

With our new Terraform file, we can get down to work. We normally interact with CodeWhisperer via comments in the code, so enter the following text

`# configure aws s3 as backend to store terraform state`

![Screen capture of editing code](https://s3.eu-west-2.amazonaws.com/headforthe.cloud/images/vscode-1701108540806.gif)

As you get to the end of the text, CodeWhisperer will insert text into the editing window. At this point you have a number of options available - after a few seconds, a popup will appear at the top of the window, offering the following choices:

1. Press `TAB` to accept the suggestion,
1. Press left and right arrows to access alternative suggestions
1. Press `Esc` to reject the suggestions.

## Another example

Let's consider a different prompt 
`# write a terraform iam policy allowing a user to get and put objects to an s3 bucket.`.

When I submit this, I get the response
``` terraform
resource "aws_iam_policy" "s3_policy" {
  name        = "s3_policy"
  description = "A test policy"

  policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],
      "Effect": "Allow",
      "Resource": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    }
  ]
}
EOF
} 
```

However, I might be working with a team that prefers to use `jsonencode` - so I can be more specific in my prompt, changing it to `# write a terraform iam policy using jsonencode allowing a user to get and put objects to an s3 bucket`. 

This time, I get an appropriate set of code as below:

``` terraform
resource "aws_iam_policy" "s3_policy" {
  name        = "s3_policy"
  description = "s3_policy"
  policy      = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = [
          "s3:GetObject",
          "s3:PutObject"
        ]
        Effect   = "Allow"
        Resource = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
      },
    ]
  })
}
```

`

## Is CodeWhisperer infallible
Like most AI tools currently available, CodeWhisperer will generally offer good suggestions but sometimes you will need to alter your prompt to get the best suggestion, so called [prompt engineering](https://en.wikipedia.org/wiki/Prompt_engineering).

Personally, I would have liked the IAM examples above to use `[ "s3://************/" ]` for the s3 resources, but it can be argued that this is down to the data used to train the AI model. 

I think it's safe to say that we're not at the point where we can deploy the generated code straight to production, but I can see that it would be very useful for a less experienced engineer.

## Conclusion
In this article, I've given a brief overview of how we can now use CodeWhisperer in VSCode to help us write our Terraform. The new capabilities also support other Infrastructure as Code languages such as CloudFormation and CDK, and no doubt the list of supported languages will increase.