Skip to main content

Module: ec2-instance

Terraform Module for provisioning a general purpose EC2 host.

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/aws"
# Cloud Posse recommends pinning every module to a specific version
# version = "x.x.x"
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
name = "ec2"
namespace = "eg"
stage = "dev"
}

Example with additional volumes and EIP

module "kafka_instance" {
source = "cloudposse/ec2-instance/aws"
# Cloud Posse recommends pinning every module to a specific version
# version = "x.x.x"
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
name = "kafka"
namespace = "eg"
stage = "dev"
additional_ips_count = 1
ebs_volume_count = 2
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"]
},
{
type = "ingress"
from_port = 53
to_port = 53
protocol = "udp"
cidr_blocks = ["0.0.0.0/0"]
},
]
}

Requirements

NameVersion
terraform>= 1.0
aws>= 4.7.0
null>= 2.0

Providers

NameVersion
aws>= 4.7.0
null>= 2.0

Modules

NameSourceVersion
label_ssm_patch_s3_log_policycloudposse/label/null0.25.0
security_groupcloudposse/security-group/aws0.3.3
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_policy.ssm_patch_s3_log_policyresource
aws_iam_role.defaultresource
aws_iam_role_policy_attachment.ssm_coreresource
aws_iam_role_policy_attachment.ssm_s3_policyresource
aws_instance.defaultresource
aws_network_interface.additionalresource
aws_network_interface_attachment.additionalresource
aws_volume_attachment.defaultresource
null_resource.check_alarm_actionresource
aws_ami.defaultdata source
aws_ami.infodata source
aws_caller_identity.defaultdata source
aws_iam_instance_profile.givendata source
aws_iam_policy_document.defaultdata source
aws_iam_policy_document.ssm_patch_s3_log_policydata source
aws_partition.defaultdata source
aws_region.defaultdata source
aws_subnet.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 instance. By default it is the AMI provided by Amazon with Ubuntu 16.04string""no
ami_ownerOwner of the given AMI (ignored if ami unset, required if set)string""no
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
burstable_modeEnable burstable mode for the instance. Can be standard or unlimited. Applicable only for T2/T3/T4g instance types.stringnullno
comparison_operatorThe arithmetic operation to use when comparing the specified Statistic and Threshold. Possible values are: GreaterThanOrEqualToThreshold, GreaterThanThreshold, LessThanThreshold, LessThanOrEqualToThreshold.string"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_alarm_actionDisable the creation of Alarm Actionboolfalseno
disable_api_terminationEnable EC2 Instance Termination Protectionboolfalseno
ebs_device_nameName 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 io1, io2 or gp3number0no
ebs_optimizedLaunched EC2 instance will be EBS-optimizedbooltrueno
ebs_throughputAmount of throughput. This must be set if volume_type is set to gp3number0no
ebs_volume_countCount of EBS volumes that will be attached to the instancenumber0no
ebs_volume_encryptedWhether to encrypt the additional EBS volumesbooltrueno
ebs_volume_sizeSize of the additional EBS volumes in gigabytesnumber10no
ebs_volume_typeThe type of the additional EBS volumes. Can be standard, gp2, gp3, io1 or io2string"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 threshold.number5no
external_network_interface_enabledWheter to attach an external ENI as the eth0 interface for the instance. Any change to the interface will force instance recreation.boolfalseno
external_network_interfacesThe external interface definitions to attach to the instances. This depends on the instance type
list(object({
delete_on_termination = bool
device_index = number
network_card_index = number
network_interface_id = string
}))
nullno
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_initiated_shutdown_behaviorSpecifies whether an instance stops or terminates when you initiate shutdown from the instance. Can be one of 'stop' or 'terminate'.stringnullno
instance_profileA pre-defined profile to attach to the instance (default is to build our own)string""no
instance_profile_enabledWhether an IAM instance profile is created to pass a role to an Amazon EC2 instance when the instance startsbooltrueno
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 subnet (-1 to use subnet default)number0no
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_put_response_hop_limitThe desired HTTP PUT response hop limit (between 1 and 64) for instance metadata requests.number2no
metadata_http_tokens_requiredWhether or not the metadata service requires session tokens, also referred to as Instance Metadata Service Version 2.booltrueno
metadata_tags_enabledWhether the tags are enabled in the metadata service.boolfalseno
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
metric_treat_missing_dataSets how this alarm is to handle missing data points. The following values are supported: missing, ignore, breaching and notBreaching. Defaults to missing.string"missing"no
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_ipPrivate IP address to associate with the instance in the VPCstringnullno
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 instring""no
root_block_device_encryptedWhether to encrypt the root block devicebooltrueno
root_block_device_kms_key_idKMS key ID used to encrypt EBS volume. When specifying root_block_device_kms_key_id, root_block_device_encrypted needs to be set to truestringnullno
root_iopsAmount of provisioned IOPS. This must be set if root_volume_type is set of io1, io2 or gp3number0no
root_throughputAmount of throughput. This must be set if root_volume_type is set to gp3number0no
root_volume_sizeSize of the root volume in gigabytesnumber10no
root_volume_typeType of root volume. Can be standard, gp2, gp3, io1 or io2string"gp2"no
secondary_private_ipsList of secondary private IP addresses to associate with the instance in the VPClist(string)[]no
security_group_descriptionThe Security Group description.string"EC2 Security Group"no
security_group_enabledWhether to create default Security Group for EC2.booltrueno
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)
[
{
"cidr_blocks": [
"0.0.0.0/0"
],
"description": "Allow all outbound traffic",
"from_port": 0,
"protocol": "-1",
"to_port": 65535,
"type": "egress"
}
]
no
security_group_use_name_prefixWhether to create a default Security Group with unique name beginning with the normalized prefix.boolfalseno
security_groupsA list of Security Group IDs to associate with EC2 instance.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 instancestringnullno
ssm_patch_manager_enabledWhether to enable SSM Patch managerboolfalseno
ssm_patch_manager_iam_policy_arnIAM policy ARN to allow Patch Manager to manage the instance. If not provided, arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore will be usedstringnullno
ssm_patch_manager_s3_log_bucketThe name of the s3 bucket to export the patch log tostringnullno
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
tenancyTenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of 'dedicated' runs on single-tenant hardware. The 'host' tenancy is not supported for the import-instance command. Valid values are 'default', 'dedicated', and 'host'.string"default"no
tenantID element _(Rarely used, not included by default)_. A customer identifier, indicating who this instance of a resource is forstringnullno
user_dataThe user data to provide when launching the instance. Do not pass gzip-compressed data via this argument; use user_data_base64 insteadstringnullno
user_data_base64Can be used instead of user_data to pass base64-encoded binary data directly. Use this instead of user_data whenever the value is not a valid UTF-8 string. For example, gzip-encoded user data must be base64-encoded and passed via this argument to avoid corruptionstringnullno
user_data_replace_on_changeWhen used in combination with user_data or user_data_base64 will trigger a destroy and recreate when set to true.boolfalseno
volume_tags_enabledWhether or not to copy instance tags to root and EBS volumesbooltrueno
vpc_idThe ID of the VPC that the instance security group belongs tostringn/ayes

Outputs

NameDescription
additional_eni_idsMap of ENI to EIP
alarmCloudWatch Alarm ID
arnARN of the instance
ebs_idsIDs of EBSs
idDisambiguated ID of the instance
instance_profileName of the instance's profile (either built or supplied)
nameInstance name
primary_network_interface_idID of the instance's primary network interface
private_dnsPrivate DNS of instance
private_ipPrivate IP of instance
public_dnsPublic DNS of instance (or DNS of EIP)
public_ipPublic IP of instance (or EIP)
roleName of AWS IAM Role associated with the instance
role_arnARN of AWS IAM Role associated with the instance
security_group_arnEC2 instance Security Group ARN
security_group_idEC2 instance Security Group ID
security_group_idsIDs on the AWS Security Groups associated with the instance
security_group_nameEC2 instance Security Group name
ssh_key_pairName of the SSH key pair provisioned on the instance