This is a sample of AWS EC2 Terraform module.
module "ec2_public" {
source = "git::https://github.com/signorrayan/aws-ec2-terraform-module.git?ref=v1.3.6" #Always try to use the latest vesrion
# Insert the required variables here
name = "${var.environment}-BastionHost"
ami = data.aws_ami.ubuntu.id
instance_type = var.instance_type
key_name = var.instance_keypair
subnet_id = var.public_subnets
vpc_security_group_ids = [var.security_group_id]
instance_count = 3
}
- In this file, there are following data blocks that I used:
aws_ami
: It is Ubuntu 22 OS, you can use it, or you can easily define your AMI id variable inside terraform.tfvarsaws_partition
: This block will lookup information about the current AWS partition in which Terraform is working. (I will use its dns_suffix output in the following data resource)aws_iam_policy_document
: In aws_iam_policy_document I wrote an IAM policy document in JSON format for use inaws_iam_role
resource. (More information)
- Locals are useful to use when you want to give the result of an expression and then re-use that result throughout your configuration. That's why I used locals to create iam_role_name and a list of instance_names.
- In this file I defined the main structure of Terraform script which:
- Will create one or more EC2 instances. (default number of instances (
instance_count
) to create is set to 1, and the defaultenvironment
is set to 'test'. So you can change them by defining these variables.) - Will create an IAM role, and an IAM instance profile. (An instance profile is a container for an IAM role that we can use to pass role information to an EC2 instance when the instance starts, that's why I defined an
aws_iam_instance_profile
) - Will create two security groups to allow outgoing traffic and allow incoming ssh connections on port 22 if variable
create_sg
is set totrue
. the default value forcreate_sg
is false, so if you want to create these security groups, define it in tfvars and set it totrue
.- (Note: even if the
create_sg
is set to false, the AWS will createoutgoing
security group by default.)
- (Note: even if the
- Will create one or more EC2 instances. (default number of instances (
- Take a look at
variables.tf
, and see what variables are defined and you want to define your values for them in tfvars. - Don't forget to specify
region
andinstance_type
in terraform.tfvars - Run the following commands to initialize the Terraform and push the settings to AWS:
terraform init terraform validate terraform plan terraform apply