Skip to content

Commit

Permalink
Fixed Issue #5
Browse files Browse the repository at this point in the history
  • Loading branch information
eerkunt committed Jun 18, 2018
1 parent cbb7e82 commit 81396c2
Show file tree
Hide file tree
Showing 15 changed files with 363 additions and 112 deletions.
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
venv
*.pyc
*.sublime-*
tf_files/*
.idea/*
build
dist
example/tf_files/*
terraform_compliance.egg-info
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License

Copyright (c) 2017-2018 Emre Erkunt, [email protected]

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:

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.
199 changes: 156 additions & 43 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,46 +1,159 @@
# terraform-compliance
----------------------

A compliancy tool that runs against terraform files kept in local with BDD style configuration.

This tool uses ;

* [radish-bdd](https://github.com/radish-bdd/radish)
* [terraform-validate](https://github.com/elmundio87/terraform_validate)

<h1 align="center">terraform-compliance</h1>

<div align="center">
<strong>BDD Testing for Terraform Files</strong>
</div>
<div align="center">
A lightweight BDD-testing Compliance Framework
</div>

<br />

<div align="center">
<!-- Stability -->
<img src="https://img.shields.io/badge/stability-experimental-orange.svg?style=flat-square"
alt="Code Stability" />
</a>
<!-- Build Status -->
<a href="https://travis-ci.org/eerkunt/terraform-compliance">
<img src="https://img.shields.io/travis/eerkunt/terraform-compliance/master.svg?style=flat-square"
alt="Build Status" />
</a>
<!-- Test Coverage -->
<a href="https://codecov.io/github/eerkunt/terraform-compliance">
<img src="https://img.shields.io/codecov/c/github/eerkunt/terraform-compliance/master.svg?style=flat-square"
alt="Test Coverage" />
</a>
<!-- Downloads -->
<a href="https://npmjs.org/package/choo">
<img src="https://img.shields.io/pypi/v/terraform-compliance.svg?style=flat-square&label=version"
alt="Downloads" />
</a>
</div>

## Table of Contents
- [Features](#features)
- [Example](#example)
- [FAQ](#faq)
- [Installation](#installation)
- [Usage](#usage)

## Features
- __compliance:__ Test your infrastructure as code before you deploy. Enforce your people to follow the policies.
- __behaviour driven development:__ We have BDD for nearly everything, why not for IaC ?
- __fixed steps:__ fixed steps coming with the package, just focus on your BDD feature/scenario files.
- __portable:__ just install it from `pip`
- __why ?:__ why not ?

## Example
![Example Run](terraform-compliance-demo.gif)

### Installation
Clone this repository

# git clone https://github.com/eeerkunt/terraform-compliance
# cd terraform-compliance


(OPTIONAL) Create a virtualenv and activate it

# virtualenv venv
# source venv/bin/activate


Install requirements

# pip install -r requirements.txt

and start playing
```sh
[~] $ terraform-compliance -f example/example_01 -t example/tf_files
terraform-compliance v0.0.1 initiated
Features : /Users/sharky/Repository/terraform-compliance/example/example_01
Steps : /Users/sharky/Repository/venv2/lib/python2.7/site-packages/terraform_compliance/steps
TF Files : /Users/sharky/Repository/terraform-compliance/example/tf_files
Validating terraform files.
All HCL files look good.
Running tests.
Feature: Security Groups should be used to protect services/instances # /path/to/example/example_01/aws/security_groups.feature
In order to improve security
As engineers
We'll use AWS Security Groups as a Perimeter Defence
Scenario Outline: Policy Structure
Given I define AWS Security Group
Then it must contain <policy_name>
Examples:
| policy_name |
| ingress |
| egress |
Scenario Outline: Well-known insecure protocol exposure on Public Network for ingress traffic
Given I define AWS Security Group
Then it must contain ingress
with <proto> protocol and not port <portNumber> for 0.0.0.0/0
Examples:
| ProtocolName | proto | portNumber |
| HTTP | tcp | 80 |
| Telnet | tcp | 23 |
| SSH | tcp | 22 |
| MySQL | tcp | 3306 |
| MSSQL | tcp | 1443 |
| NetBIOS | tcp | 139 |
| RDP | tcp | 3389 |
Feature: Subnets should be defined properly for network security # /path/to/example/example_01/aws/subnets.feature
In order to improve security
And decrease impact radius
As engineers
We'll use a layered architecture in our AWS Environment

Scenario: Subnet Count
Given I define AWS Subnet
When I count them
Then I expect the result is more than 2
AssertionError: 0 is not more than 2

2 features (1 passed, 1 failed)
10 scenarios (9 passed, 1 failed)
28 steps (27 passed, 1 failed)

[~] $ echo $?
1
[~] $
```

## FAQ

- __Q.__ Where are the steps defined ?
- __A.__ They all comes with `terraform-compliance`, you can just focus on BDD feature/scenario files.
<br /><br />
- __Q.__ What if I would like to add more steps ?
- __A.__ You are welcome to contribute on any test, or just add an issue it will be added.
<br /><br />
- __Q.__ Where should `terraform-compliance` run ?
- __A.__ Ideally in a CI/CD tool, where company policies are defined as feature files and all IaC is tested against. Trust, but verify.

## Installation
```sh
[~] $ pip install terraform-compliance
```

### Usage
Store your terraform files into any directory and pass that directory as an argument to radish.

For e.g. Assuming that your terraform files are stored in `/path/to/tf/files` and tests are stored in `./providers/aws`to run tests against it ;

~# radish providers/aws /path/to/tf/files


All radish features are available

### Going further

The capabilities are stored in [radish](radish) directory where you can add any steps as a capability.

Tests, or _features/scenarios_ in radish-style, are stored in [provider](provider) directory.
```sh
[~] $ terraform-compliance --help
usage: terraform-compliance [-h] [--features feature_directory]
[--tfdir terraform_directory]

BDD Test Framework for Hashicorp terraform

optional arguments:
-h, --help show this help message and exit
--features feature_directory, -f feature_directory
Directory consists of BDD features
--tfdir terraform_directory, -t terraform_directory
Directory consists of Terraform Files
```

You can also push additional arguments that is specific for `radish`. Just to explain how it works ;

For e.g.
```sh
[~] $ terraform-compliance -f /path/to/features -t /path/to/terraform_files -v
terraform-compliance v0.0.1 initiated
Features : /Users/sharky/Repository/terraform-compliance/example/example_01
Steps : /Users/sharky/Repository/venv2/lib/python2.7/site-packages/terraform_compliance/steps
TF Files : /Users/sharky/Repository/terraform-compliance/example/tf_files
Validating terraform files.
All HCL files look good.
Running tests.
0.8.6
```
Please note that `0.8.6` is the `radish` version comes from `-v` parameter.


## License
[MIT](https://tldrlegal.com/license/mit-license)
File renamed without changes.
File renamed without changes.
12 changes: 0 additions & 12 deletions radish/terrain.py

This file was deleted.

3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
terraform_validate
radish-bdd
radish
radish-bdd
2 changes: 2 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[wheel]
universal = 1
53 changes: 53 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"""
BDD test framework for terraform
"""
from setuptools import find_packages, setup
from terraform_compliance.main import __app_name__, __version__

dependencies = [
'radish-bdd',
'radish',
'terraform-validate'
]

setup(
name=__app_name__,
version=__version__,
url='https://github.com/eerkunt/terraform-compliance',
license='MIT',
author='Emre Erkunt',
author_email='[email protected]',
description='BDD test framework for terraform',
long_description=__doc__,
packages=find_packages(exclude=['tests']),
include_package_data=True,
zip_safe=False,
platforms='any',
install_requires=dependencies,
entry_points={
'console_scripts': [
'terraform-compliance=terraform_compliance.main:cli',
],
},
classifiers=[
# As from http://pypi.python.org/pypi?%3Aaction=list_classifiers
# 'Development Status :: 1 - Planning',
# 'Development Status :: 2 - Pre-Alpha',
# 'Development Status :: 3 - Alpha',
'Development Status :: 4 - Beta',
# 'Development Status :: 5 - Production/Stable',
# 'Development Status :: 6 - Mature',
# 'Development Status :: 7 - Inactive',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX',
'Operating System :: MacOS',
'Operating System :: Unix',
'Operating System :: Microsoft :: Windows',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
1 change: 1 addition & 0 deletions terraform_compliance/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from terraform_validate import Validator
74 changes: 74 additions & 0 deletions terraform_compliance/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import sys
import os
from argparse import ArgumentParser, ArgumentTypeError, Action
from terraform_compliance import Validator
from radish.main import main as call_radish

__app_name__ = "terraform-compliance"
__version__ = "0.0.1"


class ArgHandling(object):
def __init__(self):
self.features = None
self.steps = None
self.tf_dir = None

class readable_dir(Action):
def __call__(self, parser, namespace, values, option_string=None):
prospective_dir = values
if not os.path.isdir(prospective_dir):
print('Invalid use or arguments: {}'.format(prospective_dir))
sys.exit(1)

if os.access(prospective_dir, os.R_OK):
setattr(namespace, self.dest, prospective_dir)
else:
print('Invalid use or arguments: {}'.format(prospective_dir))
sys.exit(1)


def cli():
argument = ArgHandling()
parser = ArgumentParser(prog=__app_name__,
description="BDD Test Framework for Hashicorp terraform")
try:
parser.add_argument("--features", "-f", dest="features", metavar='feature_directory', action=readable_dir,
help="Directory consists of BDD features", required=True)
parser.add_argument("--tfdir", "-t", dest="tf_dir", metavar='terraform_directory', action=readable_dir,
help="Directory consists of Terraform Files", required=True)
except argparse.ArgumentTypeError:
print('Invalid use or arguments: {}'.format(sys.exc_info()[1]))
sys.exit(1)

# parser.parse_args(namespace=argument)
_, radish_arguments = parser.parse_known_args(namespace=argument)

print('{} v{} initiated'.format(__app_name__, __version__))

features_directory = os.path.join(os.path.abspath(argument.features))
steps_directory = os.path.join(os.path.split(os.path.abspath(__file__))[0], 'steps')
tf_directory = os.path.join(os.path.abspath(argument.tf_dir))

print('Features : {}'.format(features_directory))
print('Steps : {}'.format(steps_directory))
print('TF Files : {}'.format(tf_directory))

commands = ['radish',
features_directory,
'--basedir', steps_directory,
'--user-data=tf_dir={}'.format(tf_directory)]
commands.extend(radish_arguments)

try:
print('Validating terraform files.')
Validator(tf_directory)
print('All HCL files look good.')

except ValueError:
print('Unable to validate Terraform Files.')
print('ERROR: {}'.format(sys.exc_info()[1]))
sys.exit(1)

print('Running tests.')
return call_radish(args=commands[1:])
Empty file.
Loading

0 comments on commit 81396c2

Please sign in to comment.