Skip to main content

Module: ec2-instance-group

Terraform Module for providing N general purpose EC2 hosts.

If you only need to provision a single EC2 instance, consider using the terraform-aws-ec2-instance module instead.

IMPORTANT This module by-design does not provision an AutoScaling group. It was designed to provision a discrete number of instances suitable for running stateful services such as databases (e.g. Kafka, Redis, etc).

Included features:

  • Automatically create a Security Group
  • Option to switch EIP attachment
  • CloudWatch monitoring and automatic reboot if instance hangs
  • Assume Role capability

Usage

Note: add ${var.ssh_key_pair} private key to the ssh agent.

Include this repository as a module in your existing terraform code.

Simple example:

module "instance" {
source = "cloudposse/ec2-instance-group/aws"
# Cloud Posse recommends pinning every module to a specific version
# version = "x.x.x"
namespace = "eg"
stage = "prod"
name = "app"
ami = "ami-a4dc46db"
ami_owner = "099720109477"
ssh_key_pair = var.ssh_key_pair
instance_type = var.instance_type
vpc_id = var.vpc_id
security_groups = var.security_groups
subnet = var.subnet
instance_count = 3
}

Example with additional volumes and EIP

module "kafka_instance" {
source = "cloudposse/ec2-instance-group/aws"
# Cloud Posse recommends pinning every module to a specific version
# version = "x.x.x"

namespace = "eg"
stage = "prod"
name = "app"
ami = "ami-a4dc46db"
ami_owner = "099720109477"
ssh_key_pair = var.ssh_key_pair
vpc_id = var.vpc_id
security_groups = var.security_groups
subnet = var.subnet
associate_public_ip_address = true
additional_ips_count = 1
ebs_volume_count = 2
instance_count = 3

security_group_rules = [
{
type = "egress"
from_port = 0
to_port = 65535
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
},
{
type = "ingress"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
},
{
type = "ingress"
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
},
{
type = "ingress"
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
]
}

Additional complete working example with variations of how to use the module

In /examples directory

This module depends on these modules:

It is necessary to run terraform get or terraform init to download this module.

Now reference the label when creating an instance (for example):

resource "aws_ami_from_instance" "example" {
count = length(module.instance.*.id)
name = "app"
source_instance_id = element(module.instance.*.id, count.index)
}

Requirements

NameVersion
terraform>= 1.0
aws>= 2.0

Providers

NameVersion
aws>= 2.0

Modules

NameSourceVersion
labelcloudposse/label/null0.25.0
security_groupcloudposse/security-group/aws2.2.0
ssh_key_paircloudposse/key-pair/aws0.19.0
thiscloudposse/label/null0.25.0

Resources

NameType
aws_cloudwatch_metric_alarm.defaultresource
aws_ebs_volume.defaultresource
aws_eip.additionalresource
aws_eip.defaultresource
aws_iam_instance_profile.defaultresource
aws_iam_role.defaultresource
aws_instance.defaultresource
aws_network_interface.additionalresource
aws_network_interface_attachment.additionalresource
aws_volume_attachment.defaultresource
aws_ami.infodata source
aws_caller_identity.defaultdata source
aws_iam_policy_document.defaultdata source
aws_region.defaultdata source

Inputs

NameDescriptionTypeDefaultRequired
additional_ips_countCount of additional EIPsnumber0no
additional_tag_mapAdditional key-value pairs to add to each map in tags_as_list_of_maps. Not added to tags or id.
This is for some rare cases where resources want additional configuration of tags
and therefore take a list of maps with tag key, value, and additional configuration.
map(string){}no
amiThe AMI to use for the instancestringn/ayes
ami_ownerOwner of the given AMIstringn/ayes
applying_periodThe period in seconds over which the specified statistic is appliednumber60no
assign_eip_addressAssign an Elastic IP address to the instancebooltrueno
associate_public_ip_addressAssociate a public IP address with the instanceboolfalseno
attributesID element. Additional attributes (e.g. workers or cluster) to add to id,
in the order they appear in the list. New attributes are appended to the
end of the list. The elements of the list are joined by the delimiter
and treated as a single ID element.
list(string)[]no
availability_zoneAvailability Zone the instance is launched in. If not set, will be launched in the first AZ of the regionstring""no
comparison_operatorThe arithmetic operation to use when comparing the specified Statistic and Threshold. Possible values are: GreaterThanOrEqualToThreshold, GreaterThanThreshold, LessThanThreshold, LessThanOrEqualToThresholdstring"GreaterThanOrEqualToThreshold"no
contextSingle object for setting entire context at once.
See description of individual variables for details.
Leave string and numeric variables as null to use default value.
Individual variable settings (non-null) override settings in context object,
except for attributes, tags, and additional_tag_map, which are merged.
any
{
"additional_tag_map": {},
"attributes": [],
"delimiter": null,
"descriptor_formats": {},
"enabled": true,
"environment": null,
"id_length_limit": null,
"label_key_case": null,
"label_order": [],
"label_value_case": null,
"labels_as_tags": [
"unset"
],
"name": null,
"namespace": null,
"regex_replace_chars": null,
"stage": null,
"tags": {},
"tenant": null
}
no
default_alarm_actionDefault alarm actionstring"action/actions/AWS_EC2.InstanceId.Reboot/1.0"no
delete_on_terminationWhether the volume should be destroyed on instance terminationbooltrueno
delimiterDelimiter to be used between ID elements.
Defaults to - (hyphen). Set to "" to use no delimiter at all.
stringnullno
descriptor_formatsDescribe additional descriptors to be output in the descriptors output map.
Map of maps. Keys are names of descriptors. Values are maps of the form
{<br/> format = string<br/> labels = list(string)<br/>}
(Type is any so the map values can later be enhanced to provide additional options.)
format is a Terraform format string to be passed to the format() function.
labels is a list of labels, in order, to pass to format() function.
Label values will be normalized before being passed to format() so they will be
identical to how they appear in id.
Default is {} (descriptors output will be empty).
any{}no
disable_api_terminationEnable EC2 Instance Termination Protectionboolfalseno
ebs_device_namesName of the EBS device to mountlist(string)
[
"/dev/xvdb",
"/dev/xvdc",
"/dev/xvdd",
"/dev/xvde",
"/dev/xvdf",
"/dev/xvdg",
"/dev/xvdh",
"/dev/xvdi",
"/dev/xvdj",
"/dev/xvdk",
"/dev/xvdl",
"/dev/xvdm",
"/dev/xvdn",
"/dev/xvdo",
"/dev/xvdp",
"/dev/xvdq",
"/dev/xvdr",
"/dev/xvds",
"/dev/xvdt",
"/dev/xvdu",
"/dev/xvdv",
"/dev/xvdw",
"/dev/xvdx",
"/dev/xvdy",
"/dev/xvdz"
]
no
ebs_iopsAmount of provisioned IOPS. This must be set with a volume_type of io1number0no
ebs_optimizedLaunched EC2 instance will be EBS-optimizedboolfalseno
ebs_volume_countCount of EBS volumes that will be attached to the instancenumber0no
ebs_volume_encryptedSize of the EBS volume in gigabytesbooltrueno
ebs_volume_sizeSize of the EBS volume in gigabytesnumber10no
ebs_volume_typeThe type of EBS volume. Can be standard, gp2 or io1string"gp2"no
enabledSet to false to prevent the module from creating any resourcesboolnullno
environmentID element. Usually used for region e.g. 'uw2', 'us-west-2', OR role 'prod', 'staging', 'dev', 'UAT'stringnullno
evaluation_periodsThe number of periods over which data is compared to the specified thresholdnumber5no
generate_ssh_key_pairIf true, create a new key pair and save the pem for it to the current working directoryboolfalseno
id_length_limitLimit id to this many characters (minimum 6).
Set to 0 for unlimited length.
Set to null for keep the existing setting, which defaults to 0.
Does not affect id_full.
numbernullno
instance_countCount of ec2 instances to createnumber1no
instance_typeThe type of the instancestring"t2.micro"no
ipv6_address_countNumber of IPv6 addresses to associate with the primary network interface. Amazon EC2 chooses the IPv6 addresses from the range of your subnetnumber0no
ipv6_addressesList of IPv6 addresses from the range of the subnet to associate with the primary network interfacelist(string)[]no
kms_key_idKMS key ID used to encrypt EBS volume. When specifying kms_key_id, ebs_volume_encrypted needs to be set to truestringnullno
label_key_caseControls the letter case of the tags keys (label names) for tags generated by this module.
Does not affect keys of tags passed in via the tags input.
Possible values: lower, title, upper.
Default value: title.
stringnullno
label_orderThe order in which the labels (ID elements) appear in the id.
Defaults to ["namespace", "environment", "stage", "name", "attributes"].
You can omit any of the 6 labels ("tenant" is the 6th), but at least one must be present.
list(string)nullno
label_value_caseControls the letter case of ID elements (labels) as included in id,
set as tag values, and output by this module individually.
Does not affect values of tags passed in via the tags input.
Possible values: lower, title, upper and none (no transformation).
Set this to title and set delimiter to "" to yield Pascal Case IDs.
Default value: lower.
stringnullno
labels_as_tagsSet of labels (ID elements) to include as tags in the tags output.
Default is to include all labels.
Tags with empty values will not be included in the tags output.
Set to [] to suppress all generated tags.
Notes:
The value of the name tag, if included, will be the id, not the name.
Unlike other null-label inputs, the initial setting of labels_as_tags cannot be
changed in later chained modules. Attempts to change it will be silently ignored.
set(string)
[
"default"
]
no
metadata_http_endpoint_enabledWhether the metadata service is availablebooltrueno
metadata_http_tokens_requiredWhether or not the metadata service requires session tokens, also referred to as Instance Metadata Service Version 2.booltrueno
metric_nameThe name for the alarm's associated metric. Allowed values can be found in https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ec2-metricscollected.htmlstring"StatusCheckFailed_Instance"no
metric_namespaceThe namespace for the alarm's associated metric. Allowed values can be found in https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/aws-namespaces.htmlstring"AWS/EC2"no
metric_thresholdThe value against which the specified statistic is comparednumber1no
monitoringLaunched EC2 instance will have detailed monitoring enabledbooltrueno
nameID element. Usually the component or solution name, e.g. 'app' or 'jenkins'.
This is the only ID element not also included as a tag.
The "name" tag is set to the full id string. There is no tag with the value of the name input.
stringnullno
namespaceID element. Usually an abbreviation of your organization name, e.g. 'eg' or 'cp', to help ensure generated IDs are globally uniquestringnullno
permissions_boundary_arnPolicy ARN to attach to instance role as a permissions boundarystring""no
private_ipsPrivate IP address to associate with the instances in the VPClist(string)[]no
regex_replace_charsTerraform regular expression (regex) string.
Characters matching the regex will be removed from the ID elements.
If not set, "/[^a-zA-Z0-9-]/" is used to remove all characters other than hyphens, letters and digits.
stringnullno
regionAWS Region the instance is launched instringn/ayes
root_block_device_encryptedWhether to encrypt the root block devicebooltrueno
root_iopsAmount of provisioned IOPS. This must be set if root_volume_type is set to io1number0no
root_volume_sizeSize of the root volume in gigabytesnumber10no
root_volume_typeType of root volume. Can be standard, gp2 or io1string"gp2"no
security_group_descriptionThe Security Group description.string"EC2 instances Security Group"no
security_group_enabledWhether to create default Security Group for EC2 instances.booltrueno
security_group_nameThe name to assign to the security group. Must be unique within the VPC.
If not provided, will be derived from the null-label.context passed in.
If create_before_destroy is true, will be used as a name prefix.
list(string)[]no
security_group_rulesA list of maps of Security Group rules.
The values of map is fully complated with aws_security_group_rule resource.
To get more info see https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group_rule .
list(any)[]no
security_groupsA list of Security Group IDs to associate with EC2 instances.list(string)[]no
source_dest_checkControls if traffic is routed to the instance when the destination address does not match the instance. Used for NAT or VPNsbooltrueno
ssh_key_pairSSH key pair to be provisioned on the instancestring""no
ssh_key_pair_pathPath to where the generated key pairs will be created. Defaults to $${path.cwd}string""no
stageID element. Usually used to indicate role, e.g. 'prod', 'staging', 'source', 'build', 'test', 'deploy', 'release'stringnullno
statistic_levelThe statistic to apply to the alarm's associated metric. Allowed values are: SampleCount, Average, Sum, Minimum, Maximumstring"Maximum"no
subnetVPC Subnet ID the instance is launched instringn/ayes
tagsAdditional tags (e.g. {'BusinessUnit': 'XYZ'}).
Neither the tag keys nor the tag values will be modified by this module.
map(string){}no
tenantID element _(Rarely used, not included by default)_. A customer identifier, indicating who this instance of a resource is forstringnullno
user_dataInstance user data. Do not pass gzip-compressed data via this argumentstring""no
vpc_idThe ID of the VPC that the instance security group belongs tostringn/ayes

Outputs

NameDescription
alarm_idsCloudWatch Alarm IDs
aws_key_pair_nameName of AWS key pair
ebs_idsIDs of EBSs
eip_per_instance_countNumber of EIPs per instance.
eni_to_eip_mapMap of ENI with EIP
idsDisambiguated IDs list
instance_countTotal number of instances created
nameInstance(s) name
new_ssh_keypair_generatedWas a new ssh_key_pair generated
primary_network_interface_idsIDs of the instance's primary network interface
private_dnsPrivate DNS records of instances
private_ipsPrivate IPs of instances
public_dnsAll public DNS records for the public interfaces and ENIs
public_ipsList of Public IPs of instances (or EIP)
role_namesNames of AWS IAM Roles associated with creating instance
security_group_arnEC2 instances Security Group ARN
security_group_idEC2 instances Security Group ID
security_group_idsID on the new AWS Security Group associated with creating instance
security_group_nameEC2 instances Security Group name
ssh_key_pem_pathPath where SSH key pair was created (if applicable)