diff --git a/LICENSE b/LICENSE index fe36d3a..39327c9 100644 --- a/LICENSE +++ b/LICENSE @@ -1,13 +1,21 @@ -Copyright 2021 Sven Lito +MIT License -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at +Copyright (c) 2018 The terraform-docs Authors. - http://www.apache.org/licenses/LICENSE-2.0 +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index dd1e178..ee30bd0 100644 --- a/README.md +++ b/README.md @@ -1,394 +1,210 @@ -# AWS EventBridge Terraform module +# terraform-docs -Terraform module to create EventBridge resources. +[![Build Status](https://github.com/terraform-docs/terraform-docs/workflows/ci/badge.svg)](https://github.com/terraform-docs/terraform-docs/actions) [![GoDoc](https://pkg.go.dev/badge/github.com/terraform-docs/terraform-docs)](https://pkg.go.dev/github.com/terraform-docs/terraform-docs) [![Go Report Card](https://goreportcard.com/badge/github.com/terraform-docs/terraform-docs)](https://goreportcard.com/report/github.com/terraform-docs/terraform-docs) [![Codecov Report](https://codecov.io/gh/terraform-docs/terraform-docs/branch/master/graph/badge.svg)](https://codecov.io/gh/terraform-docs/terraform-docs) [![License](https://img.shields.io/github/license/terraform-docs/terraform-docs)](https://github.com/terraform-docs/terraform-docs/blob/master/LICENSE) [![Latest release](https://img.shields.io/github/v/release/terraform-docs/terraform-docs)](https://github.com/terraform-docs/terraform-docs/releases) -## Supported Features +![terraform-docs-teaser](./images/terraform-docs-teaser.png) -- Creates AWS EventBridge Resources (bus, rules, targets, permissions, connections, destinations, pipes, schedules and schedule groups) -- Attach resources to an existing EventBridge bus -- Support AWS EventBridge Archives and Replays -- Conditional creation for many types of resources -- Support IAM policy attachments and various ways to create and attach additional policies +## What is terraform-docs -## Usage - -### EventBridge Complete +A utility to generate documentation from Terraform modules in various output formats. -Most common use-case which creates custom bus, rules and targets. +## Installation -```hcl -module "eventbridge" { - source = "terraform-aws-modules/eventbridge/aws" +macOS users can install using [Homebrew]: - bus_name = "my-bus" - - rules = { - orders = { - description = "Capture all order data" - event_pattern = jsonencode({ "source" : ["myapp.orders"] }) - enabled = true - } - } - - targets = { - orders = [ - { - name = "send-orders-to-sqs" - arn = aws_sqs_queue.queue.arn - dead_letter_arn = aws_sqs_queue.dlq.arn - }, - { - name = "send-orders-to-kinesis" - arn = aws_kinesis_stream.this.arn - dead_letter_arn = aws_sqs_queue.dlq.arn - input_transformer = local.kinesis_input_transformer - }, - { - name = "log-orders-to-cloudwatch" - arn = aws_cloudwatch_log_group.this.arn - } - ] - } - - tags = { - Name = "my-bus" - } -} +```bash +brew install terraform-docs ``` -### EventBridge Bus +or -```hcl -module "eventbridge" { - source = "terraform-aws-modules/eventbridge/aws" +```bash +brew install terraform-docs/tap/terraform-docs +``` - bus_name = "my-bus" +Windows users can install using [Scoop]: - tags = { - Name = "my-bus" - } -} +```bash +scoop bucket add terraform-docs https://github.com/terraform-docs/scoop-bucket +scoop install terraform-docs ``` -### EventBridge Rule +or [Chocolatey]: -```hcl -module "eventbridge" { - source = "terraform-aws-modules/eventbridge/aws" - - bus_name = "my-bus" +```bash +choco install terraform-docs +``` - create_targets = false +Stable binaries are also available on the [releases] page. To install, download the +binary for your platform from "Assets" and place this into your `$PATH`: - rules = { - logs = { - description = "Capture log data" - event_pattern = jsonencode({ "source" : ["my.app.logs"] }) - } - } -} +```bash +curl -Lo ./terraform-docs.tar.gz https://github.com/terraform-docs/terraform-docs/releases/download/v0.20.0/terraform-docs-v0.20.0-$(uname)-amd64.tar.gz +tar -xzf terraform-docs.tar.gz +chmod +x terraform-docs +mv terraform-docs /usr/local/bin/terraform-docs ``` -### EventBridge Target - -```hcl -module "eventbridge" { - source = "terraform-aws-modules/eventbridge/aws" +**NOTE:** Windows releases are in `ZIP` format. - bus_name = "my-bus" +The latest version can be installed using `go install` or `go get`: - rules = { - logs = { - description = "Capture log data" - event_pattern = jsonencode({ "source" : ["my.app.logs"] }) - } - } - - targets = { - logs = [ - { - name = "send-logs-to-sqs" - arn = aws_sqs_queue.queue.arn - }, - { - name = "send-logs-to-cloudwatch" - arn = aws_cloudwatch_log_stream.logs.arn - } - ] - } -} +```bash +# go1.17+ +go install github.com/terraform-docs/terraform-docs@v0.20.0 ``` -### EventBridge Archive - -```hcl -module "eventbridge_with_archive" { - source = "terraform-aws-modules/eventbridge/aws" +```bash +# go1.16 +GO111MODULE="on" go get github.com/terraform-docs/terraform-docs@v0.20.0 +``` - bus_name = "my-bus" +**NOTE:** please use the latest Go to do this, minimum `go1.16` is required. - create_archives = true +This will put `terraform-docs` in `$(go env GOPATH)/bin`. If you encounter the error +`terraform-docs: command not found` after installation then you may need to either add +that directory to your `$PATH` as shown [here] or do a manual installation by cloning +the repo and run `make build` from the repository which will put `terraform-docs` in: - archives = { - "my-bus-launch-archive" = { - description = "EC2 AutoScaling Event archive", - retention_days = 1 - event_pattern = < doc.md +``` - rules = { - crons = { - description = "Run state machine everyday 10:00 UTC" - schedule_expression = "cron(0 10 * * ? *)" - } - } - - targets = { - crons = [ - { - name = "your-awesome-state-machine" - arn = "arn:aws:states:us-east-1:123456789012:stateMachine:your-awesome-state-machine" - attach_role_arn = true - } - ] - } - - sfn_target_arns = ["arn:aws:states:us-east-1:123456789012:stateMachine:your-awesome-state-machine"] - attach_sfn_policy = true -} +**NOTE:** Docker tag `latest` refers to _latest_ stable released version and `edge` +refers to HEAD of `master` at any given point in time. + +### Using GitHub Actions + +To use terraform-docs GitHub Action, configure a YAML workflow file (e.g. +`.github/workflows/documentation.yml`) with the following: + +```yaml +name: Generate terraform docs +on: + - pull_request + +jobs: + docs: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + ref: ${{ github.event.pull_request.head.ref }} + + - name: Render terraform docs and push changes back to PR + uses: terraform-docs/gh-actions@main + with: + working-dir: . + output-file: README.md + output-method: inject + git-push: "true" ``` -### EventBridge Scheduler which triggers Lambda Function +Read more about [terraform-docs GitHub Action] and its configuration and +examples. -```hcl -module "eventbridge" { - source = "terraform-aws-modules/eventbridge/aws" +### pre-commit hook - bus_name = "example" # "default" bus already support schedule_expression in rules +With pre-commit, you can ensure your Terraform module documentation is kept +up-to-date each time you make a commit. - attach_lambda_policy = true - lambda_target_arns = ["arn:aws:lambda:us-east-1:135367859851:function:resolved-penguin-lambda"] +First [install pre-commit] and then create or update a `.pre-commit-config.yaml` +in the root of your Git repo with at least the following content: - schedules = { - lambda-cron = { - description = "Trigger for a Lambda" - schedule_expression = "rate(1 day)" - timezone = "Europe/London" - arn = "arn:aws:lambda:us-east-1:135367859851:function:resolved-penguin-lambda" - input = jsonencode({ "job" : "cron-by-rate" }) - } - } -} +```yaml +repos: + - repo: https://github.com/terraform-docs/terraform-docs + rev: "v0.20.0" + hooks: + - id: terraform-docs-go + args: ["markdown", "table", "--output-file", "README.md", "./mymodule/path"] ``` -### EventBridge API Destination - -```hcl -module "eventbridge_with_api_destination" { - source = "terraform-aws-modules/eventbridge/aws" - - bus_name = "my-bus" - - create_connections = true - create_api_destinations = true - - attach_api_destination_policy = true - - connections = { - smee = { - authorization_type = "OAUTH_CLIENT_CREDENTIALS" - auth_parameters = { - oauth = { - authorization_endpoint = "https://oauth.endpoint.com" - http_method = "GET" - - client_parameters = { - client_id = "1234567890" - client_secret = "Pass1234!" - } - - oauth_http_parameters = { - body = [{ - key = "body-parameter-key" - value = "body-parameter-value" - is_value_secret = false - }] - - header = [{ - key = "header-parameter-key1" - value = "header-parameter-value1" - }, { - key = "header-parameter-key2" - value = "header-parameter-value2" - is_value_secret = true - }] - - query_string = [{ - key = "query-string-parameter-key" - value = "query-string-parameter-value" - is_value_secret = false - }] - } - } - } - } - } - - api_destinations = { - smee = { - description = "my smee endpoint" - invocation_endpoint = "https://smee.io/hgoubgoibwekt331" - http_method = "POST" - invocation_rate_limit_per_second = 200 - } - } -} -``` - -## Additional IAM policies for Step Function +Then run: -In addition to all supported AWS service integrations you may want to create and attach additional policies. - -There are 5 supported ways to attach additional IAM policies to IAM role used by Step Function: - - 1. `policy_json` - JSON string or heredoc, when `attach_policy_json = true`. - 2. `policy_jsons` - List of JSON strings or heredoc, when `attach_policy_jsons = true` and `number_of_policy_jsons > 0`. - 3. `policy` - ARN of existing IAM policy, when `attach_policy = true`. - 4. `policies` - List of ARNs of existing IAM policies, when `attach_policies = true` and `number_of_policies > 0`. - 5. `policy_statements` - Map of maps to define IAM statements which will be generated as IAM policy. Requires `attach_policy_statements = true`. See `examples/complete` for more information. +```bash +pre-commit install +pre-commit install-hooks +``` -## Conditional creation +Further changes to your module's `.tf` files will cause an update to documentation +when you make a commit. -Sometimes you need to have a way to create resources conditionally but Terraform does not allow usage of `count` inside `module` block, so the solution is to specify `create` arguments. +## Configuration -```hcl -module "eventbridge" { - source = "terraform-aws-modules/eventbridge/aws" +terraform-docs can be configured with a yaml file. The default name of this file is +`.terraform-docs.yml` and the path order for locating it is: - create = false # to disable all resources +1. root of module directory +1. `.config/` folder at root of module directory +1. current directory +1. `.config/` folder at current directory +1. `$HOME/.tfdocs.d/` - create_bus = false # to control creation of the EventBridge Bus and related resources - create_rules = false # to control creation of EventBridge Rules and related resources - create_targets = false # to control creation of EventBridge Targets and related resources - create_archives = false # to control creation of EventBridge Archives - create_permissions = false # to control creation of EventBridge Permissions - create_role = false # to control creation of the IAM role and policies required for EventBridge - create_pipe_role_only = false # to control creation of the IAM role and policies required for EventBridge Pipes only - create_connections = false # to control creation of EventBridge Connection resources - create_api_destinations = false # to control creation of EventBridge Destination resources - create_schedule_groups = false # to control creation of EventBridge Schedule Group resources - create_schedules = false # to control creation of EventBridge Schedule resources - create_pipes = false # to control creation of EventBridge Pipes resources +```yaml +formatter: "" # this is required - attach_cloudwatch_policy = false - attach_ecs_policy = false - attach_kinesis_policy = false - attach_kinesis_firehose_policy = false - attach_lambda_policy = false - attach_sfn_policy = false - attach_sqs_policy = false - attach_tracing_policy = false - attach_api_destination_policy = false +version: "" - # ... omitted -} -``` +header-from: main.tf +footer-from: "" -## Examples +recursive: + enabled: false + path: modules + include-main: true -* [Complete](https://github.com/terraform-aws-modules/terraform-aws-eventbridge/tree/master/examples/complete) - Creates EventBridge resources (bus, rules and targets) and connect with SQS queues, Kinesis Stream, Step Function, CloudWatch Logs, Lambda Functions, and more. -* [HTTP API Gateway](https://github.com/terraform-aws-modules/terraform-aws-eventbridge/tree/master/examples/api-gateway-event-source) - Creates an integration with HTTP API Gateway as event source. -* [Using Default Bus](https://github.com/terraform-aws-modules/terraform-aws-eventbridge/tree/master/examples/default-bus) - Creates resources in the `default` bus. -* [Archive](https://github.com/terraform-aws-modules/terraform-aws-eventbridge/tree/master/examples/with-archive) - EventBridge Archives resources in various configurations. -* [Permissions](https://github.com/terraform-aws-modules/terraform-aws-eventbridge/tree/master/examples/with-permissions) - Controls permissions to EventBridge. -* [Scheduler](https://github.com/terraform-aws-modules/terraform-aws-eventbridge/tree/master/examples/with-schedules) - EventBridge Scheduler which works with any bus (recommended way). -* [ECS Scheduling Events](https://github.com/terraform-aws-modules/terraform-aws-eventbridge/tree/master/examples/with-ecs-scheduling) - Use default bus to schedule events on ECS. -* [Lambda Scheduling Events](https://github.com/terraform-aws-modules/terraform-aws-eventbridge/tree/master/examples/with-lambda-scheduling) - Trigger Lambda functions on schedule (works only with default bus). -* [API Destination](https://github.com/terraform-aws-modules/terraform-aws-eventbridge/tree/master/examples/with-api-destination) - Control access to EventBridge using API destinations. -* [Pipes](https://github.com/terraform-aws-modules/terraform-aws-eventbridge/tree/master/examples/with-pipes) - EventBridge Pipes with lots of configurations. +sections: + hide: [] + show: [] +content: "" - +output: + file: "" + mode: inject + template: |- + ## Requirements | Name | Version | |------|---------| | [terraform](#requirement\_terraform) | >= 1.5.7 | -| [aws](#requirement\_aws) | >= 6.0 | +| [aws](#requirement\_aws) | >= 6.2 | ## Providers | Name | Version | |------|---------| -| [aws](#provider\_aws) | >= 6.0 | +| [aws](#provider\_aws) | >= 6.2 | ## Modules @@ -581,10 +397,237 @@ No modules. | [eventbridge\_targets](#output\_eventbridge\_targets) | The EventBridge Targets created and their attributes | -## Authors +output-values: + enabled: false + from: "" + +sort: + enabled: true + by: name + +settings: + anchor: true + color: true + default: true + description: false + escape: true + hide-empty: false + html: true + indent: 2 + lockfile: true + read-comments: true + required: true + sensitive: true + type: true +``` + +## Content Template + +Generated content can be customized further away with `content` in configuration. +If the `content` is empty the default order of sections is used. + +Compatible formatters for customized content are `asciidoc` and `markdown`. `content` +will be ignored for other formatters. + +`content` is a Go template with following additional variables: + +- `{{ .Header }}` +- `{{ .Footer }}` +- `{{ .Inputs }}` +- `{{ .Modules }}` +- `{{ .Outputs }}` +- `{{ .Providers }}` +- `{{ .Requirements }}` +- `{{ .Resources }}` + +and following functions: + +- `{{ include "relative/path/to/file" }}` + +These variables are the generated output of individual sections in the selected +formatter. For example `{{ .Inputs }}` is Markdown Table representation of _inputs_ +when formatter is set to `markdown table`. + +Note that sections visibility (i.e. `sections.show` and `sections.hide`) takes +precedence over the `content`. + +Additionally there's also one extra special variable avaialble to the `content`: + +- `{{ .Module }}` + +As opposed to the other variables mentioned above, which are generated sections +based on a selected formatter, the `{{ .Module }}` variable is just a `struct` +representing a [Terraform module]. + +````yaml +content: |- + Any arbitrary text can be placed anywhere in the content + + {{ .Header }} + + and even in between sections + + {{ .Providers }} + + and they don't even need to be in the default order + + {{ .Outputs }} + + include any relative files + + {{ include "relative/path/to/file" }} + + {{ .Inputs }} + + # Examples + + ```hcl + {{ include "examples/foo/main.tf" }} + ``` + + ## Resources + + {{ range .Module.Resources }} + - {{ .GetMode }}.{{ .Spec }} ({{ .Position.Filename }}#{{ .Position.Line }}) + {{- end }} +```` + +## Build on top of terraform-docs + +terraform-docs primary use-case is to be utilized as a standalone binary, but +some parts of it is also available publicly and can be imported in your project +as a library. + +```go +import ( + "github.com/terraform-docs/terraform-docs/format" + "github.com/terraform-docs/terraform-docs/print" + "github.com/terraform-docs/terraform-docs/terraform" +) + +// buildTerraformDocs for module root `path` and provided content `tmpl`. +func buildTerraformDocs(path string, tmpl string) (string, error) { + config := print.DefaultConfig() + config.ModuleRoot = path // module root path (can be relative or absolute) + + module, err := terraform.LoadWithOptions(config) + if err != nil { + return "", err + } + + // Generate in Markdown Table format + formatter := format.NewMarkdownTable(config) + + if err := formatter.Generate(module); err != nil { + return "", err + } + + // // Note: if you don't intend to provide additional template for the generated + // // content, or the target format doesn't provide templating (e.g. json, yaml, + // // xml, or toml) you can use `Content()` function instead of `Render()`. + // // `Content()` returns all the sections combined with predefined order. + // return formatter.Content(), nil + + return formatter.Render(tmpl) +} +``` + +## Plugin + +Generated output can be heavily customized with [`content`], but if using that +is not enough for your use-case, you can write your own plugin. + +In order to install a plugin the following steps are needed: + +- download the plugin and place it in `~/.tfdocs.d/plugins` (or `./.tfdocs.d/plugins`) +- make sure the plugin file name is `tfdocs-format-` +- modify [`formatter`] of `.terraform-docs.yml` file to be `` + +**Important notes:** + +- if the plugin file name is different than the example above, terraform-docs won't +be able to to pick it up nor register it properly +- you can only use plugin thorough `.terraform-docs.yml` file and it cannot be used +with CLI arguments + +To create a new plugin create a new repository called `tfdocs-format-` with +following `main.go`: + +```go +package main + +import ( + _ "embed" //nolint + + "github.com/terraform-docs/terraform-docs/plugin" + "github.com/terraform-docs/terraform-docs/print" + "github.com/terraform-docs/terraform-docs/template" + "github.com/terraform-docs/terraform-docs/terraform" +) + +func main() { + plugin.Serve(&plugin.ServeOpts{ + Name: "", + Version: "0.1.0", + Printer: printerFunc, + }) +} + +//go:embed sections.tmpl +var tplCustom []byte + +// printerFunc the function being executed by the plugin client. +func printerFunc(config *print.Config, module *terraform.Module) (string, error) { + tpl := template.New(config, + &template.Item{Name: "custom", Text: string(tplCustom)}, + ) + + rendered, err := tpl.Render("custom", module) + if err != nil { + return "", err + } + + return rendered, nil +} +``` + +Please refer to [tfdocs-format-template] for more details. You can create a new +repository from it by clicking on `Use this template` button. + +## Documentation + +- **Users** + - Read the [User Guide] to learn how to use terraform-docs + - Read the [Formats Guide] to learn about different output formats of terraform-docs + - Refer to [Config File Reference] for all the available configuration options +- **Developers** + - Read [Contributing Guide] before submitting a pull request + +Visit [our website] for all documentation. + +## Community -Module managed by [Sven Lito](https://github.com/svenlito). Check out [serverless.tf](https://serverless.tf) to learn more about doing serverless with Terraform. +- Discuss terraform-docs on [Slack] ## License -Apache 2 Licensed. See LICENSE for full details. +MIT License - Copyright (c) 2021 The terraform-docs Authors. + +[Chocolatey]: https://www.chocolatey.org +[Config File Reference]: https://terraform-docs.io/user-guide/configuration/ +[`content`]: https://terraform-docs.io/user-guide/configuration/content/ +[Contributing Guide]: CONTRIBUTING.md +[Formats Guide]: https://terraform-docs.io/reference/terraform-docs/ +[`formatter`]: https://terraform-docs.io/user-guide/configuration/formatter/ +[here]: https://golang.org/doc/code.html#GOPATH +[Homebrew]: https://brew.sh +[install pre-commit]: https://pre-commit.com/#install +[`output`]: https://terraform-docs.io/user-guide/configuration/output/ +[releases]: https://github.com/terraform-docs/terraform-docs/releases +[Scoop]: https://scoop.sh/ +[Slack]: https://slack.terraform-docs.io/ +[terraform-docs GitHub Action]: https://github.com/terraform-docs/gh-actions +[Terraform module]: https://pkg.go.dev/github.com/terraform-docs/terraform-docs/terraform#Module +[tfdocs-format-template]: https://github.com/terraform-docs/tfdocs-format-template +[our website]: https://terraform-docs.io/ +[User Guide]: https://terraform-docs.io/user-guide/introduction/ diff --git a/examples/with-archive/README.md b/examples/with-archive/README.md index 00840dd..6101fb1 100644 --- a/examples/with-archive/README.md +++ b/examples/with-archive/README.md @@ -36,6 +36,7 @@ Note that this example may create resources which cost money. Run `terraform des |------|--------|---------| | [eventbridge](#module\_eventbridge) | ../../ | n/a | | [eventbridge\_archive\_only](#module\_eventbridge\_archive\_only) | ../../ | n/a | +| [kms](#module\_kms) | terraform-aws-modules/kms/aws | ~> 2.0 | ## Resources @@ -43,6 +44,8 @@ Note that this example may create resources which cost money. Run `terraform des |------|------| | [aws_cloudwatch_event_bus.existing_bus](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_event_bus) | resource | | [random_pet.this](https://registry.terraform.io/providers/hashicorp/random/latest/docs/resources/pet) | resource | +| [aws_caller_identity.current](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/caller_identity) | data source | +| [aws_region.current](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/region) | data source | ## Inputs diff --git a/main.tf b/main.tf index 55634ed..184dc1a 100644 --- a/main.tf +++ b/main.tf @@ -285,7 +285,7 @@ resource "aws_cloudwatch_event_archive" "this" { region = var.region name = lookup(each.value, "name", each.key) - event_source_arn = try(each.value["event_source_arn"], aws_cloudwatch_event_bus.this[0].arn) + event_source_arn = try(each.value["event_source_arn"], var.create_bus ? aws_cloudwatch_event_bus.this[0].arn : data.aws_cloudwatch_event_bus.this[0].arn) description = lookup(each.value, "description", null) event_pattern = lookup(each.value, "event_pattern", null)