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"]
},
]
}
Variables
Required Variables
subnet
(string
) requiredVPC Subnet ID the instance is launched in
vpc_id
(string
) requiredThe ID of the VPC that the instance security group belongs to
Optional Variables
additional_ips_count
(number
) optionalCount of additional EIPs
Default value:
0
ami
(string
) optionalThe AMI to use for the instance. By default it is the AMI provided by Amazon with Ubuntu 16.04
Default value:
""
ami_owner
(string
) optionalOwner of the given AMI (ignored if
ami
unset, required if set)Default value:
""
applying_period
(number
) optionalThe period in seconds over which the specified statistic is applied
Default value:
60
assign_eip_address
(bool
) optionalAssign an Elastic IP address to the instance
Default value:
true
associate_public_ip_address
(bool
) optionalAssociate a public IP address with the instance
Default value:
false
availability_zone
(string
) optionalAvailability Zone the instance is launched in. If not set, will be launched in the first AZ of the region
Default value:
""
burstable_mode
(string
) optionalEnable burstable mode for the instance. Can be standard or unlimited. Applicable only for T2/T3/T4g instance types.
Default value:
null
comparison_operator
(string
) optionalThe 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
) optionalDefault alarm action
Default value:
"action/actions/AWS_EC2.InstanceId.Reboot/1.0"
delete_on_termination
(bool
) optionalWhether the volume should be destroyed on instance termination
Default value:
true
disable_alarm_action
(bool
) optionalDisable the creation of Alarm Action
Default value:
false
disable_api_stop
(bool
) optionalEnable EC2 Instance Stop Protection
Default value:
false
disable_api_termination
(bool
) optionalEnable EC2 Instance Termination Protection
Default value:
false
ebs_device_name
(list(string)
) optionalName 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
) optionalAmount of provisioned IOPS. This must be set with a volume_type of
io1
,io2
orgp3
Default value:
0
ebs_optimized
(bool
) optionalLaunched EC2 instance will be EBS-optimized
Default value:
true
ebs_throughput
(number
) optionalAmount of throughput. This must be set if volume_type is set to
gp3
Default value:
0
ebs_volume_count
(number
) optionalCount of EBS volumes that will be attached to the instance
Default value:
0
ebs_volume_encrypted
(bool
) optionalWhether to encrypt the additional EBS volumes
Default value:
true
ebs_volume_size
(number
) optionalSize of the additional EBS volumes in gigabytes
Default value:
10
ebs_volume_type
(string
) optionalThe type of the additional EBS volumes. Can be standard, gp2, gp3, io1 or io2
Default value:
"gp2"
evaluation_periods
(number
) optionalThe number of periods over which data is compared to the specified threshold.
Default value:
5
external_network_interface_enabled
(bool
) optionalWheter to attach an external ENI as the eth0 interface for the instance. Any change to the interface will force instance recreation.
Default value:
false
external_network_interfaces
optionalThe external interface definitions to attach to the instances. This depends on the instance type
Type:
list(object({
delete_on_termination = bool
device_index = number
network_card_index = number
network_interface_id = string
}))Default value:
null
force_detach_ebs
(bool
) optionalforce the volume/s to detach from the instance.
Default value:
false
instance_initiated_shutdown_behavior
(string
) optionalSpecifies whether an instance stops or terminates when you initiate shutdown from the instance. Can be one of 'stop' or 'terminate'.
Default value:
null
instance_profile
(string
) optionalA pre-defined profile to attach to the instance (default is to build our own)
Default value:
""
instance_profile_enabled
(bool
) optionalWhether an IAM instance profile is created to pass a role to an Amazon EC2 instance when the instance starts
Default value:
true
instance_type
(string
) optionalThe type of the instance
Default value:
"t2.micro"
ipv6_address_count
(number
) optionalNumber 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)
Default value:
0
ipv6_addresses
(list(string)
) optionalList of IPv6 addresses from the range of the subnet to associate with the primary network interface
Default value:
[ ]
kms_key_id
(string
) optionalKMS 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
) optionalWhether the metadata service is available
Default value:
true
metadata_http_put_response_hop_limit
(number
) optionalThe desired HTTP PUT response hop limit (between 1 and 64) for instance metadata requests.
Default value:
2
metadata_http_tokens_required
(bool
) optionalWhether or not the metadata service requires session tokens, also referred to as Instance Metadata Service Version 2.
Default value:
true
metadata_tags_enabled
(bool
) optionalWhether the tags are enabled in the metadata service.
Default value:
false
metric_name
(string
) optionalThe 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
) optionalThe 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
) optionalThe value against which the specified statistic is compared
Default value:
1
metric_treat_missing_data
(string
) optionalSets how this alarm is to handle missing data points. The following values are supported:
missing
,ignore
,breaching
andnotBreaching
. Defaults tomissing
.Default value:
"missing"
monitoring
(bool
) optionalLaunched EC2 instance will have detailed monitoring enabled
Default value:
true
permissions_boundary_arn
(string
) optionalPolicy ARN to attach to instance role as a permissions boundary
Default value:
""
private_ip
(string
) optionalPrivate IP address to associate with the instance in the VPC
Default value:
null
region
(string
) optionalAWS Region the instance is launched in
Default value:
""
root_block_device_encrypted
(bool
) optionalWhether to encrypt the root block device
Default value:
true
root_block_device_kms_key_id
(string
) optionalKMS key ID used to encrypt EBS volume. When specifying root_block_device_kms_key_id, root_block_device_encrypted needs to be set to true
Default value:
null
root_iops
(number
) optionalAmount of provisioned IOPS. This must be set if root_volume_type is set of
io1
,io2
orgp3
Default value:
0
root_throughput
(number
) optionalAmount of throughput. This must be set if root_volume_type is set to
gp3
Default value:
0
root_volume_size
(number
) optionalSize of the root volume in gigabytes
Default value:
10
root_volume_type
(string
) optionalType of root volume. Can be standard, gp2, gp3, io1 or io2
Default value:
"gp2"
secondary_private_ips
(list(string)
) optionalList of secondary private IP addresses to associate with the instance in the VPC
Default value:
[ ]
security_group_description
(string
) optionalThe Security Group description.
Default value:
"EC2 Security Group"
security_group_enabled
(bool
) optionalWhether to create default Security Group for EC2.
Default value:
true
security_group_rules
(list(any)
) optionalA list of maps of Security Group rules.
The values of map is fully complated withaws_security_group_rule
resource.
To get more info see https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group_rule .Default value:
[
{
"cidr_blocks": [
"0.0.0.0/0"
],
"description": "Allow all outbound traffic",
"from_port": 0,
"protocol": "-1",
"to_port": 65535,
"type": "egress"
}
]security_group_use_name_prefix
(bool
) optionalWhether to create a default Security Group with unique name beginning with the normalized prefix.
Default value:
false
security_groups
(list(string)
) optionalA list of Security Group IDs to associate with EC2 instance.
Default value:
[ ]
source_dest_check
(bool
) optionalControls 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
) optionalSSH key pair to be provisioned on the instance
Default value:
null
ssm_patch_manager_enabled
(bool
) optionalWhether to enable SSM Patch manager
Default value:
false
ssm_patch_manager_iam_policy_arn
(string
) optionalIAM policy ARN to allow Patch Manager to manage the instance. If not provided,
arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
will be usedDefault value:
null
ssm_patch_manager_s3_log_bucket
(string
) optionalThe name of the s3 bucket to export the patch log to
Default value:
null
statistic_level
(string
) optionalThe statistic to apply to the alarm's associated metric. Allowed values are: SampleCount, Average, Sum, Minimum, Maximum
Default value:
"Maximum"
stop_ec2_before_detaching_vol
(bool
) optionalSet this to true to ensure that the target instance is stopped before trying to detach the volume/s.
Default value:
false
tenancy
(string
) optionalTenancy 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'.
Default value:
"default"
user_data
(string
) optionalThe user data to provide when launching the instance. Do not pass gzip-compressed data via this argument; use
user_data_base64
insteadDefault value:
null
user_data_base64
(string
) optionalCan be used instead of
user_data
to pass base64-encoded binary data directly. Use this instead ofuser_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 corruptionDefault value:
null
user_data_replace_on_change
(bool
) optionalWhen used in combination with user_data or user_data_base64 will trigger a destroy and recreate when set to true.
Default value:
false
volume_tags_enabled
(bool
) optionalWhether or not to copy instance tags to root and EBS volumes
Default value:
true
Context Variables
The following variables are defined in the context.tf
file of this module and part of the terraform-null-label pattern.
context.tf
file of this module and part of the terraform-null-label pattern.additional_tag_map
(map(string)
) optionalAdditional key-value pairs to add to each map in
tags_as_list_of_maps
. Not added totags
orid
.
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)
) optionalID element. Additional attributes (e.g.
workers
orcluster
) to add toid
,
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 thedelimiter
and treated as a single ID element.Required: No
Default value:
[ ]
context
(any
) optionalSingle object for setting entire context at once.
See description of individual variables for details.
Leave string and numeric variables asnull
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
) optionalDelimiter 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
) optionalDescribe 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 isany
so the map values can later be enhanced to provide additional options.)
format
is a Terraform format string to be passed to theformat()
function.
labels
is a list of labels, in order, to pass toformat()
function.
Label values will be normalized before being passed toformat()
so they will be
identical to how they appear inid
.
Default is{}
(descriptors
output will be empty).Required: No
Default value:
{ }
enabled
(bool
) optionalSet to false to prevent the module from creating any resources
Required: NoDefault value:
null
environment
(string
) optionalID element. Usually used for region e.g. 'uw2', 'us-west-2', OR role 'prod', 'staging', 'dev', 'UAT'
Required: NoDefault value:
null
id_length_limit
(number
) optionalLimit
id
to this many characters (minimum 6).
Set to0
for unlimited length.
Set tonull
for keep the existing setting, which defaults to0
.
Does not affectid_full
.Required: No
Default value:
null
label_key_case
(string
) optionalControls the letter case of the
tags
keys (label names) for tags generated by this module.
Does not affect keys of tags passed in via thetags
input.
Possible values:lower
,title
,upper
.
Default value:title
.Required: No
Default value:
null
label_order
(list(string)
) optionalThe 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
) optionalControls 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 thetags
input.
Possible values:lower
,title
,upper
andnone
(no transformation).
Set this totitle
and setdelimiter
to""
to yield Pascal Case IDs.
Default value:lower
.Required: No
Default value:
null
labels_as_tags
(set(string)
) optionalSet 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 thetags
output.
Set to[]
to suppress all generated tags.
Notes:
The value of thename
tag, if included, will be theid
, not thename
.
Unlike othernull-label
inputs, the initial setting oflabels_as_tags
cannot be
changed in later chained modules. Attempts to change it will be silently ignored.Required: No
Default value:
[
"default"
]name
(string
) optionalID element. Usually the component or solution name, e.g. 'app' or 'jenkins'.
This is the only ID element not also included as atag
.
The "name" tag is set to the fullid
string. There is no tag with the value of thename
input.Required: No
Default value:
null
namespace
(string
) optionalID element. Usually an abbreviation of your organization name, e.g. 'eg' or 'cp', to help ensure generated IDs are globally unique
Required: NoDefault value:
null
regex_replace_chars
(string
) optionalTerraform 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
) optionalID element. Usually used to indicate role, e.g. 'prod', 'staging', 'source', 'build', 'test', 'deploy', 'release'
Required: NoDefault value:
null
tags
(map(string)
) optionalAdditional 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
) optionalID element (Rarely used, not included by default). A customer identifier, indicating who this instance of a resource is for
Required: NoDefault value:
null
Outputs
additional_eni_ids
Map of ENI to EIP
alarm
CloudWatch Alarm ID
arn
ARN of the instance
ebs_ids
IDs of EBSs
id
Disambiguated ID of the instance
instance_profile
Name of the instance's profile (either built or supplied)
name
Instance name
primary_network_interface_id
ID of the instance's primary network interface
private_dns
Private DNS of instance
private_ip
Private IP of instance
public_dns
Public DNS of instance (or DNS of EIP)
public_ip
Public IP of instance (or EIP)
role
Name of AWS IAM Role associated with the instance
role_arn
ARN of AWS IAM Role associated with the instance
security_group_arn
EC2 instance Security Group ARN
security_group_id
EC2 instance Security Group ID
security_group_ids
IDs on the AWS Security Groups associated with the instance
security_group_name
EC2 instance Security Group name
ssh_key_pair
Name of the SSH key pair provisioned on the instance
Dependencies
Requirements
terraform
, version:>= 1.0
aws
, version:>= 4.7.0
null
, version:>= 2.0
Providers
aws
, version:>= 4.7.0
null
, version:>= 2.0
Modules
Name | Version | Source | Description |
---|---|---|---|
label_ssm_patch_s3_log_policy | 0.25.0 | cloudposse/label/null | n/a |
security_group | 0.3.3 | cloudposse/security-group/aws | n/a |
this | 0.25.0 | cloudposse/label/null | n/a |
Resources
The following resources are used by this module:
aws_cloudwatch_metric_alarm.default
(resource)aws_ebs_volume.default
(resource)aws_eip.additional
(resource)aws_eip.default
(resource)aws_iam_instance_profile.default
(resource)aws_iam_policy.ssm_patch_s3_log_policy
(resource)aws_iam_role.default
(resource)aws_iam_role_policy_attachment.ssm_core
(resource)aws_iam_role_policy_attachment.ssm_s3_policy
(resource)aws_instance.default
(resource)aws_network_interface.additional
(resource)aws_network_interface_attachment.additional
(resource)aws_volume_attachment.default
(resource)null_resource.check_alarm_action
(resource)
Data Sources
The following data sources are used by this module:
aws_ami.default
(data source)aws_ami.info
(data source)aws_caller_identity.default
(data source)aws_iam_instance_profile.given
(data source)aws_iam_policy_document.default
(data source)aws_iam_policy_document.ssm_patch_s3_log_policy
(data source)aws_partition.default
(data source)aws_region.default
(data source)aws_subnet.default
(data source)