⚙️ Terraform create AWS EC2 instance with Python environment
Terraform can provision an AWS EC2 instance and set up a Python virtual environment in a single, reproducible run — the whole workflow is declarative and version‑controlled. 📑 Table of Contents 💻 Terraform — How to Provision an EC2 Instance 🔧 AWS Provider — Configuring Credentials 🐍 Python Environment — Setting up a Virtualenv on the Instance 📦 Installing Python and venv 📦 Activating and Using the Environment 📦 User Data — Automating Installation with Terraform 🟩 Final Thoughts ❓ Frequently Asked Questions How do I store the Terraform state securely? Can I use a different Linux distribution for the EC2 instance? Is it possible to attach an Elastic IP to the instance? 📚 References & Further Reading 💻 Terraform — How to Provision an EC2 Instance A Terraform configuration file describes the desired state of AWS resources; applying it makes the real cloud match that state. First, install Terraform (version 1.5.0 or newer). The binary is a single executable, so the operating system loads it directly into memory and the process performs HTTP requests to AWS endpoints. $ terraform version Terraform v1.5.0 on linux_amd64 + provider registry.terraform.io/hashicorp/aws v5.12.0 Next, create a main.tf that declares an aws_instance resource. The provider block authenticates with AWS using either environment variables or a shared credentials file. # main.tf terraform { required_version = ">= 1.5.0" required_providers { aws = { source = "hashicorp/aws" version = "~> 5.12" } } } provider "aws" { region = "us-east-1" } resource "aws_instance" "app_server" { ami = "ami-0c02fb55956c7d316" # Amazon Linux 2 instance_type = "t3.micro" # User data will be defined later user_data = data.template_file.init.rendered tags = { Name = "terraform-ec2-python" } } Running terraform init contacts the provider registry, downloads the provider plugin, and stores it under .terraform . The generated .terraform.lock.hcl file records exact plugin checksums, guaranteeing that subsequent runs use the same