{"id":13602656,"url":"https://github.com/cloudposse/terraform-aws-security-group","last_synced_at":"2025-04-09T08:09:32.463Z","repository":{"id":39911477,"uuid":"333037754","full_name":"cloudposse/terraform-aws-security-group","owner":"cloudposse","description":"Terraform module to provision an AWS Security Group","archived":false,"fork":false,"pushed_at":"2024-12-11T22:18:16.000Z","size":4264,"stargazers_count":36,"open_issues_count":5,"forks_count":36,"subscribers_count":14,"default_branch":"main","last_synced_at":"2025-04-02T05:09:25.715Z","etag":null,"topics":["aws","terraform","terraform-module","terraform-modules"],"latest_commit_sha":null,"homepage":"https://cloudposse.com/accelerate","language":"HCL","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/cloudposse.png","metadata":{"funding":{"github":"cloudposse"},"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-01-26T09:43:08.000Z","updated_at":"2024-10-11T03:05:07.000Z","dependencies_parsed_at":"2024-03-08T13:31:57.408Z","dependency_job_id":"54d55eac-751c-4283-8235-5bfdaf721385","html_url":"https://github.com/cloudposse/terraform-aws-security-group","commit_stats":{"total_commits":49,"total_committers":14,"mean_commits":3.5,"dds":0.7142857142857143,"last_synced_commit":"276a4949330eba485147edc56c5f584b1298cbab"},"previous_names":[],"tags_count":23,"template":false,"template_full_name":"cloudposse/terraform-example-module","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cloudposse%2Fterraform-aws-security-group","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cloudposse%2Fterraform-aws-security-group/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cloudposse%2Fterraform-aws-security-group/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cloudposse%2Fterraform-aws-security-group/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cloudposse","download_url":"https://codeload.github.com/cloudposse/terraform-aws-security-group/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247999861,"owners_count":21031046,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aws","terraform","terraform-module","terraform-modules"],"created_at":"2024-08-01T18:01:32.935Z","updated_at":"2025-04-09T08:09:32.438Z","avatar_url":"https://github.com/cloudposse.png","language":"HCL","funding_links":["https://github.com/sponsors/cloudposse"],"categories":["aws"],"sub_categories":[],"readme":"\n\n\u003c!-- markdownlint-disable --\u003e\n\u003ca href=\"https://cpco.io/homepage\"\u003e\u003cimg src=\"https://github.com/cloudposse/terraform-aws-security-group/blob/main/.github/banner.png?raw=true\" alt=\"Project Banner\"/\u003e\u003c/a\u003e\u003cbr/\u003e\n    \u003cp align=\"right\"\u003e\n\u003ca href=\"https://github.com/cloudposse/terraform-aws-security-group/releases/latest\"\u003e\u003cimg src=\"https://img.shields.io/github/release/cloudposse/terraform-aws-security-group.svg?style=for-the-badge\" alt=\"Latest Release\"/\u003e\u003c/a\u003e\u003ca href=\"https://github.com/cloudposse/terraform-aws-security-group/commits\"\u003e\u003cimg src=\"https://img.shields.io/github/last-commit/cloudposse/terraform-aws-security-group.svg?style=for-the-badge\" alt=\"Last Updated\"/\u003e\u003c/a\u003e\u003ca href=\"https://slack.cloudposse.com\"\u003e\u003cimg src=\"https://slack.cloudposse.com/for-the-badge.svg\" alt=\"Slack Community\"/\u003e\u003c/a\u003e\u003c/p\u003e\n\u003c!-- markdownlint-restore --\u003e\n\n\u003c!--\n\n\n\n\n  ** DO NOT EDIT THIS FILE\n  **\n  ** This file was automatically generated by the `cloudposse/build-harness`.\n  ** 1) Make all changes to `README.yaml`\n  ** 2) Run `make init` (you only need to do this once)\n  ** 3) Run`make readme` to rebuild this file.\n  **\n  ** (We maintain HUNDREDS of open source projects. This is how we maintain our sanity.)\n  **\n\n\n\n\n\n--\u003e\n\nTerraform module to create AWS Security Group and rules.\n\n\n\u003e [!TIP]\n\u003e #### 👽 Use Atmos with Terraform\n\u003e Cloud Posse uses [`atmos`](https://atmos.tools) to easily orchestrate multiple environments using Terraform. \u003cbr/\u003e\n\u003e Works with [Github Actions](https://atmos.tools/integrations/github-actions/), [Atlantis](https://atmos.tools/integrations/atlantis), or [Spacelift](https://atmos.tools/integrations/spacelift).\n\u003e\n\u003e \u003cdetails\u003e\n\u003e \u003csummary\u003e\u003cstrong\u003eWatch demo of using Atmos with Terraform\u003c/strong\u003e\u003c/summary\u003e\n\u003e \u003cimg src=\"https://github.com/cloudposse/atmos/blob/master/docs/demo.gif?raw=true\"/\u003e\u003cbr/\u003e\n\u003e \u003ci\u003eExample of running \u003ca href=\"https://atmos.tools\"\u003e\u003ccode\u003eatmos\u003c/code\u003e\u003c/a\u003e to manage infrastructure from our \u003ca href=\"https://atmos.tools/quick-start/\"\u003eQuick Start\u003c/a\u003e tutorial.\u003c/i\u003e\n\u003e \u003c/detalis\u003e\n\n\n\n\n\n## Usage\n\nThis module is primarily for setting security group rules on a security group. You can provide the\nID of an existing security group to modify, or, by default, this module will create a new security\ngroup and apply the given rules to it.\n\nThis module can be used very simply, but it is actually quite complex because it is attempting to handle\nnumerous interrelationships, restrictions, and a few bugs in ways that offer a choice between zero\nservice interruption for updates to a security group not referenced by other security groups\n(by replacing the security group with a new one) versus brief service interruptions for security groups that must be preserved.\n\n### Avoiding Service Interruptions\n\nIt is desirable to avoid having service interruptions when updating a security group. This is not always\npossible due to the way Terraform organizes its activities and the fact that AWS will reject an attempt\nto create a duplicate of an existing security group rule. There is also the issue that while most AWS\nresources can be associated with and disassociated from security groups at any time, there remain some\nthat may not have their security group association changed, and an attempt to change their security group\nwill cause Terraform to delete and recreate the resource.\n\n#### The 2 Ways Security Group Changes Cause Service Interruptions\n\nChanges to a security group can cause service interruptions in 2 ways:\n\n1. Changing rules may be implemented as deleting existing rules and creating new ones. During the\n   period between deleting the old rules and creating the new rules, the security group will block\n   traffic intended to be allowed by the new rules.\n2. Changing rules may alternately be implemented as creating a new security group with the new rules\n   and replacing the existing security group with the new one (then deleting the old one).\n   This usually works with no service interruption in the case where all resources that reference the\n   security group are part of the same Terraform plan.\n   However, if, for example, the security group ID is referenced in a security group\n   rule in a security group that is not part of the same Terraform plan, then AWS will not allow the\n   existing (referenced) security group to be deleted, and even if it did, Terraform would not know\n   to update the rule to reference the new security group.\n\nThe key question you need to answer to decide which configuration to use is \"will anything break\nif the security group ID changes\". If not, then use the defaults `create_before_destroy = true` and\n`preserve_security_group_id = false` and do not worry about providing \"keys\" for\nsecurity group rules. This is the default because it is the easiest and safest solution when\nthe way the security group is being used allows it.\n\nIf things will break when the security group ID changes, then set `preserve_security_group_id`\nto `true`. Also read and follow the guidance below about [keys](#the-importance-of-keys) and\n[limiting Terraform security group rules to a single AWS security group rule](#terraform-rules-vs-aws-rules)\nif you want to mitigate against service interruptions caused by rule changes.\nNote that even in this case, you probably want to keep `create_before_destroy = true` because otherwise,\nif some change requires the security group to be replaced, Terraform will likely succeed\nin deleting all the security group rules but fail to delete the security group itself,\nleaving the associated resources completely inaccessible. At least with `create_before_destroy = true`,\nthe new security group will be created and used where Terraform can make the changes,\neven though the old security group will still fail to be deleted.\n\n#### The 3 Ways to Mitigate Against Service Interruptions\n\n##### Security Group `create_before_destroy = true`\n\nThe most important option is `create_before_destroy` which, when set to `true` (the default),\nensures that a new replacement security group is created before an existing one is destroyed.\nThis is particularly important because a security group cannot be destroyed while it is associated with\na resource (e.g. a load balancer), but \"destroy before create\" behavior causes Terraform\nto try to destroy the security group before disassociating it from associated resources,\nso plans fail to apply with the error\n\n```\nError deleting security group: DependencyViolation: resource sg-XXX has a dependent object\n```\n\nWith \"create before destroy\" and any resources dependent on the security group as part of the\nsame Terraform plan, replacement happens successfully:\n\n1. New security group is created\n2. Resource is associated with the new security group and disassociated from the old one\n3. Old security group is deleted successfully because there is no longer anything associated with it\n\n(If there is a resource dependent on the security group that is also outside the scope of\nthe Terraform plan, the old security group will fail to be deleted and you will have to\naddress the dependency manually.)\n\nNote that the module's default configuration of `create_before_destroy = true` and\n`preserve_security_group_id = false` will force \"create before destroy\" behavior on the target security\ngroup, even if the module did not create it and instead you provided a `target_security_group_id`.\n\nUnfortunately, just creating the new security group first is not enough to prevent a service interruption. Keep reading.\n\n##### Setting Rule Changes to Force Replacement of the Security Group\n\nA security group by itself is just a container for rules. It only functions as desired when all the rules are in place.\nIf using the Terraform default \"destroy before create\" behavior for rules, even when using `create_before_destroy` for the\nsecurity group itself, an outage occurs when updating the rules or security group, because the order of operations is:\n\n1. Delete existing security group rules (triggering a service interruption)\n2. Create the new security group\n3. Associate the new security group with resources and disassociate the old one (which can take a substantial\n   amount of time for a resource like a NAT Gateway)\n4. Create the new security group rules (restoring service)\n5. Delete the old security group\n\nTo resolve this issue, the module's default configuration of `create_before_destroy = true` and\n`preserve_security_group_id = false` causes any change in the security group rules\nto trigger the creation of a new security group. With that, a rule change causes operations to occur in this order:\n\n1. Create the new security group\n2. Create the new security group rules\n3. Associate the new security group with resources and disassociate the old one\n4. Delete the old security group rules\n5. Delete the old security group\n\n##### Preserving the Security Group\n\nThere can be a downside to creating a new security group with every rule change.\nIf you want to prevent the security group ID from changing unless absolutely necessary, perhaps because the associated\nresource does not allow the security group to be changed or because the ID is referenced somewhere (like in\nanother security group's rules) outside of this Terraform plan, then you need to set `preserve_security_group_id` to `true`.\n\nThe main drawback of this configuration is that there will normally be\na service outage during an update, because existing rules will be deleted before replacement\nrules are created. Using keys to identify rules can help limit the impact, but even with keys, simply adding a\nCIDR to the list of allowed CIDRs will cause that entire rule to be deleted and recreated, causing a temporary\naccess denial for all of the CIDRs in the rule. (For more on this and how to mitigate against it, see [The Importance\nof Keys](#the-importance-of-keys) below.)\n\nAlso note that setting `preserve_security_group_id` to `true` does not prevent Terraform from replacing the\nsecurity group when modifying it is not an option, such as when its name or description changes.\nHowever, if you can control the configuration adequately, you can maintain the security group ID and eliminate\nimpact on other security groups by setting `preserve_security_group_id` to `true`. We still recommend\nleaving `create_before_destroy` set to `true` for the times when the security group must be replaced,\nto avoid the `DependencyViolation` described above.\n\n### Defining Security Group Rules\n\nWe provide a number of different ways to define rules for the security group for a few reasons:\n- Terraform type constraints make it difficult to create collections of objects with optional members\n- Terraform resource addressing can cause resources that did not actually change to nevertheless be replaced\n  (deleted and recreated), which, in the case of security group rules, then causes a brief service interruption\n- Terraform resource addresses must be known at `plan` time, making it challenging to create rules that\n  depend on resources being created during `apply` and at the same time are not replaced needlessly when something else changes\n- When Terraform rules can be successfully created before being destroyed, there is no service interruption for the resources\n  associated with that security group (unless the security group ID is used in other security group rules outside\n  of the scope of the Terraform plan)\n\n#### The Importance of Keys\n\nIf you are using \"create before destroy\" behavior for the security group and security group rules, then\nyou can skip this section and much of the discussion about keys in the later sections, because keys do not matter\nin this configuration. However, if you are using \"destroy before create\" behavior, then a full understanding of keys\nas applied to security group rules will help you minimize service interruptions due to changing rules.\n\nWhen creating a collection of resources, Terraform requires each resource to be identified by a key,\nso that each resource has a unique \"address\", and changes to resources are tracked by that key.\nEvery security group rule input to this module accepts optional identifying keys (arbitrary strings) for each rule.\nIf you do not supply keys, then the rules are treated as a list,\nand the index of the rule in the list will be used as its key. This has the unwelcome behavior that removing a rule\nfrom the list will cause all the rules later in the list to be destroyed and recreated. For example, changing\n`[A, B, C, D]` to `[A, C, D]` causes rules 1(`B`), 2(`C`), and 3(`D`) to be deleted and new rules 1(`C`) and\n2(`D`) to be created.\n\nTo mitigate against this problem, we allow you to specify keys (arbitrary strings) for each rule. (Exactly how you specify\nthe key is explained in the next sections.) Going back to our example, if the\ninitial set of rules were specified with keys, e.g. `[{A: A}, {B: B}, {C: C}, {D: D}]`, then removing `B` from the list\nwould only cause `B` to be deleted, leaving `C` and `D` intact.\n\nNote, however, two cautions. First, the keys must be known at `terraform plan` time and therefore cannot depend\non resources that will be created during `apply`. Second, in order to be helpful, the keys must remain consistently\nattached to the same rules. For example, if you did\n\n```hcl\nrule_map = { for i, v in rule_list : i =\u003e v }\n```\n\nthen you will have merely recreated the initial problem with using a plain list. If you cannot attach\nmeaningful keys to the rules, there is no advantage to specifying keys at all.\n\n#### Terraform Rules vs AWS Rules\n\nA single security group rule input can actually specify multiple AWS security group rules. For example,\n`ipv6_cidr_blocks` takes a list of CIDRs. However, AWS security group rules do not allow for a list\nof CIDRs, so the AWS Terraform provider converts that list of CIDRs into a list of AWS security group rules,\none for each CIDR. (This is the underlying cause of several AWS Terraform provider bugs,\nsuch as [#25173](https://github.com/hashicorp/terraform-provider-aws/issues/25173).)\nAs of this writing, any change to any element of such a rule will cause\nall the AWS rules specified by the Terraform rule to be deleted and recreated, causing the same kind of\nservice interruption we sought to avoid by providing keys for the rules, or, when create_before_destroy = true,\ncausing a complete failure as Terraform tries to create duplicate rules which AWS rejects. To guard against this issue,\nwhen not using the default behavior, you should avoid the convenience of specifying multiple AWS rules\nin a single Terraform rule and instead create a separate Terraform rule for each source or destination specification.\n\n##### `rules` and `rules_map` inputs\nThis module provides 3 ways to set security group rules. You can use any or all of them at the same time.\n\nThe easy way to specify rules is via the `rules` input. It takes a list of rules. (We will define\na rule [a bit later](#definition-of-a-rule).) The problem is that a Terraform list must be composed\nof elements that are all the exact same type, and rules can be any of several\ndifferent Terraform types. So to get around this restriction, the second\nway to specify rules is via the `rules_map` input, which is more complex.\n\n\u003cdetails\u003e\u003csummary\u003eWhy the input is so complex (click to reveal)\u003c/summary\u003e\n\n- Terraform has 3 basic simple types: bool, number, string\n- Terraform then has 3 collections of simple types: list, map, and set\n- Terraform then has 2 structural types: object and tuple. However, these are not really single\ntypes. They are catch-all labels for values that are themselves combination of other values.\n(This will become a bit clearer after we define `maps` and contrast them with `objects`)\n\nOne [rule of the collection types](https://www.terraform.io/docs/language/expressions/type-constraints.html#collection-types)\nis that the values in the collections must all be the exact same type.\nFor example, you cannot have a list where some values are boolean and some are string. Maps require\nthat all keys be strings, but the map values can be any type, except again all the values in a map\nmust be the same type. In other words, the values of a map must form a valid list.\n\nObjects look just like maps. The difference between an object and a map is that the values in an\nobject do not all have to be the same type.\n\nThe \"type\" of an object is itself an object: the keys are the same, and the values are the types of the values in the object.\n\nSo although `{ foo = \"bar\", baz = {} }` and `{ foo = \"bar\", baz = [] }` are both objects,\nthey are not of the same type, and you can get error messages like\n\n```\nError: Inconsistent conditional result types\nThe true and false result expressions must have consistent types. The given\nexpressions are object and object, respectively.\n```\n\nThis means you cannot put them both in the same list or the same map,\neven though you can put them in a single tuple or object.\nSimilarly, and closer to the problem at hand,\n\n```hcl\ncidr_rule = {\n  type        = \"ingress\"\n  cidr_blocks = [\"0.0.0.0/0\"]\n}\n```\nis not the same type as\n\n```hcl\nself_rule = {\n  type        = \"ingress\"\n  self        = true\n}\n```\n\nThis means you cannot put both of those in the same list.\n\n```hcl\nrules = tolist([local.cidr_rule, local.self_rule])\n```\n\nGenerates the error\n\n```text\nInvalid value for \"v\" parameter: cannot convert tuple to list of any single type.\n```\n\nYou could make them the same type and put them in a list,\nlike this:\n\n```hcl\nrules = tolist([{\n  type        = \"ingress\"\n  cidr_blocks = [\"0.0.0.0/0\"]\n  self        = null\n},\n{\n  type        = \"ingress\"\n  cidr_blocks = []\n  self        = true\n}])\n```\n\nThat remains an option for you when generating the rules, and is probably better when you have full control over all the rules.\nHowever, what if some of the rules are coming from a source outside of your control? You cannot simply add those rules\nto your list. So, what to do? Create an object whose attributes' values can be of different types.\n\n```hcl\n{ mine = local.my_rules, theirs = var.their_rules }\n```\n\nThat is why the `rules_map` input is available. It will accept a structure like that, an object whose\nattribute values are lists of rules, where the lists themselves can be different types.\n\n\u003c/details\u003e\n\nThe `rules_map` input takes an object.\n- The attribute names (keys) of the object can be anything you want, but need to be known during `terraform plan`,\nwhich means they cannot depend on any resources created or changed by Terraform.\n- The values of the attributes are lists of rule objects, each object representing one Security Group Rule. As explained\n  above in \"Why the input is so complex\", each object in the list must be exactly the same type. To use multiple types,\n  you must put them in separate lists and put the lists in a map with distinct keys.\n\nExample:\n\n```hcl\nrules_map = {\n  ingress = [{\n    key         = \"ingress\"\n    type        = \"ingress\"\n    from_port   = 0\n    to_port     = 2222\n    protocol    = \"tcp\"\n    cidr_blocks = module.subnets.nat_gateway_public_ips\n    self        = null\n    description = \"2222\"\n  }],\n  egress = [{\n    key         = \"egress\"\n    type        = \"egress\"\n    from_port   = 0\n    to_port     = 0\n    protocol    = \"-1\"\n    cidr_blocks = [\"0.0.0.0/0\"]\n    self        = null\n    description = \"All output traffic\"\n  }]\n}\n```\n\n###### Definition of a Rule\n\nFor this module, a rule is defined as an object.\n- The attributes and values of the rule objects are fully compatible (have the same keys and accept the same values) as the\nTerraform [aws_security_group_rule resource](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group_rule),\nexcept:\n   - The `security_group_id` will be ignored, if present\n   - You can include an optional `key` attribute. If present, its value must be unique among all security group rules in the\n     security group, and it must be known in the Terraform \"plan\" phase, meaning it cannot depend on anything being\n     generated or created by Terraform.\n\nThe `key` attribute value, if provided, will be used to identify the Security Group Rule to Terraform in order to\nprevent Terraform from modifying it unnecessarily. If the `key` is not provided, Terraform will assign an identifier\nbased on the rule's position in its list, which can cause a ripple effect of rules being deleted and recreated if\na rule gets deleted from start of a list, causing all the other rules to shift position.\nSee [\"Unexpected changes...\"](#unexpected-changes-during-plan-and-apply) below for more details.\n\n\n##### `rule_matrix` Input\n\nThe other way to set rules is via the `rule_matrix` input. This splits the attributes of the `aws_security_group_rule`\nresource into two sets: one set defines the rule and description, the other set defines the subjects of the rule.\nAgain, optional \"key\" values can provide stability, but cannot contain derived values. This input is an attempt\nat convenience, and should not be used unless you are using the default settings of `create_before_destroy = true` and\n`preserve_security_group_id = false`, or else a number of failure modes or service interruptions are possible: use\n`rules_map` instead.\n\nAs with `rules` and explained above in \"Why the input is so complex\", all elements of the list must be the exact same type.\nThis also holds for all the elements of the `rules_matrix.rules` list. Because `rule_matrix` is already\nso complex, we do not provide the ability to mix types by packing object within more objects.\nAll of the elements of the `rule_matrix` list must be exactly the same type. You can make them all the same\ntype by following a few rules:\n\n- Every object in a list must have the exact same set of attributes. Most attributes are optional and can be omitted,\n  but any attribute appearing in one object must appear in all the objects.\n- Any attribute that takes a list value in any object must contain a list in all objects.\n  Use an empty list rather than `null` to indicate \"no value\". Passing in `null` instead of a list\n  may cause Terraform to crash or emit confusing error messages (e.g. \"number is required\").\n- Any attribute that takes a value of type other than list can be set to `null` in objects where no value is needed.\n\nThe schema for `rule_matrix` is:\n\n```hcl\n{\n  # these top level lists define all the subjects to which rule_matrix rules will be applied\n  key                       = an optional unique key to keep these rules from being affected when other rules change\n  source_security_group_ids = list of source security group IDs to apply all rules to\n  cidr_blocks               = list of ipv4 CIDR blocks to apply all rules to\n  ipv6_cidr_blocks          = list of ipv6 CIDR blocks to apply all rules to\n  prefix_list_ids           = list of prefix list IDs to apply all rules to\n\n  self = boolean value; set it to \"true\" to apply the rules to the created or existing security group, null otherwise\n\n  # each rule in the rules list will be applied to every subject defined above\n  rules = [{\n    key       = an optional unique key to keep this rule from being affected when other rules change\n    type      = type of rule, either \"ingress\" or \"egress\"\n    from_port = start range of protocol port\n    to_port   = end range of protocol port, max is 65535\n    protocol  = IP protocol name or number, or \"-1\" for all protocols and ports\n\n    description = free form text description of the rule\n  }]\n}\n```\n\n### Important Notes\n\n##### Unexpected changes during plan and apply\n\nWhen configuring this module for \"create before destroy\" behavior, any change to\na security group rule will cause an entire new security group to be created with\nall new rules. This can make a small change look like a big one, but is intentional\nand should not cause concern.\n\nAs explained above under [The Importance of Keys](#the-importance-of-keys),\nwhen using \"destroy before create\" behavior, security group rules without keys\nare identified by their indices in the input lists. If a rule is deleted and the other rules therefore move\ncloser to the start of the list, those rules will be deleted and recreated. This\ncan make a small change look like a big one when viewing the output of Terraform plan,\nand will likely cause a brief (seconds) service interruption.\n\nYou can avoid this for the most part by providing the optional keys, and [limiting each rule\nto a single source or destination](#terraform-rules-vs-aws-rules). Rules with keys will not be\nchanged if their keys do not change and the rules themselves do not change, except in the case of\n`rule_matrix`, where the rules are still dependent on the order of the security groups in\n`source_security_group_ids`. You can avoid this by using `rules` or `rules_map` instead of `rule_matrix` when you have\nmore than one security group in the list. You cannot avoid this by sorting the\n`source_security_group_ids`, because that leads to the \"Invalid `for_each` argument\" error\nbecause of [terraform#31035](https://github.com/hashicorp/terraform/issues/31035).\n\n##### Invalid for_each argument\n\nYou can supply a number of rules as inputs to this module, and they (usually) get transformed into\n`aws_security_group_rule` resources. However, Terraform works in 2 steps: a `plan` step where it\ncalculates the changes to be made, and an `apply` step where it makes the changes. This is so you\ncan review and approve the plan before changing anything. One big limitation of this approach is\nthat it requires that Terraform be able to count the number of resources to create without the\nbenefit of any data generated during the `apply` phase. So if you try to generate a rule based\non something you are creating at the same time, you can get an error like\n\n```\nError: Invalid for_each argument\nThe \"for_each\" value depends on resource attributes that cannot be determined until apply,\nso Terraform cannot predict how many instances will be created.\n```\n\nThis module uses lists to minimize the chance of that happening, as all it needs to know\nis the length of the list, not the values in it, but this error still can\nhappen for subtle reasons. Most commonly, using a function like `compact` on a list\nwill cause the length to become unknown (since the values have to be checked and `null`s removed).\nIn the case of `source_security_group_ids`, just sorting the list using `sort`\nwill cause this error. (See [terraform#31035](https://github.com/hashicorp/terraform/issues/31035).)\nIf you run into this error, check for functions like `compact` somewhere\nin the chain that produces the list and remove them if you find them.\n\n\n##### WARNINGS and Caveats\n\n**_Setting `inline_rules_enabled` is not recommended and NOT SUPPORTED_**: Any issues arising from setting\n`inlne_rules_enabled = true` (including issues about setting it to `false` after setting it to `true`) will\nnot be addressed, because they flow from [fundamental problems](https://github.com/hashicorp/terraform-provider-aws/issues/20046)\nwith the underlying `aws_security_group` resource. The setting is provided for people who know and accept the\nlimitations and trade-offs and want to use it anyway. The main advantage is that when using inline rules,\nTerraform will perform \"drift detection\" and attempt to remove any rules it finds in place but not\nspecified inline. See [this post](https://github.com/hashicorp/terraform-provider-aws/pull/9032#issuecomment-639545250)\nfor a discussion of the difference between inline and resource rules,\nand some of the reasons inline rules are not satisfactory.\n\n**_KNOWN ISSUE_** ([#20046](https://github.com/hashicorp/terraform-provider-aws/issues/20046)):\nIf you set `inline_rules_enabled = true`, you cannot later set it to `false`. If you try,\nTerraform will [complain](https://github.com/hashicorp/terraform/pull/2376) and fail.\nYou will either have to delete and recreate the security group or manually delete all\nthe security group rules via the AWS console or CLI before applying `inline_rules_enabled = false`.\n\n**_Objects not of the same type_**: Any time you provide a list of objects, Terraform requires that all objects in the list\nmust be [the exact same type](https://www.terraform.io/docs/language/expressions/type-constraints.html#dynamic-types-the-quot-any-quot-constraint).\nThis means that all objects in the list have exactly the same set of attributes and that each attribute has the same type\nof value in every object. So while some attributes are optional for this module, if you include an attribute in any one of the objects in a list, then you\nhave to include that same attribute in all of them.  In rules where the key would othewise be omitted, include the key with value of `null`,\nunless the value is a list type, in which case set the value to `[]` (an empty list), due to [#28137](https://github.com/hashicorp/terraform/issues/28137).\n\n\u003e [!IMPORTANT]\n\u003e In Cloud Posse's examples, we avoid pinning modules to specific versions to prevent discrepancies between the documentation\n\u003e and the latest released versions. However, for your own projects, we strongly advise pinning each module to the exact version\n\u003e you're using. This practice ensures the stability of your infrastructure. Additionally, we recommend implementing a systematic\n\u003e approach for updating versions to avoid unexpected changes.\n\n\n\n\n\n## Examples\n\n\nSee [examples/complete/main.tf](https://github.com/cloudposse/terraform-aws-security-group/blob/master/examples/complete/main.tf) for\neven more examples.\n\n```hcl\nmodule \"label\" {\n  source = \"cloudposse/label/null\"\n  # Cloud Posse recommends pinning every module to a specific version\n  # version = \"x.x.x\"\n  namespace  = \"eg\"\n  stage      = \"prod\"\n  name       = \"bastion\"\n  attributes = [\"public\"]\n  delimiter  = \"-\"\n\n  tags = {\n    \"BusinessUnit\" = \"XYZ\",\n    \"Snapshot\"     = \"true\"\n  }\n}\n\nmodule \"vpc\" {\n  source = \"cloudposse/vpc/aws\"\n  # Cloud Posse recommends pinning every module to a specific version\n  # version = \"x.x.x\"\n  cidr_block = \"10.0.0.0/16\"\n\n  context = module.label.context\n}\n\nmodule \"sg\" {\n  source = \"cloudposse/security-group/aws\"\n  # Cloud Posse recommends pinning every module to a specific version\n  # version = \"x.x.x\"\n\n  # Security Group names must be unique within a VPC.\n  # This module follows Cloud Posse naming conventions and generates the name\n  # based on the inputs to the null-label module, which means you cannot\n  # reuse the label as-is for more than one security group in the VPC.\n  #\n  # Here we add an attribute to give the security group a unique name.\n  attributes = [\"primary\"]\n\n  # Allow unlimited egress\n  allow_all_egress = true\n\n  rules = [\n    {\n      key         = \"ssh\"\n      type        = \"ingress\"\n      from_port   = 22\n      to_port     = 22\n      protocol    = \"tcp\"\n      cidr_blocks = [\"0.0.0.0/0\"]\n      self        = null  # preferable to self = false\n      description = \"Allow SSH from anywhere\"\n    },\n    {\n      key         = \"HTTP\"\n      type        = \"ingress\"\n      from_port   = 80\n      to_port     = 80\n      protocol    = \"tcp\"\n      cidr_blocks = []\n      self        = true\n      description = \"Allow HTTP from inside the security group\"\n    }\n  ]\n\n  vpc_id  = module.vpc.vpc_id\n\n  context = module.label.context\n}\n\nmodule \"sg_mysql\" {\n  source = \"cloudposse/security-group/aws\"\n  # Cloud Posse recommends pinning every module to a specific version\n  # version = \"x.x.x\"\n\n  # Add an attribute to give the Security Group a unique name\n  attributes = [\"mysql\"]\n\n  # Allow unlimited egress\n  allow_all_egress = true\n\n  rule_matrix =[\n    # Allow any of these security groups or the specified prefixes to access MySQL\n    {\n      source_security_group_ids = [var.dev_sg, var.uat_sg, var.staging_sg]\n      prefix_list_ids = [var.mysql_client_prefix_list_id]\n      rules = [\n        {\n          key         = \"mysql\"\n          type        = \"ingress\"\n          from_port   = 3306\n          to_port     = 3306\n          protocol    = \"tcp\"\n          description = \"Allow MySQL access from trusted security groups\"\n        }\n      ]\n    }\n  ]\n\n  vpc_id  = module.vpc.vpc_id\n\n  context = module.label.context\n}\n\n```\n\n\u003e [!TIP]\n\u003e #### Use Terraform Reference Architectures for AWS\n\u003e\n\u003e Use Cloud Posse's ready-to-go [terraform architecture blueprints](https://cloudposse.com/reference-architecture/) for AWS to get up and running quickly.\n\u003e\n\u003e ✅ We build it together with your team.\u003cbr/\u003e\n\u003e ✅ Your team owns everything.\u003cbr/\u003e\n\u003e ✅ 100% Open Source and backed by fanatical support.\u003cbr/\u003e\n\u003e\n\u003e \u003ca href=\"https://cpco.io/commercial-support?utm_source=github\u0026utm_medium=readme\u0026utm_campaign=cloudposse/terraform-aws-security-group\u0026utm_content=commercial_support\"\u003e\u003cimg alt=\"Request Quote\" src=\"https://img.shields.io/badge/request%20quote-success.svg?style=for-the-badge\"/\u003e\u003c/a\u003e\n\u003e \u003cdetails\u003e\u003csummary\u003e📚 \u003cstrong\u003eLearn More\u003c/strong\u003e\u003c/summary\u003e\n\u003e\n\u003e \u003cbr/\u003e\n\u003e\n\u003e Cloud Posse is the leading [**DevOps Accelerator**](https://cpco.io/commercial-support?utm_source=github\u0026utm_medium=readme\u0026utm_campaign=cloudposse/terraform-aws-security-group\u0026utm_content=commercial_support) for funded startups and enterprises.\n\u003e\n\u003e *Your team can operate like a pro today.*\n\u003e\n\u003e Ensure that your team succeeds by using Cloud Posse's proven process and turnkey blueprints. Plus, we stick around until you succeed.\n\u003e #### Day-0:  Your Foundation for Success\n\u003e - **Reference Architecture.** You'll get everything you need from the ground up built using 100% infrastructure as code.\n\u003e - **Deployment Strategy.** Adopt a proven deployment strategy with GitHub Actions, enabling automated, repeatable, and reliable software releases.\n\u003e - **Site Reliability Engineering.** Gain total visibility into your applications and services with Datadog, ensuring high availability and performance.\n\u003e - **Security Baseline.** Establish a secure environment from the start, with built-in governance, accountability, and comprehensive audit logs, safeguarding your operations.\n\u003e - **GitOps.** Empower your team to manage infrastructure changes confidently and efficiently through Pull Requests, leveraging the full power of GitHub Actions.\n\u003e\n\u003e \u003ca href=\"https://cpco.io/commercial-support?utm_source=github\u0026utm_medium=readme\u0026utm_campaign=cloudposse/terraform-aws-security-group\u0026utm_content=commercial_support\"\u003e\u003cimg alt=\"Request Quote\" src=\"https://img.shields.io/badge/request%20quote-success.svg?style=for-the-badge\"/\u003e\u003c/a\u003e\n\u003e\n\u003e #### Day-2: Your Operational Mastery\n\u003e - **Training.** Equip your team with the knowledge and skills to confidently manage the infrastructure, ensuring long-term success and self-sufficiency.\n\u003e - **Support.** Benefit from a seamless communication over Slack with our experts, ensuring you have the support you need, whenever you need it.\n\u003e - **Troubleshooting.** Access expert assistance to quickly resolve any operational challenges, minimizing downtime and maintaining business continuity.\n\u003e - **Code Reviews.** Enhance your team’s code quality with our expert feedback, fostering continuous improvement and collaboration.\n\u003e - **Bug Fixes.** Rely on our team to troubleshoot and resolve any issues, ensuring your systems run smoothly.\n\u003e - **Migration Assistance.** Accelerate your migration process with our dedicated support, minimizing disruption and speeding up time-to-value.\n\u003e - **Customer Workshops.** Engage with our team in weekly workshops, gaining insights and strategies to continuously improve and innovate.\n\u003e\n\u003e \u003ca href=\"https://cpco.io/commercial-support?utm_source=github\u0026utm_medium=readme\u0026utm_campaign=cloudposse/terraform-aws-security-group\u0026utm_content=commercial_support\"\u003e\u003cimg alt=\"Request Quote\" src=\"https://img.shields.io/badge/request%20quote-success.svg?style=for-the-badge\"/\u003e\u003c/a\u003e\n\u003e \u003c/details\u003e\n\n\n\n\u003c!-- markdownlint-disable --\u003e\n## Makefile Targets\n```text\nAvailable targets:\n\n  help                                Help screen\n  help/all                            Display help for all targets\n  help/short                          This help short screen\n  lint                                Lint terraform code\n\n```\n\u003c!-- markdownlint-restore --\u003e\n\u003c!-- markdownlint-disable --\u003e\n## Requirements\n\n| Name | Version |\n|------|---------|\n| \u003ca name=\"requirement_terraform\"\u003e\u003c/a\u003e [terraform](#requirement\\_terraform) | \u003e= 1.0.0 |\n| \u003ca name=\"requirement_aws\"\u003e\u003c/a\u003e [aws](#requirement\\_aws) | \u003e= 3.0 |\n| \u003ca name=\"requirement_null\"\u003e\u003c/a\u003e [null](#requirement\\_null) | \u003e= 3.0 |\n| \u003ca name=\"requirement_random\"\u003e\u003c/a\u003e [random](#requirement\\_random) | \u003e= 3.0 |\n\n## Providers\n\n| Name | Version |\n|------|---------|\n| \u003ca name=\"provider_aws\"\u003e\u003c/a\u003e [aws](#provider\\_aws) | \u003e= 3.0 |\n| \u003ca name=\"provider_null\"\u003e\u003c/a\u003e [null](#provider\\_null) | \u003e= 3.0 |\n| \u003ca name=\"provider_random\"\u003e\u003c/a\u003e [random](#provider\\_random) | \u003e= 3.0 |\n\n## Modules\n\n| Name | Source | Version |\n|------|--------|---------|\n| \u003ca name=\"module_this\"\u003e\u003c/a\u003e [this](#module\\_this) | cloudposse/label/null | 0.25.0 |\n\n## Resources\n\n| Name | Type |\n|------|------|\n| [aws_security_group.cbd](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group) | resource |\n| [aws_security_group.default](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group) | resource |\n| [aws_security_group_rule.dbc](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group_rule) | resource |\n| [aws_security_group_rule.keyed](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group_rule) | resource |\n| [null_resource.sync_rules_and_sg_lifecycles](https://registry.terraform.io/providers/hashicorp/null/latest/docs/resources/resource) | resource |\n| [random_id.rule_change_forces_new_security_group](https://registry.terraform.io/providers/hashicorp/random/latest/docs/resources/id) | resource |\n\n## Inputs\n\n| Name | Description | Type | Default | Required |\n|------|-------------|------|---------|:--------:|\n| \u003ca name=\"input_additional_tag_map\"\u003e\u003c/a\u003e [additional\\_tag\\_map](#input\\_additional\\_tag\\_map) | Additional key-value pairs to add to each map in `tags_as_list_of_maps`. Not added to `tags` or `id`.\u003cbr/\u003eThis is for some rare cases where resources want additional configuration of tags\u003cbr/\u003eand therefore take a list of maps with tag key, value, and additional configuration. | `map(string)` | `{}` | no |\n| \u003ca name=\"input_allow_all_egress\"\u003e\u003c/a\u003e [allow\\_all\\_egress](#input\\_allow\\_all\\_egress) | A convenience that adds to the rules specified elsewhere a rule that allows all egress.\u003cbr/\u003eIf this is false and no egress rules are specified via `rules` or `rule-matrix`, then no egress will be allowed. | `bool` | `true` | no |\n| \u003ca name=\"input_attributes\"\u003e\u003c/a\u003e [attributes](#input\\_attributes) | ID element. Additional attributes (e.g. `workers` or `cluster`) to add to `id`,\u003cbr/\u003ein the order they appear in the list. New attributes are appended to the\u003cbr/\u003eend of the list. The elements of the list are joined by the `delimiter`\u003cbr/\u003eand treated as a single ID element. | `list(string)` | `[]` | no |\n| \u003ca name=\"input_context\"\u003e\u003c/a\u003e [context](#input\\_context) | Single object for setting entire context at once.\u003cbr/\u003eSee description of individual variables for details.\u003cbr/\u003eLeave string and numeric variables as `null` to use default value.\u003cbr/\u003eIndividual variable settings (non-null) override settings in context object,\u003cbr/\u003eexcept for attributes, tags, and additional\\_tag\\_map, which are merged. | `any` | \u003cpre\u003e{\u003cbr/\u003e  \"additional_tag_map\": {},\u003cbr/\u003e  \"attributes\": [],\u003cbr/\u003e  \"delimiter\": null,\u003cbr/\u003e  \"descriptor_formats\": {},\u003cbr/\u003e  \"enabled\": true,\u003cbr/\u003e  \"environment\": null,\u003cbr/\u003e  \"id_length_limit\": null,\u003cbr/\u003e  \"label_key_case\": null,\u003cbr/\u003e  \"label_order\": [],\u003cbr/\u003e  \"label_value_case\": null,\u003cbr/\u003e  \"labels_as_tags\": [\u003cbr/\u003e    \"unset\"\u003cbr/\u003e  ],\u003cbr/\u003e  \"name\": null,\u003cbr/\u003e  \"namespace\": null,\u003cbr/\u003e  \"regex_replace_chars\": null,\u003cbr/\u003e  \"stage\": null,\u003cbr/\u003e  \"tags\": {},\u003cbr/\u003e  \"tenant\": null\u003cbr/\u003e}\u003c/pre\u003e | no |\n| \u003ca name=\"input_create_before_destroy\"\u003e\u003c/a\u003e [create\\_before\\_destroy](#input\\_create\\_before\\_destroy) | Set `true` to enable terraform `create_before_destroy` behavior on the created security group.\u003cbr/\u003eWe only recommend setting this `false` if you are importing an existing security group\u003cbr/\u003ethat you do not want replaced and therefore need full control over its name.\u003cbr/\u003eNote that changing this value will always cause the security group to be replaced. | `bool` | `true` | no |\n| \u003ca name=\"input_delimiter\"\u003e\u003c/a\u003e [delimiter](#input\\_delimiter) | Delimiter to be used between ID elements.\u003cbr/\u003eDefaults to `-` (hyphen). Set to `\"\"` to use no delimiter at all. | `string` | `null` | no |\n| \u003ca name=\"input_descriptor_formats\"\u003e\u003c/a\u003e [descriptor\\_formats](#input\\_descriptor\\_formats) | Describe additional descriptors to be output in the `descriptors` output map.\u003cbr/\u003eMap of maps. Keys are names of descriptors. Values are maps of the form\u003cbr/\u003e`{\u003cbr/\u003e   format = string\u003cbr/\u003e   labels = list(string)\u003cbr/\u003e}`\u003cbr/\u003e(Type is `any` so the map values can later be enhanced to provide additional options.)\u003cbr/\u003e`format` is a Terraform format string to be passed to the `format()` function.\u003cbr/\u003e`labels` is a list of labels, in order, to pass to `format()` function.\u003cbr/\u003eLabel values will be normalized before being passed to `format()` so they will be\u003cbr/\u003eidentical to how they appear in `id`.\u003cbr/\u003eDefault is `{}` (`descriptors` output will be empty). | `any` | `{}` | no |\n| \u003ca name=\"input_enabled\"\u003e\u003c/a\u003e [enabled](#input\\_enabled) | Set to false to prevent the module from creating any resources | `bool` | `null` | no |\n| \u003ca name=\"input_environment\"\u003e\u003c/a\u003e [environment](#input\\_environment) | ID element. Usually used for region e.g. 'uw2', 'us-west-2', OR role 'prod', 'staging', 'dev', 'UAT' | `string` | `null` | no |\n| \u003ca name=\"input_id_length_limit\"\u003e\u003c/a\u003e [id\\_length\\_limit](#input\\_id\\_length\\_limit) | Limit `id` to this many characters (minimum 6).\u003cbr/\u003eSet to `0` for unlimited length.\u003cbr/\u003eSet to `null` for keep the existing setting, which defaults to `0`.\u003cbr/\u003eDoes not affect `id_full`. | `number` | `null` | no |\n| \u003ca name=\"input_inline_rules_enabled\"\u003e\u003c/a\u003e [inline\\_rules\\_enabled](#input\\_inline\\_rules\\_enabled) | NOT RECOMMENDED. Create rules \"inline\" instead of as separate `aws_security_group_rule` resources.\u003cbr/\u003eSee [#20046](https://github.com/hashicorp/terraform-provider-aws/issues/20046) for one of several issues with inline rules.\u003cbr/\u003eSee [this post](https://github.com/hashicorp/terraform-provider-aws/pull/9032#issuecomment-639545250) for details on the difference between inline rules and rule resources. | `bool` | `false` | no |\n| \u003ca name=\"input_label_key_case\"\u003e\u003c/a\u003e [label\\_key\\_case](#input\\_label\\_key\\_case) | Controls the letter case of the `tags` keys (label names) for tags generated by this module.\u003cbr/\u003eDoes not affect keys of tags passed in via the `tags` input.\u003cbr/\u003ePossible values: `lower`, `title`, `upper`.\u003cbr/\u003eDefault value: `title`. | `string` | `null` | no |\n| \u003ca name=\"input_label_order\"\u003e\u003c/a\u003e [label\\_order](#input\\_label\\_order) | The order in which the labels (ID elements) appear in the `id`.\u003cbr/\u003eDefaults to [\"namespace\", \"environment\", \"stage\", \"name\", \"attributes\"].\u003cbr/\u003eYou can omit any of the 6 labels (\"tenant\" is the 6th), but at least one must be present. | `list(string)` | `null` | no |\n| \u003ca name=\"input_label_value_case\"\u003e\u003c/a\u003e [label\\_value\\_case](#input\\_label\\_value\\_case) | Controls the letter case of ID elements (labels) as included in `id`,\u003cbr/\u003eset as tag values, and output by this module individually.\u003cbr/\u003eDoes not affect values of tags passed in via the `tags` input.\u003cbr/\u003ePossible values: `lower`, `title`, `upper` and `none` (no transformation).\u003cbr/\u003eSet this to `title` and set `delimiter` to `\"\"` to yield Pascal Case IDs.\u003cbr/\u003eDefault value: `lower`. | `string` | `null` | no |\n| \u003ca name=\"input_labels_as_tags\"\u003e\u003c/a\u003e [labels\\_as\\_tags](#input\\_labels\\_as\\_tags) | Set of labels (ID elements) to include as tags in the `tags` output.\u003cbr/\u003eDefault is to include all labels.\u003cbr/\u003eTags with empty values will not be included in the `tags` output.\u003cbr/\u003eSet to `[]` to suppress all generated tags.\u003cbr/\u003e**Notes:**\u003cbr/\u003e  The value of the `name` tag, if included, will be the `id`, not the `name`.\u003cbr/\u003e  Unlike other `null-label` inputs, the initial setting of `labels_as_tags` cannot be\u003cbr/\u003e  changed in later chained modules. Attempts to change it will be silently ignored. | `set(string)` | \u003cpre\u003e[\u003cbr/\u003e  \"default\"\u003cbr/\u003e]\u003c/pre\u003e | no |\n| \u003ca name=\"input_name\"\u003e\u003c/a\u003e [name](#input\\_name) | ID element. Usually the component or solution name, e.g. 'app' or 'jenkins'.\u003cbr/\u003eThis is the only ID element not also included as a `tag`.\u003cbr/\u003eThe \"name\" tag is set to the full `id` string. There is no tag with the value of the `name` input. | `string` | `null` | no |\n| \u003ca name=\"input_namespace\"\u003e\u003c/a\u003e [namespace](#input\\_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 |\n| \u003ca name=\"input_preserve_security_group_id\"\u003e\u003c/a\u003e [preserve\\_security\\_group\\_id](#input\\_preserve\\_security\\_group\\_id) | When `false` and `create_before_destroy` is `true`, changes to security group rules\u003cbr/\u003ecause a new security group to be created with the new rules, and the existing security group is then\u003cbr/\u003ereplaced with the new one, eliminating any service interruption.\u003cbr/\u003eWhen `true` or when changing the value (from `false` to `true` or from `true` to `false`),\u003cbr/\u003eexisting security group rules will be deleted before new ones are created, resulting in a service interruption,\u003cbr/\u003ebut preserving the security group itself.\u003cbr/\u003e**NOTE:** Setting this to `true` does not guarantee the security group will never be replaced,\u003cbr/\u003eit only keeps changes to the security group rules from triggering a replacement.\u003cbr/\u003eSee the README for further discussion. | `bool` | `false` | no |\n| \u003ca name=\"input_regex_replace_chars\"\u003e\u003c/a\u003e [regex\\_replace\\_chars](#input\\_regex\\_replace\\_chars) | Terraform regular expression (regex) string.\u003cbr/\u003eCharacters matching the regex will be removed from the ID elements.\u003cbr/\u003eIf not set, `\"/[^a-zA-Z0-9-]/\"` is used to remove all characters other than hyphens, letters and digits. | `string` | `null` | no |\n| \u003ca name=\"input_revoke_rules_on_delete\"\u003e\u003c/a\u003e [revoke\\_rules\\_on\\_delete](#input\\_revoke\\_rules\\_on\\_delete) | Instruct Terraform to revoke all of the Security Group's attached ingress and egress rules before deleting\u003cbr/\u003ethe security group itself. This is normally not needed. | `bool` | `false` | no |\n| \u003ca name=\"input_rule_matrix\"\u003e\u003c/a\u003e [rule\\_matrix](#input\\_rule\\_matrix) | A convenient way to apply the same set of rules to a set of subjects. See README for details. | `any` | `[]` | no |\n| \u003ca name=\"input_rules\"\u003e\u003c/a\u003e [rules](#input\\_rules) | A list of Security Group rule objects. All elements of a list must be exactly the same type;\u003cbr/\u003euse `rules_map` if you want to supply multiple lists of different types.\u003cbr/\u003eThe keys and values of the Security Group rule objects are fully compatible with the `aws_security_group_rule` resource,\u003cbr/\u003eexcept for `security_group_id` which will be ignored, and the optional \"key\" which, if provided, must be unique\u003cbr/\u003eand known at \"plan\" time.\u003cbr/\u003eTo get more info see the `security_group_rule` [documentation](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group_rule).\u003cbr/\u003e\\_\\_\\_Note:\\_\\_\\_ The length of the list must be known at plan time.\u003cbr/\u003eThis means you cannot use functions like `compact` or `sort` when computing the list. | `list(any)` | `[]` | no |\n| \u003ca name=\"input_rules_map\"\u003e\u003c/a\u003e [rules\\_map](#input\\_rules\\_map) | A map-like object of lists of Security Group rule objects. All elements of a list must be exactly the same type,\u003cbr/\u003eso this input accepts an object with keys (attributes) whose values are lists so you can separate different\u003cbr/\u003etypes into different lists and still pass them into one input. Keys must be known at \"plan\" time.\u003cbr/\u003eThe keys and values of the Security Group rule objects are fully compatible with the `aws_security_group_rule` resource,\u003cbr/\u003eexcept for `security_group_id` which will be ignored, and the optional \"key\" which, if provided, must be unique\u003cbr/\u003eand known at \"plan\" time.\u003cbr/\u003eTo get more info see the `security_group_rule` [documentation](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group_rule). | `any` | `{}` | no |\n| \u003ca name=\"input_security_group_create_timeout\"\u003e\u003c/a\u003e [security\\_group\\_create\\_timeout](#input\\_security\\_group\\_create\\_timeout) | How long to wait for the security group to be created. | `string` | `\"10m\"` | no |\n| \u003ca name=\"input_security_group_delete_timeout\"\u003e\u003c/a\u003e [security\\_group\\_delete\\_timeout](#input\\_security\\_group\\_delete\\_timeout) | How long to retry on `DependencyViolation` errors during security group deletion from\u003cbr/\u003elingering ENIs left by certain AWS services such as Elastic Load Balancing. | `string` | `\"15m\"` | no |\n| \u003ca name=\"input_security_group_description\"\u003e\u003c/a\u003e [security\\_group\\_description](#input\\_security\\_group\\_description) | The description to assign to the created Security Group.\u003cbr/\u003eWarning: Changing the description causes the security group to be replaced. | `string` | `\"Managed by Terraform\"` | no |\n| \u003ca name=\"input_security_group_name\"\u003e\u003c/a\u003e [security\\_group\\_name](#input\\_security\\_group\\_name) | The name to assign to the security group. Must be unique within the VPC.\u003cbr/\u003eIf not provided, will be derived from the `null-label.context` passed in.\u003cbr/\u003eIf `create_before_destroy` is true, will be used as a name prefix. | `list(string)` | `[]` | no |\n| \u003ca name=\"input_stage\"\u003e\u003c/a\u003e [stage](#input\\_stage) | ID element. Usually used to indicate role, e.g. 'prod', 'staging', 'source', 'build', 'test', 'deploy', 'release' | `string` | `null` | no |\n| \u003ca name=\"input_tags\"\u003e\u003c/a\u003e [tags](#input\\_tags) | Additional tags (e.g. `{'BusinessUnit': 'XYZ'}`).\u003cbr/\u003eNeither the tag keys nor the tag values will be modified by this module. | `map(string)` | `{}` | no |\n| \u003ca name=\"input_target_security_group_id\"\u003e\u003c/a\u003e [target\\_security\\_group\\_id](#input\\_target\\_security\\_group\\_id) | The ID of an existing Security Group to which Security Group rules will be assigned.\u003cbr/\u003eThe Security Group's name and description will not be changed.\u003cbr/\u003eNot compatible with `inline_rules_enabled` or `revoke_rules_on_delete`.\u003cbr/\u003eIf not provided (the default), this module will create a security group. | `list(string)` | `[]` | no |\n| \u003ca name=\"input_tenant\"\u003e\u003c/a\u003e [tenant](#input\\_tenant) | ID element \\_(Rarely used, not included by default)\\_. A customer identifier, indicating who this instance of a resource is for | `string` | `null` | no |\n| \u003ca name=\"input_vpc_id\"\u003e\u003c/a\u003e [vpc\\_id](#input\\_vpc\\_id) | The ID of the VPC where the Security Group will be created. | `string` | n/a | yes |\n\n## Outputs\n\n| Name | Description |\n|------|-------------|\n| \u003ca name=\"output_arn\"\u003e\u003c/a\u003e [arn](#output\\_arn) | The created Security Group ARN (null if using existing security group) |\n| \u003ca name=\"output_id\"\u003e\u003c/a\u003e [id](#output\\_id) | The created or target Security Group ID |\n| \u003ca name=\"output_name\"\u003e\u003c/a\u003e [name](#output\\_name) | The created Security Group Name (null if using existing security group) |\n| \u003ca name=\"output_rules_terraform_ids\"\u003e\u003c/a\u003e [rules\\_terraform\\_ids](#output\\_rules\\_terraform\\_ids) | List of Terraform IDs of created `security_group_rule` resources, primarily provided to enable `depends_on` |\n\u003c!-- markdownlint-restore --\u003e\n\n\n## Related Projects\n\nCheck out these related projects.\n\n- [terraform-null-label](https://github.com/cloudposse/terraform-null-label) - Terraform module designed to generate consistent names and tags for resources. Use terraform-null-label to implement a strict naming convention.\n\n\n## References\n\nFor additional context, refer to some of these links.\n\n- [terraform-provider-aws](https://registry.terraform.io/providers/hashicorp/aws/latest) - Terraform AWS provider\n\n\n\n\n## ✨ Contributing\n\nThis project is under active development, and we encourage contributions from our community.\n\n\n\nMany thanks to our outstanding contributors:\n\n\u003ca href=\"https://github.com/cloudposse/terraform-aws-security-group/graphs/contributors\"\u003e\n  \u003cimg src=\"https://contrib.rocks/image?repo=cloudposse/terraform-aws-security-group\u0026max=24\" /\u003e\n\u003c/a\u003e\n\nFor 🐛 bug reports \u0026 feature requests, please use the [issue tracker](https://github.com/cloudposse/terraform-aws-security-group/issues).\n\nIn general, PRs are welcome. We follow the typical \"fork-and-pull\" Git workflow.\n 1. Review our [Code of Conduct](https://github.com/cloudposse/terraform-aws-security-group/?tab=coc-ov-file#code-of-conduct) and [Contributor Guidelines](https://github.com/cloudposse/.github/blob/main/CONTRIBUTING.md).\n 2. **Fork** the repo on GitHub\n 3. **Clone** the project to your own machine\n 4. **Commit** changes to your own branch\n 5. **Push** your work back up to your fork\n 6. Submit a **Pull Request** so that we can review your changes\n\n**NOTE:** Be sure to merge the latest changes from \"upstream\" before making a pull request!\n\n### 🌎 Slack Community\n\nJoin our [Open Source Community](https://cpco.io/slack?utm_source=github\u0026utm_medium=readme\u0026utm_campaign=cloudposse/terraform-aws-security-group\u0026utm_content=slack) 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.\n\n### 📰 Newsletter\n\nSign up for [our newsletter](https://cpco.io/newsletter?utm_source=github\u0026utm_medium=readme\u0026utm_campaign=cloudposse/terraform-aws-security-group\u0026utm_content=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.\nDropped straight into your Inbox every week — and usually a 5-minute read.\n\n### 📆 Office Hours \u003ca href=\"https://cloudposse.com/office-hours?utm_source=github\u0026utm_medium=readme\u0026utm_campaign=cloudposse/terraform-aws-security-group\u0026utm_content=office_hours\"\u003e\u003cimg src=\"https://img.cloudposse.com/fit-in/200x200/https://cloudposse.com/wp-content/uploads/2019/08/Powered-by-Zoom.png\" align=\"right\" /\u003e\u003c/a\u003e\n\n[Join us every Wednesday via Zoom](https://cloudposse.com/office-hours?utm_source=github\u0026utm_medium=readme\u0026utm_campaign=cloudposse/terraform-aws-security-group\u0026utm_content=office_hours) for your weekly dose of insider DevOps trends, AWS news and Terraform insights, all sourced from our SweetOps community, plus a _live Q\u0026A_ that you can’t find anywhere else.\nIt's **FREE** for everyone!\n## License\n\n\u003ca href=\"https://opensource.org/licenses/Apache-2.0\"\u003e\u003cimg src=\"https://img.shields.io/badge/License-Apache%202.0-blue.svg?style=for-the-badge\" alt=\"License\"\u003e\u003c/a\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003ePreamble to the Apache License, Version 2.0\u003c/summary\u003e\n\u003cbr/\u003e\n\u003cbr/\u003e\n\nComplete license is available in the [`LICENSE`](LICENSE) file.\n\n```text\nLicensed to the Apache Software Foundation (ASF) under one\nor more contributor license agreements.  See the NOTICE file\ndistributed with this work for additional information\nregarding copyright ownership.  The ASF licenses this file\nto you under the Apache License, Version 2.0 (the\n\"License\"); you may not use this file except in compliance\nwith the License.  You may obtain a copy of the License at\n\n  https://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing,\nsoftware distributed under the License is distributed on an\n\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, either express or implied.  See the License for the\nspecific language governing permissions and limitations\nunder the License.\n```\n\u003c/details\u003e\n\n## Trademarks\n\nAll other trademarks referenced herein are the property of their respective owners.\n\n\n## Copyrights\n\nCopyright © 2021-2024 [Cloud Posse, LLC](https://cloudposse.com)\n\n\n\n\u003ca href=\"https://cloudposse.com/readme/footer/link?utm_source=github\u0026utm_medium=readme\u0026utm_campaign=cloudposse/terraform-aws-security-group\u0026utm_content=readme_footer_link\"\u003e\u003cimg alt=\"README footer\" src=\"https://cloudposse.com/readme/footer/img\"/\u003e\u003c/a\u003e\n\n\u003cimg alt=\"Beacon\" width=\"0\" src=\"https://ga-beacon.cloudposse.com/UA-76589703-4/cloudposse/terraform-aws-security-group?pixel\u0026cs=github\u0026cm=readme\u0026an=terraform-aws-security-group\"/\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcloudposse%2Fterraform-aws-security-group","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcloudposse%2Fterraform-aws-security-group","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcloudposse%2Fterraform-aws-security-group/lists"}