How to get code onto aws ec2 instance using terraform and gitlabs
Setup a Jenkins server. Please do code checkout using Jenkins. Jenkins supports parameterized build. you can pass selected parameter from Jenkins UI to linux bash.
Then use linux's cli command to fire terraform.Terraform supports several workspace. You can use same code for dev, test and prod.
terraform workspace new dev
Use this command to create new workspace. After that , we can use this workspace name to your code. Below is the content of local.tf
locals {
  env = terraform.workspace
}

Like below use the same code for multiple env.
resource &quot;aws_autoscaling_group&quot; &quot;asg&quot; {
  name = &quot;${local.env}-${local.project}-demo-asg&quot;
}

Moreover to save your state file securely , you can use s3 as backend.
terraform {
  backend &quot;s3&quot; {
    bucket = &quot;tfstate-demo&quot;
    key = &quot;keyfiles&quot;
    region = &quot;ap-southeast-1&quot;
    dynamodb_table = &quot;tfstate-demo&quot;
  }
}

To separate backend and frontend service, use best practice of AWS. Create a public ALB for frontend and then move traffic to backend services via private ALB.
You can use Ansible as a configuration manager to build your server then create a AMI of that using packer. Later on, use the same AMI in ASG.