Most Asked Interview Scenarios of Terraform
Scenerio-1
A DevOps Engineer manually created infrastructure on AWS, and now there is a requirement to use Terraform to manage it. How would you import these resources into Terraform code?
Steps to import an existing EC2 instance into Terraform:
- Write a Terraform Configuration File (
main.tf):
First, create a Terraform configuration file (main.tf) with the AWS provider.
provider "aws" {
region = "us-east-1"
}
import {
id = "i-01a6172adfbfab273"
to = aws_instance.example
}
- Run
terraform init:
Initialize Terraform, which will download the necessary provider plugins and set up your environment.
terraform init

- Generate the Configuration (Optional but Recommended):
This command generates a configuration output that reflects the current state of the EC2 instance in AWS and saves it to a file named generated_resources.tf. Remove the import block, copy the generated AWS resource configuration into your main.tf file
terraform plan -generate-config-out=generated_resources.tf

- Delete the Generated Resource File (if created):
After copying the configuration into your main.tf, make sure to delete the generated_resources.tf file. Additionally, remove any IPv6-related configuration lines from your main.tf to avoid conflicts, as they may not match your current setup.

5. Run terraform import (To Create State File):
Now that your configuration is set up correctly, run the terraform import command to create the Terraform state file (terraform.tfstate):
terraform import aws_instance.example i-01a6172adfbfab273

This command will update the Terraform state file to reflect the current configuration of the EC2 instance.
- Verify the Configuration with
terraform plan:
Run terraform plan to ensure that Terraform is now managing the EC2 instance correctly. It will show the changes it plans to make (if any).

Conclusion:
After following these steps, Terraform will now manage your existing EC2 instance. You can update the configuration or manage the resource as needed in the future. The key idea is that Terraform uses the terraform import command to associate an existing resource (like an EC2 instance) with a resource in your Terraform configuration, and it keeps track of the state using the terraform.tfstate file.
Scenario 1: Drift Detection in Terraform
How do you ensure that Terraform detects and manages manual changes made to infrastructure outside of Terraform, such as changes made directly through the AWS Management Console? How would you automate this process to ensure the state is always up to date?
When changes are made outside of Terraform (e.g., manually in the AWS console), Terraform won’t know about them until you run terraform plan. This is known as drift detection.
Solution:
Use
terraform refreshregularly to sync the state file with the actual infrastructure.Set up a cron job to automate
terraform refreshand runterraform planto detect any drift.
Example Cron Job:
# Run terraform refresh daily at midnight
0 0 * * * cd /path/to/terraform/project && terraform refresh && terraform plan
Scenario 2: Strict IAM Policies and Manual Change Detection
How would you handle a scenario where strict IAM policies are enforced, and you're not allowed to make manual changes to AWS infrastructure? How would you monitor for manual changes and ensure that only Terraform-managed resources are modified?
If you’re not allowed to make manual changes in AWS, you can enforce strict IAM policies and use AWS Lambda to monitor changes.
Solution:
IAM Policies: Restrict manual access to AWS resources. Only allow Terraform to manage infrastructure.
Lambda: Set up a Lambda function to monitor AWS CloudTrail logs for manual changes and notify your team.
To effectively explain these scenarios in an interview, you can focus on showcasing your understanding of drift detection, infrastructure as code (IaC) practices, and security best practices. Here's how you can frame your response concisely and confidently:
Scenario 1: Drift Detection in Terraform
"In Terraform, drift occurs when changes are made manually outside of Terraform’s management, like directly through the AWS Management Console. This can cause Terraform’s state file to become outdated, leading to inconsistencies in the infrastructure.
To detect drift, I would regularly run
terraform refreshto synchronize Terraform's state file with the actual state of resources in AWS. After refreshing, I would useterraform planto check for any discrepancies between the infrastructure defined in Terraform and the current state.To automate this process, I would set up a cron job that runs
terraform refreshandterraform planperiodically (e.g., daily). This ensures that any manual changes made outside Terraform are quickly detected and can be addressed.For example, if an S3 lifecycle policy is manually updated via the AWS console, Terraform wouldn't be aware of this until the next
terraform planis executed. By setting up drift detection, we can proactively monitor and rectify any inconsistencies in the infrastructure."
Scenario 2: Strict IAM Policies and Monitoring Manual Changes
"In a controlled environment, we can enforce strict IAM policies to ensure that only automated tools like Terraform are allowed to modify infrastructure, while manual changes are strictly prohibited.
I would define IAM roles with minimal permissions for users and ensure that only the Terraform role has the necessary privileges to manage infrastructure resources. This minimizes the risk of accidental or unauthorized changes by users.
Additionally, to monitor for manual changes, I would set up an AWS Lambda function that integrates with AWS CloudTrail. CloudTrail logs all API calls made in AWS, including actions taken through the console. If any manual changes are detected, the Lambda function can immediately send alerts to the team, ensuring that the infrastructure remains consistent and secure.
For example, if someone manually modifies an S3 lifecycle policy, the Lambda function would capture this change and notify the team, allowing for quick resolution. This way, we ensure that all changes are made through Terraform, which is auditable and version-controlled."
Key Points to Emphasize:
Terraform Drift Detection: Demonstrating knowledge of detecting and managing manual changes (drift) in infrastructure.
Automation: Setting up automated checks using
terraform refreshandterraform planto ensure infrastructure consistency.Security Best Practices: Enforcing strict IAM policies and using Lambda for auditing manual changes to prevent unauthorized access or modifications.
Proactive Monitoring: Using tools like CloudTrail and Lambda for real-time alerts on manual changes, ensuring infrastructure integrity.


