1+ import os
2+
3+ project_name = "MyTerraform"
4+ base_dir = "app/media/"
5+ terraform_dir = os .path .join (base_dir , project_name , "terraform" )
6+ modules_dir = os .path .join (terraform_dir , "modules" )
7+ ci_dir = os .path .join (base_dir , project_name , ".github" , "workflows" )
8+
9+ os .makedirs (terraform_dir , exist_ok = True )
10+ os .makedirs (modules_dir , exist_ok = True )
11+ os .makedirs (ci_dir , exist_ok = True )
12+
13+ # Create main.tf
14+ with open (os .path .join (terraform_dir , "main.tf" ), 'w' ) as f :
15+ f .write (f'''provider "aws" {{
16+ region = "us-west-2"
17+ }}
18+
19+ module "ec2_instance" {{
20+ source = "./modules/ec2"
21+
22+ instance_type = "t2.micro"
23+ ami = "ami-0c55b159cbfafe1f0" # Update with a valid AMI ID
24+ }}
25+ ''' )
26+
27+ # Create variables.tf
28+ with open (os .path .join (terraform_dir , "variables.tf" ), 'w' ) as f :
29+ f .write ('''variable "instance_type" {
30+ description = "Type of EC2 instance"
31+ type = string
32+ default = "t2.micro"
33+ }
34+
35+ variable "ami" {
36+ description = "AMI ID for the EC2 instance"
37+ type = string
38+ }
39+ ''' )
40+
41+ # Create outputs.tf
42+ with open (os .path .join (terraform_dir , "outputs.tf" ), 'w' ) as f :
43+ f .write ('''output "instance_id" {
44+ value = module.ec2_instance.instance_id
45+ }
46+ ''' )
47+
48+ # Create EC2 module directory
49+ ec2_module_dir = os .path .join (modules_dir , "ec2" )
50+ os .makedirs (ec2_module_dir , exist_ok = True )
51+
52+ # Create ec2/main.tf for the module
53+ with open (os .path .join (ec2_module_dir , "main.tf" ), 'w' ) as f :
54+ f .write ('''resource "aws_instance" "this" {
55+ ami = var.ami
56+ instance_type = var.instance_type
57+
58+ tags = {
59+ Name = "TerraformEC2Instance"
60+ }
61+ }
62+
63+ output "instance_id" {
64+ value = aws_instance.this.id
65+ }
66+ ''' )
67+
68+ # Create CI pipeline file
69+ with open (os .path .join (ci_dir , "terraform.yml" ), 'w' ) as f :
70+ f .write ('''name: Terraform
71+
72+ on:
73+ push:
74+ branches:
75+ - main
76+
77+ jobs:
78+ terraform:
79+ runs-on: ubuntu-latest
80+
81+ steps:
82+ - name: Checkout Code
83+ uses: actions/checkout@v2
84+
85+ - name: Set up Terraform
86+ uses: hashicorp/setup-terraform@v1
87+ with:
88+ terraform_version: 1.0.0
89+
90+ - name: Terraform Init
91+ run: terraform init
92+
93+ - name: Terraform Plan
94+ run: terraform plan
95+
96+ - name: Terraform Apply
97+ run: terraform apply -auto-approve
98+ ''' )
0 commit comments