Code Monkey home page Code Monkey logo

terraform-aws-ec2-instance's Introduction

Project Banner

Latest ReleaseLast UpdatedSlack Community

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

Tip

๐Ÿ‘ฝ Use Atmos with Terraform

Cloud Posse uses atmos to easily orchestrate multiple environments using Terraform.
Works with Github Actions, Atlantis, or Spacelift.

Watch demo of using Atmos with Terraform
Example of running atmos to manage infrastructure from our Quick Start tutorial.

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"]
    },
  ]
}

Important

In Cloud Posse's examples, we avoid pinning modules to specific versions to prevent discrepancies between the documentation and the latest released versions. However, for your own projects, we strongly advise pinning each module to the exact version you're using. This practice ensures the stability of your infrastructure. Additionally, we recommend implementing a systematic approach for updating versions to avoid unexpected changes.

Makefile Targets

Available targets:

  help                                Help screen
  help/all                            Display help for all targets
  help/short                          This help short screen
  lint                                Lint terraform code

Requirements

Name Version
terraform >= 1.0
aws >= 4.7.0
null >= 2.0

Providers

Name Version
aws >= 4.7.0
null >= 2.0

Modules

Name Source Version
label_ssm_patch_s3_log_policy cloudposse/label/null 0.25.0
security_group cloudposse/security-group/aws 0.3.3
this cloudposse/label/null 0.25.0

Resources

Name Type
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
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

Inputs

Name Description Type Default Required
additional_ips_count Count of additional EIPs number 0 no
additional_tag_map 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.
map(string) {} no
ami The AMI to use for the instance. By default it is the AMI provided by Amazon with Ubuntu 16.04 string "" no
ami_owner Owner of the given AMI (ignored if ami unset, required if set) string "" no
applying_period The period in seconds over which the specified statistic is applied number 60 no
assign_eip_address Assign an Elastic IP address to the instance bool true no
associate_public_ip_address Associate a public IP address with the instance bool false no
attributes 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.
list(string) [] no
availability_zone Availability Zone the instance is launched in. If not set, will be launched in the first AZ of the region string "" no
burstable_mode Enable burstable mode for the instance. Can be standard or unlimited. Applicable only for T2/T3/T4g instance types. string null no
comparison_operator The arithmetic operation to use when comparing the specified Statistic and Threshold. Possible values are: GreaterThanOrEqualToThreshold, GreaterThanThreshold, LessThanThreshold, LessThanOrEqualToThreshold. string "GreaterThanOrEqualToThreshold" no
context 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.
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_action Default alarm action string "action/actions/AWS_EC2.InstanceId.Reboot/1.0" no
delete_on_termination Whether the volume should be destroyed on instance termination bool true no
delimiter Delimiter to be used between ID elements.
Defaults to - (hyphen). Set to "" to use no delimiter at all.
string null no
descriptor_formats 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).
any {} no
disable_alarm_action Disable the creation of Alarm Action bool false no
disable_api_stop Enable EC2 Instance Stop Protection bool false no
disable_api_termination Enable EC2 Instance Termination Protection bool false no
ebs_device_name Name of the EBS device to mount list(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_iops Amount of provisioned IOPS. This must be set with a volume_type of io1, io2 or gp3 number 0 no
ebs_optimized Launched EC2 instance will be EBS-optimized bool true no
ebs_throughput Amount of throughput. This must be set if volume_type is set to gp3 number 0 no
ebs_volume_count Count of EBS volumes that will be attached to the instance number 0 no
ebs_volume_encrypted Whether to encrypt the additional EBS volumes bool true no
ebs_volume_size Size of the additional EBS volumes in gigabytes number 10 no
ebs_volume_type The type of the additional EBS volumes. Can be standard, gp2, gp3, io1 or io2 string "gp2" no
enabled Set to false to prevent the module from creating any resources bool null no
environment ID element. Usually used for region e.g. 'uw2', 'us-west-2', OR role 'prod', 'staging', 'dev', 'UAT' string null no
evaluation_periods The number of periods over which data is compared to the specified threshold. number 5 no
external_network_interface_enabled Wheter to attach an external ENI as the eth0 interface for the instance. Any change to the interface will force instance recreation. bool false no
external_network_interfaces The 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
}))
null no
id_length_limit 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.
number null no
instance_initiated_shutdown_behavior Specifies whether an instance stops or terminates when you initiate shutdown from the instance. Can be one of 'stop' or 'terminate'. string null no
instance_profile A pre-defined profile to attach to the instance (default is to build our own) string "" no
instance_profile_enabled Whether an IAM instance profile is created to pass a role to an Amazon EC2 instance when the instance starts bool true no
instance_type The type of the instance string "t2.micro" no
ipv6_address_count Number 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) number 0 no
ipv6_addresses List of IPv6 addresses from the range of the subnet to associate with the primary network interface list(string) [] no
kms_key_id KMS key ID used to encrypt EBS volume. When specifying kms_key_id, ebs_volume_encrypted needs to be set to true string null no
label_key_case 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.
string null no
label_order 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.
list(string) null no
label_value_case 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.
string null no
labels_as_tags 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.
set(string)
[
"default"
]
no
metadata_http_endpoint_enabled Whether the metadata service is available bool true no
metadata_http_put_response_hop_limit The desired HTTP PUT response hop limit (between 1 and 64) for instance metadata requests. number 2 no
metadata_http_tokens_required Whether or not the metadata service requires session tokens, also referred to as Instance Metadata Service Version 2. bool true no
metadata_tags_enabled Whether the tags are enabled in the metadata service. bool false no
metric_name 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 string "StatusCheckFailed_Instance" no
metric_namespace 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 string "AWS/EC2" no
metric_threshold The value against which the specified statistic is compared number 1 no
metric_treat_missing_data Sets 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
monitoring Launched EC2 instance will have detailed monitoring enabled bool true no
name 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.
string null no
namespace ID element. Usually an abbreviation of your organization name, e.g. 'eg' or 'cp', to help ensure generated IDs are globally unique string null no
permissions_boundary_arn Policy ARN to attach to instance role as a permissions boundary string "" no
private_ip Private IP address to associate with the instance in the VPC string null no
regex_replace_chars 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.
string null no
region AWS Region the instance is launched in string "" no
root_block_device_encrypted Whether to encrypt the root block device bool true no
root_block_device_kms_key_id KMS 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 string null no
root_iops Amount of provisioned IOPS. This must be set if root_volume_type is set of io1, io2 or gp3 number 0 no
root_throughput Amount of throughput. This must be set if root_volume_type is set to gp3 number 0 no
root_volume_size Size of the root volume in gigabytes number 10 no
root_volume_type Type of root volume. Can be standard, gp2, gp3, io1 or io2 string "gp2" no
secondary_private_ips List of secondary private IP addresses to associate with the instance in the VPC list(string) [] no
security_group_description The Security Group description. string "EC2 Security Group" no
security_group_enabled Whether to create default Security Group for EC2. bool true no
security_group_rules 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 .
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_prefix Whether to create a default Security Group with unique name beginning with the normalized prefix. bool false no
security_groups A list of Security Group IDs to associate with EC2 instance. list(string) [] no
source_dest_check Controls if traffic is routed to the instance when the destination address does not match the instance. Used for NAT or VPNs bool true no
ssh_key_pair SSH key pair to be provisioned on the instance string null no
ssm_patch_manager_enabled Whether to enable SSM Patch manager bool false no
ssm_patch_manager_iam_policy_arn IAM policy ARN to allow Patch Manager to manage the instance. If not provided, arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore will be used string null no
ssm_patch_manager_s3_log_bucket The name of the s3 bucket to export the patch log to string null no
stage ID element. Usually used to indicate role, e.g. 'prod', 'staging', 'source', 'build', 'test', 'deploy', 'release' string null no
statistic_level The statistic to apply to the alarm's associated metric. Allowed values are: SampleCount, Average, Sum, Minimum, Maximum string "Maximum" no
subnet VPC Subnet ID the instance is launched in string n/a yes
tags Additional tags (e.g. {'BusinessUnit': 'XYZ'}).
Neither the tag keys nor the tag values will be modified by this module.
map(string) {} no
tenancy Tenancy 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
tenant ID element _(Rarely used, not included by default)_. A customer identifier, indicating who this instance of a resource is for string null no
user_data The user data to provide when launching the instance. Do not pass gzip-compressed data via this argument; use user_data_base64 instead string null no
user_data_base64 Can 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 corruption string null no
user_data_replace_on_change When used in combination with user_data or user_data_base64 will trigger a destroy and recreate when set to true. bool false no
volume_tags_enabled Whether or not to copy instance tags to root and EBS volumes bool true no
vpc_id The ID of the VPC that the instance security group belongs to string n/a yes

Outputs

Name Description
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

Related Projects

Check out these related projects.

References

For additional context, refer to some of these links.

Tip

Use Terraform Reference Architectures for AWS

Use Cloud Posse's ready-to-go terraform architecture blueprints for AWS to get up and running quickly.

โœ… We build it together with your team.
โœ… Your team owns everything.
โœ… 100% Open Source and backed by fanatical support.

Request Quote

๐Ÿ“š Learn More

Cloud Posse is the leading DevOps Accelerator for funded startups and enterprises.

Your team can operate like a pro today.

Ensure that your team succeeds by using Cloud Posse's proven process and turnkey blueprints. Plus, we stick around until you succeed.

Day-0: Your Foundation for Success

  • Reference Architecture. You'll get everything you need from the ground up built using 100% infrastructure as code.
  • Deployment Strategy. Adopt a proven deployment strategy with GitHub Actions, enabling automated, repeatable, and reliable software releases.
  • Site Reliability Engineering. Gain total visibility into your applications and services with Datadog, ensuring high availability and performance.
  • Security Baseline. Establish a secure environment from the start, with built-in governance, accountability, and comprehensive audit logs, safeguarding your operations.
  • GitOps. Empower your team to manage infrastructure changes confidently and efficiently through Pull Requests, leveraging the full power of GitHub Actions.

Request Quote

Day-2: Your Operational Mastery

  • Training. Equip your team with the knowledge and skills to confidently manage the infrastructure, ensuring long-term success and self-sufficiency.
  • Support. Benefit from a seamless communication over Slack with our experts, ensuring you have the support you need, whenever you need it.
  • Troubleshooting. Access expert assistance to quickly resolve any operational challenges, minimizing downtime and maintaining business continuity.
  • Code Reviews. Enhance your teamโ€™s code quality with our expert feedback, fostering continuous improvement and collaboration.
  • Bug Fixes. Rely on our team to troubleshoot and resolve any issues, ensuring your systems run smoothly.
  • Migration Assistance. Accelerate your migration process with our dedicated support, minimizing disruption and speeding up time-to-value.
  • Customer Workshops. Engage with our team in weekly workshops, gaining insights and strategies to continuously improve and innovate.

Request Quote

โœจ Contributing

This project is under active development, and we encourage contributions from our community.

Many thanks to our outstanding contributors:

For ๐Ÿ› bug reports & feature requests, please use the issue tracker.

In general, PRs are welcome. We follow the typical "fork-and-pull" Git workflow.

  1. Review our Code of Conduct and Contributor Guidelines.
  2. Fork the repo on GitHub
  3. Clone the project to your own machine
  4. Commit changes to your own branch
  5. Push your work back up to your fork
  6. Submit a Pull Request so that we can review your changes

NOTE: Be sure to merge the latest changes from "upstream" before making a pull request!

๐ŸŒŽ Slack Community

Join our Open Source Community on Slack. It's FREE for everyone! Our "SweetOps" community is where you get to talk with others who share a similar vision for how to rollout and manage infrastructure. This is the best place to talk shop, ask questions, solicit feedback, and work together as a community to build totally sweet infrastructure.

๐Ÿ“ฐ Newsletter

Sign up for our newsletter and join 3,000+ DevOps engineers, CTOs, and founders who get insider access to the latest DevOps trends, so you can always stay in the know. Dropped straight into your Inbox every week โ€” and usually a 5-minute read.

๐Ÿ“† Office Hours

Join us every Wednesday via Zoom for your weekly dose of insider DevOps trends, AWS news and Terraform insights, all sourced from our SweetOps community, plus a live Q&A that you canโ€™t find anywhere else. It's FREE for everyone!

License

License

Preamble to the Apache License, Version 2.0

Complete license is available in the LICENSE file.

Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

  https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.

Trademarks

All other trademarks referenced herein are the property of their respective owners.


Copyright ยฉ 2017-2024 Cloud Posse, LLC

README footer

Beacon

terraform-aws-ec2-instance's People

Contributors

actions-user avatar aknysh avatar bwmetcalf avatar cloudpossebot avatar drama17 avatar dylanbannon avatar flightlesstux avatar gowiem avatar haidargit avatar it-praktyk avatar ivan-pinatti avatar jamengual avatar korenyoni avatar kris-nabis avatar mariot8 avatar max-lobur avatar maximmi avatar nitrocode avatar osterman avatar renovate[bot] avatar roock avatar rsrchboy avatar s2504s avatar sebastianmacarescu avatar solairerove avatar sweetops avatar vadim-hleif avatar vale21 avatar woz5999 avatar wschultz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

terraform-aws-ec2-instance's Issues

Invalid index in aws_volume_attachment volume_id parameter

Describe the Bug

The following error is returned if the value of ebs_volume_count is more than 0, for any value.

plan. Resource actions are indicated with the following symbols:                                                                                                                     
  + create                                                                                                                                                                           
                                                                                                                                                                                                                                                                                                                                                                           
Terraform planned the following actions, but then encountered a problem:                                                                                                             
                                                                                                                                                                                     
  # module.ec2_instance_test.aws_ebs_volume.default[0] will be created                                                                                                         
  + resource "aws_ebs_volume" "default" {                                                                                                                                                                                                                                                                                                                                  
      + arn               = (known after apply)                                                                                                                                      
      + availability_zone = "eu-central-1a"                                                                                                                                             
      + encrypted         = true                                                                                                                                                     
      + final_snapshot    = false                                                                                                                                                    
      + id                = (known after apply)                                                                                                                                                                                                                                                                                                                            
      + iops              = 3000                                                                                                                                                                                                                                                                                                                                           
      + kms_key_id        = "arn:aws:kms:eu-central-1:xxxxxxxxxxxx:key/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"                                                                            
      + size              = 200                                                                                                                                                      
      + snapshot_id       = (known after apply)                                                                                                                                      
      + tags              = {                                                                                                                                                        
          + "Backup"      = "daily"                                                                                                                                                  
          + "Environment" = "legacy"                                                                                                                                                 
          + "Name"        = "test-legacy-test"                                                                                                                                  
          + "Namespace"   = "test"                                                                                                                                                                                                                                                                                                                                          
        }                                                                                                                                                                                                                                                                                                                                                                  
      + tags_all          = {                                                                                                                                                        
          + "Backup"      = "daily"                                                                                                                                                                                                                                                                                                                                        
          + "Environment" = "legacy"                                                                                                                                                 
          + "Name"        = "test-legacy-test"                                                                                                                                                                                                                                                                                                                        
          + "Namespace"   = "test"                                                                                                                                                    
        }                                                                                                                                                                                                                                                                                                                                                                  
      + throughput        = 125                                                                                                                                                                                                                                                                                                                                            
      + type              = "gp3"                                                                                                                                                                                                                                                                                                                                          
    }                                                                                                                                                                                
                                                                                                                                                                                                                                                                                                                                                                           
Plan: 1 to add, 0 to change, 0 to destroy.                                                                                                                                                                                                                                                                                                                                 
โ•ท                                                                                                                                                                                    
โ”‚ Error: Invalid index                                                                                                                                                               
โ”‚                                                                                                                                                                                    
โ”‚   on .terraform/modules/ec2_instance_controller/main.tf line 194, in resource "aws_volume_attachment" "default":                                                                                                                                                                                                                                                         
โ”‚  194:   volume_id   = one(aws_ebs_volume.default[*].id[count.index])                                                                                                               
โ”‚     โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€                                                                                                                                                              
โ”‚     โ”‚ count.index is 0                                                                                                                                                             
โ”‚                                                                                                                                                                                    
โ”‚ This value does not have any indices.                                                                                                                                                                                                                                                                                                                                    
โ•ต                                                                                                                                                                                    
Releasing state lock. This may take a few moments...                                                                                                                                 
ERRO[0018] 1 error occurred:                                                              
        * exit status 1 

The problem seems to be at line 194 of the main.tf file in resource aws_volume_attachment and it is fixed changing line 194 from one(aws_ebs_volume.default[*].id[count.index]) to one(aws_ebs_volume.default[*].id)

Expected Behavior

Attach the EBS volume with no errors

Steps to Reproduce

Set variable ebs_volume_count to be > 0

Screenshots

No response

Environment

  • OS: Ubuntu 20.04.2
  • Terraform 1.4.6
  • Terragrunt 0.35.14

Additional Context

No response

Support configuration of instance tenancy

Have a question? Please checkout our Slack Community or visit our Slack Archive.

Slack Community

Describe the Feature

I'd like the ability to use this module to create an instance using tenancy other than the default.

Expected Behavior

If I set tenancy = "dedicated" (for example), it will create the instance using dedicated tenancy instead of default (shared) tenancy.

Use Case

An organization that I work with has a security policy that requires use of dedicated tenancy.

Describe Ideal Solution

A new variable tenancy is available that allows me to set any of the accepted values, which are default, dedicated, or host. See https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance#tenancy

Alternatives Considered

Use a different module

Getting the error while calling through custom ami

Found a bug? Maybe our Slack Community can help.

Slack Community

Describe the Bug

A clear and concise description of what the bug is.

Expected Behavior

A clear and concise description of what you expected to happen.

Steps to Reproduce

Steps to reproduce the behavior:

  1. Go to '...'
  2. Run '....'
  3. Enter '....'
  4. See error

Screenshots

If applicable, add screenshots or logs to help explain your problem.

Environment (please complete the following information):

Anything that will help us triage the bug will help. Here are some ideas:

  • OS: [e.g. Linux, OSX, WSL, etc]
  • Version [e.g. 10.15]
    Error: Your query returned no results. Please change your search criteria and try again.
    โ”‚
    โ”‚ with module.bastion.data.aws_ami.info,
    โ”‚ on ../../module/terraform-aws-ec2-instance/main.tf line 90, in data "aws_ami" "info":
    โ”‚ 90: data "aws_ami" "info" {
    โ”‚

Additional Context

Add any other context about the problem here.

Unable to create an instance without any IAM role

Describe the Bug

When using terraform aws_instance or AWS web GUI, it is possible to launch an instance which doesn't have any IAM role attached.
It seems to me that it's not possible to launch an instance without any IAM role when using cloudposse/ec2-instance/aws.

Expected Behavior

IAM role for an instance should not be created when not wanted nor needed.

Steps to Reproduce

It should be possible to set "instance_profile" to a value which does not create and attach an IAM role.

Screenshots

No response

Environment

No response

Additional Context

No response

The default value `ebs_optimized = true` makes some instance types unable to provision.

Describe the Bug

Because the default value of ebs_optimized changed to true in this PR #159, some instance types (such as t2.micro) are unable to provision because they are simply unsupported for EBS-optimized instances.
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-optimized.html

So the following code causes an error:

module "my-ec2" {
  source  = "cloudposse/ec2-instance/aws"
  version = "1.1.0"

  vpc_id = module.shared_vpc.vpc_id

  ami              = "ami-06fdbb60c8e83aa5e"
  instance_type    = "t2.micro"
  ami_owner        = "137112412989"
  subnet           = module.shared_dynamic_subnets.private_subnet_ids[0]
}
 Error: creating EC2 Instance: Unsupported: The requested configuration is currently not supported. Please check the documentation for supported configurations.

Expected Behavior

EC2 instances of types that do not support EBS-optimized configurations can still be provisioned using default values.

Steps to Reproduce

Terraform v1.5.6

aws = {
source = "hashicorp/aws"
version = ">=5.12.0, <6.0.0"
}

Then applying the code above will reproduce.

Screenshots

No response

Environment

No response

Additional Context

No response

allow multiple volumes mount with different size or differnt types

Have a question? Please checkout our Slack Community or visit our Slack Archive.

Slack Community

Describe the Feature

Allow to have multiple volumes attach to instance with different sizes and differnt types

Expected Behavior

Allow to have multiple volumes attach to instance with different sizes and differnt types

Use Case

We need 2 volume mounts but the one volume is for log purpose and anohter where major data get stored. There size might differ as generated logs are 20% of data saved in data volume. also data volume need ssd where logs can be stored on gp2/gp3

Describe Ideal Solution

Take each ebs details in array and create volume and attach

Attribute 'network_interface_id' not found

What

Error: Error applying plan:

1 error(s) occurred:

* module.instance_01.output.network_interface_id: Resource 'aws_instance.default' does not have attribute 'network_interface_id' for variable 'aws_instance.default.*.network_interface_id'

TF project

module "instance_01" {
  source                        = "git::https://github.com/cloudposse/terraform-aws-ec2-instance.git?ref=master"
  ssh_key_pair                  = "${var.key_pair}"
  security_groups               = ["${aws_security_group.ops_sg.id}"]
  subnet                        = "${data.aws_subnet_ids.default_subnet.ids[0]}"
  instance_type                 = "${var.instance_type}"
  vpc_id                        = "${data.aws_vpcs.account_vpc.ids[0]}"
  name                          = "${var.name}_01"
  namespace                     = "${var.namespace}"
  stage                         = "${var.stage}"
  ami                           = "${data.aws_ami.base_ami.image_id}"
  ami_owner                     = "${var.ami_owner_id}"
  create_default_security_group = "false"
}

Replication

A lot is abstracted across a few .envrcs so hard to send it all over, but in principal it is the above and then running terraform apply.

Allow to specify the ID of a Capacity Reservation in which to run an instance - capacity_reservation_id

Have a question? Please checkout our Slack Community or visit our Slack Archive.

Slack Community

Describe the Feature

Add option for setting capacity_reservation_id param in the aws_instance resource.

Expected Behavior

Launch an EC2 instance using a pre-existing Capacity Reservation

Describe Ideal Solution

# AWS Capacity Reservation
resource "aws_ec2_capacity_reservation" "win_g4dn_xlarge_usw2a" {
  instance_type     = "g4dn.xlarge"
  availability_zone = "us-west2-a"
  instance_platform = "Windows"
  instance_count    = 1
}

# AWS Instance
module "instance_from_capacity_reservation" {
  source = "cloudposse/ec2-instance/aws"
  version = "x.x.x"
  ...
  ...
  capacity_reservation_id = aws_ec2_capacity_reservation.win_g4dn_xlarge_usw2a.id
  ...
  ...
}

Additional Context

I'm not sure if the solution would be something as simple as adding:

  • variables.tf:
variable "capacity_reservation_id" {
  type        = string
  default     = null
  description = "The ID of the Capacity Reservation in which to run the instance"
}
  • main.tf:
resource "aws_instance" "default" {
  ...
  ...
  capacity_reservation_specification {
    capacity_reservation_target {
      capacity_reservation_id = var.capacity_reservation_id != null ? var.capacity_reservation_id : null
    }
  }
  ...
  ...
}

Support for volume_tags

Describe the Feature

There's an aws_instance argument for volume_tags, a mapping of tags to assign to the devices created by the instance at launch time.

It would be useful of this was accessible either as a map, or perhaps just default to the instance tags.

Thanks
/g

instance_profile error with invalid count on first apply

Describe the Bug

Input instance_profile will throw the below error on apply

โ”‚ Error: Invalid count argument
โ”‚ 
โ”‚   on .terraform/modules/instance/main.tf line 85, in data "aws_iam_instance_profile" "given":
โ”‚   85:   count = local.enabled && var.instance_profile_enabled && var.instance_profile != "" ? 1 : 0
โ”‚ 
โ”‚ The "count" value depends on resource attributes that cannot be determined until apply, so Terraform cannot predict how many instances will be created. To work
โ”‚ around this, use the -target argument to first apply only the resources that the count depends on.
โ•ต
โ•ท
โ”‚ Error: Invalid count argument
โ”‚ 
โ”‚   on .terraform/modules/instance/main.tf line 96, in resource "aws_iam_role" "default":
โ”‚   96:   count                = var.instance_profile_enabled ? local.instance_profile_count : 0
โ”‚ 
โ”‚ The "count" value depends on resource attributes that cannot be determined until apply, so Terraform cannot predict how many instances will be created. To work
โ”‚ around this, use the -target argument to first apply only the resources that the count depends on.

Expected Behavior

Expected behavior is that the instance will use the precreated instance profile

Steps to Reproduce

resource "aws_iam_role" "default" {
  depends_on = [aws_iam_policy.default]
  name = "test-role"
  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": [
          "ec2.amazonaws.com"
        ]
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOF
}

resource "aws_iam_policy" "default" {
  name        = "test-policy"
  path        = "/"
  description = "IAM  Policy"

  policy = jsonencode({
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": "s3:ListBucket",
            "Resource": *,
            "Effect": "Allow"
        },
        {
            "Action": [
                "s3:PutObject*",
                "s3:GetObject*",
                "s3:DeleteObject*"
            ],
            "Resource": *,
            "Effect": "Allow"
        }
    ]
})
}

resource "aws_iam_role_policy_attachment" "default" {
  depends_on = [aws_iam_policy.default, aws_iam_role.default ]
  policy_arn = aws_iam_policy.default.arn
  role       = aws_iam_role.default.name
}

resource "aws_iam_role_policy_attachment" "ssm_attach" {
  role       = aws_iam_role.default.name
  policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
}

resource "aws_iam_instance_profile" "default" {
  name        = "${var.aws_profile}-${local.service}"
  role        = aws_iam_role.default.name
  depends_on  = [aws_iam_policy.default, aws_iam_role.default, aws_iam_role_policy_attachment.default ]
}

Module

module "instance" {
  source  = "cloudposse/ec2-instance/aws"
  version = "1.4.0"

  ssh_key_pair                = var.ssh_key_pair
  instance_type               = var.instance_type
  instance_profile      = aws_iam_instance_profile.default.id
  vpc_id                      = var.vpc_id
  security_groups             = var.security_groups
  subnet                      = var.subnet
  name                        = "ec2"
}

Will throw the earlier Error "Invalid count argument"
Comment instance_profile and it will work

module "instance" {
  source  = "cloudposse/ec2-instance/aws"
  version = "1.4.0"

  ssh_key_pair                = var.ssh_key_pair
  instance_type               = var.instance_type
  #instance_profile      = aws_iam_instance_profile.default.id
  vpc_id                      = var.vpc_id
  security_groups             = var.security_groups
  subnet                      = var.subnet
  name                        = "ec2"
}

After initial apply, you can then un-comment instance_profile and it will apply

module "instance" {
  source  = "cloudposse/ec2-instance/aws"
  version = "1.4.0"

  ssh_key_pair                = var.ssh_key_pair
  instance_type               = var.instance_type
  instance_profile      = aws_iam_instance_profile.default.id
  vpc_id                      = var.vpc_id
  security_groups             = var.security_groups
  subnet                      = var.subnet
  name                        = "ec2"
}

Screenshots

No response

Environment

Mac OS
TF 1.8.2

Additional Context

No response

Value for unconfigurable attribute in resource `aws_eip` causes terraform fail

Describe the Bug

The Module plan fails when provisioning EC2 instance because of the "aws_eip" resource vpc argument.

module "ec2" {
  source = "cloudposse/ec2-instance/aws"
  version     = "1.1.0"
  ssh_key_pair                = "ec2"
  vpc_id                      = module.vpc.vpc_id
  subnet                      = module.vpc.subnet_ids[0]
}
Acquiring state lock. This may take a few moments...
Releasing state lock. This may take a few moments...
โ•ท
โ”‚ Error: Value for unconfigurable attribute
โ”‚
โ”‚   with module.logstash.module.ec2_logstash.aws_eip.additional,
โ”‚   on .terraform/modules/logstash.ec2_logstash/eni.tf line 29, in resource "aws_eip" "additional":
โ”‚   29:   domain            = "vpc"
โ”‚
โ”‚ Can't configure a value for "domain": its value will be decided automatically based on the result of applying this configuration.
โ•ต
โ•ท
โ”‚ Error: Value for unconfigurable attribute
โ”‚
โ”‚   with module.logstash.module.ec2_logstash.aws_eip.default,
โ”‚   on .terraform/modules/logstash.ec2_logstash/main.tf line 175, in resource "aws_eip" "default":
โ”‚  175:   domain   = "vpc"
โ”‚
โ”‚ Can't configure a value for "domain": its value will be decided automatically based on the result of applying this configuration.

Expected Behavior

Terraform should plan an EC2 instance.

Steps to Reproduce

run terraform plan for the minimal module setup

Screenshots

No response

Environment

No response

Additional Context

No response

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Repository problems

These problems occurred while renovating this repository. View logs.

  • WARN: Base branch does not exist - skipping

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.

Detected dependencies

Branch main
terraform
security_group.tf
  • cloudposse/security-group/aws 0.3.3
ssm_patch.tf
  • cloudposse/label/null 0.25.0
versions.tf
  • aws >= 4.7.0
  • null >= 2.0
  • hashicorp/terraform >= 1.0
Branch release/v0
terraform
security_group.tf
  • cloudposse/security-group/aws 0.3.3
ssm_patch.tf
  • cloudposse/label/null 0.25.0
versions.tf
  • aws >= 2.0, < 5
  • null >= 2.0
  • hashicorp/terraform >= 1.0

  • Check this box to trigger a request for Renovate to run again on this repository

Error: owners.0 must not be empty

I get the following error if using the following code.
not sure what I am doing wrong.


  on .terraform/modules/ec2_instance/main.tf line 57, in data "aws_ami" "info":
  57: data "aws_ami" "info" {
ami_owner = "137112412989"

locals {
  ami                  = var.ami != "" ? var.ami : data.aws_ami.default.image_id
  ami_owner            = var.ami != "" ? var.ami_owner : data.aws_ami.default.owner_id
}

data "aws_ami" "default" {
  most_recent = "true"

  filter {
    name   = "name"
    values = ["amzn2-ami-hvm*"]
  }

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

  owners = ["137112412989"]
}

data "aws_ami" "info" {
  filter {
    name   = "image-id"
    values = [local.ami]
  }

  owners = [local.ami_owner]
}

module "ec2_instance" {
  source                      = "git::https://github.com/cloudposse/terraform-aws-ec2-instance.git?ref=tags/0.13.0"
 ...
  ami                         = local.ami
}

Dependency on aws provider >5.0

Describe the Bug

The recent changes to aws_eip force a dependency on the 5.0 aws provider. Using 4.x throws errors with

on .terraform/modules/data_host.box/main.tf line 175, in resource "aws_eip" "default":
  domain   = "vpc"
Can't configure a value for "domain": its value will be decided automatically based on the result of applying this configuration.

Caused by #159, if this is intended behavior, documentation and version requirements should be updated to not say the dependency is against >= 2.0

Expected Behavior

Resources deploy fine

Steps to Reproduce

Try to use module with 4.x aws provider

Screenshots

No response

Environment

No response

Additional Context

No response

Role create by module has no policy attached to it

The role created by the module is empty.

I tried manually adding the policy below to the role:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "ec2.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

and get the following error: "This policy contains the following error: Has prohibited field Principal For more information about the IAM policy grammar, see AWS IAM Policies"

The EC2 instance is up, but without the role I cannot connect to the EC2 instance neither through SSH nor through EC2 Instance Connect. Any suggestions?

Error with creating resource `security group rules` when `create_default_security_group` is `false`

Terraform Version

Terraform v0.10.8

Output

Error running plan: 1 error(s) occurred:

* module.vm.aws_security_group_rule.egress: 1 error(s) occurred:

* module.vm.aws_security_group_rule.egress: Resource 'aws_security_group.default' not found for variable 'aws_security_group.default.id'

Terraform Configuration Files

module "vm" {
  source                        = "git::https://github.com/cloudposse/terraform-aws-ec2-instance.git?ref=tags/0.5.0"
  associate_public_ip_address   = "false"
  create_default_security_group = "false"
  source_dest_check             = "false"
  name                          = "vm"
  namespace                     = "${var.namespace}"
  stage                         = "${var.stage}"
  vpc_id                        = "${module.vpc.vpc_id}"
  security_groups               = ["${aws_security_group.vm.id}"]
}

Debug Output

------------------------------------------------------------------------
Error running plan: 1 error(s) occurred:

* module.vm.aws_security_group_rule.egress: 1 error(s) occurred:

* module.vm.aws_security_group_rule.egress: Resource 'aws_security_group.default' not found for variable 'aws_security_group.default.id'

Expected Behavior

Instance should be created

Actual Behavior

Error running plan: 1 error(s) occurred:

Steps to Reproduce

  • terraform plan

Edge case when providing `instance_profile` that does not yet exist

Found a bug? Maybe our Slack Community can help.

Slack Community

Describe the Bug

When creating an instance profile and passing it into this module, this data lookup fails because the instance profile has not yet been created. The following error occurs when running terraform plan on the provided example code below.

I think a possible solution is to accept an instance_profile_arn instead of the name of the instance profile, since it's a generated value.

Error: Error getting instance profiles: NoSuchEntity: Instance Profile test cannot be found.
	status code: 404, request id: fcf2a09c-bfb3-4041-babd-95133304cf34

  on .terraform/modules/ec2_bug/main.tf line 73, in data "aws_iam_instance_profile" "given":
  73: data "aws_iam_instance_profile" "given" {

Expected Behavior

I expect Terraform to wait for the instance profile to be created before attempting to look it up, so I can create an instance profile and pass it into the EC2 module at the same time.

For context, I'm doing this in order to grant the EC2 instance permissions to reach out to S3 as part of the user_data script. I considered adding a policy to the default instance profile created by the module, but at that point it's too late since the user data will have already executed.

Steps to Reproduce

Here is an example to reproduce the error. Run terraform plan on this code, assuming a default VPC exists:

variable "aws_assume_role_arn" {}

provider "aws" {
  version = "~> 2.46"

  assume_role {
    role_arn = var.aws_assume_role_arn
  }
}

data "aws_caller_identity" "current" {}

resource "aws_iam_role" "test" {
  assume_role_policy = ""
}
resource "aws_iam_instance_profile" "test" {
  name = "test"
  role = aws_iam_role.test.name
}

data "aws_vpc" "default" {
  default = true
}

resource "aws_subnet" "default" {
  vpc_id     = data.aws_vpc.default.id
  cidr_block = "10.0.1.0/24"
}

module "aws_key_pair" {
  source              = "git::https://github.com/cloudposse/terraform-aws-key-pair.git?ref=tags/0.4.0"
  namespace           = "namespace"
  stage               = "stage"
  name                = "test"
  ssh_public_key_path = "/secrets"
  generate_ssh_key    = true
}

module "ec2_bug" {
  source           = "git::https://github.com/cloudposse/terraform-aws-ec2-instance.git?ref=master"
  name             = "test"
  environment      = "test"
  instance_type    = "t2.micro"
  ami_owner        = data.aws_caller_identity.current.account_id
  instance_profile = aws_iam_instance_profile.test.name
  vpc_id           = data.aws_vpc.default.id
  subnet           = aws_subnet.default.id
  ssh_key_pair     = module.aws_key_pair.key_name
}

Screenshots

n/a

Environment (please complete the following information):

Anything that will help us triage the bug will help. Here are some ideas:

  • OS: MacOS, but using geodesic
  • Terraform v0.12.21

Additional Context

Feature introduced here: #60

Incorrect AWS provider version requirement

Describe the Bug

The AWS provider requirement is still listed as >=2.x, but creating an instance with this module with an AWS provider version <5.x will result in the error Can't configure a value for "domain": its value will be decided automatically based on the result of applying this configuration. due to attempting to set the "domain" value on main.tf:181

Expected Behavior

No errors about setting derived attributes that can't be set or overridden in any way without back-versioning the module to a version where this line doesn't exist

Steps to Reproduce

Attempt to create an instance using this module, with AWS provider <5.x

Screenshots

โ•ท
โ”‚ Error: Value for unconfigurable attribute
โ”‚ 
โ”‚   with module.ec2_zscaler.aws_eip.additional,
โ”‚   on .terraform/modules/ec2_zscaler/eni.tf line 29, in resource "aws_eip" "additional":
โ”‚   29:   domain            = "vpc"
โ”‚ 
โ”‚ Can't configure a value for "domain": its value will be decided
โ”‚ automatically based on the result of applying this configuration.
โ•ต
โ•ท
โ”‚ Error: Value for unconfigurable attribute
โ”‚ 
โ”‚   with module.ec2_zscaler.aws_eip.default,
โ”‚   on .terraform/modules/ec2_zscaler/main.tf line 181, in resource "aws_eip" "default":
โ”‚  181:   domain   = "vpc"
โ”‚ 
โ”‚ Can't configure a value for "domain": its value will be decided
โ”‚ automatically based on the result of applying this configuration.
โ•ต

Environment

No response

Additional Context

No response

Tags for EIPs

Describe the Feature

After changing additional_ips_count from 0 to 1, the newly created secondary EIP does not inherit tags from the pre-existing EC2 instance. Can tags be enabled explicitly for EIPs by the module?

Expected Behavior

All EIPs are properly tagged.

Use Case

I've created a new EC2 instance with public EIP using the module. After some time I had to add another public static IP to the EC2, so I've increased additional_ips_count from 0 to 1. The additional EIP was created, but without any tags.

Describe Ideal Solution

All EIPs have tags automatically assigned to them either explicitly by the module or by AWS.

Alternatives Considered

Adding default_tags {} section into AWS provider block adds tags to EIP, but also to other resources. In case of EC2's EBS, it tried to add the same tags each terraform apply, which was inconvenient.

Additional Context

No response

Call to function "map" failed: the "map" function was deprecated in Terraform v0.12 and is no longer available; use tomap({ ... }) syntax to write a literal map.

Hi there

I know you have developed a useful module, but I've got a problem as following.

โ”‚ Error: Error in function call
โ”‚
โ”‚ on .terraform/modules/subnets/private.tf line 8, in module "private_label":
โ”‚ 8: map(var.subnet_type_tag_key, format(var.subnet_type_tag_value_format, "private"))
โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
โ”‚ โ”‚ var.subnet_type_tag_key is a string, known only after apply
โ”‚ โ”‚ var.subnet_type_tag_value_format is a string, known only after apply
โ”‚
โ”‚ Call to function "map" failed: the "map" function was deprecated in Terraform v0.12 and is no
โ”‚ longer available; use tomap({ ... }) syntax to write a literal map.

Could you please help me, or re-check your subnet module?

Output for Public IP is empty

Found a bug? Maybe our Slack Community can help.

Slack Community

Describe the Bug

Output for Public IP returns empty list.

Expected Behavior

Output for Public IP returns a public IP address.

Steps to Reproduce

Steps to reproduce the behavior:
module "instance" {
source = "git::https://github.com/clouddrove/terraform-aws-ec2.git?ref=tags/0.12.6"
key_name = var.ssh_key_pair
instance_type = var.ec2
instance_count = 1
tenancy = "default"
ami = var.ami
disk_size = 10
ebs_optimized = false
ebs_volume_type = "gp2"
assign_eip_address = false
associate_public_ip_address = true
vpc_security_group_ids_list = [aws_security_group.sg_instance.id]
subnet_ids = [lookup(module.public_subnets.az_subnet_ids, var.az1)]
application = "app"
managedby = "terraform"
name = "app"
environment = var.stage
label_order = ["environment", "name"]
instance_tags = var.instance_tags
}

output "instance_public_ip" {
value = module.instance.public_ip
}

Screenshots

If applicable, add screenshots or logs to help explain your problem.

Environment (please complete the following information):

Anything that will help us triage the bug will help. Here are some ideas:

  • OS: MacOS 10.15.6
  • terraform providers --version
    Terraform v0.12.26
  • provider.aws v2.70.0
  • provider.local v1.4.0
  • provider.null v2.1.2
  • provider.template v2.1.2

Additional Context

Add any other context about the problem here.

"Your query returned no results" error once the AMI ID is not listed within AWS marketplace.

The AWS instance configured via module, the 'ami' and 'ami_owner' parameters were configured, the instance was created successfully. Once the AMI-ID is removed from the AWS latest amis list (approx in 4 months), there is an error:

โ”‚ Error: Your query returned no results. Please change your search criteria and try again. โ”‚ โ”‚ with module.myInstance.data.aws_ami.info, โ”‚ on .terraform/modules/myInstance/main.tf line 71, in data "aws_ami" "info": โ”‚ 71: data "aws_ami" "info" {

It's needed to mention, that actual values for the 'AMI' and 'ami_owner' were saved and haven't changed.
the module version "0.44.0"

issue with output `public_dns` with terraform 0.11.0

Terraform Version

0.11.0

Crash Output

* module.admin_tier.output.public_dns: Resource 'null_resource.eip' does not have attribute 'triggers.public_dns' for variable 'null_resource.eip.*.triggers.public_dns'

Steps to Reproduce

terrafrom plan

Add support for `user_data_replace_on_change` field

Describe the Bug

The aws provider changed behavior in version 4. Previously, changes to the user_data field of an ec2 instance caused the instance to be torn down and recreated. Now, the user_data will be updated but the instance won't be recreatead. This means that, in most cases, the user_data script will not be run until the user somehow manually recreates the instance. If the user knows what's going on, they might choose to mark the instance for recreation using taint before or -replace on apply.

The change is discussed here and the field user_data_replace_on_change was added to aws_instance to provide the old behavior for those who wanted it.

Expected Behavior

I'd expect to be able to use this new field to continue having the longstanding behavior when the user_data is changed.

Steps to Reproduce

Steps to reproduce the behavior:

  1. Create an instance using user_data or user_data_base64
  2. Apply the change so the instance shows up
  3. Change the user_data
  4. Re-apply
  5. Notice that the instance has not been recreated.

Environment (please complete the following information):

Anything that will help us triage the bug will help. Here are some ideas:

$ terraform version
Terraform v1.2.5
on darwin_arm64
+ provider registry.terraform.io/hashicorp/archive v2.2.0
+ provider registry.terraform.io/hashicorp/aws v4.23.0
+ provider registry.terraform.io/hashicorp/cloudinit v2.2.0
+ provider registry.terraform.io/hashicorp/local v2.2.3
+ provider registry.terraform.io/hashicorp/null v3.1.1
+ provider registry.terraform.io/hashicorp/random v3.3.2
+ provider registry.terraform.io/hashicorp/tls v4.0.0

EBS volumes will be created if enabled = false

When the variable enabled = false is set the instance is not created but any count of the EBS volumes is.

It is expected from the documentation of enabled that setting this to false will stop creation of the EBS volumes and all resources.

Secondary private IPs not supported

Found a bug? Maybe our Slack Community can help.

Slack Community

Describe the Bug

I cannot set secondary private IPs to my EC2 instance using your module

Expected Behavior

Being able to set secondary private IPs to my EC2 instance using your module

Steps to Reproduce

Steps to reproduce the behavior:

N/A

Screenshots

If applicable, add screenshots or logs to help explain your problem.

N/A

Environment (please complete the following information):

Anything that will help us triage the bug will help. Here are some ideas:

  • OS: [e.g. Linux, OSX, WSL, etc]
  • Version [e.g. 10.15]

Additional Context

Add any other context about the problem here.

Failure associating EIP: InvalidInstanceID: The terminated instance 'i-xxxxxxxxxxxxx' is not in a valid state for this operation

Found a bug? Maybe our Slack Community can help.

Slack Community

Describe the Bug

When change ami and have enabled assign_eip_address i got error:

Error: Failure associating EIP: InvalidInstanceID: The terminated instance 'i-xxxxxxxxxxxx is not in a valid state for this operation.
	status code: 400, request id: 3cb8d8f6-d7a9-4466-a66f-96e12df06904
  on main.tf line 146, in resource "aws_eip" "default":
 146: resource "aws_eip" "default" {
time=2021-05-04T08:48:19Z level=error msg=Module /builds/decoking/terraform-aws/terra-files/eu-west-1/prod/infra-static-ip has finished with an error: Hit multiple errors:
Hit multiple errors:

aws_instance first is destroy and next is creating

Expected Behavior

aws instance are recreated and correct assign eip

Steps to Reproduce

Steps to reproduce the behavior:

  1. Use https://github.com/cloudposse/terraform-aws-ec2-instance.git module
  2. Create ec2 with ami1 and assign_eip_address=true
  3. Change ami to ami2
  4. apply changes

Screenshots

If applicable, add screenshots or logs to help explain your problem.

Environment (please complete the following information):

Anything that will help us triage the bug will help. Here are some ideas:

  • OS: linux
  • Version 0.30.4

Additional Context

Probably the instance state prevents connection to eip. The second time it executes the code everything works.

Only get data "aws_ami" "info" if it's actually required

Describe the Bug

This module does not specify a lifecycle policy ignoring AMI changes. As such any machine using a Windows AMI (which are cycled out of existence frequently) will make terraform fail (due to this data section) or will be forced to change the ami (thus recycling the running host).

Expected Behavior

Data blocks gathering AMI information should only be used if required, there should be variables allowing you to override any information they are gathering and you should be able to disable their usage completely.

Steps to Reproduce

Go deploy windows ami - ami-064e97759f52d11a7 and wait a few months till they cycle it out of the catalog. Then try to run terraform.

Alternatively create a private ami of something, deploy using this module, and then delete the ami and see how this terraform reacts to that change.

Screenshots

n/a

Environment (please complete the following information):

n/a

Additional Context

n/a

ebs_throughput default value is out of range

When using 0.44.0 I get
โ”‚ Error: expected throughput to be in the range (125 - 1000), got 0 โ”‚ โ”‚ with module.instance.aws_ebs_volume.default[0], โ”‚ on .terraform/modules/instance/main.tf line 178, in resource "aws_ebs_volume" "default": โ”‚ 178: throughput = local.ebs_throughput
the issue is caused by the ebs_throughput default which is set to 0 but it needs to be between 125 and 1000 i.e.

ebs_throughput = var.ebs_volume_type == "gp3" ? var.ebs_throughput : "0"
should be for example
ebs_throughput = var.ebs_volume_type == "gp3" ? var.ebs_throughput : "125"

Issue handling 'io2' and 'gp3' volume types

Description

When using provisioned IOPS SSD other than io1 the specified iops value for root_iops and/or ebs_iops get set to 0

Expected Behavior

'io2' and 'gp3' volume types should also set the given iops value when supplied

Steps to Reproduce

Steps to reproduce the behavior:

With a module used

module "instance" {
  source  = "cloudposse/ec2-instance/aws"
  version = "0.39.0"
  
  #Other required parameters

  root_volume_type = "gp3"
  root_iops                = 6000
  
  ...
 }

The instance will be created, however the default value of 0 will be applied on subsequent runs

Screenshots

Example of subsequent runs

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  ~ update in-place

Terraform will perform the following actions:

  # module.instance.aws_instance.default[0] will be updated in-place
  ~ resource "aws_instance" "default" {
        id                                   = "i-00000000000000000"
        tags                                 = {
            "Environment" = "xxx"
            "Name"        = "xxx"
            "Namespace"   = "xxx"
        }
        # (30 unchanged attributes hidden)

      ~ root_block_device {
          ~ iops                  = 3000 -> 0
            tags                  = {}
            # (8 unchanged attributes hidden)
        }
        # (4 unchanged blocks hidden)
    }

Plan: 0 to add, 1 to change, 0 to destroy.

Add "treat_missing_data" as variable for the cloudwatch alarm

Describe the Feature

When I create EC2 instances, I also attach specific run schedules to them. This causes alerting when the CloudWatch checks see missing data while they are offline.

I would like add the treat_missing_data variable to the module, so i can set the CloudWatch alarm to ignore missing data.

Expected Behavior

I specifying treat_missing_data would create a cloudwatch alarm that honors the variable value
treat_missing_data

Use Case

This is valuable to me because we use this tool called "Marbot", which alerts automatically for any cloudwatch alarms. Insufficient data falling into this scope. I'd like my EC2 alarms to stay in a "Good" state, when we shut them down for the weekend.

Describe Ideal Solution

Simple version updating allowing me to use treat_missing_data as a variable

Alternatives Considered

I've looked into somehow editing the alarm after this module creates it, although im not sure this is best practice or feasible

Additional Context

Ability to disable the Cloudwatch Alarm

Have a question? Please checkout our Slack Community or visit our Slack Archive.

Slack Community

Describe the Feature

I'd like the ability to turn off the Cloudwatch Alarm that gets created through use of a variable such as create_cloudwatch_alarm = false.

Expected Behavior

I'm able to use this module to create an EC2 instance without having to create the Cloudwatch Alarm

Use Case

The AWS account I'm in does not authorize me to perform iam:CreateServiceLinkedRole which is necessary to create the cloudwatch alarm. The error I get is:

Error: failed creating CloudWatch Metric Alarm (<redacted>-dev-bastion): AccessDenied: User: arn:<redacted> is not authorized to perform: iam:CreateServiceLinkedRole on resource: arn:<redacted>:role/aws-service-role/events.amazonaws.com/AWSServiceRoleForCloudWatchEvents because no identity-based policy allows the iam:CreateServiceLinkedRole action
โ”‚       status code: 403, request id: e0ffb57c-5ad2-4b02-9176-dc889c640583
โ”‚ 
โ”‚   with module.bastion.aws_cloudwatch_metric_alarm.default[0],
โ”‚   on .terraform/modules/bastion/cloudwatch-alarm.tf line 11, in resource "aws_cloudwatch_metric_alarm" "default":
โ”‚   11: resource "aws_cloudwatch_metric_alarm" "default" {

Describe Ideal Solution

A new variable called something like create_cloudwatch_alarm with type bool that changes the count param to 0 when it is set to false. It can stay true by default to preserve backward compatibility.

Alternatives Considered

Forking the module and disabling the cloudwatch alarm, or using another module, or making my own module.

Additional Context

none

`associate_public_ip_address` triggers recreation if instance is stopped

Describe the Bug

Creating an instance using this module with the following flags:

  associate_public_ip_address = true
  assign_eip_address          = false

causes the instance to be recreated when it is stopped because the "public address" (not EIP) is released when the server is shutdown.

To prevent this from happening we could add a lifecycle configuration which ignores this particular key. Unfortunately this cannot be done on a module object within Terraform so it must be done from inside the module itself.

Expected Behavior

No instance re-creation.

Steps to Reproduce

Steps to reproduce the behavior:

  1. Create an instance with the above flags
  2. Stop the instance
  3. Re-run plan and see that it will be recreated

Add Example Usage

what

  • Add example invocation

why

  • We need this so we can soon enable automated continuous integration testing of module

Error: module.instance.data.aws_ami.info: "owners": required field is not set

Greetings,

I ran into an issue while evaluating this module with the basic example:

$> terraform plan
Acquiring state lock. This may take a few moments...
Releasing state lock. This may take a few moments...

Error: module.instance.data.aws_ami.info: "owners": required field is not set

$> terraform version
Terraform v0.11.11
+ provider.archive v1.1.0
+ provider.aws v1.59.0
+ provider.null v2.0.0
+ provider.random v2.0.0

According to the terraform docs, it looks like 'owners' is (now?) a required argument for an 'aws_ami' data source.

The argument seems to be missing for the 'info' data source in this module, which results in a '"owners": required field is not set' error from terraform.

I'm pretty sure this module worked fine with the last terraform version.

If this is indeed the case, this fault probably also impacts your terraform-aws-ec2-instance-group module.

If you require further info, please let me know.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.