DEV Community

Cover image for Importing my AWS IAM Role to Terraform using Terraform Search
Bervianto Leo Pratama
Bervianto Leo Pratama

Posted on

Importing my AWS IAM Role to Terraform using Terraform Search

Cover image is generated by AI

Motivation

A long time ago... I want to manage my IAM Role with Terraform. But, I'm quite lazy for writing it manually... Especially for my existing IAM Role. I heard about Terraform Search, which helps me import existing resources to write the resource configuration! Wow!

Imagine you write the query something like this.

list aws_iam_role dev {
  provider = aws
}
Enter fullscreen mode Exit fullscreen mode

Run this command.

terraform query -generate-config-out=generated.tf
Enter fullscreen mode Exit fullscreen mode

Boom! You got a generated resource file with the import blocks.

Easy, right?

How did I do?

Prerequisite

  • Terraform 1.14.x (still beta right now...)

If you want to read more, please visit here.

Keep in mind. Terraform Search supports are based on the Terraform provider.

Documentation

Run it locally

Okay, you need to do it locally because HCP won't have the beta right now, except that Terraform 1.14 has been released. So, basically, these are my steps. In this case, I want to manage the state in HCP Terraform.

  1. Install Terraform 1.14.x in Local
  2. Ensure you have the AWS Credentials in your local.
  3. Configure a workspace in HCP Terraform. Ensure you have the AWS Credentials. But temporarily set it as local execution.
  4. Write the main.tf to configure the provider, in this case AWS provider.
  5. Write the .tfquery.hcl file (look above section).
  6. Let's init first. terraform init.
  7. Run the query command terraform query -generate-config-out=generated.tf.
  8. Copy only resources that I want to manage.
  9. Run terraform plan just to ensure it will import!
  10. Run terraform apply if I'm sure of the configuration.
  11. Now my IAM Roles are managed by HCP Terraform!
  12. You may now change the execution to HCP Terraform (if you want to run it there).

Notes:

  • It may expose your AWS Account ID and some information. Before you commit those codes, you may need to extract some information to create some variables.

HCP Result

Result

You can visit my repo here.

GitHub logo bervProject / AWSSecurityAsACode

AWS Security as a Code for BervProjects

My First AWS Security as Code

Generate the resources import

terraform query -generate-config-out=generated.tf
Enter fullscreen mode Exit fullscreen mode

or

./generate.sh
Enter fullscreen mode Exit fullscreen mode

LICENSE

MIT






Thank you

Thank you for reading!

If you have any feedback, feel free to comment here.

Gracias GIF

Top comments (0)