Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
EreminAnton committed Jun 7, 2024
0 parents commit 0060cf1
Show file tree
Hide file tree
Showing 21 changed files with 2,605 additions and 0 deletions.
43 changes: 43 additions & 0 deletions .github/workflows/code-guru.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
name: CodeGuru Review

on:
push:
branches: [ "*" ]

permissions:
contents: read
security-events: write
id-token: write

jobs:
deploy:
name: Deploy
runs-on: ubuntu-latest
environment: production

steps:
# Step 1: Checkout the repository and provide your AWS credentials
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0

- name: Configure AWS Credentials
uses: aws-actions/configure-aws-credentials@v4
with:
aws-region: eu-central-1
role-to-assume: ${{ secrets.DEVELOPMENT_ACCOUNT_ROLE_ARN }}
role-duration-seconds: 3600
role-session-name: ${{ github.event.repository.name }}

# Step 2: Add CodeGuru Reviewer Action
- name: CodeGuru Reviewer
uses: aws-actions/codeguru-reviewer@v1.1
with:
s3_bucket: codeguru-reviewer-mambo-jumbo

# Step 3: Upload results into GitHub
- name: Upload review result
uses: github/codeql-action/upload-sarif@v2
with:
sarif_file: codeguru-results.sarif.json
162 changes: 162 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

tmp/
5 changes: 5 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"python.envFile": "${workspaceFolder}/.env",
"python.terminal.activateEnvInCurrentTerminal": true,
"python.defaultInterpreterPath": "${workspaceFolder}/right-start-tools/.venv/bin/python"
}
38 changes: 38 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# FivexL RightStart Tools
**Please note!**
This repository is still a work in progress and is subject to change, so please be careful when running it in production environments.

This repository contains a set of tools that can simplify the management of AWS accounts within an AWS Organization.

To use it, please follow the instructions below:

Clone the repository locally.
- Navigate to the required directory: cd right-start-tools
- Install dependencies using Poetry: `poetry install`
- Log in to AWS: `aws-vault exec <profile>` / `aws configure`
- Run the tool you need: `rst <command>`


```
Information Commands:
- rst check-baseline
Check if the RightStart account baseline is deployed to all accounts.
- rst gen-tf-backend
Generate backend.tf file based on the current AWS environment.
- rst show-org-structure
Show the tree structure of the AWS Organization
```

```
Commands:
- rst create-roles
Check if 'OrganizationAccountAccessRole' and 'AWSControlTowerExecution' are deployed to all accounts and create them if needed.
- rst process-vpcs
Intended to be used in the management account, requires Control Tower or AWSControlTowerExecution role. Will delete all default VPCs and internet gateways in all accounts in all regions.
Note! This process will go through all accounts and regions and delete default VPCs and IGWs. This process may take a while (~3-4 minutes per account).
```

If you need to create cross-account tags for VPCs, please refer to the README.md in the tag_vpc directory.
15 changes: 15 additions & 0 deletions clean_terraform_init.zsh
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/bin/zsh

#Simple zsh script to clean .terraform terraform.lock.hcl in every directory of the project, it might be useful when you want to reinitialize terraform in a project

# Base directories to search in
base_dirs=("modules" "organization")

# Loop through base directories
for base_dir in "${base_dirs[@]}"; do
# Find and delete .terraform directories recursively
find "$base_dir" -type d -name ".terraform" -print -exec rm -rf {} \;

# Find and delete .terraform.lock.hcl files recursively
find "$base_dir" -type f -name ".terraform.lock.hcl" -print -exec rm -f {} \;
done
1,380 changes: 1,380 additions & 0 deletions right-start-tools/poetry.lock

Large diffs are not rendered by default.

24 changes: 24 additions & 0 deletions right-start-tools/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
[tool.poetry]
name = "right-start-tools"
version = "0.1.0"
description = ""
authors = ["Eremin <haru.eaa@gmail.com>"]
readme = "README.md"

[tool.poetry.dependencies]
python = "^3.9"
boto3 = "^1.34.64"
boto3-stubs = {extras = ["organizations", "sts", "iam", "ec2"], version = "^1.34.64"}
click = "^8.1.7"


[tool.poetry.group.dev.dependencies]
ipykernel = "^6.29.3"

[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

[tool.poetry.scripts]
rst = "right_start_tools.cli:cli"

3 changes: 3 additions & 0 deletions right-start-tools/right_start_tools/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from . import constants, tools

ALL = [tools, constants]
3 changes: 3 additions & 0 deletions right-start-tools/right_start_tools/aws.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from boto3.session import Session

session = Session()
49 changes: 49 additions & 0 deletions right-start-tools/right_start_tools/backend.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import hashlib

import boto3
import click
from mypy_boto3_sts import STSClient


def get_aws_account_id(client: STSClient) -> str:
account_id = client.get_caller_identity()["Account"]
return account_id


def hash_environment_id(tf_environment_id):
# Create a SHA-1 hash object
hash_object = hashlib.sha1()
# Update the hash object with the bytes of the string, encoding needed to convert str to bytes
hash_object.update(tf_environment_id.encode("utf-8"))
# Get the hexadecimal representation of the digest
hashed_environment_id = hash_object.hexdigest()
return hashed_environment_id


def write_backend_config(aws_default_region, hashed_environment_id):
backend_config = f"""terraform {{
backend "s3" {{
bucket = "terraform-state-{hashed_environment_id}"
key = "terraform/main/main.tfstate"
region = "{aws_default_region}"
encrypt = true
dynamodb_table = "terraform-state-lock-{hashed_environment_id}"
}}
}}
"""
with open("backend.tf", "w") as f:
f.write(backend_config)


@click.command(short_help="Generate backend.tf file based on current AWS environment.")
def gen_tf_backend():
"""Generate backend.tf file."""
session = boto3.Session()
client = session.client("sts")
aws_account_id = get_aws_account_id(client)
region = session.region_name
env_id = hash_environment_id(f"{aws_account_id}-{region}")
click.echo("Writing backend.tf...")
click.echo(f" AWS Account ID: {aws_account_id}")
click.echo(f" AWS Region: {region}")
write_backend_config(region, env_id)
Loading

0 comments on commit 0060cf1

Please sign in to comment.