Giter VIP home page Giter VIP logo

terraform-aws-modules / terraform-aws-notify-slack Goto Github PK

View Code? Open in Web Editor NEW
461.0 15.0 331.0 232 KB

Terraform module to create AWS resources for sending notifications to Slack πŸ‡ΊπŸ‡¦

Home Page: https://registry.terraform.io/modules/terraform-aws-modules/notify-slack/aws

License: Apache License 2.0

Python 73.15% HCL 26.85%
aws aws-lambda terraform-module aws-cloudwatch slack

terraform-aws-notify-slack's Issues

string indices must be integers: TypeError

Just rolled out the latest pull, which still contains an error:

string indices must be integers: TypeError
Traceback (most recent call last):
File "/var/task/automanager_notification.py", line 78, in lambda_handler
notify_slack(message, region)
File "/var/task/automanager_notification.py", line 63, in notify_slack
notification = cloudwatch_notification(message, region)
File "/var/task/automanager_notification.py", line 22, in cloudwatch_notification
"color": states[message['NewStateValue']],
TypeError: string indices must be integers

I am worthless when it comes to python, so I don't have a clue as to how to solve this one. When publishing plain text to this topic, it does work.

Lambda error with GuardDuty findings

Hi all,

I have set up this module to get slack notifications when a GuardDuty finding is found. There is a CW event that publishes the message to the SNS topic. I generate the samples findings from the GuardDuty console but nothing arrives. Looking to the lambda execution logs, I found this errors:

15:43:05
START RequestId: 10f8c40c-7e40-485f-a04e-1a9ae36c3586 Version: $LATEST

15:43:05
[ERROR] 2019-11-20T15:43:05.132Z 10f8c40c-7e40-485f-a04e-1a9ae36c3586 JSON decode error: Expecting value: line 1 column 1 (char 0)

15:43:05
Traceback (most recent call last):

15:43:05
File "/var/task/notify_slack.py", line 64, in notify_slack

15:43:05
message = json.loads(message)

15:43:05
File "/var/lang/lib/python3.7/json/__init__.py", line 348, in loads

15:43:05
return _default_decoder.decode(s)

15:43:05
File "/var/lang/lib/python3.7/json/decoder.py", line 337, in decode

15:43:05
obj, end = self.raw_decode(s, idx=_w(s, 0).end())

15:43:05
File "/var/lang/lib/python3.7/json/decoder.py", line 355, in raw_decode

15:43:05
raise JSONDecodeError("Expecting value", s, err.value) from None

15:43:05
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

15:43:05
[ERROR] HTTPError: HTTP Error 404: Not Found Traceback (most recent call last):   File "/var/task/notify_slack.py", line 84, in lambda_handler     notify_slack(subject, message, region)   File "/var/task/notify_slack.py", line 77, in notify_slack     urllib.request.urlopen(req, data)   File "/var/lang/lib/python3.7/urllib/request.py", line 222, in urlopen     return opener.open(url, data, timeout)

15:43:05
END RequestId: 10f8c40c-7e40-485f-a04e-1a9ae36c3586
ο„Ώ
15:43:05
REPORT RequestId: 10f8c40c-7e40-485f-a04e-1a9ae36c3586 Duration: 381.32 ms Billed Duration: 400 ms Memory Size: 128 MB Max Memory Used: 72 MB Init Duration: 329.24 ms

I supposed this lambda is not made for parsing GD findings.
Any workaround?

Add RDS Events Support

Is your request related to a new offering from AWS?

No. Existing AWS Feature.

Yes, available. See: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/db_event_subscription

Is your request related to a problem? Please describe.

AWS RDS can send DB instance events to SNS. The events can be routed via SNS to Lambda to Slack. Currently, there is no support to handle such events in this Terraform module.

Describe the solution you'd like.

In addition to handling CloudWatch Alarms and Logs, add support to handle RDS events in this module.

Describe alternatives you've considered.

No alternatives within this Terraform module.

Additional context

https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/MonitoringOverview.html

[enhancement] Use name_prefix for cloudwatch log group to avoid namespace collisions

name = "/aws/lambda/${var.lambda_function_name}"

We already have another similarly named group and so I get this error.

Error: Creating CloudWatch Log Group failed: ResourceAlreadyExistsException: The specified log group already exists:  The CloudWatch Log Group '/aws/lambda/notify_slack' already exists.

This can be avoided by using a name_prefix, https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_log_group#name_prefix

Unable to load Lambda function using shared state

Ran into this error when a teammate tried to run an apply on the state. My absolute state seems to have been written to the state.

* module.notify_slack.aws_lambda_function.notify_slack: 1 error(s) occurred:

* aws_lambda_function.notify_slack: Unable to load "/Users/srutner/infrastructure/terraform/providers/aws/us_east_1_dev/.terraform/modules/8e09be21bce706ab71a4446c9c3501c9/terraform-aws-modules-terraform-aws-notify-slack-cd06615/functions/notify_slack.zip": open /Users/srutner/infrastructure/terraform/providers/aws/us_east_1_dev/.terraform/modules/8e09be21bce706ab71a4446c9c3501c9/terraform-aws-modules-terraform-aws-notify-slack-cd06615/functions/notify_slack.zip: no such file or directory

This looks like an emergence of hashicorp/terraform#7613

Any way to upgrade lambda module version to relax the AWS provider version requirement for TF 0.12?

Note This issue might belong in terraform-aws-modules/terraform-aws-lambda - sorry if that's the case

Context

The latest version for TF 0.12 as of this writing is v3.4.0, and relies on https://github.com/terraform-aws-modules/terraform-aws-lambda/tree/v1.6.0.

Unfortunately, terraform-aws-modules/terraform-aws-lambda v1.6.0 has a pretty strict version requirement on the aws provider:

https://github.com/terraform-aws-modules/terraform-aws-lambda/blob/aea2b6da21bcde99ed5fdd0ccc27378b84eeda25/versions.tf#L5

Question

What are your thoughts on creating a Terraform 0.12-compatible version of terraform-aws-modules/terraform-aws-lambda with a more relaxed AWS provider version pin such as aws = ">= 2.46".

Creating CloudWatch Log Group failed: OperationAbortedException

$ terraform apply 
module.notify_slack.aws_cloudwatch_log_group.lambda[0]: Creating...
module.notify_slack.aws_sns_topic.this[0]: Creating...
aws_cloudwatch_log_group.lambda[0]: Creating...
module.notify_slack.aws_iam_role.lambda[0]: Creating...
aws_iam_role.lambda[0]: Creating...
aws_sns_topic.this[0]: Creating...
aws_cloudwatch_log_group.lambda[0]: Creation complete after 3s [id=/aws/lambda/notify_slack]
data.aws_iam_policy_document.lambda[0]: Refreshing state...
module.notify_slack.aws_sns_topic.this[0]: Creation complete after 3s [id=arn:aws:sns:eu-west-2:2603123456:slack-topic]
aws_sns_topic.this[0]: Creation complete after 3s [id=arn:aws:sns:eu-west-2:2603123456:slack-topic]
module.notify_slack.aws_iam_role.lambda[0]: Creation complete after 3s [id=lambda20200105142156051900000001]
aws_iam_role.lambda[0]: Creation complete after 3s [id=lambda20200105142156052100000002]
aws_iam_role_policy.lambda[0]: Creating...
aws_lambda_function.notify_slack[0]: Creating...
aws_iam_role_policy.lambda[0]: Creation complete after 3s [id=lambda20200105142156052100000002:lambda-policy-20200105142159112700000003]
aws_lambda_function.notify_slack[0]: Still creating... [10s elapsed]
aws_lambda_function.notify_slack[0]: Still creating... [20s elapsed]
aws_lambda_function.notify_slack[0]: Creation complete after 22s [id=notify_slack]
aws_sns_topic_subscription.sns_notify_slack[0]: Creating...
aws_lambda_permission.sns_notify_slack[0]: Creating...
aws_lambda_permission.sns_notify_slack[0]: Creation complete after 2s [id=AllowExecutionFromSNS]
aws_sns_topic_subscription.sns_notify_slack[0]: Creation complete after 3s [id=arn:aws:sns:eu-west-2:2603123456:slack-topic:c0afe839-0b4b-4d44-b5ec-19df0a00fee4]

Error: Creating CloudWatch Log Group failed: OperationAbortedException: A conflicting operation is currently in progress against this resource. Please try again.
	status code: 400, request id: 67b61c29-cd84-4b01-bbd8-3e645d2c084e '/aws/lambda/notify_slack'

  on .terraform/modules/notify_slack/terraform-aws-modules-terraform-aws-notify-slack-415fe44/main.tf line 26, in resource "aws_cloudwatch_log_group" "lambda":
  26: resource "aws_cloudwatch_log_group" "lambda" {

I thought may be resource already exits. so ran terraform destroy to give a clean restart and verified manually. Again, failed when it is tried to create log Group which is correct as it already exists. Any help will be appreciated. :)

terraform-provider-aws v3.0.0 breaks aws_cloudwatch_log_group output

When upgrading to v3.0.0 of terraform-provider-aws I get the following diff which looks like a breaking change:

  ~ resource "aws_iam_policy" "additional_json" {
        arn    = "arn:aws:iam::XXXX:policy/notify_slack"
        id     = "arn:aws:iam::XXXX:policy/notify_slack"
        name   = "notify_slack"
        path   = "/"
      ~ policy = jsonencode(
          ~ {
              ~ Statement = [
                  ~ {
                        Action   = [
                            "logs:PutLogEvents",
                            "logs:CreateLogStream",
                        ]
                        Effect   = "Allow"
                      ~ Resource = "arn:aws:logs:eu-central-1:XXXX:log-group:/aws/lambda/notify_slack:*" -> "arn:aws:logs:eu-central-1:XXXX:log-group:/aws/lambda/notify_slack"
                        Sid      = "AllowWriteToCloudwatchLogs"
                    },
                ]
                Version   = "2012-10-17"
            }
        )
    }

Please see:
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/guides/version-3-upgrade#resource-aws_cloudwatch_log_group

Similar Issues:
nozaq/terraform-aws-secure-baseline#118

Error "value of 'count' cannot be computed"

So I'm mostly copied the code from cloudwatch-alerts-to-slack example.
And I'm getting error:

Error: Error refreshing state: 1 error(s) occurred:

* module.notify_slack.data.aws_iam_policy_document.lambda: data.aws_iam_policy_document.lambda: value of 'count' cannot be computed

Here's the copied code:

resource "aws_kms_key" "this" {
  description = "KMS key for notify-slack test"
}

resource "aws_kms_alias" "this" {
  name          = "alias/kms-test-key"
  target_key_id = "${aws_kms_key.this.id}"
}

data "aws_kms_ciphertext" "slack_url" {
  # i'm aware this is wrong :)
  plaintext = "https://hooks.slack.com/services/AAA/BBB/CCC"
  # or?
  # key_id    = "${aws_kms_key.this.key_id}"
  key_id    = "${aws_kms_key.this.arn}"
}

module "notify_slack" {
  source = "terraform-aws-modules/notify-slack/aws"
  version = "1.3.0"

  sns_topic_name = "slack-topic"

  slack_webhook_url = "${data.aws_kms_ciphertext.slack_url.ciphertext_blob}"
  slack_channel     = "aws-notification"
  slack_username    = "reporter"

  kms_key_arn = "${aws_kms_key.this.arn}"
}

resource "aws_cloudwatch_metric_alarm" "LambdaDuration" {
  alarm_name          = "NotifySlackDuration"
  comparison_operator = "GreaterThanOrEqualToThreshold"
  evaluation_periods  = "1"
  metric_name         = "Duration"
  namespace           = "AWS/Lambda"
  period              = "60"
  statistic           = "Average"
  threshold           = "5000"
  alarm_description   = "Duration of notifying slack exceeds threshold"

  alarm_actions = ["${module.notify_slack.this_slack_topic_arn}"]

  dimensions {
    FunctionName = "${module.notify_slack.notify_slack_lambda_function_name}"
  }
}

Am I missing something?

Tried v3.0.0 - unexpected terraform replacement

Tried using the new version , with this setup:

module "notify_slack_module" {
  source = "github.com/terraform-aws-modules/terraform-aws-notify-slack.git?ref=v3.0.0"
  sns_topic_name    = var.some_topic
  slack_webhook_url = var.slack_webhook_url
  slack_channel     = var.slack_channel
  slack_username    = var.slack_username
  lambda_function_name = "function_name"
}

First time terraform apply works perfectly fine, however on a re-run, this is the outcome:

  # module.notify_slack_module.module.lambda.null_resource.archive[0] must be replaced
-/+ resource "null_resource" "archive" {
      ~ id       = "5201291547049430426" -> (known after apply)
      ~ triggers = { # forces replacement
            "filename"  = "builds/d75764cc658ab477397eb09fabff2b67473cfe1246224a1e50360327a2c8e7a3.zip"
          ~ "timestamp" = "1591642297725210000" -> "1591643174300057800"
        }
    }

The resource shouldn't be expected to be replaced every time you run the terraform apply command just because there's a different timestamp.

Upgrading to 0.13

I am trying to upgrade to terraform 0.13, I have updated the version. I am facing this err when running plan

To work with
module.infra.module.slack_notification.module.cloudwatch_event_notification.data.archive_file.notify_slack[0]
its original provider configuration at
provider["registry.terraform.io/-/archive"] is required, but it has been
removed. This occurs when a provider configuration is removed while objects
created by that provider still exist in the state. Re-add the provider
configuration to destroy
module.infra.module.slack_notification.module.cloudwatch_event_notification.data.archive_file.notify_slack[0],
after which you can remove the provider configuration again.

Thanks

Error: rpc error: code = Canceled desc = context canceled

Description

After performing terraform plan I get multiples Error: rpc error: code = Canceled desc = context canceled.

Versions

  • source = "terraform-aws-modules/notify-slack/aws"
  • version = "4.24.0"

Actual behavior

[DEBUG] provider.stdio: received EOF, stopping recv loop: err="rpc error: code = Unavailable desc = transport is closing"
[DEBUG] provider: plugin process exited: path=.terraform/providers/registry.terraform.io/hashicorp/random/3.1.0/linux_amd64/terraform-provider-random_v3.1.0_x5 pid=9848
[DEBUG] provider: plugin exited
[DEBUG] provider.stdio: received EOF, stopping recv loop: err="rpc error: code = Unavailable desc = transport is closing"
[DEBUG] provider: plugin process exited: path=.terraform/providers/registry.terraform.io/hashicorp/archive/2.2.0/linux_amd64/terraform-provider-archive_v2.2.0_x5 pid=9836
[DEBUG] provider: plugin exited
[DEBUG] provider: plugin process exited: path=.terraform/providers/registry.terraform.io/hashicorp/template/2.2.0/linux_amd64/terraform-provider-template_v2.2.0_x4 pid=9798
[DEBUG] provider: plugin exited
[DEBUG] provider.stdio: received EOF, stopping recv loop: err="rpc error: code = Unavailable desc = transport is closing"
[DEBUG] provider: plugin process exited: path=.terraform/providers/registry.terraform.io/hashicorp/external/2.2.0/linux_amd64/terraform-provider-external_v2.2.0_x5 pid=9824
[DEBUG] provider: plugin exited
[DEBUG] provider.stdio: received EOF, stopping recv loop: err="rpc error: code = Unavailable desc = transport is closing"
[DEBUG] provider: plugin process exited: path=.terraform/providers/registry.terraform.io/hashicorp/local/2.1.0/linux_amd64/terraform-provider-local_v2.1.0_x5 pid=9886
[DEBUG] provider: plugin exited
[DEBUG] provider.stdio: received EOF, stopping recv loop: err="rpc error: code = Unavailable desc = transport is closing"
[DEBUG] provider: plugin process exited: path=.terraform/providers/registry.terraform.io/hashicorp/null/3.1.0/linux_amd64/terraform-provider-null_v3.1.0_x5 pid=9785
[DEBUG] provider: plugin exited
[DEBUG] provider.stdio: received EOF, stopping recv loop: err="rpc error: code = Unavailable desc = transport is closing"
[DEBUG] provider: plugin process exited: path=.terraform/providers/registry.terraform.io/hashicorp/aws/4.2.0/linux_amd64/terraform-provider-aws_v4.2.0_x5 pid=9872
[DEBUG] provider: plugin exited

Invalid Index Error

I recently ran the build and it caused this. Previously it was working fine. No updates
terraform version: 0.12.12
module version: 2.0

Error: Invalid index

on .terraform/modules/sns_lambda_slack_notifier/main.tf line 50, in resource "aws_lambda_permission" "sns_notify_slack":
50: function_name = aws_lambda_function.notify_slack[0].function_name
|----------------
| aws_lambda_function.notify_slack is empty tuple

The given key does not identify an element in this collection value.

Error: Invalid index

on .terraform/modules/sns_lambda_slack_notifier_error/main.tf line 50, in resource "aws_lambda_permission" "sns_notify_slack":
50: function_name = aws_lambda_function.notify_slack[0].function_name
|----------------
| aws_lambda_function.notify_slack is empty tuple

The given key does not identify an element in this collection value.

Formatting Issue after v4.11.0

I am using codepipeline notification to get informed about the execution status.

The message aws returned is like this:

image

But in the slack channel , the message was transformed into this:

image

The detail resources are missing.
Looks like array field and object field is missing after formatting.

Lambda function HTTP Error

Hi all!

I using this module to send all alerts of the AWS, but when this function run occurs this error.

What is the problem? Security Group?

Thanks!

[ERROR] HTTPError: HTTP Error 404: Not Found Traceback (most recent call last): File "/var/task/notify_slack.py", line 84, in lambda_handler notify_slack(subject, message, region) File "/var/task/notify_slack.py", line 77, in notify_slack urllib.request.urlopen(req, data) File "/var/lang/lib/python3.7/urllib/request.py", line 222, in urlopen return opener.open(url, data, timeout)

[ERROR] HTTPError: HTTP Error 404: Not Found Traceback (most recent call last): File "/var/task/notify_slack.py", line 84, in lambda_handler notify_slack(subject, message, region) File "/var/task/notify_slack.py", line 77, in notify_slack urllib.request.urlopen(req, data) File "/var/lang/lib/python3.7/urllib/request.py", line 222, in urlopen return opener.open(url, data, timeout) File "/var/lang/lib/python3.7/urllib/request.py", line 531, in open response = meth(req, response) File "/var/lang/lib/python3.7/urllib/request.py", line 641, in http_response 'http', request, response, code, msg, hdrs) File "/var/lang/lib/python3.7/urllib/request.py", line 569, in error return self._call_chain(*args) File "/var/lang/lib/python3.7/urllib/request.py", line 503, in _call_chain result = func(*args) File "/var/lang/lib/python3.7/urllib/request.py", line 649, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp)

Support Terraform 0.15

Description

Terraform 0.15 (changelog) removed the deprecated functions list and map which this module uses.

Versions

  • Terraform: 0.15

Reproduction

Steps to reproduce the behavior:

  • Terraform file (see below)
  • terraform init && terraform validate

Code Snippet to Reproduce

terraform {
  required_version = ">= 0.15"
}
provider "aws" {
  region = "eu-west-1"
}

module "slack_notifications" {
  source  = "terraform-aws-modules/notify-slack/aws"
  version = "4.13.0"

  sns_topic_name = "topic-name"

  slack_webhook_url = "https://fake-url.com"
  slack_channel     = "some-channel"
  slack_username    = "AWS Cloud Watch - Dead-letter queue alarms"

  cloudwatch_log_group_retention_in_days = 14

  iam_role_name_prefix = ""

  lambda_function_name = "lambda-name"
  lambda_description   = "description"
}

Expected behavior

terraform validate should not fail.

Actual behavior

terraform validate fails with

β”‚ Error: Error in function call
β”‚
β”‚   on .terraform/modules/slack_notifications.lambda/iam.tf line 23, in data "aws_iam_policy_document" "assume_role":
β”‚   23:       identifiers = distinct(concat(slice(list("lambda.amazonaws.com", "edgelambda.amazonaws.com"), 0, var.lambda_at_edge ? 2 : 1), var.trusted_entities))
β”‚
β”‚ Call to function "list" failed: the "list" function was deprecated in
β”‚ Terraform v0.12 and is no longer available; use tolist([ ... ]) syntax to
β”‚ write a literal list.
β•΅
β•·
β”‚ Error: Error in function call
β”‚
β”‚   on .terraform/modules/slack_notifications.lambda/outputs.tf line 98, in output "s3_object":
β”‚   98:   value       = map("bucket", local.s3_bucket, "key", local.s3_key, "version_id", local.s3_object_version)
β”‚     β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚     β”‚ local.s3_bucket is a string, known only after apply
β”‚     β”‚ local.s3_key will be known only after apply
β”‚     β”‚ local.s3_object_version will be 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.
|
β”‚ Error: Error in function call
β”‚
β”‚   on .terraform/modules/slack_notifications/main.tf line 29, in locals:
β”‚   29:     resources = [replace("${element(concat(aws_cloudwatch_log_group.lambda[*].arn, list("")), 0)}:*", ":*:*", ":*")]
β”‚
β”‚ Call to function "list" failed: the "list" function was deprecated in
β”‚ Terraform v0.12 and is no longer available; use tolist([ ... ]) syntax to
β”‚ write a literal list.

Version 4.20.0 has breaking changes to outputs

Description

All the outputs changed their names in version 4.20.0

Versions

doesn't matter. verision 4.20.0 broke things.

Reproduction

Try to use version 4.20.0 with existing terraform.

Expected behavior

Breaking changes have major version number updates, as per semver.org

Given a version number MAJOR.MINOR.PATCH, increment the:

MAJOR version when you make incompatible API changes,
MINOR version when you add functionality in a backwards compatible manner

Actual behavior

The 'this_' prefix on all outputs were removed

Typo on subscription_filter_policy

The input parameter: subsription_filter_policy has a typo. It's missing a c :

so just need to change subsription_filter_policy to subscription_filter_policy

Resource gets modified when absolute path to module changes

Hello. It appears the absolute path of the module is encoded in the state such that using the exact same Terraform in two different paths produces state changes instead of producing no changes at all.

For example:

  ~ module.notify_slack_engineering.aws_lambda_function.notify_slack
      filename:           "/Users/foo/src/project/.terraform/modules/d040de6279d8f75cc8478e75c8a39e23/terraform-aws-modules-terraform-aws-notify-slack-5cdd039/functions/notify_slack.zip" => "/Users/bar/src/project/.terraform/modules/d040de6279d8f75cc8478e75c8a39e23/terraform-aws-modules-terraform-aws-notify-slack-5cdd039/functions/notify_slack.zip"
      last_modified:      "2018-04-17T23:20:20.668+0000" => <computed>

This is problematic for having different users running terraform plan locally while doing development work as they end up getting this false change in their output.

Is there a way to use a relative path?

Errors when upgrading to terraform 0.13

When trying to update to terraform 0.13 using terraform-aws-notify-slack v4.4.0, I am getting the following error during planning:

Error: Provider configuration not present

To work with
module.tivo_cluster.module.notify-slack.module.lambda.data.aws_caller_identity.current[0]
its original provider configuration at
module.tivo_cluster.provider["registry.terraform.io/-/aws"] is required, but
it has been removed. This occurs when a provider configuration is removed
while objects created by that provider still exist in the state. Re-add the
provider configuration to destroy
module.tivo_cluster.module.notify-slack.module.lambda.data.aws_caller_identity.current[0],
after which you can remove the provider configuration again.


Error: Provider configuration not present

To work with
module.tivo_cluster.module.notify-slack.module.lambda.data.aws_partition.current[0]
its original provider configuration at
module.tivo_cluster.provider["registry.terraform.io/-/aws"] is required, but
it has been removed. This occurs when a provider configuration is removed
while objects created by that provider still exist in the state. Re-add the
provider configuration to destroy
module.tivo_cluster.module.notify-slack.module.lambda.data.aws_partition.current[0],
after which you can remove the provider configuration again.


Error: Provider configuration not present

To work with
module.tivo_cluster.module.notify-slack.module.lambda.data.aws_region.current[0]
its original provider configuration at
module.tivo_cluster.provider["registry.terraform.io/-/aws"] is required, but
it has been removed. This occurs when a provider configuration is removed
while objects created by that provider still exist in the state. Re-add the
provider configuration to destroy
module.tivo_cluster.module.notify-slack.module.lambda.data.aws_region.current[0],
after which you can remove the provider configuration again.

Note that I have already run terraform 0.13upgrade on my modules and deployment terraform. Looking at the
notify-slack module, it appears you are not unisg explicit provider source locations in your code? Please read
https://www.terraform.io/upgrade-guides/0-13.html#explicit-provider-source-locations

It appears you are still using 0.12 format? e.g.

  required_providers {
    aws = ">= 2.35, < 4.0"
  }

rather than

  required_providers {
    aws = {
      source = "hashicorp/aws"
      version = ">= 2.35, < 4.0"
    }
  }

feature: Support systems-manager / patch-manager events.

Is your request related to a new offering from AWS?

not new feature or provider

Is your request related to a problem? Please describe.

no

Describe the solution you'd like.

funnel events from patch-manager (scans/updates and outcomes) https://docs.aws.amazon.com/systems-manager/latest/userguide/monitoring-sns-notifications.html into slack

Describe alternatives you've considered.

one could go with zapier/triggermesh or 3rd parties, but that leaks into other infras and brings hassles and goes outside of tf/aws.

Additional context

Error when adding the module with "create" set to false

Hi!

This is how I'm setting the module up:

module "notify-slack" {
  source  = "terraform-aws-modules/notify-slack/aws"
  version = "~> v2.8"

  create = false

  sns_topic_name       = "${local.name}-sns"
  lambda_function_name = "${local.name}-notify-slack"
  slack_webhook_url    = var.error_alarm_slack_webhook_url
  slack_username       = "${local.name} ${var.error_alarm_slack_username}"
  slack_channel        = var.error_alarm_slack_channel
  slack_emoji          = var.error_alarm_slack_emoji
}

And I'm getting the following error:

Error: Invalid index

  on .terraform/modules/....notify-slack/terraform-aws-modules-terraform-aws-notify-slack-415fe44/iam.tf line 9, in locals:
   9:     resources = [aws_cloudwatch_log_group.lambda[0].arn]
    |----------------
    | aws_cloudwatch_log_group.lambda is empty tuple

The given key does not identify an element in this collection value.

Is there any other way I should be making use of the create input variable? Can't find any examples in the codebase either.

Thanks

Module fails to update .source_code_hash in aws_lambda_function.this when TF_RECREATE_MISSING_LAMBDA_PACKAGE is false

Description

Terraform apply failing with Error: Provider produced inconsistent final plan after updates to module causing archive to be rebuilt when TF_RECREATE_MISSING_LAMBDA_PACKAGE is set to 'false'

Versions

  • Terraform: 1.0.8
  • Provider(s):
  • hashicorp/null v3.1.0
  • hashicorp/external v2.1.0
  • hashicorp/aws v3.62.0
  • hashicorp/template v2.2.0
  • hashicorp/local v2.1.0
  • hashicorp/random v3.1.0
  • Module: 4.17.0 -> Module 4.18.0

Reproduction

Steps to reproduce the behavior:

  • Set environment variable TF_RECREATE_MISSING_LAMBDA_PACKAGE='false'
  • Run terraform apply using module version 4.17
  • Delete local cache including all terraform generated files and build directory
  • Change module version to 4.18
  • Run terraform apply

Code Snippet to Reproduce

terraform {
  required_version = ">= 1.0.0, < 2.0.0"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.27"
    }
  }
}

provider "aws" {
  profile = "default"
  region  = "us-west-1"
}

terraform {
  backend "s3" {
    bucket         = "<bucket name>"
    key            = "aws-notify-slack-test"
    region         = "us-west-1"
  }
}

module "notify_slack_test" {
  source               = "terraform-aws-modules/notify-slack/aws"
  version              = "4.18"

  sns_topic_name       = "terraform-aws-modules-notify-slack-test"
  lambda_function_name = "terraform-aws-modules-notify-slack-test"
  slack_webhook_url    = var.slack_webhook_url
  slack_channel        = "test"
  slack_username       = "AWS (terraform-aws-modules-notify-slack-test)"
  slack_emoji          = ":warning:"
  create               = true
  create_sns_topic     = true
}

Expected behavior

Terraform should apply changes as expected

Actual behavior

Apply fails to update module.lambda.aws_lambda_function.this[0]

Terminal Output Screenshot(s)

image

Add formatting of EventBridge events

Is your request related to a new offering from AWS?

aws_cloudwatch_event_rule and aws_cloudwatch_event_target

Is your request related to a problem? Please describe.

Formatting of Amazon EventBridge events

Describe the solution you'd like.

AWS EventBridge events are formatted rather than just json.

Describe alternatives you've considered.

None.

Additional context

We are already using terraform-aws-notify-slack to send alerts from our AWS setup as nicely formatted slack messages. We have both CloudWatch Alarms and CloudWatch LogMetric Alarms. However, now we would like to have some EventBridge events, too.

Consecutive terraform plan always show changes to Lambda function

Description

Every time a terraform plan is run, the filename of the Lambda function is changing. "null_resource" "archive" is different every time, and thus the lambda function is destroyed and recreated on every apply.

I think the issue is related to executing this module twice in the same config. According to the docs for the Lambda module, a collision can occur if you do that and so there's an extra_hash you can add, but I don't see that as an input for this module.

⚠️ Note

Before you submit an issue, please perform the following first:

  1. Remove the local .terraform directory (! ONLY if state is stored remotely, which hopefully you are following that best practice!): rm -rf .terraform/
  2. Re-initialize the project root to pull down modules: terraform init
  3. Re-attempt your terraform plan or apply and check if the issue still persists

Versions

  • Terraform:
    v1.1.2
  • Provider(s):
  • provider registry.terraform.io/hashicorp/aws v3.71.0
  • provider registry.terraform.io/hashicorp/external v2.2.0
  • provider registry.terraform.io/hashicorp/local v2.1.0
  • provider registry.terraform.io/hashicorp/null v3.1.0
  • Module:

Reproduction

Steps to reproduce the behavior:

  1. Define this module twice in the same config. You will need to override the lambda_function_name otherwise there will be a collision.

No

Yes

  1. Apply once successfully
  2. Change nothing, immediately run terraform plan and see that several resources are proposed to be replaced.

Code Snippet to Reproduce

Expected behavior

I would expect that a successful apply and subsequent plan would not have any changes

Actual behavior

What is actually happening is that 6 resources are being proposed to be added, 5 changed, and 6 destroyed.

Terminal Output Screenshot(s)

Screen Shot 2022-01-13 at 8 57 56 PM

Additional context

lambda-notify_slack and log group /aws/lambda/notify_slack already exists when calling module multiple times

Trying to execute module twice for 2 separate SNS topic and slack channels, is this supported?

Does not look like it is supported as IAM Role and Log group is duplicated.

Error: Error creating IAM Role lambda-notify_slack: EntityAlreadyExists: Role with name lambda-notify_slack already exists.
	status code: 409, request id: f1f0c7d6-68c7-49ab-962b-b0b00615cdce

Error: Creating CloudWatch Log Group failed: ResourceAlreadyExistsException: The specified log group already exists:  The CloudWatch Log Group '/aws/lambda/notify_slack' already exists.

Once for_each is implemented, then a list of slack_channel can be passed in.

Eventually I would like to pass down a list of slack channels as shown below. In the meantime I have to individually create each module for each slack channel

== main.tf ==

# for_each was supposed to be released in 0.12, still not in 0.12.29 release. 
module "notify_slack" {
  for_each   = var.slack_channel
  source  = "terraform-aws-modules/notify-slack/aws"
  version = "~> v3.5.0"

  sns_topic_name    = "slack-${each.key}"
  slack_channel     = each.key
  slack_username    = var.slack_username == "" ? var.environment : var.slack_username
  slack_webhook_url = var.slack_webhook_url
}

Here's an inverse if what you could implement as I already implemented in my own branch

$ git diff
diff --git a/main.tf b/main.tf
index 4a0ee36..7398989 100644
--- a/main.tf
+++ b/main.tf
@@ -30,8 +30,6 @@ locals {
     actions   = ["kms:Decrypt"]
     resources = [var.kms_key_arn]
   }
-
-  lambda_function_name  = var.lambda_function_name == "" ? "${var.sns_topic_name}" : var.lambda_function_name
 }
 
 data "aws_iam_policy_document" "lambda" {
@@ -51,7 +49,7 @@ data "aws_iam_policy_document" "lambda" {
 resource "aws_cloudwatch_log_group" "lambda" {
   count = var.create ? 1 : 0
 
-  name              = "/aws/lambda/${local.lambda_function_name}"
+  name              = "/aws/lambda/${var.lambda_function_name}"
   retention_in_days = var.cloudwatch_log_group_retention_in_days
   kms_key_id        = var.cloudwatch_log_group_kms_key_id
 
@@ -73,7 +71,7 @@ module "lambda" {
 
   create = var.create
 
-  function_name = local.lambda_function_name
+  function_name = var.lambda_function_name
   description   = var.lambda_description
 
   handler                        = "notify_slack.lambda_handler"
@@ -95,7 +93,7 @@ module "lambda" {
   }
 
   create_role               = true
-  role_name                 = "${var.iam_role_name_prefix}-${local.lambda_function_name}"
+  role_name                 = "${var.iam_role_name_prefix}-${var.lambda_function_name}"
   role_permissions_boundary = var.iam_role_boundary_policy_arn
   role_tags                 = var.iam_role_tags
 
diff --git a/variables.tf b/variables.tf
index 19298ca..fbcfe97 100644
--- a/variables.tf
+++ b/variables.tf
@@ -13,7 +13,7 @@ variable "create_sns_topic" {
 variable "lambda_function_name" {
   description = "The name of the Lambda function to create"
   type        = string
-  default     = ""
+  default     = "notify_slack"
 }
 
 variable "lambda_description" {

FileNotFoundError when creating module instance

Setup

Terraform version: 0.13.5
Module version: 4.7.0
module "notify_slack" used according to the basic example

In the "apply" stage for terraform, I get this output. Mind you, the module actually seems to work correctly.
I have messages arriving in slack.

What is this error relating to? My terraform pipeline stays red because of this...

module.notify_slack["my_app"].module.lambda.null_resource.archive[0]: Destroying... [id=8360185324643769328]
module.notify_slack["my_app"].module.lambda.null_resource.archive[0]: Destruction complete after 0s
module.notify_slack["my_app"].module.lambda.data.external.archive_prepare[0]: Reading... [id=-]
module.notify_slack["my_app"].module.lambda.data.external.archive_prepare[0]: Read complete after 0s [id=-]
aws_autoscaling_notification.an["my_app"]: Creating...
module.notify_slack["my_app"].module.lambda.null_resource.archive[0]: Creating...
module.notify_slack["my_app"].module.lambda.null_resource.archive[0]: Provisioning with 'local-exec'...
module.notify_slack["my_app"].module.lambda.null_resource.archive[0] (local-exec): Executing: ["python3" ".terraform/modules/notify_slack.lambda/package.py" "build" "--timestamp" "1605787059469616800" "builds/5b24c39941d01dbddea733983e6a591d958660e6eeb0fcd7965098fb348aeeaa.plan.json"]
module.notify_slack["my_app"].module.lambda.null_resource.archive[0] (local-exec): Traceback (most recent call last):
module.notify_slack["my_app"].module.lambda.null_resource.archive[0] (local-exec):   File ".terraform/modules/notify_slack.lambda/package.py", line 1246, in <module>
module.notify_slack["my_app"].module.lambda.null_resource.archive[0] (local-exec):     main()
module.notify_slack["my_app"].module.lambda.null_resource.archive[0] (local-exec):   File ".terraform/modules/notify_slack.lambda/package.py", line 1242, in main
module.notify_slack["my_app"].module.lambda.null_resource.archive[0] (local-exec):     exit(args.command(args))
module.notify_slack["my_app"].module.lambda.null_resource.archive[0] (local-exec):   File ".terraform/modules/notify_slack.lambda/package.py", line 1113, in build_command
module.notify_slack["my_app"].module.lambda.null_resource.archive[0] (local-exec):     with open(args.build_plan_file) as f:
module.notify_slack["my_app"].module.lambda.null_resource.archive[0] (local-exec): FileNotFoundError: [Errno 2] No such file or directory: 'builds/5b24c39941d01dbddea733983e6a591d958660e6eeb0fcd7965098fb348aeeaa.plan.json'
aws_autoscaling_notification.an["my_app"]: Creation complete after 0s [id=arn:aws:sns:eu-west-1:380983831295:my_app]
Error: Error running command 'builds/5b24c39941d01dbddea733983e6a591d958660e6eeb0fcd7965098fb348aeeaa.plan.json': exit status 1. Output: Traceback (most recent call last):
  File ".terraform/modules/notify_slack.lambda/package.py", line 1246, in <module>
    main()
  File ".terraform/modules/notify_slack.lambda/package.py", line 1242, in main
    exit(args.command(args))
  File ".terraform/modules/notify_slack.lambda/package.py", line 1113, in build_command
    with open(args.build_plan_file) as f:
FileNotFoundError: [Errno 2] No such file or directory: 'builds/5b24c39941d01dbddea733983e6a591d958660e6eeb0fcd7965098fb348aeeaa.plan.json'

Failed to execute python3 on Terraform Cloud

We added this module to a workspace in Terraform Cloud and received the following error:

Error: failed to execute "python3": Traceback (most recent call last):
  File ".terraform/modules/notify_slack.lambda/terraform-aws-lambda-1.6.0/package.py", line 6, in <module>
    raise RuntimeError("A python version 3.7 or newer is required")
RuntimeError: A python version 3.7 or newer is required


  on .terraform/modules/notify_slack.lambda/terraform-aws-lambda-1.6.0/package.tf line 3, in data "external" "archive_prepare":
   3: data "external" "archive_prepare" {

Looking at the latest commit for terraform-aws-lambda, the Python version is locked at 3.6 rather than 3.7.

I'm not sure if Terraform Cloud provides a python runtime, or if the Python runtime is required to run the module.

Is this module expected to work when used with Terraform Cloud? Is there a workaround or configuration that should be used for it?

Exit code 1 on errors

Hello,

I recently encountered an HTTP 404 caused by an invalid Slack web hook URL (default channel got deleted in Slack, so the web hook got automatically disabled).

It took time to identify this issue because the Lambda monitoring reported a 100% success rate for this function.

I think it would make sense to set the exit code to 1 if the Slack response isn't a HTTP 200.

What do you think?

Lambda environment changes on every apply when KMS used

The SLACK_WEBHOOK_URL variable changes on every terraform apply when KMS encryption is used. This causes aws_lambda_permission.current_version_triggers to require replacement due to the version of the lambda function incrementing.

I'm not sure what to do about this - you can't ignore_changes in modules

Legacy Incoming Webhooks vs. Slack Apps

Slack now appears to have the concept of Legacy Incoming Webhooks (https://api.slack.com/legacy/custom-integrations/incoming-webhooks) and new Incoming Webhooks (or Slack Apps - https://api.slack.com/incoming-webhooks).

When setting up an incoming webhook the new way (a Slack App), this TF module still works, however the slack_channel, slack_username, and slack_emoji Terraform inputs no longer appear to be needed and/or modifiable via Lambda, as they are a part of the creation process of a Slack App webhook.

I don't personally have a solution, but wanted to at least bring awareness to this concept and how that may drive future changes to this module.

slack_channel     = "aws-notification"
slack_username    = "reporter"
slack_emoji       = ":thing:"

It is also worth noting that the first 2 sentences of this README now link to each of the Webhook creation methods which could be confusing to people setting up a webhook and using this module for the first time.

  • The first sentence links to the new Slack Apps creation process
  • The second sentence links to the creation of a legacy Incoming Webhook

De-duplicate detection and omission

Is your request related to a new offering from AWS?

No

Is your request related to a problem? Please describe.

Yes, one direct use-case is when using GuardDuty on multiple regions account-level issues will all generate the same(ish) output and cause some insane spam on your Slack channel.

Describe the solution you'd like.

An option to enable/disable some intelligent duplicate detection within' this stack. This could be globally, or per alert-type. This could be rather simple or extremely complex.

Describe alternatives you've considered.

I suppose a "de-dupe" SNS forwarding topic/service could be used instead if such an thing exists. A google search didn't find any such examples out there.

Additional context

See example:
Screen Shot 2021-07-13 at 5 26 21 AM

[bug] CloudWatch log group gets created twice and throws an error

Running the latest version I noticed a CW log group gets created by both this module and the underlying lambda module, check output:

# module.notify_slack.aws_cloudwatch_log_group.lambda[0] will be created
  + resource "aws_cloudwatch_log_group" "lambda" {
      + arn               = (known after apply)
      + id                = (known after apply)
      + name              = "/aws/lambda/slack-notifications"
      + retention_in_days = 0
    }

# module.notify_slack.module.lambda.aws_cloudwatch_log_group.lambda[0] will be created
  + resource "aws_cloudwatch_log_group" "lambda" {
      + arn               = (known after apply)
      + id                = (known after apply)
      + name              = "/aws/lambda/slack-notifications"
      + retention_in_days = 0
      + tags              = {
          + "Terraform"    = "true"
        }
    }

Then because of this, an error is thrown every time:

Error: Creating CloudWatch Log Group failed: ResourceAlreadyExistsException: The specified log group already exists:  The CloudWatch Log Group '/aws/lambda/slack-notifications' already exists.

  on .terraform/modules/notify_slack.lambda/terraform-aws-lambda-1.18.0/main.tf line 109, in resource "aws_cloudwatch_log_group" "lambda":
 109: resource "aws_cloudwatch_log_group" "lambda" {

cloudwatch error in Lambda decoder.

With the simple example, I get the following cloudwatch error:

Expecting value: line 1 column 1 (char 0): JSONDecodeError
Traceback (most recent call last):
File "/var/task/notify_slack.py", line 76, in lambda_handler
message = json.loads(event['Records'][0]['Sns']['Message'])
File "/var/lang/lib/python3.6/json/__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "/var/lang/lib/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/var/lang/lib/python3.6/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I am trying to send an SNS message via CLI:

aws sns publish --topic-arn --topic-arn <my_sns_topic> --message " This is a test"
upon which I receive a MessageId.

What am I doing wrong here?

Module not idempotent

Description

The module is not idempotent and causes resources to be recreated with each plan.

Versions

  • Terraform: Terraform v0.13.6
  • Provider(s): hashicorp/aws v3.20.0
  • Module: terraform-aws-modules/notify-slack/aws 4.12.0

Reproduction

Steps to reproduce the behavior:

  • Run the plan twice in a row: terraform plan

Code Snippet to Reproduce

module "notify_slack" {
  source  = "terraform-aws-modules/notify-slack/aws"
  version = "~> 4.0"

  lambda_function_name = "${var.environment}-${var.region}-lambda-notify-slack"

  slack_webhook_url = var.slack_alerts_webhook
  slack_channel     = var.slack_alerts_channel
  slack_username    = "our-slack-username"

  sns_topic_name = "Slack-Alerts"

Expected behavior

The second time I run the terraform plan command, there should not be any new resource created.

Actual behavior

A resource get recreated every time.

 # module.notify_slack.module.lambda.null_resource.archive[0] must be replaced
-/+ resource "null_resource" "archive" {
      ~ id       = "8162547318031137166" -> (known after apply)
      ~ triggers = { # forces replacement
            "filename"  = "builds/e0cb3a6677325caaef83e21b18d31cd83bfb70b2f5a3b45d81368dfa72822a07.zip"
          ~ "timestamp" = "1615392751274272000" -> "1615501960953185000"
        }
    }

Unable to load notify_slack.zip (no such file or directory)

When I run apply I have this error:

Error: Error applying plan:

1 error(s) occurred:

* module.databases.module.rds_notify_slack.module.notify_slack.aws_lambda_function.notify_slack: 1 error(s) occurred:

* aws_lambda_function.notify_slack: Unable to load ".terraform/modules/3a5c185cc1a32f4eca766d82a36b2ef2/functions/notify_slack.zip": open .terraform/modules/3a5c185cc1a32f4eca766d82a36b2ef2/functions/notify_slack.zip: no such file or directory

Terraform does not automatically rollback in the face of errors.
Instead, your Terraform state file has been partially updated with
any resources that successfully completed. Please address the error
above and apply again to incrementally change your infrastructure.

My module source is:

module "notify_slack" {
  source               = "git::https://github.com/terraform-aws-modules/terraform-aws-notify-slack?ref=tags/v1.10.0"
  create               = "${var.create}"
  create_sns_topic     = "${var.create_sns_topic}"
  create_with_kms_key  = "${var.create_with_kms_key}"
  slack_webhook_url    = "${var.slack_webhook_url}"
  slack_channel        = "${var.slack_channel}"
  slack_username       = "${var.slack_username}"
  slack_emoji          = "${var.slack_emoji}"
  kms_key_arn          = "${var.kms_key_arn}"
  sns_topic_name       = "${var.sns_topic_name}"
}

And I reference it using:

module "rds_notify_slack" {
  source            = "../notify_slack"
  slack_webhook_url = "https://hooks.slack.com/services/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"
  slack_channel     = "aws-rds-backup"
  slack_username    = "aws-notify"
  sns_topic_name    = "${terraform.workspace}-rds-events"
  create_sns_topic  = true
}

'count' or 'for_each' with module breaks package.py

Steps to reproduce:

  1. Try to create multiple notifiers using for_each:
module "notify_slack" {
  for_each = toset([
    "builds-develop",
    "builds-release",
    "builds-misc"
  ])

  source  = "terraform-aws-modules/notify-slack/aws"
  version = "~> 4.0"

  lambda_function_name = "${each.key}-slack"
  sns_topic_name       = "${each.key}-slack"
  slack_webhook_url    = "https://coolurl"
  slack_channel        = each.key
  slack_username       = "Jenkins"
}

Expected behaviour:

3 sets of lambda and sns have been created

Actual result:

Terraform fails with error:

Error: failed to execute "python3": Traceback (most recent call last):
  File ".terraform/modules/notify_slack.lambda/package.py", line 1228, in <module>
    main()
  File ".terraform/modules/notify_slack.lambda/package.py", line 1224, in main
    exit(args.command(args))
  File ".terraform/modules/notify_slack.lambda/package.py", line 1068, in prepare_command
    os.makedirs(artifacts_dir)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/os.py", line 221, in makedirs
    mkdir(name, mode)
FileExistsError: [Errno 17] File exists: 'builds'




Error: failed to execute "python3": Traceback (most recent call last):
  File ".terraform/modules/notify_slack.lambda/package.py", line 1228, in <module>
    main()
  File ".terraform/modules/notify_slack.lambda/package.py", line 1224, in main
    exit(args.command(args))
  File ".terraform/modules/notify_slack.lambda/package.py", line 1068, in prepare_command
    os.makedirs(artifacts_dir)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/os.py", line 221, in makedirs
    mkdir(name, mode)
FileExistsError: [Errno 17] File exists: 'builds'

There is a variable in the lamda module called artifacts_dir. May be we should be able to modify the variable.

When passing in SNS Topic, there's a race condition if it's not already created

If the SNS topic passed in is NOT already created, the notify-slack module will fail. This is due to notify-slack's data objects being resolved before my resource objects.

resource "aws_sns_topic" "my_sns" {
  name  = "my-sns"
}

module "notify_slack" {
  source  = "terraform-aws-modules/notify-slack/aws"
  version = "2.0.0"
  slack_channel        = "my_channel"
  slack_username       = "My SNS"
  slack_webhook_url    = "https://hooks.slack.com/services/<SNIP>"
  sns_topic_name       = aws_sns_topic.my_sns.name  #<<<<<<<
  create_sns_topic     = false                #<<<<<<<<<
  slack_emoji          = ":yuk:"
  lambda_function_name = "${var.name_prefix}-my-slack-lambda"
}

From what I can tell, the only usage of the data resource is to ensure that SNS exists before running, and then to craft the ARN. I'd suggest hand-crafting the ARN with the Topic Name instead. I can submit a PR if it would be helpful.

Error: Duplicate variable declaration when performing Plan,Apply,Refresh

Description

After performing terraform init, terraform workspace select prod, if I ever try to plan, apply or refresh I get the following error: Error: Duplicate variable declaration.

I have tried the following:

  1. rm -rf .terraform
  2. terraform init
  3. terraform workspace select prod
  4. terraform refresh <-- it works!
  5. terraform plan <-- I get the errors below

Versions

  • Terraform:
Terraform v1.0.9
on darwin_amd64
  • Provider(s):
+ provider registry.terraform.io/hashicorp/aws v3.74.0
+ provider registry.terraform.io/hashicorp/external v2.2.0
+ provider registry.terraform.io/hashicorp/local v2.1.0
+ provider registry.terraform.io/hashicorp/null v3.1.0
+ provider registry.terraform.io/hashicorp/template v2.2.0

Code Snippet to Reproduce

resource "aws_kms_ciphertext" "slack_url" {
  count     = terraform.workspace == "prod" ? 1 : 0
  plaintext = "https://hooks.slack.com/services/TC________ss"
  key_id    = aws_kms_key.notify_slack[count.index].arn
}

module "notify_slack" {
  count   = terraform.workspace == "prod" ? 1 : 0
  source  = "terraform-aws-modules/notify-slack/aws"
  version = "~> 4.0"

  sns_topic_name = "slack-sns-topic"

  slack_webhook_url = aws_kms_ciphertext.slack_url[count.index].ciphertext_blob
  slack_channel     = "foo_alerts"
  slack_username    = "CloudWatch"

  kms_key_arn = aws_kms_key.notify_slack[count.index].arn

  lambda_description = "Lambda function which sends notifications to Slack"
  log_events         = true

  tags = {
    Name = "cloudwatch-alerts-to-slack"
  }
}

Actual behavior

Error: Duplicate variable declaration
β”‚
β”‚   on .terraform/modules/notify_slack/variables.tf line 135:
β”‚  135: variable "lambda_function_tags" {
β”‚
β”‚ A variable named "lambda_function_tags" was already declared at .terraform/modules/notify_slack/variables 2.tf:135,1-32. Variable names must be unique within a module.
β•΅
β•·
β”‚ Error: Duplicate variable declaration
β”‚
β”‚   on .terraform/modules/notify_slack/variables.tf line 141:
β”‚  141: variable "lambda_function_vpc_subnet_ids" {
β”‚
β”‚ A variable named "lambda_function_vpc_subnet_ids" was already declared at .terraform/modules/notify_slack/variables 2.tf:141,1-42. Variable names must be unique within a module.
β•΅
β•·
β”‚ Error: Duplicate variable declaration
β”‚
β”‚   on .terraform/modules/notify_slack/variables.tf line 147:
β”‚  147: variable "lambda_function_vpc_security_group_ids" {
β”‚
β”‚ A variable named "lambda_function_vpc_security_group_ids" was already declared at .terraform/modules/notify_slack/variables 2.tf:147,1-50. Variable names must be unique within a module.
β•΅
β•·
β”‚ Error: Duplicate variable declaration
β”‚
β”‚   on .terraform/modules/notify_slack/variables.tf line 153:
β”‚  153: variable "lambda_function_store_on_s3" {
β”‚
β”‚ A variable named "lambda_function_store_on_s3" was already declared at .terraform/modules/notify_slack/variables 2.tf:153,1-39. Variable names must be unique within a module.
β•΅
β•·
β”‚ Error: Duplicate variable declaration
β”‚
β”‚   on .terraform/modules/notify_slack/variables.tf line 159:
β”‚  159: variable "lambda_function_s3_bucket" {
β”‚
β”‚ A variable named "lambda_function_s3_bucket" was already declared at .terraform/modules/notify_slack/variables 2.tf:159,1-37. Variable names must be unique within a module.
β•΅
β•·
β”‚ Error: Duplicate variable declaration
β”‚
β”‚   on .terraform/modules/notify_slack/variables.tf line 165:
β”‚  165: variable "sns_topic_tags" {
β”‚
β”‚ A variable named "sns_topic_tags" was already declared at .terraform/modules/notify_slack/variables 2.tf:165,1-26. Variable names must be unique within a module.
β•΅
β•·
β”‚ Error: Duplicate variable declaration
β”‚
β”‚   on .terraform/modules/notify_slack/variables.tf line 171:
β”‚  171: variable "cloudwatch_log_group_tags" {
β”‚
β”‚ A variable named "cloudwatch_log_group_tags" was already declared at .terraform/modules/notify_slack/variables 2.tf:171,1-37. Variable names must be unique within a module.
β•΅
β•·
β”‚ Error: Duplicate variable declaration
β”‚
β”‚   on .terraform/modules/notify_slack/variables.tf line 177:
β”‚  177: variable "subscription_filter_policy" {
β”‚
β”‚ A variable named "subscription_filter_policy" was already declared at .terraform/modules/notify_slack/variables 2.tf:177,1-38. Variable names must be unique within a module.
β•΅
β•·
β”‚ Error: Duplicate required providers configuration
β”‚
β”‚   on .terraform/modules/notify_slack/versions.tf line 4, in terraform:
β”‚    4:   required_providers {
β”‚
β”‚ A module may have only one required providers configuration. The required providers were previously configured at .terraform/modules/notify_slack/versions 2.tf:4,3-21.

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.