Skip to content

Commit

Permalink
Merge pull request #7 from timmyeats/dev
Browse files Browse the repository at this point in the history
Merge dev for new feature
  • Loading branch information
timmyeats authored Mar 6, 2024
2 parents 0aa2c35 + e6c92e4 commit df5a1cb
Show file tree
Hide file tree
Showing 17 changed files with 385 additions and 96 deletions.
63 changes: 63 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# EditorConfig is awesome: https://EditorConfig.org

# top-most EditorConfig file
root = true

# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
charset = utf-8
insert_final_newline = true
indent_style = space
indent_size = 2
trim_trailing_whitespace = true

# Dockerfile
[{Dockerfile,Dockerfile.template.erb,Dockerfile.sample}]
indent_style = space
indent_size = 4

# Batch Files
[*.{cmd,bat}]
end_of_line = crlf

# Bash Files
[*.sh]
end_of_line = lf

# tsv use tab to separate fields
[*.tsv]
indent_style = tab

# Applies to all Markdown files
[*.{md,mdx}]
trim_trailing_whitespace = false

# Matches multiple files with brace expansion notation
# Set default charset
[*.{js,py}]
charset = utf-8

# Web Files
[*.{htm,html,js,jsm,ts,tsx,cjs,cts,ctsx,mjs,mts,mtsx,css,sass,scss,less,pcss,svg,vue}]
indent_size = 2

# 4 space indentation
[*.py]
indent_style = space
indent_size = 4
max_line_length = 79

# Tab indentation (no size specified)
[Makefile]
indent_style = tab

# Indentation override for all JS under lib directory
[lib/**.js]
indent_style = space
indent_size = 2

# Matches the exact files either package.json or .travis.yml
[{package.json,.travis.yml}]
indent_style = space
indent_size = 2
65 changes: 65 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
default_language_version:
python: python3.9
repos:
# General
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: detect-aws-credentials
args: [--allow-missing-credentials]
- id: detect-private-key
- id: check-added-large-files
- id: check-merge-conflict
- id: check-ast
- id: check-case-conflict
- id: check-executables-have-shebangs
- id: check-json
- id: check-yaml
- id: check-toml
- id: check-symlinks
- id: check-xml
- id: destroyed-symlinks
- id: end-of-file-fixer
- id: check-byte-order-marker
- id: mixed-line-ending
- id: name-tests-test
- id: requirements-txt-fixer
- id: trailing-whitespace
args: [--markdown-linebreak-ext=md]
- repo: https://github.com/zricethezav/gitleaks
rev: v8.18.1
hooks:
- id: gitleaks

# Python
- repo: https://github.com/psf/black # Can choose between black or autopep8
rev: 24.1.1
hooks:
- id: black
args: [-t, py39]
- repo: https://github.com/asottile/pyupgrade
rev: v3.15.0
hooks:
- id: pyupgrade
args: [--py39-plus]
- repo: https://github.com/asottile/add-trailing-comma
rev: v3.1.0
hooks:
- id: add-trailing-comma
- repo: https://github.com/asottile/reorder_python_imports
rev: v3.1.0
hooks:
- id: reorder-python-imports

# Terraform
- repo: https://github.com/terraform-docs/terraform-docs
rev: v0.17.0
hooks:
- id: terraform-docs-go
args:
["markdown", "table", "--output-file", "README.md", "."]
- repo: https://github.com/antonbabenko/pre-commit-terraform
rev: v1.86.0
hooks:
- id: terraform_fmt
args: [--args=-diff]
79 changes: 71 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# AWS Magic Tagging Resources

Use the EventBridge to trigger a Lambda function to tag resources in AWS.
This script is designed to automatically tag AWS resources when certain events occur. It is intended to be used as an AWS Lambda function, triggered by AWS EventBridge.

## Prerequisites

Expand Down Expand Up @@ -31,6 +31,8 @@ resource_tags = {
- IAM Policy
- Log Group
- EventBridge Rule
- Resource Group
- CloudWatch Dashboard

## How to use this

Expand Down Expand Up @@ -62,23 +64,84 @@ Deploy this terraform and verify the resource tags are created.

`sh multi-region-destroy.sh`

## Functionality

1. **Extracting Tag Information**: The `get_tag_information` function extracts tag information from the event, including the source IP address, event time, and user agent. It also calls the `taggers.get_event_time` and `taggers.get_identity_type` functions to get additional tag information.

2. **Adding Tags**: The `lambda_handler` function is the entry point for the Lambda function. It first calls the `get_tag_information` function to get the tag information, then decides which type of AWS resource to add tags to based on the source of the event. For example, if the source of the event is "aws.ec2", it calls the `ec2_tagger.tagger` function to add tags to EC2 resources.


### Support auto-tagging resources

- EC2
- ELB
- RDS
- CloudFront
- Lambda
- SNS
- IAM
- AutoScaling


### Default tags

- Owner
- SourceIP
- UserType
- EventTime
- UserName / RoleName

- Owner
- SourceIP
- UserType
- EventTime
- UserName / RoleName


<!-- BEGIN_TF_DOCS -->
## Requirements

| Name | Version |
|------|---------|
| <a name="requirement_terraform"></a> [terraform](#requirement\_terraform) | >= 0.14 |
| <a name="requirement_aws"></a> [aws](#requirement\_aws) | 4.22.0 |

## Providers

| Name | Version |
|------|---------|
| <a name="provider_aws"></a> [aws](#provider\_aws) | 4.22.0 |

## Modules

| Name | Source | Version |
|------|--------|---------|
| <a name="module_lambda"></a> [lambda](#module\_lambda) | terraform-aws-modules/lambda/aws | 3.3.1 |

## Resources

| Name | Type |
|------|------|
| [aws_cloudwatch_dashboard.dashboard](https://registry.terraform.io/providers/hashicorp/aws/4.22.0/docs/resources/cloudwatch_dashboard) | resource |
| [aws_cloudwatch_event_rule.event_rule](https://registry.terraform.io/providers/hashicorp/aws/4.22.0/docs/resources/cloudwatch_event_rule) | resource |
| [aws_cloudwatch_event_target.event_rule](https://registry.terraform.io/providers/hashicorp/aws/4.22.0/docs/resources/cloudwatch_event_target) | resource |
| [aws_iam_policy.lambda_tagging_policy](https://registry.terraform.io/providers/hashicorp/aws/4.22.0/docs/resources/iam_policy) | resource |
| [aws_iam_role.lambda_function_role](https://registry.terraform.io/providers/hashicorp/aws/4.22.0/docs/resources/iam_role) | resource |
| [aws_iam_role_policy_attachment.lambda_basic_policy](https://registry.terraform.io/providers/hashicorp/aws/4.22.0/docs/resources/iam_role_policy_attachment) | resource |
| [aws_iam_role_policy_attachment.lambda_tagging_policy](https://registry.terraform.io/providers/hashicorp/aws/4.22.0/docs/resources/iam_role_policy_attachment) | resource |
| [aws_lambda_permission.event_rule](https://registry.terraform.io/providers/hashicorp/aws/4.22.0/docs/resources/lambda_permission) | resource |
| [aws_resourcegroups_group.resource_group](https://registry.terraform.io/providers/hashicorp/aws/4.22.0/docs/resources/resourcegroups_group) | resource |
| [aws_caller_identity.current](https://registry.terraform.io/providers/hashicorp/aws/4.22.0/docs/data-sources/caller_identity) | data source |
| [aws_iam_role.lambda_function_role](https://registry.terraform.io/providers/hashicorp/aws/4.22.0/docs/data-sources/iam_role) | data source |
| [aws_region.current](https://registry.terraform.io/providers/hashicorp/aws/4.22.0/docs/data-sources/region) | data source |

## Inputs

| Name | Description | Type | Default | Required |
|------|-------------|------|---------|:--------:|
| <a name="input_aws_region"></a> [aws\_region](#input\_aws\_region) | The AWS region to use | `string` | `"us-east-1"` | no |
| <a name="input_enable_cloudwatch_dashboard"></a> [enable\_cloudwatch\_dashboard](#input\_enable\_cloudwatch\_dashboard) | Enable the CloudWatch Dashboard | `bool` | `false` | no |
| <a name="input_lambda_function_name"></a> [lambda\_function\_name](#input\_lambda\_function\_name) | The name of the Lambda function | `string` | `"AWSAutoTaggingFunction"` | no |
| <a name="input_lambda_function_role_name"></a> [lambda\_function\_role\_name](#input\_lambda\_function\_role\_name) | The name of the Lambda function role | `string` | `"AWSAutoTaggingFunctionRole"` | no |
| <a name="input_resource_tags"></a> [resource\_tags](#input\_resource\_tags) | Tags to apply to resources | `map(string)` | `null` | no |

## Outputs

| Name | Description |
|------|-------------|
| <a name="output_completed_region"></a> [completed\_region](#output\_completed\_region) | The region that the Lambda function was created |
<!-- END_TF_DOCS -->
3 changes: 2 additions & 1 deletion cw_dashboard.tf
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
locals {
dashboard_query = <<-EOT
SOURCE '/aws/lambda/${var.lambda_function_name}'
SOURCE '/aws/lambda/${var.lambda_function_name}'
| fields @timestamp, @message
| filter @message not like 'START RequestId'
| filter @message not like 'REPORT RequestId'
| filter @message not like 'END RequestId'
| filter @message not like 'INIT_START'
| sort @timestamp desc
| limit 100
EOT
Expand Down
5 changes: 5 additions & 0 deletions eventbridge.tf
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ locals {
service = "IAM"
source = ["aws.iam"]
event_name = ["CreateRole", "CreatePolicy"]
},
{
service = "AutoScaling"
source = ["aws.autoscaling"]
event_name = ["CreateAutoScalingGroup"]
}
]
}
Expand Down
14 changes: 9 additions & 5 deletions handler/main.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import resource_tagger.autoscaling_tagger as asg_tagger
import resource_tagger.cloudfront_tagger as cf_tagger
import resource_tagger.ec2_tagger as ec2_tagger
import resource_tagger.elb_tagger as elb_tagger
import resource_tagger.iam_tagger as iam_tagger
import resource_tagger.lambda_tagger as lambda_tagger
import resource_tagger.rds_tagger as rds_tagger
import resource_tagger.cloudfront_tagger as cf_tagger
import resource_tagger.sns_tagger as sns_tagger
import resource_tagger.lambda_tagger as lambda_tagger
import resource_tagger.iam_tagger as iam_tagger
import resource_tagger.taggers as taggers


Expand Down Expand Up @@ -33,7 +34,7 @@ def lambda_handler(event, context):

elif event["source"] == "aws.rds":
response = rds_tagger.tagger(event, tags)

elif event["source"] == "aws.cloudfront":
response = cf_tagger.tagger(event, tags)

Expand All @@ -46,10 +47,13 @@ def lambda_handler(event, context):
elif event["source"] == "aws.iam":
response = iam_tagger.tagger(event, tags)

elif event["source"] == "aws.autoscaling":
response = asg_tagger.tagger(event, tags)

else:
response = "[LOG] No support source found!"
else:
response = "[LOG] No tags found!"

print(response)
return response
36 changes: 36 additions & 0 deletions handler/resource_tagger/autoscaling_tagger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import boto3

from .taggers import changing_tag_to_array


# Create tags for AWS resources
def add_tags_in_resource(tags, resource):
asg_converted_tags = []
converted_tags = changing_tag_to_array(tags)

try:
for tag in converted_tags:
tag["ResourceId"] = resource
tag["ResourceType"] = "auto-scaling-group"
tag["PropagateAtLaunch"] = True
asg_converted_tags.append(tag)
client = boto3.client("autoscaling")
response = client.create_or_update_tags(Tags=asg_converted_tags)
except Exception as e:
response = {"[LOG] Error: ": str(e)}

return response, converted_tags


def tagger(event, tags):
request_parameters = event["detail"]["requestParameters"]
autoscaling_group_name = request_parameters["autoScalingGroupName"]

if autoscaling_group_name is not None:
response, converted_tags = add_tags_in_resource(tags, autoscaling_group_name)
response["autoscaling_group_name"] = autoscaling_group_name
response["converted_tags"] = converted_tags
return response

else:
return "[LOG] No resource id found!"
Loading

0 comments on commit df5a1cb

Please sign in to comment.