resource "aws_instance" "my_first_linux" {
    instance_type = "t2.micro"
    ami = "ami-06971c49acd687c30"

	security_groups = ["ssh-access-witch"]

    tags = {
        Name = "labs"
    }
}

resource "aws_s3_bucket" "resume-bucket" {
    tags = {
        Name = "labs"
    }
}

resource "aws_s3_bucket" "lab-bucket" {
    tags = {
        Name = "labs"
    }
}

## Security Group
resource "aws_security_group" "ec2_security_group" {
  description = "Restrict SSH to my IP"
}

resource "aws_security_group" "default" {
   description = "default VPC security group"
}


## Roles
resource "aws_iam_role" "daphodell_role" {
    assume_role_policy = jsonencode({
	"Version": "2012-10-17",
	"Statement": [
		{
			"Effect": "Allow",
			"Principal": {
				"Service": "ec2.amazonaws.com"
			},
			"Action": "sts:AssumeRole"
		},
		{
			"Effect": "Allow",
			"Principal": {
				"AWS": var.ACCOUNT_ROOT_ARN
			},
			"Action": "sts:AssumeRole",
			"Condition": {
				"BoolIfExists": {
					"aws:MultiFactorAuthPresent": "true"
				}
			}
		}
	]})
    tags = {
        Name = "labs"
    }
}

## Policies
## Allow user CLI -> S3 read/write
resource "aws_iam_policy" "assume_role_s3_policy" {
    policy = jsonencode({
			"Version": "2012-10-17",
		    "Statement": [
		        {
		            "Effect": "Allow",
		            "Action": "sts:AssumeRole",
		            "Resource": aws_iam_role.daphodell_role.arn
		        }
		    ]
	})
    tags = {
        Name = "labs"
    }
}

## Allow ec2 -> s3 read/write
resource "aws_iam_policy" "ec2_s3_policy" {
	policy = jsonencode({
    		"Version": "2012-10-17",
    		"Statement": [
    		    {
    		        "Effect": "Allow",
    		        "Action": "s3:ListBucket",
    		        "Resource": "arn:aws:s3:::witch-lab-3"
    		    },
    		    {
    		        "Effect": "Allow",
    		        "Action": "s3:GetObject",
    		        "Resource": "arn:aws:s3:::witch-lab-3/*"
    		    }
    		]
	})
    tags = {
        Name = "labs"
    }
}

# Create AMI
resource "aws_ami_from_instance" "ami_snapshot" {
  name = "ami-snapshot-2025-06-17"
  source_instance_id = aws_instance.my_first_linux.id
  snapshot_without_reboot = true

  tags = {
    Name = "labs"
  }
}

# Launch new instance from AMI
resource "aws_instance" "my_second_linux" {
    instance_type = "t2.micro"
    ami = aws_ami_from_instance.ami_snapshot.id
	security_groups = ["ssh-access-witch"]

    tags = {
        Name = "labs"
    }
}    
    
    
    
    
    
    

    
    
    
    