Terraform Scenario Qus

Terraform Scenario Qus

ยท

2 min read

Scenario 1 : Terraform Migration of AWS Resource

Step 1: Import Resource Configuration

  • Import Block: Add the import block in main.tf to specify the EC2 resource ID and target resource name:

      import {
        id = "instance ID"
        to = aws_instance.example
      }
    
  • Generate Resource Configuration: Run the command to fetch the resource configuration:

      terraform plan -generate-config-out=generated_resources.tf
    
  • Copy Code: Copy the generated resource block from generated_resources.tf to main.tf.

  • Cleanup: Delete generated_resources.tf as it is no longer needed.

Step 2: Import Resource into Statefile

  • Run the import command to bring the resource into Terraform state:

      terraform import aws_instance.example <instance ID>
    
  • Result: The resource data is imported into the Terraform state file, ensuring the state matches the actual resource.

Scenario 2 : Terraform Drift Detection

Terraform doesn't automatically detect manual changes made directly in the AWS cloud.

Solution 1: Use a Cron Job to Refresh Terraform State

  • Set up a cron job to periodically run terraform refresh, which updates the Terraform state with the latest changes in the cloud.

Solution 2: Use Audit Logs or Event Notifications

  • Audit Logs: Enable AWS CloudTrail to log and monitor all changes.

  • AWS Lambda/Notification: Use AWS Lambda functions or event notifications to alert or trigger Terraform updates when manual changes happen by IAM users.

ย