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)
}

Variables

Required Variables

ami (string) required

The AMI to use for the instance

ami_owner (string) required

Owner of the given AMI

region (string) required

AWS Region the instance is launched in

subnet (string) required

VPC Subnet ID the instance is launched in

vpc_id (string) required

The ID of the VPC that the instance security group belongs to

Optional Variables

additional_ips_count (number) optional

Count of additional EIPs


Default value: 0

applying_period (number) optional

The period in seconds over which the specified statistic is applied


Default value: 60

assign_eip_address (bool) optional

Assign an Elastic IP address to the instance


Default value: true

associate_public_ip_address (bool) optional

Associate a public IP address with the instance


Default value: false

availability_zone (string) optional

Availability Zone the instance is launched in. If not set, will be launched in the first AZ of the region


Default value: ""

comparison_operator (string) optional

The arithmetic operation to use when comparing the specified Statistic and Threshold. Possible values are: GreaterThanOrEqualToThreshold, GreaterThanThreshold, LessThanThreshold, LessThanOrEqualToThreshold


Default value: "GreaterThanOrEqualToThreshold"

default_alarm_action (string) optional

Default alarm action


Default value: "action/actions/AWS_EC2.InstanceId.Reboot/1.0"

delete_on_termination (bool) optional

Whether the volume should be destroyed on instance termination


Default value: true

disable_api_termination (bool) optional

Enable EC2 Instance Termination Protection


Default value: false

ebs_device_names (list(string)) optional

Name of the EBS device to mount


Default value:

[
"/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"
]
ebs_iops (number) optional

Amount of provisioned IOPS. This must be set with a volume_type of io1


Default value: 0

ebs_optimized (bool) optional

Launched EC2 instance will be EBS-optimized


Default value: false

ebs_volume_count (number) optional

Count of EBS volumes that will be attached to the instance


Default value: 0

ebs_volume_encrypted (bool) optional

Size of the EBS volume in gigabytes


Default value: true

ebs_volume_size (number) optional

Size of the EBS volume in gigabytes


Default value: 10

ebs_volume_type (string) optional

The type of EBS volume. Can be standard, gp2 or io1


Default value: "gp2"

evaluation_periods (number) optional

The number of periods over which data is compared to the specified threshold


Default value: 5

generate_ssh_key_pair (bool) optional

If true, create a new key pair and save the pem for it to the current working directory


Default value: false

instance_count (number) optional

Count of ec2 instances to create


Default value: 1

instance_type (string) optional

The type of the instance


Default value: "t2.micro"

ipv6_address_count (number) optional

Number of IPv6 addresses to associate with the primary network interface. Amazon EC2 chooses the IPv6 addresses from the range of your subnet


Default value: 0

ipv6_addresses (list(string)) optional

List of IPv6 addresses from the range of the subnet to associate with the primary network interface


Default value: [ ]

kms_key_id (string) optional

KMS key ID used to encrypt EBS volume. When specifying kms_key_id, ebs_volume_encrypted needs to be set to true


Default value: null

metadata_http_endpoint_enabled (bool) optional

Whether the metadata service is available


Default value: true

metadata_http_tokens_required (bool) optional

Whether or not the metadata service requires session tokens, also referred to as Instance Metadata Service Version 2.


Default value: true

metric_name (string) optional

The name for the alarm's associated metric. Allowed values can be found in https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ec2-metricscollected.html


Default value: "StatusCheckFailed_Instance"

metric_namespace (string) optional

The namespace for the alarm's associated metric. Allowed values can be found in https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/aws-namespaces.html


Default value: "AWS/EC2"

metric_threshold (number) optional

The value against which the specified statistic is compared


Default value: 1

monitoring (bool) optional

Launched EC2 instance will have detailed monitoring enabled


Default value: true

permissions_boundary_arn (string) optional

Policy ARN to attach to instance role as a permissions boundary


Default value: ""

private_ips (list(string)) optional

Private IP address to associate with the instances in the VPC


Default value: [ ]

root_block_device_encrypted (bool) optional

Whether to encrypt the root block device


Default value: true

root_iops (number) optional

Amount of provisioned IOPS. This must be set if root_volume_type is set to io1


Default value: 0

root_volume_size (number) optional

Size of the root volume in gigabytes


Default value: 10

root_volume_type (string) optional

Type of root volume. Can be standard, gp2 or io1


Default value: "gp2"

security_group_description (string) optional

The Security Group description.


Default value: "EC2 instances Security Group"

security_group_enabled (bool) optional

Whether to create default Security Group for EC2 instances.


Default value: true

security_group_name (list(string)) optional

The 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.



Default value: [ ]

security_group_rules (list(any)) optional

A 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 .



Default value: [ ]

security_groups (list(string)) optional

A list of Security Group IDs to associate with EC2 instances.


Default value: [ ]

source_dest_check (bool) optional

Controls if traffic is routed to the instance when the destination address does not match the instance. Used for NAT or VPNs


Default value: true

ssh_key_pair (string) optional

SSH key pair to be provisioned on the instance


Default value: ""

ssh_key_pair_path (string) optional

Path to where the generated key pairs will be created. Defaults to $${path.cwd}


Default value: ""

statistic_level (string) optional

The statistic to apply to the alarm's associated metric. Allowed values are: SampleCount, Average, Sum, Minimum, Maximum


Default value: "Maximum"

user_data (string) optional

Instance user data. Do not pass gzip-compressed data via this argument


Default value: ""

Context Variables

The following variables are defined in the context.tf file of this module and part of the terraform-null-label pattern.

additional_tag_map (map(string)) optional

Additional 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.


Required: No

Default value: { }

attributes (list(string)) optional

ID 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.


Required: No

Default value: [ ]

context (any) optional

Single 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.


Required: No

Default value:

{
"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
}
delimiter (string) optional

Delimiter to be used between ID elements.
Defaults to - (hyphen). Set to "" to use no delimiter at all.


Required: No

Default value: null

descriptor_formats (any) optional

Describe 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).


Required: No

Default value: { }

enabled (bool) optional

Set to false to prevent the module from creating any resources
Required: No

Default value: null

environment (string) optional

ID element. Usually used for region e.g. 'uw2', 'us-west-2', OR role 'prod', 'staging', 'dev', 'UAT'
Required: No

Default value: null

id_length_limit (number) optional

Limit 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.


Required: No

Default value: null

label_key_case (string) optional

Controls 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.


Required: No

Default value: null

label_order (list(string)) optional

The 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.


Required: No

Default value: null

label_value_case (string) optional

Controls 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.


Required: No

Default value: null

labels_as_tags (set(string)) optional

Set 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.


Required: No

Default value:

[
"default"
]
name (string) optional

ID 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.


Required: No

Default value: null

namespace (string) optional

ID element. Usually an abbreviation of your organization name, e.g. 'eg' or 'cp', to help ensure generated IDs are globally unique
Required: No

Default value: null

regex_replace_chars (string) optional

Terraform 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.


Required: No

Default value: null

stage (string) optional

ID element. Usually used to indicate role, e.g. 'prod', 'staging', 'source', 'build', 'test', 'deploy', 'release'
Required: No

Default value: null

tags (map(string)) optional

Additional tags (e.g. {'BusinessUnit': 'XYZ'}).
Neither the tag keys nor the tag values will be modified by this module.


Required: No

Default value: { }

tenant (string) optional

ID element (Rarely used, not included by default). A customer identifier, indicating who this instance of a resource is for
Required: No

Default value: null

Outputs

alarm_ids

CloudWatch Alarm IDs

aws_key_pair_name

Name of AWS key pair

ebs_ids

IDs of EBSs

eip_per_instance_count

Number of EIPs per instance.

eni_to_eip_map

Map of ENI with EIP

ids

Disambiguated IDs list

instance_count

Total number of instances created

name

Instance(s) name

new_ssh_keypair_generated

Was a new ssh_key_pair generated

primary_network_interface_ids

IDs of the instance's primary network interface

private_dns

Private DNS records of instances

private_ips

Private IPs of instances

public_dns

All public DNS records for the public interfaces and ENIs

public_ips

List of Public IPs of instances (or EIP)

role_names

Names of AWS IAM Roles associated with creating instance

security_group_arn

EC2 instances Security Group ARN

security_group_id

EC2 instances Security Group ID

security_group_ids

ID on the new AWS Security Group associated with creating instance

security_group_name

EC2 instances Security Group name

ssh_key_pem_path

Path where SSH key pair was created (if applicable)

Dependencies

Requirements

  • terraform, version: >= 1.0
  • aws, version: >= 2.0

Providers

  • aws, version: >= 2.0

Modules

NameVersionSourceDescription
label0.25.0cloudposse/label/nulln/a
security_group2.2.0cloudposse/security-group/awsn/a
ssh_key_pair0.19.0cloudposse/key-pair/awsn/a
this0.25.0cloudposse/label/nulln/a

Resources

The following resources are used by this module:

Data Sources

The following data sources are used by this module: