From 05dc9ffaecb977214c932a98367de1c62b306a3a Mon Sep 17 00:00:00 2001 From: Nikola Velkovski Date: Tue, 16 Apr 2019 22:46:26 +0200 Subject: [PATCH] Cloudwatch agent (#1) * Add documentation * Add a gitignore and travis yaml * add a makefile * add all the variables related to this project * add the outputs that will be imported * add the cloud-init configuration for installing and starting the cloudwatch agent * add the standard and advanced cloudwatch configuration * add the main.tf template for this module * Update README.yaml Co-Authored-By: parabolic * Update README.yaml change the namespace so that it doesn't collide with the existing ones. Co-Authored-By: parabolic * Update main.tf Co-Authored-By: parabolic * add all the cloudwatch related project * Update README.yaml Typo Co-Authored-By: parabolic * Update README.yaml typo Co-Authored-By: parabolic * use aws_iam_policy_document instead of HEREDOC * Update variables.tf typo Co-Authored-By: parabolic * update the descirption for the disk_resources parameter * Update variables.tf typo Co-Authored-By: parabolic * Update variables.tf typo Co-Authored-By: parabolic * Update variables.tf typo Co-Authored-By: parabolic * make the namespace required * Update variables.tf typo Co-Authored-By: parabolic * fix the variables descriptions and use stage instead of environments * use stage instead of environment * update the readme * add the important text , remove empty git repo * use usage instead of examples and regenerate the README.md file --- .gitignore | 11 + .travis.yml | 16 + Makefile | 10 + README.md | 338 +++++++++++++++++- README.yaml | 174 +++++++++ docs/targets.md | 10 + docs/terraform.md | 23 ++ main.tf | 96 +++++ outputs.tf | 9 + templates/cloud_init.yaml | 40 +++ ...oudwatch_agent_configuration_advanced.json | 141 ++++++++ ...oudwatch_agent_configuration_standard.json | 53 +++ variables.tf | 74 ++++ 13 files changed, 994 insertions(+), 1 deletion(-) create mode 100644 .gitignore create mode 100644 .travis.yml create mode 100644 Makefile create mode 100644 README.yaml create mode 100644 docs/targets.md create mode 100644 docs/terraform.md create mode 100644 main.tf create mode 100644 outputs.tf create mode 100644 templates/cloud_init.yaml create mode 100644 templates/cloudwatch_agent_configuration_advanced.json create mode 100644 templates/cloudwatch_agent_configuration_standard.json create mode 100644 variables.tf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b6abc3c --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +# Compiled files +*.tfstate +*.tfstate.backup + +# Module directory +.terraform +.idea +*.iml + +.build-harness +build-harness diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..241026e --- /dev/null +++ b/.travis.yml @@ -0,0 +1,16 @@ +addons: + apt: + packages: + - git + - make + - curl + +install: + - make init + +script: + - make terraform/install + - make terraform/get-plugins + - make terraform/get-modules + - make terraform/lint + - make terraform/validate diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..97d8087 --- /dev/null +++ b/Makefile @@ -0,0 +1,10 @@ +SHELL := /bin/bash + +# List of targets the `readme` target should call before generating the readme +export README_DEPS ?= docs/targets.md docs/terraform.md + +-include $(shell curl -sSL -o .build-harness "https://git.io/build-harness"; echo .build-harness) + +## Lint terraform code +lint: + $(SELF) terraform/install terraform/get-modules terraform/get-plugins terraform/lint terraform/validate diff --git a/README.md b/README.md index 6f7c7e5..160b55c 100644 --- a/README.md +++ b/README.md @@ -1 +1,337 @@ -# terraform-aws-cloudwatch-agent \ No newline at end of file + +[![README Header][readme_header_img]][readme_header_link] + +[![Cloud Posse][logo]](https://cpco.io/homepage) + +# terraform-aws-cloudwatch-agent [![Build Status](https://travis-ci.org/cloudposse/terraform-aws-cloudwatch-agent.svg?branch=master)](https://travis-ci.org/cloudposse/terraform-aws-cloudwatch-agent) [![Latest Release](https://img.shields.io/github/release/cloudposse/terraform-aws-cloudwatch-agent.svg)](https://github.com/cloudposse/terraform-aws-cloudwatch-agent/releases/latest) [![Slack Community](https://slack.cloudposse.com/badge.svg)](https://slack.cloudposse.com) + + +Terraform module to install the CloudWatch agent on EC2 instances using `cloud-init`. + + +--- + +This project is part of our comprehensive ["SweetOps"](https://cpco.io/sweetops) approach towards DevOps. +[][share_email] +[][share_googleplus] +[][share_facebook] +[][share_reddit] +[][share_linkedin] +[][share_twitter] + + +[![Terraform Open Source Modules](https://docs.cloudposse.com/images/terraform-open-source-modules.svg)][terraform_modules] + + + +It's 100% Open Source and licensed under the [APACHE2](LICENSE). + + + + + + + +We literally have [*hundreds of terraform modules*][terraform_modules] that are Open Source and well-maintained. Check them out! + + + + + + + +## Usage + + +**IMPORTANT:** The `master` branch is used in `source` just as an example. In your code, do not pin to `master` because there may be breaking changes between releases. +Instead pin to the release tag (e.g. `?ref=tags/x.y.z`) of one of our [latest releases](https://github.com/cloudposse/terraform-aws-cloudwatch-agent/releases). + + + +### Example with launch configuration: + +```hcl +module "cloudwatch_agent" { + source = "git::https://github.com/cloudposse/terraform-aws-cloudwatch-agent?ref=master" + + name = "cloudwatch_agent" +} + +resource "aws_launch_configuration" "multipart" { + name_prefix = "cloudwatch_agent" + image_id = "${data.aws_ami.ecs-optimized.id}" + iam_instance_profile = "${aws_iam_instance_profile.cloudwatch_agent.name}" + instance_type = "t2.micro" + user_data_base64 = "${module.cloudwatch_agent.user_data}" + security_groups = ["${aws_security_group.ecs.id}"] + key_name = "${var.ssh_key_pair}" + + lifecycle { + create_before_destroy = true + } +} +``` + +### Example with passing user-data and using the role from the module using advanced metrics configuration: + +```hcl +module "cloudwatch_agent" { + source = "git::https://github.com/cloudposse/terraform-aws-cloudwatch-agent?ref=master" + + name = "cloudwatch_agent" + environment = "dev" + namespace = "eg" + + metrics_config = "advanced" + userdata_part_content = "${data.template_file.cloud-init.rendered}" +} + +data "template_file" "cloud-init" { + template = "${file("${path.module}/cloud-init.yml")}" +} + +resource "aws_launch_configuration" "multipart" { + name_prefix = "cloudwatch_agent" + image_id = "${data.aws_ami.ecs-optimized.id}" + iam_instance_profile = "${aws_iam_instance_profile.cloudwatch_agent.name}" + instance_type = "t2.micro" + user_data_base64 = "${module.cloudwatch_agent.user_data}" + security_groups = ["${aws_security_group.ecs.id}"] + key_name = "${var.ssh_key_pair}" + + lifecycle { + create_before_destroy = true + } +} + +resource "aws_iam_instance_profile" "cloudwatch_agent" { + name_prefix = "cloudwatch_agent" + role = "${module.cloudwatch_agent.role_name}" +} +``` + + + + + + +## Makefile Targets +``` +Available targets: + + help Help screen + help/all Display help for all targets + help/short This help short screen + lint Lint terraform code + +``` +## Inputs + +| Name | Description | Type | Default | Required | +|------|-------------|:----:|:-----:|:-----:| +| aggregation_dimensions | Specifies the dimensions that collected metrics are to be aggregated on. | list | `` | no | +| cpu_resources | Specifies that per-cpu metrics are to be collected. The only allowed value is *. If you include this field and value, per-cpu metrics are collected. | string | `"resources": ["*"],` | no | +| disk_resources | Specifies an array of disk mount points. This field limits CloudWatch to collect metrics from only the listed mount points. You can specify * as the value to collect metrics from all mount points. Defaults to the root / mountpount. | list | `` | no | +| metrics_collection_interval | Specifies how often to collect the cpu metrics, overriding the global metrics_collection_interval specified in the agent section of the configuration file. If you set this value below 60 seconds, each metric is collected as a high-resolution metric. | string | `60` | no | +| metrics_config | "Which metrics should we send to cloudwatch, the default is standard. Setting this variable to advanced will send all the available metrics that are provided by the agent. You can find more information here https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/create-cloudwatch-agent-configuration-file-wizard.html." | string | `standard` | no | +| name | Solution name, e.g. 'app'. | string | - | yes | +| namespace | Namespace, which could be your organization name or abbreviation, e.g. 'eg' or 'cp'. | string | - | yes | +| stage | Stage, e.g. 'prod', 'staging', 'dev', or 'test'. | string | `` | no | +| userdata_part_content | The user data that should be passed along from the caller of the module. | string | `` | no | +| userdata_part_content_type | What format is userdata_part_content in - eg 'text/cloud-config' or 'text/x-shellscript'. | string | `text/cloud-config` | no | +| userdata_part_merge_type | Control how cloud-init merges user-data sections. | string | `list(append)+dict(recurse_array)+str()` | no | + +## Outputs + +| Name | Description | +|------|-------------| +| role_name | The role name that should be attached to the role policy | +| user_data | The user_data with the cloudwatch_agent configuration in base64 and gzipped | + + + + +## Share the Love + +Like this project? Please give it a ★ on [our GitHub](https://github.com/cloudposse/terraform-aws-cloudwatch-agent)! (it helps us **a lot**) + +Are you using this project or any of our other projects? Consider [leaving a testimonial][testimonial]. =) + + +## Related Projects + +Check out these related projects. + +- [terraform-aws-ec2-instance](https://github.com/cloudposse/terraform-aws-ec2-instance) - Terraform Module for provisioning a general purpose EC2 host. +- [terraform-aws-cloudtrail-cloudwatch-alarms](https://github.com/cloudposse/terraform-aws-cloudtrail-cloudwatch-alarms) - Terraform module for creating alarms for tracking important changes and occurrences from cloudtrail. +- [terraform-aws-rds-cloudwatch-sns-alarms](https://github.com/cloudposse/terraform-aws-rds-cloudwatch-sns-alarms) - Terraform module that configures important RDS alerts using CloudWatch and sends them to an SNS topic +- [terraform-aws-cloudwatch-logs](https://github.com/cloudposse/terraform-aws-cloudwatch-logs) - Terraform Module to Provide a CloudWatch Logs Endpoint +- [terraform-aws-alb-target-group-cloudwatch-sns-alarms](https://github.com/cloudposse/terraform-aws-alb-target-group-cloudwatch-sns-alarms) - Terraform module to create CloudWatch Alarms on ALB Target level metrics. +- [terraform-aws-cloudwatch-flow-logs](https://github.com/cloudposse/terraform-aws-cloudwatch-flow-logs) - Terraform module for enabling flow logs for vpc and subnets. +- [terraform-aws-ecs-cloudwatch-autoscaling](https://github.com/cloudposse/terraform-aws-ecs-cloudwatch-autoscaling) - Terraform module to autoscale ECS Service based on CloudWatch metrics +- [terraform-aws-elasticache-cloudwatch-sns-alarms](https://github.com/cloudposse/terraform-aws-elasticache-cloudwatch-sns-alarms) - Terraform module that configures CloudWatch SNS alerts for ElastiCache +- [terraform-aws-efs-cloudwatch-sns-alarms](https://github.com/cloudposse/terraform-aws-efs-cloudwatch-sns-alarms) - Terraform module that configures CloudWatch SNS alerts for EFS +- [terraform-aws-ecs-cloudwatch-sns-alarms](https://github.com/cloudposse/terraform-aws-ecs-cloudwatch-sns-alarms) - Terraform module to create CloudWatch Alarms on ECS Service level metrics. +- [terraform-aws-ec2-cloudwatch-sns-alarms](https://github.com/cloudposse/terraform-aws-ec2-cloudwatch-sns-alarms) - Terraform module that configures CloudWatch SNS alerts for EC2 instances +- [terraform-aws-sqs-cloudwatch-sns-alarms](https://github.com/cloudposse/terraform-aws-sqs-cloudwatch-sns-alarms) - Terraform module for creating alarms for SQS and notifying endpoints +- [terraform-aws-lambda-cloudwatch-sns-alarms](https://github.com/cloudposse/terraform-aws-lambda-cloudwatch-sns-alarms) - Terraform module for creating a set of Lambda alarms and outputting to an endpoint + + + +## Help + +**Got a question?** + +File a GitHub [issue](https://github.com/cloudposse/terraform-aws-cloudwatch-agent/issues), send us an [email][email] or join our [Slack Community][slack]. + +[![README Commercial Support][readme_commercial_support_img]][readme_commercial_support_link] + +## Commercial Support + +Work directly with our team of DevOps experts via email, slack, and video conferencing. + +We provide [*commercial support*][commercial_support] for all of our [Open Source][github] projects. As a *Dedicated Support* customer, you have access to our team of subject matter experts at a fraction of the cost of a full-time engineer. + +[![E-Mail](https://img.shields.io/badge/email-hello@cloudposse.com-blue.svg)][email] + +- **Questions.** We'll use a Shared Slack channel between your team and ours. +- **Troubleshooting.** We'll help you triage why things aren't working. +- **Code Reviews.** We'll review your Pull Requests and provide constructive feedback. +- **Bug Fixes.** We'll rapidly work to fix any bugs in our projects. +- **Build New Terraform Modules.** We'll [develop original modules][module_development] to provision infrastructure. +- **Cloud Architecture.** We'll assist with your cloud strategy and design. +- **Implementation.** We'll provide hands-on support to implement our reference architectures. + + + +## Terraform Module Development + +Are you interested in custom Terraform module development? Submit your inquiry using [our form][module_development] today and we'll get back to you ASAP. + + +## Slack Community + +Join our [Open Source Community][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. + +## Newsletter + +Signup for [our newsletter][newsletter] that covers everything on our technology radar. Receive updates on what we're up to on GitHub as well as awesome new projects we discover. + +## Contributing + +### Bug Reports & Feature Requests + +Please use the [issue tracker](https://github.com/cloudposse/terraform-aws-cloudwatch-agent/issues) to report any bugs or file feature requests. + +### Developing + +If you are interested in being a contributor and want to get involved in developing this project or [help out](https://cpco.io/help-out) with our other projects, we would love to hear from you! Shoot us an [email][email]. + +In general, PRs are welcome. We follow the typical "fork-and-pull" Git workflow. + + 1. **Fork** the repo on GitHub + 2. **Clone** the project to your own machine + 3. **Commit** changes to your own branch + 4. **Push** your work back up to your fork + 5. Submit a **Pull Request** so that we can review your changes + +**NOTE:** Be sure to merge the latest changes from "upstream" before making a pull request! + + +## Copyright + +Copyright © 2017-2019 [Cloud Posse, LLC](https://cpco.io/copyright) + + + +## License + +[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) + +See [LICENSE](LICENSE) for full details. + + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + + + + + + + + + +## Trademarks + +All other trademarks referenced herein are the property of their respective owners. + +## About + +This project is maintained and funded by [Cloud Posse, LLC][website]. Like it? Please let us know by [leaving a testimonial][testimonial]! + +[![Cloud Posse][logo]][website] + +We're a [DevOps Professional Services][hire] company based in Los Angeles, CA. We ❤️ [Open Source Software][we_love_open_source]. + +We offer [paid support][commercial_support] on all of our projects. + +Check out [our other projects][github], [follow us on twitter][twitter], [apply for a job][jobs], or [hire us][hire] to help with your cloud strategy and implementation. + + + +### Contributors + +| [![Nikola Velkovski][parabolic_avatar]][parabolic_homepage]
[Nikola Velkovski][parabolic_homepage] | +|---| + + [parabolic_homepage]: https://github.com/parabolic + [parabolic_avatar]: https://github.com/parabolic.png?size=150 + + + +[![README Footer][readme_footer_img]][readme_footer_link] +[![Beacon][beacon]][website] + + [logo]: https://cloudposse.com/logo-300x69.svg + [docs]: https://cpco.io/docs + [website]: https://cpco.io/homepage + [github]: https://cpco.io/github + [jobs]: https://cpco.io/jobs + [hire]: https://cpco.io/hire + [slack]: https://cpco.io/slack + [linkedin]: https://cpco.io/linkedin + [twitter]: https://cpco.io/twitter + [testimonial]: https://cpco.io/leave-testimonial + [newsletter]: https://cpco.io/newsletter + [email]: https://cpco.io/email + [commercial_support]: https://cpco.io/commercial-support + [we_love_open_source]: https://cpco.io/we-love-open-source + [module_development]: https://cpco.io/module-development + [terraform_modules]: https://cpco.io/terraform-modules + [readme_header_img]: https://cloudposse.com/readme/header/img?repo=cloudposse/terraform-aws-cloudwatch-agent + [readme_header_link]: https://cloudposse.com/readme/header/link?repo=cloudposse/terraform-aws-cloudwatch-agent + [readme_footer_img]: https://cloudposse.com/readme/footer/img?repo=cloudposse/terraform-aws-cloudwatch-agent + [readme_footer_link]: https://cloudposse.com/readme/footer/link?repo=cloudposse/terraform-aws-cloudwatch-agent + [readme_commercial_support_img]: https://cloudposse.com/readme/commercial-support/img?repo=cloudposse/terraform-aws-cloudwatch-agent + [readme_commercial_support_link]: https://cloudposse.com/readme/commercial-support/link?repo=cloudposse/terraform-aws-cloudwatch-agent + [share_twitter]: https://twitter.com/intent/tweet/?text=terraform-aws-cloudwatch-agent&url=https://github.com/cloudposse/terraform-aws-cloudwatch-agent + [share_linkedin]: https://www.linkedin.com/shareArticle?mini=true&title=terraform-aws-cloudwatch-agent&url=https://github.com/cloudposse/terraform-aws-cloudwatch-agent + [share_reddit]: https://reddit.com/submit/?url=https://github.com/cloudposse/terraform-aws-cloudwatch-agent + [share_facebook]: https://facebook.com/sharer/sharer.php?u=https://github.com/cloudposse/terraform-aws-cloudwatch-agent + [share_googleplus]: https://plus.google.com/share?url=https://github.com/cloudposse/terraform-aws-cloudwatch-agent + [share_email]: mailto:?subject=terraform-aws-cloudwatch-agent&body=https://github.com/cloudposse/terraform-aws-cloudwatch-agent + [beacon]: https://ga-beacon.cloudposse.com/UA-76589703-4/cloudposse/terraform-aws-cloudwatch-agent?pixel&cs=github&cm=readme&an=terraform-aws-cloudwatch-agent diff --git a/README.yaml b/README.yaml new file mode 100644 index 0000000..985308a --- /dev/null +++ b/README.yaml @@ -0,0 +1,174 @@ +--- +# +# This is the canonical configuration for the `README.md` +# Run `make readme` to rebuild the `README.md` +# +# Name of this project +name: terraform-aws-cloudwatch-agent + +# Tags of this project +tags: + - aws + - terraform + - terraform-modules + - platform + - cloudwatch + - agent + - cloudwatch-agent + +# Categories of this project +categories: + - terraform-modules/platform + +# Logo for this project +#logo: docs/logo.png + +# License of this project +license: "APACHE2" + +# Canonical GitHub repo +github_repo: cloudposse/terraform-aws-cloudwatch-agent + +# Badges to display +badges: + - name: "Build Status" + image: "https://travis-ci.org/cloudposse/terraform-aws-cloudwatch-agent.svg?branch=master" + url: "https://travis-ci.org/cloudposse/terraform-aws-cloudwatch-agent" + - name: "Latest Release" + image: "https://img.shields.io/github/release/cloudposse/terraform-aws-cloudwatch-agent.svg" + url: "https://github.com/cloudposse/terraform-aws-cloudwatch-agent/releases/latest" + - name: "Slack Community" + image: "https://slack.cloudposse.com/badge.svg" + url: "https://slack.cloudposse.com" + +related: + - name: "terraform-aws-ec2-instance" + description: "Terraform Module for provisioning a general purpose EC2 host." + url: "https://github.com/cloudposse/terraform-aws-ec2-instance" + + - name: "terraform-aws-cloudtrail-cloudwatch-alarms" + description: "Terraform module for creating alarms for tracking important changes and occurrences from cloudtrail." + url: "https://github.com/cloudposse/terraform-aws-cloudtrail-cloudwatch-alarms" + + - name: "terraform-aws-rds-cloudwatch-sns-alarms" + description: "Terraform module that configures important RDS alerts using CloudWatch and sends them to an SNS topic" + url: "https://github.com/cloudposse/terraform-aws-rds-cloudwatch-sns-alarms" + + - name: "terraform-aws-cloudwatch-logs" + description: "Terraform Module to Provide a CloudWatch Logs Endpoint" + url: "https://github.com/cloudposse/terraform-aws-cloudwatch-logs" + + - name: "terraform-aws-alb-target-group-cloudwatch-sns-alarms" + description: "Terraform module to create CloudWatch Alarms on ALB Target level metrics." + url: "https://github.com/cloudposse/terraform-aws-alb-target-group-cloudwatch-sns-alarms" + + - name: "terraform-aws-cloudwatch-flow-logs" + description: "Terraform module for enabling flow logs for vpc and subnets." + url: "https://github.com/cloudposse/terraform-aws-cloudwatch-flow-logs" + + - name: "terraform-aws-ecs-cloudwatch-autoscaling" + description: "Terraform module to autoscale ECS Service based on CloudWatch metrics" + url: "https://github.com/cloudposse/terraform-aws-ecs-cloudwatch-autoscaling" + + - name: "terraform-aws-elasticache-cloudwatch-sns-alarms" + description: "Terraform module that configures CloudWatch SNS alerts for ElastiCache" + url: "https://github.com/cloudposse/terraform-aws-elasticache-cloudwatch-sns-alarms" + + - name: "terraform-aws-efs-cloudwatch-sns-alarms" + description: "Terraform module that configures CloudWatch SNS alerts for EFS" + url: "https://github.com/cloudposse/terraform-aws-efs-cloudwatch-sns-alarms" + + - name: "terraform-aws-ecs-cloudwatch-sns-alarms" + description: "Terraform module to create CloudWatch Alarms on ECS Service level metrics." + url: "https://github.com/cloudposse/terraform-aws-ecs-cloudwatch-sns-alarms" + + - name: "terraform-aws-ec2-cloudwatch-sns-alarms" + description: "Terraform module that configures CloudWatch SNS alerts for EC2 instances" + url: "https://github.com/cloudposse/terraform-aws-ec2-cloudwatch-sns-alarms" + + - name: "terraform-aws-sqs-cloudwatch-sns-alarms" + description: "Terraform module for creating alarms for SQS and notifying endpoints" + url: "https://github.com/cloudposse/terraform-aws-sqs-cloudwatch-sns-alarms" + + - name: "terraform-aws-lambda-cloudwatch-sns-alarms" + description: "Terraform module for creating a set of Lambda alarms and outputting to an endpoint" + url: "https://github.com/cloudposse/terraform-aws-lambda-cloudwatch-sns-alarms" + +# Short description of this project +description: |- + Terraform module to install the CloudWatch agent on EC2 instances using `cloud-init`. + +# How to use this project + +usage: |- + + ### Example with launch configuration: + + ```hcl + module "cloudwatch_agent" { + source = "git::https://github.com/cloudposse/terraform-aws-cloudwatch-agent?ref=master" + + name = "cloudwatch_agent" + } + + resource "aws_launch_configuration" "multipart" { + name_prefix = "cloudwatch_agent" + image_id = "${data.aws_ami.ecs-optimized.id}" + iam_instance_profile = "${aws_iam_instance_profile.cloudwatch_agent.name}" + instance_type = "t2.micro" + user_data_base64 = "${module.cloudwatch_agent.user_data}" + security_groups = ["${aws_security_group.ecs.id}"] + key_name = "${var.ssh_key_pair}" + + lifecycle { + create_before_destroy = true + } + } + ``` + + ### Example with passing user-data and using the role from the module using advanced metrics configuration: + + ```hcl + module "cloudwatch_agent" { + source = "git::https://github.com/cloudposse/terraform-aws-cloudwatch-agent?ref=master" + + name = "cloudwatch_agent" + environment = "dev" + namespace = "eg" + + metrics_config = "advanced" + userdata_part_content = "${data.template_file.cloud-init.rendered}" + } + + data "template_file" "cloud-init" { + template = "${file("${path.module}/cloud-init.yml")}" + } + + resource "aws_launch_configuration" "multipart" { + name_prefix = "cloudwatch_agent" + image_id = "${data.aws_ami.ecs-optimized.id}" + iam_instance_profile = "${aws_iam_instance_profile.cloudwatch_agent.name}" + instance_type = "t2.micro" + user_data_base64 = "${module.cloudwatch_agent.user_data}" + security_groups = ["${aws_security_group.ecs.id}"] + key_name = "${var.ssh_key_pair}" + + lifecycle { + create_before_destroy = true + } + } + + resource "aws_iam_instance_profile" "cloudwatch_agent" { + name_prefix = "cloudwatch_agent" + role = "${module.cloudwatch_agent.role_name}" + } + ``` + +include: + - "docs/targets.md" + - "docs/terraform.md" + +# Contributors to this project +contributors: + - name: "Nikola Velkovski" + github: "parabolic" diff --git a/docs/targets.md b/docs/targets.md new file mode 100644 index 0000000..3d4be2a --- /dev/null +++ b/docs/targets.md @@ -0,0 +1,10 @@ +## Makefile Targets +``` +Available targets: + + help Help screen + help/all Display help for all targets + help/short This help short screen + lint Lint terraform code + +``` diff --git a/docs/terraform.md b/docs/terraform.md new file mode 100644 index 0000000..b6ec6f8 --- /dev/null +++ b/docs/terraform.md @@ -0,0 +1,23 @@ +## Inputs + +| Name | Description | Type | Default | Required | +|------|-------------|:----:|:-----:|:-----:| +| aggregation_dimensions | Specifies the dimensions that collected metrics are to be aggregated on. | list | `` | no | +| cpu_resources | Specifies that per-cpu metrics are to be collected. The only allowed value is *. If you include this field and value, per-cpu metrics are collected. | string | `"resources": ["*"],` | no | +| disk_resources | Specifies an array of disk mount points. This field limits CloudWatch to collect metrics from only the listed mount points. You can specify * as the value to collect metrics from all mount points. Defaults to the root / mountpount. | list | `` | no | +| metrics_collection_interval | Specifies how often to collect the cpu metrics, overriding the global metrics_collection_interval specified in the agent section of the configuration file. If you set this value below 60 seconds, each metric is collected as a high-resolution metric. | string | `60` | no | +| metrics_config | "Which metrics should we send to cloudwatch, the default is standard. Setting this variable to advanced will send all the available metrics that are provided by the agent. You can find more information here https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/create-cloudwatch-agent-configuration-file-wizard.html." | string | `standard` | no | +| name | Solution name, e.g. 'app'. | string | - | yes | +| namespace | Namespace, which could be your organization name or abbreviation, e.g. 'eg' or 'cp'. | string | - | yes | +| stage | Stage, e.g. 'prod', 'staging', 'dev', or 'test'. | string | `` | no | +| userdata_part_content | The user data that should be passed along from the caller of the module. | string | `` | no | +| userdata_part_content_type | What format is userdata_part_content in - eg 'text/cloud-config' or 'text/x-shellscript'. | string | `text/cloud-config` | no | +| userdata_part_merge_type | Control how cloud-init merges user-data sections. | string | `list(append)+dict(recurse_array)+str()` | no | + +## Outputs + +| Name | Description | +|------|-------------| +| role_name | The role name that should be attached to the role policy | +| user_data | The user_data with the cloudwatch_agent configuration in base64 and gzipped | + diff --git a/main.tf b/main.tf new file mode 100644 index 0000000..a559c87 --- /dev/null +++ b/main.tf @@ -0,0 +1,96 @@ +module "label" { + source = "git::https://github.com/cloudposse/terraform-null-label.git?ref=tags/0.7.0" + stage = "${var.stage}" + name = "${var.name}" + namespace = "${var.namespace}" +} + +data "template_file" "cloud_init_cloudwatch_agent" { + template = "${file("${path.module}/templates/cloud_init.yaml")}" + + vars { + cloudwatch_agent_configuration = "${var.metrics_config == "standard" ? base64encode(data.template_file.cloudwatch_agent_configuration_standard.rendered) : base64encode(data.template_file.cloudwatch_agent_configuration_advanced.rendered)}" + } +} + +data "template_file" "cloudwatch_agent_configuration_advanced" { + template = "${file("${path.module}/templates/cloudwatch_agent_configuration_advanced.json")}" + + vars { + aggregation_dimensions = "${jsonencode(var.aggregation_dimensions)}" + cpu_resources = "${var.cpu_resources}" + disk_resources = "${jsonencode(var.disk_resources)}" + metrics_collection_interval = "${var.metrics_collection_interval}" + } +} + +data "template_file" "cloudwatch_agent_configuration_standard" { + template = "${file("${path.module}/templates/cloudwatch_agent_configuration_standard.json")}" + + vars { + aggregation_dimensions = "${jsonencode(var.aggregation_dimensions)}" + cpu_resources = "${var.cpu_resources}" + disk_resources = "${jsonencode(var.disk_resources)}" + metrics_collection_interval = "${var.metrics_collection_interval}" + } +} + +data "template_cloudinit_config" "cloud_init_merged" { + gzip = true + base64_encode = true + + part { + filename = "userdata_part_cloudwatch.cfg" + content = "${data.template_file.cloud_init_cloudwatch_agent.rendered}" + content_type = "text/cloud-config" + } + + part { + filename = "userdata_part_caller.cfg" + content = "${var.userdata_part_content}" + content_type = "${var.userdata_part_content_type}" + merge_type = "${var.userdata_part_merge_type}" + } +} + +data "aws_iam_policy_document" "ec2_cloudwatch" { + statement { + effect = "Allow" + actions = ["sts:AssumeRole"] + + principals = { + type = "Service" + identifiers = ["ec2.amazonaws.com"] + } + } +} + +resource "aws_iam_role" "ec2_cloudwatch" { + name = "${module.label.id}" + + assume_role_policy = "${data.aws_iam_policy_document.ec2_cloudwatch.json}" + + tags = { + Name = "${module.label.id}" + } +} + +data "aws_iam_policy_document" "wildcard_cloudwatch_agent" { + statement { + effect = "Allow" + + actions = [ + "ec2:DescribeTags", + "cloudwatch:PutMetricData", + ] + + resources = ["*"] + } +} + +resource "aws_iam_role_policy" "wildcard_cloudwatch_agent" { + name = "${module.label.id}" + + role = "${aws_iam_role.ec2_cloudwatch.id}" + policy = "${data.aws_iam_policy_document.wildcard_cloudwatch_agent.json}" +} diff --git a/outputs.tf b/outputs.tf new file mode 100644 index 0000000..b04a559 --- /dev/null +++ b/outputs.tf @@ -0,0 +1,9 @@ +output "user_data" { + description = "The user_data with the cloudwatch_agent configuration in base64 and gzipped" + value = "${data.template_cloudinit_config.cloud_init_merged.rendered}" +} + +output "role_name" { + description = "The role name that should be attached to the role policy" + value = "${aws_iam_role.ec2_cloudwatch.name}" +} diff --git a/templates/cloud_init.yaml b/templates/cloud_init.yaml new file mode 100644 index 0000000..753d18d --- /dev/null +++ b/templates/cloud_init.yaml @@ -0,0 +1,40 @@ +write_files: + - encoding: b64 + path: /etc/cloudwatch_agent.json + owner: root:root + permissions: '0644' + content: ${cloudwatch_agent_configuration} + +runcmd: + - | + . /etc/os-release + + case $NAME in + "Amazon Linux") echo "Installing the cloudwatch agent for Amazon Linux." + curl -O https://s3.amazonaws.com/amazoncloudwatch-agent/amazon_linux/amd64/latest/amazon-cloudwatch-agent.rpm + rpm -U ./amazon-cloudwatch-agent.rpm + ;; + Centos) echo "Installing the cloudwatch agent for Centos Linux." + curl -O https://s3.amazonaws.com/amazoncloudwatch-agent/centos/amd64/latest/amazon-cloudwatch-agent.rpm + rpm -U ./amazon-cloudwatch-agent.rpm + ;; + Debian) echo "Installing the cloudwatch agent for Debian Linux." + curl -O https://s3.amazonaws.com/amazoncloudwatch-agent/debian/amd64/latest/amazon-cloudwatch-agent.deb + dpkg -i -E ./amazon-cloudwatch-agent.deb + ;; + Redhat) echo "Installing the cloudwatch agent for Redhat Linux." + curl -O https://s3.amazonaws.com/amazoncloudwatch-agent/redhat/amd64/latest/amazon-cloudwatch-agent.rpm + rpm -U ./amazon-cloudwatch-agent.rpm + ;; + Suse) echo "Installing the cloudwatch agent for Suse Linux." + curl -O https://s3.amazonaws.com/amazoncloudwatch-agent/suse/amd64/latest/amazon-cloudwatch-agent.rpm + rpm -U ./amazon-cloudwatch-agent.rpm + ;; + Ubuntu) echo "Installing the cloudwatch agent for Ubuntu Linux." + curl -O https://s3.amazonaws.com/amazoncloudwatch-agent/ubuntu/amd64/latest/amazon-cloudwatch-agent.deb + dpkg -i -E ./amazon-cloudwatch-agent.deb + ;; + *) + echo "Operating system not supported. Please refer to the official documents for more info https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/install-CloudWatch-Agent-on-first-instance.html" + esac + - /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -c file:/etc/cloudwatch_agent.json -s diff --git a/templates/cloudwatch_agent_configuration_advanced.json b/templates/cloudwatch_agent_configuration_advanced.json new file mode 100644 index 0000000..cad6e3c --- /dev/null +++ b/templates/cloudwatch_agent_configuration_advanced.json @@ -0,0 +1,141 @@ +{ + "metrics": { + "aggregation_dimensions": [ + ["InstanceId"], + ["AutoScalingGroupName"] + ], + "append_dimensions": { + "AutoScalingGroupName": "$${aws:AutoScalingGroupName}", + "InstanceId": "$${aws:InstanceId}" + }, + "metrics_collected": { + "cpu": { + "measurement": [ + "cpu_time_active", + "cpu_time_guest", + "cpu_time_guest_nice", + "cpu_time_idle", + "cpu_time_iowait", + "cpu_time_irq", + "cpu_time_nice", + "cpu_time_softirq", + "cpu_time_steal", + "cpu_time_system", + "cpu_time_user", + "cpu_usage_active", + "cpu_usage_guest", + "cpu_usage_guest_nice", + "cpu_usage_idle", + "cpu_usage_iowait", + "cpu_usage_irq", + "cpu_usage_nice", + "cpu_usage_softirq", + "cpu_usage_steal", + "cpu_usage_system", + "cpu_usage_user" + ], + "metrics_collection_interval": ${metrics_collection_interval}, + ${cpu_resources} + "totalcpu": true + }, + "disk": { + "measurement": [ + "disk_free", + "disk_inodes_free", + "disk_inodes_total", + "disk_inodes_used", + "disk_total", + "disk_used", + "disk_used_percent" + ], + "metrics_collection_interval": ${metrics_collection_interval}, + "resources": ${disk_resources} + }, + "diskio": { + "measurement": [ + "diskio_iops_in_progress", + "diskio_io_time", + "diskio_reads", + "diskio_read_bytes", + "diskio_read_time", + "diskio_writes", + "diskio_write_bytes", + "diskio_write_time" + ], + "metrics_collection_interval": ${metrics_collection_interval}, + "resources": ${disk_resources} + }, + "mem": { + "measurement": [ + "mem_active", + "mem_available", + "mem_available_percent", + "mem_buffered", + "mem_cached", + "mem_free", + "mem_inactive", + "mem_total", + "mem_used", + "mem_used_percent" + ], + "metrics_collection_interval": ${metrics_collection_interval} + }, + "swap": { + "measurement": [ + "swap_used_percent", + "swap_used", + "swap_free" + ], + "metrics_collection_interval": ${metrics_collection_interval} + }, + "net": { + "measurement": [ + "net_bytes_recv", + "net_bytes_sent", + "net_drop_in", + "net_drop_out", + "net_err_in", + "net_err_out", + "net_packets_sent", + "net_packets_recv" + ], + "metrics_collection_interval": ${metrics_collection_interval} + }, + "netstat": { + "measurement": [ + "netstat_tcp_close", + "netstat_tcp_close_wait", + "netstat_tcp_closing", + "netstat_tcp_established", + "netstat_tcp_fin_wait1", + "netstat_tcp_fin_wait2", + "netstat_tcp_last_ack", + "netstat_tcp_listen", + "netstat_tcp_none", + "netstat_tcp_syn_recv", + "netstat_tcp_syn_sent", + "netstat_tcp_time_wait", + "netstat_udp_socket" + ], + "metrics_collection_interval": ${metrics_collection_interval} + }, + "processes": { + "measurement": [ + "processes_blocked", + "processes_dead", + "processes_idle", + "processes_paging", + "processes_running", + "processes_sleeping", + "processes_stopped", + "processes_total", + "processes_total_threads", + "processes_wait", + "processes_zombies" + ], + "metrics_collection_interval": ${metrics_collection_interval} + } + } + } +} + diff --git a/templates/cloudwatch_agent_configuration_standard.json b/templates/cloudwatch_agent_configuration_standard.json new file mode 100644 index 0000000..c82f006 --- /dev/null +++ b/templates/cloudwatch_agent_configuration_standard.json @@ -0,0 +1,53 @@ +{ + "metrics": { + "aggregation_dimensions": [ + ["InstanceId"], + ["AutoScalingGroupName"] + ], + "append_dimensions": { + "AutoScalingGroupName": "$${aws:AutoScalingGroupName}", + "InstanceId": "$${aws:InstanceId}" + }, + "metrics_collected": { + "cpu": { + "measurement": [ + "cpu_usage_idle", + "cpu_usage_iowait", + "cpu_usage_user", + "cpu_usage_system" + ], + "metrics_collection_interval": ${metrics_collection_interval}, + ${cpu_resources} + "totalcpu": true + }, + "disk": { + "measurement": [ + "used_percent", + "inodes_free" + ], + "metrics_collection_interval": ${metrics_collection_interval}, + "resources": ${disk_resources} + }, + "diskio": { + "measurement": [ + "io_time" + ], + "metrics_collection_interval": ${metrics_collection_interval}, + "resources": ${disk_resources} + }, + "mem": { + "measurement": [ + "mem_used_percent" + ], + "metrics_collection_interval": ${metrics_collection_interval} + }, + "swap": { + "measurement": [ + "swap_used_percent" + ], + "metrics_collection_interval": ${metrics_collection_interval} + } + } + } +} + diff --git a/variables.tf b/variables.tf new file mode 100644 index 0000000..3b3d3ee --- /dev/null +++ b/variables.tf @@ -0,0 +1,74 @@ +variable "aggregation_dimensions" { + description = "Specifies the dimensions that collected metrics are to be aggregated on." + type = "list" + + default = [ + ["InstanceId"], + ["AutoScalingGroupName"], + ] +} + +variable "cpu_resources" { + description = "Specifies that per-cpu metrics are to be collected. The only allowed value is *. If you include this field and value, per-cpu metrics are collected." + type = "string" + default = "\"resources\": [\"*\"]," +} + +variable "disk_resources" { + description = "Specifies an array of disk mount points. This field limits CloudWatch to collect metrics from only the listed mount points. You can specify * as the value to collect metrics from all mount points. Defaults to the root / mountpount." + type = "list" + default = ["/"] +} + +variable "userdata_part_content" { + description = "The user data that should be passed along from the caller of the module." + type = "string" + default = "" +} + +variable "userdata_part_content_type" { + description = "What format is userdata_part_content in - eg 'text/cloud-config' or 'text/x-shellscript'." + type = "string" + default = "text/cloud-config" +} + +variable "userdata_part_merge_type" { + description = "Control how cloud-init merges user-data sections." + type = "string" + default = "list(append)+dict(recurse_array)+str()" +} + +variable "namespace" { + description = "Namespace, which could be your organization name or abbreviation, e.g. 'eg' or 'cp'." + type = "string" +} + +variable "stage" { + description = "Stage, e.g. 'prod', 'staging', 'dev', or 'test'." + type = "string" + default = "" +} + +variable "name" { + description = "Solution name, e.g. 'app'." + type = "string" +} + +variable "metrics_config" { + description = <