Home

Awesome

AWS EC2 Instance Terraform module

Terraform module which creates an EC2 instance on AWS.

SWUbanner

Usage

Single EC2 Instance

module "ec2_instance" {
  source  = "terraform-aws-modules/ec2-instance/aws"

  name = "single-instance"

  instance_type          = "t2.micro"
  key_name               = "user1"
  monitoring             = true
  vpc_security_group_ids = ["sg-12345678"]
  subnet_id              = "subnet-eddcdzz4"

  tags = {
    Terraform   = "true"
    Environment = "dev"
  }
}

Multiple EC2 Instance

module "ec2_instance" {
  source  = "terraform-aws-modules/ec2-instance/aws"

  for_each = toset(["one", "two", "three"])

  name = "instance-${each.key}"

  instance_type          = "t2.micro"
  key_name               = "user1"
  monitoring             = true
  vpc_security_group_ids = ["sg-12345678"]
  subnet_id              = "subnet-eddcdzz4"

  tags = {
    Terraform   = "true"
    Environment = "dev"
  }
}

Spot EC2 Instance

module "ec2_instance" {
  source  = "terraform-aws-modules/ec2-instance/aws"

  name = "spot-instance"

  create_spot_instance = true
  spot_price           = "0.60"
  spot_type            = "persistent"

  instance_type          = "t2.micro"
  key_name               = "user1"
  monitoring             = true
  vpc_security_group_ids = ["sg-12345678"]
  subnet_id              = "subnet-eddcdzz4"

  tags = {
    Terraform   = "true"
    Environment = "dev"
  }
}

Module wrappers

Users of this Terraform module can create multiple similar resources by using for_each meta-argument within module block which became available in Terraform 0.13.

Users of Terragrunt can achieve similar results by using modules provided in the wrappers directory, if they prefer to reduce amount of configuration files.

Examples

Make an encrypted AMI for use

This module does not support encrypted AMI's out of the box however it is easy enough for you to generate one for use

This example creates an encrypted image from the latest ubuntu 16.04 base image.

provider "aws" {
  region = "us-west-2"
}

data "aws_ami" "ubuntu" {
  most_recent = true
  owners      = ["679593333241"]

  filter {
    name   = "name"
    values = ["ubuntu-minimal/images/hvm-ssd/ubuntu-focal-20.04-*"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }
}

resource "aws_ami_copy" "ubuntu_encrypted_ami" {
  name              = "ubuntu-encrypted-ami"
  description       = "An encrypted root ami based off ${data.aws_ami.ubuntu.id}"
  source_ami_id     = data.aws_ami.ubuntu.id
  source_ami_region = "eu-west-2"
  encrypted         = true

  tags = { Name = "ubuntu-encrypted-ami" }
}

data "aws_ami" "encrypted-ami" {
  most_recent = true

  filter {
    name   = "name"
    values = [aws_ami_copy.ubuntu_encrypted_ami.id]
  }

  owners = ["self"]
}

Conditional creation

The following combinations are supported to conditionally create resources:

  create = false
  create_spot_instance = true

Notes

<!-- BEGIN_TF_DOCS -->

Requirements

NameVersion
<a name="requirement_terraform"></a> terraform>= 1.0
<a name="requirement_aws"></a> aws>= 4.66

Providers

NameVersion
<a name="provider_aws"></a> aws>= 4.66

Modules

No modules.

Resources

NameType
aws_eip.thisresource
aws_iam_instance_profile.thisresource
aws_iam_role.thisresource
aws_iam_role_policy_attachment.thisresource
aws_instance.ignore_amiresource
aws_instance.thisresource
aws_spot_instance_request.thisresource
aws_iam_policy_document.assume_role_policydata source
aws_partition.currentdata source
aws_ssm_parameter.thisdata source

Inputs

NameDescriptionTypeDefaultRequired
<a name="input_ami"></a> amiID of AMI to use for the instancestringnullno
<a name="input_ami_ssm_parameter"></a> ami_ssm_parameterSSM parameter name for the AMI ID. For Amazon Linux AMI SSM parameters see referencestring"/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2"no
<a name="input_associate_public_ip_address"></a> associate_public_ip_addressWhether to associate a public IP address with an instance in a VPCboolnullno
<a name="input_availability_zone"></a> availability_zoneAZ to start the instance instringnullno
<a name="input_capacity_reservation_specification"></a> capacity_reservation_specificationDescribes an instance's Capacity Reservation targeting optionany{}no
<a name="input_cpu_core_count"></a> cpu_core_countSets the number of CPU cores for an instancenumbernullno
<a name="input_cpu_credits"></a> cpu_creditsThe credit option for CPU usage (unlimited or standard)stringnullno
<a name="input_cpu_options"></a> cpu_optionsDefines CPU options to apply to the instance at launch time.any{}no
<a name="input_cpu_threads_per_core"></a> cpu_threads_per_coreSets the number of CPU threads per core for an instance (has no effect unless cpu_core_count is also set)numbernullno
<a name="input_create"></a> createWhether to create an instancebooltrueno
<a name="input_create_eip"></a> create_eipDetermines whether a public EIP will be created and associated with the instance.boolfalseno
<a name="input_create_iam_instance_profile"></a> create_iam_instance_profileDetermines whether an IAM instance profile is created or to use an existing IAM instance profileboolfalseno
<a name="input_create_spot_instance"></a> create_spot_instanceDepicts if the instance is a spot instanceboolfalseno
<a name="input_disable_api_stop"></a> disable_api_stopIf true, enables EC2 Instance Stop Protectionboolnullno
<a name="input_disable_api_termination"></a> disable_api_terminationIf true, enables EC2 Instance Termination Protectionboolnullno
<a name="input_ebs_block_device"></a> ebs_block_deviceAdditional EBS block devices to attach to the instancelist(any)[]no
<a name="input_ebs_optimized"></a> ebs_optimizedIf true, the launched EC2 instance will be EBS-optimizedboolnullno
<a name="input_eip_domain"></a> eip_domainIndicates if this EIP is for use in VPCstring"vpc"no
<a name="input_eip_tags"></a> eip_tagsA map of additional tags to add to the eipmap(string){}no
<a name="input_enable_volume_tags"></a> enable_volume_tagsWhether to enable volume tags (if enabled it conflicts with root_block_device tags)booltrueno
<a name="input_enclave_options_enabled"></a> enclave_options_enabledWhether Nitro Enclaves will be enabled on the instance. Defaults to falseboolnullno
<a name="input_ephemeral_block_device"></a> ephemeral_block_deviceCustomize Ephemeral (also known as Instance Store) volumes on the instancelist(map(string))[]no
<a name="input_get_password_data"></a> get_password_dataIf true, wait for password data to become available and retrieve itboolnullno
<a name="input_hibernation"></a> hibernationIf true, the launched EC2 instance will support hibernationboolnullno
<a name="input_host_id"></a> host_idID of a dedicated host that the instance will be assigned to. Use when an instance is to be launched on a specific dedicated hoststringnullno
<a name="input_iam_instance_profile"></a> iam_instance_profileIAM Instance Profile to launch the instance with. Specified as the name of the Instance Profilestringnullno
<a name="input_iam_role_description"></a> iam_role_descriptionDescription of the rolestringnullno
<a name="input_iam_role_name"></a> iam_role_nameName to use on IAM role createdstringnullno
<a name="input_iam_role_path"></a> iam_role_pathIAM role pathstringnullno
<a name="input_iam_role_permissions_boundary"></a> iam_role_permissions_boundaryARN of the policy that is used to set the permissions boundary for the IAM rolestringnullno
<a name="input_iam_role_policies"></a> iam_role_policiesPolicies attached to the IAM rolemap(string){}no
<a name="input_iam_role_tags"></a> iam_role_tagsA map of additional tags to add to the IAM role/profile createdmap(string){}no
<a name="input_iam_role_use_name_prefix"></a> iam_role_use_name_prefixDetermines whether the IAM role name (iam_role_name or name) is used as a prefixbooltrueno
<a name="input_ignore_ami_changes"></a> ignore_ami_changesWhether changes to the AMI ID changes should be ignored by Terraform. Note - changing this value will result in the replacement of the instanceboolfalseno
<a name="input_instance_initiated_shutdown_behavior"></a> instance_initiated_shutdown_behaviorShutdown behavior for the instance. Amazon defaults this to stop for EBS-backed instances and terminate for instance-store instances. Cannot be set on instance-store instancestringnullno
<a name="input_instance_tags"></a> instance_tagsAdditional tags for the instancemap(string){}no
<a name="input_instance_type"></a> instance_typeThe type of instance to startstring"t3.micro"no
<a name="input_ipv6_address_count"></a> ipv6_address_countA number of IPv6 addresses to associate with the primary network interface. Amazon EC2 chooses the IPv6 addresses from the range of your subnetnumbernullno
<a name="input_ipv6_addresses"></a> ipv6_addressesSpecify one or more IPv6 addresses from the range of the subnet to associate with the primary network interfacelist(string)nullno
<a name="input_key_name"></a> key_nameKey name of the Key Pair to use for the instance; which can be managed using the aws_key_pair resourcestringnullno
<a name="input_launch_template"></a> launch_templateSpecifies a Launch Template to configure the instance. Parameters configured on this resource will override the corresponding parameters in the Launch Templatemap(string){}no
<a name="input_maintenance_options"></a> maintenance_optionsThe maintenance options for the instanceany{}no
<a name="input_metadata_options"></a> metadata_optionsCustomize the metadata options of the instancemap(string)<pre>{<br/> "http_endpoint": "enabled",<br/> "http_put_response_hop_limit": 1,<br/> "http_tokens": "optional"<br/>}</pre>no
<a name="input_monitoring"></a> monitoringIf true, the launched EC2 instance will have detailed monitoring enabledboolnullno
<a name="input_name"></a> nameName to be used on EC2 instance createdstring""no
<a name="input_network_interface"></a> network_interfaceCustomize network interfaces to be attached at instance boot timelist(map(string))[]no
<a name="input_placement_group"></a> placement_groupThe Placement Group to start the instance instringnullno
<a name="input_private_dns_name_options"></a> private_dns_name_optionsCustomize the private DNS name options of the instancemap(string){}no
<a name="input_private_ip"></a> private_ipPrivate IP address to associate with the instance in a VPCstringnullno
<a name="input_putin_khuylo"></a> putin_khuyloDo you agree that Putin doesn't respect Ukrainian sovereignty and territorial integrity? More info: https://en.wikipedia.org/wiki/Putin_khuylo!booltrueno
<a name="input_root_block_device"></a> root_block_deviceCustomize details about the root block device of the instance. See Block Devices for detailslist(any)[]no
<a name="input_secondary_private_ips"></a> secondary_private_ipsA list of secondary private IPv4 addresses to assign to the instance's primary network interface (eth0) in a VPC. Can only be assigned to the primary network interface (eth0) attached at instance creation, not a pre-existing network interface i.e. referenced in a network_interface blocklist(string)nullno
<a name="input_source_dest_check"></a> source_dest_checkControls if traffic is routed to the instance when the destination address does not match the instance. Used for NAT or VPNsboolnullno
<a name="input_spot_block_duration_minutes"></a> spot_block_duration_minutesThe required duration for the Spot instances, in minutes. This value must be a multiple of 60 (60, 120, 180, 240, 300, or 360)numbernullno
<a name="input_spot_instance_interruption_behavior"></a> spot_instance_interruption_behaviorIndicates Spot instance behavior when it is interrupted. Valid values are terminate, stop, or hibernatestringnullno
<a name="input_spot_launch_group"></a> spot_launch_groupA launch group is a group of spot instances that launch together and terminate together. If left empty instances are launched and terminated individuallystringnullno
<a name="input_spot_price"></a> spot_priceThe maximum price to request on the spot market. Defaults to on-demand pricestringnullno
<a name="input_spot_type"></a> spot_typeIf set to one-time, after the instance is terminated, the spot request will be closed. Default persistentstringnullno
<a name="input_spot_valid_from"></a> spot_valid_fromThe start date and time of the request, in UTC RFC3339 format(for example, YYYY-MM-DDTHH:MM:SSZ)stringnullno
<a name="input_spot_valid_until"></a> spot_valid_untilThe end date and time of the request, in UTC RFC3339 format(for example, YYYY-MM-DDTHH:MM:SSZ)stringnullno
<a name="input_spot_wait_for_fulfillment"></a> spot_wait_for_fulfillmentIf set, Terraform will wait for the Spot Request to be fulfilled, and will throw an error if the timeout of 10m is reachedboolnullno
<a name="input_subnet_id"></a> subnet_idThe VPC Subnet ID to launch instringnullno
<a name="input_tags"></a> tagsA mapping of tags to assign to the resourcemap(string){}no
<a name="input_tenancy"></a> tenancyThe tenancy of the instance (if the instance is running in a VPC). Available values: default, dedicated, hoststringnullno
<a name="input_timeouts"></a> timeoutsDefine maximum timeout for creating, updating, and deleting EC2 instance resourcesmap(string){}no
<a name="input_user_data"></a> user_dataThe user data to provide when launching the instance. Do not pass gzip-compressed data via this argument; see user_data_base64 insteadstringnullno
<a name="input_user_data_base64"></a> 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
<a name="input_user_data_replace_on_change"></a> 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. Defaults to false if not setboolnullno
<a name="input_volume_tags"></a> volume_tagsA mapping of tags to assign to the devices created by the instance at launch timemap(string){}no
<a name="input_vpc_security_group_ids"></a> vpc_security_group_idsA list of security group IDs to associate withlist(string)nullno

Outputs

NameDescription
<a name="output_ami"></a> amiAMI ID that was used to create the instance
<a name="output_arn"></a> arnThe ARN of the instance
<a name="output_availability_zone"></a> availability_zoneThe availability zone of the created instance
<a name="output_capacity_reservation_specification"></a> capacity_reservation_specificationCapacity reservation specification of the instance
<a name="output_ebs_block_device"></a> ebs_block_deviceEBS block device information
<a name="output_ephemeral_block_device"></a> ephemeral_block_deviceEphemeral block device information
<a name="output_iam_instance_profile_arn"></a> iam_instance_profile_arnARN assigned by AWS to the instance profile
<a name="output_iam_instance_profile_id"></a> iam_instance_profile_idInstance profile's ID
<a name="output_iam_instance_profile_unique"></a> iam_instance_profile_uniqueStable and unique string identifying the IAM instance profile
<a name="output_iam_role_arn"></a> iam_role_arnThe Amazon Resource Name (ARN) specifying the IAM role
<a name="output_iam_role_name"></a> iam_role_nameThe name of the IAM role
<a name="output_iam_role_unique_id"></a> iam_role_unique_idStable and unique string identifying the IAM role
<a name="output_id"></a> idThe ID of the instance
<a name="output_instance_state"></a> instance_stateThe state of the instance
<a name="output_ipv6_addresses"></a> ipv6_addressesThe IPv6 address assigned to the instance, if applicable
<a name="output_outpost_arn"></a> outpost_arnThe ARN of the Outpost the instance is assigned to
<a name="output_password_data"></a> password_dataBase-64 encoded encrypted password data for the instance. Useful for getting the administrator password for instances running Microsoft Windows. This attribute is only exported if get_password_data is true
<a name="output_primary_network_interface_id"></a> primary_network_interface_idThe ID of the instance's primary network interface
<a name="output_private_dns"></a> private_dnsThe private DNS name assigned to the instance. Can only be used inside the Amazon EC2, and only available if you've enabled DNS hostnames for your VPC
<a name="output_private_ip"></a> private_ipThe private IP address assigned to the instance
<a name="output_public_dns"></a> public_dnsThe public DNS name assigned to the instance. For EC2-VPC, this is only available if you've enabled DNS hostnames for your VPC
<a name="output_public_ip"></a> public_ipThe public IP address assigned to the instance, if applicable.
<a name="output_root_block_device"></a> root_block_deviceRoot block device information
<a name="output_spot_bid_status"></a> spot_bid_statusThe current bid status of the Spot Instance Request
<a name="output_spot_instance_id"></a> spot_instance_idThe Instance ID (if any) that is currently fulfilling the Spot Instance request
<a name="output_spot_request_state"></a> spot_request_stateThe current request state of the Spot Instance Request
<a name="output_tags_all"></a> tags_allA map of tags assigned to the resource, including those inherited from the provider default_tags configuration block
<!-- END_TF_DOCS -->

Authors

Module is maintained by Anton Babenko with help from these awesome contributors.

License

Apache 2 Licensed. See LICENSE for full details.

Additional information for users from Russia and Belarus