Skip to content

Commit

Permalink
Merge branch 'dev'
Browse files Browse the repository at this point in the history
  • Loading branch information
Rich Jones committed Jul 27, 2016
2 parents 77c41f3 + 28659b4 commit add819c
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 18 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ _Before you begin, make sure you have a valid AWS account and your [AWS credenti

$ pip install zappa

Please note that Zappa *must* be installed into your project's [virtual environment](http://docs.python-guide.org/en/latest/dev/virtualenvs/).
Please note that Zappa *must* be installed into your project's [virtual environment](http://docs.python-guide.org/en/latest/dev/virtualenvs/). If you use pyenv and love to manage virtualenvs with **pyenv-virtualenv**, you just have to call `pyenv local [your_venv_name]` and it's ready.

If you're looking for Django-specific integration, you should probably check out _**[django-zappa](https://github.com/Miserlou/django-zappa)**_ instead.

Expand Down Expand Up @@ -148,6 +148,8 @@ to change Zappa's behavior. Use these at your own risk!
```javascript
{
"dev": {
"assume_policy": "my_assume_policy.json", // optional, IAM assume policy JSON file
"attach_policy": "my_attach_policy.json", // optional, IAM attach policy JSON file
"aws_region": "us-east-1", // AWS Region (default US East),
"cache_cluster_enabled": false, // Use APIGW cache cluster (default False)
"cache_cluster_size": .5, // APIGW Cache Cluster size (default 0.5)
Expand Down
6 changes: 5 additions & 1 deletion test_settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
"delete_zip": true,
"debug": true,
"parameter_depth": 2,
"prebuild_script": "test_settings.prebuild_me"
"prebuild_script": "test_settings.prebuild_me",
"events": [{
"function": "tests.test_app.schedule_me",
"expression": "rate(1 minute)"
}]
}
}
15 changes: 10 additions & 5 deletions zappa/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
from zappa import Zappa, logger

CUSTOM_SETTINGS = [
'assume_policy',
'attach_policy',
'aws_region',
'delete_zip',
'exclude',
Expand Down Expand Up @@ -362,13 +364,13 @@ def schedule(self):
if self.zappa_settings[self.api_stage].get('events'):
events = self.zappa_settings[self.api_stage]['events']

if type(events) != list:
if not isinstance(events, list): # pragma: no cover
print("Events must be supplied as a list.")
return

try:
function_response = self.zappa.lambda_client.get_function(FunctionName=self.lambda_name)
except botocore.exceptions.ClientError as e:
except botocore.exceptions.ClientError as e: # pragma: no cover
print("Function does not exist, please deploy first. Ex: zappa deploy {}".format(self.api_stage))
return

Expand All @@ -389,7 +391,7 @@ def unschedule(self):
if self.zappa_settings[self.api_stage].get('events', None):
events = self.zappa_settings[self.api_stage]['events']

if type(events) != type([]):
if not isinstance(events, list): # pragma: no cover
print("Events must be supplied as a list.")
return

Expand Down Expand Up @@ -623,8 +625,11 @@ def load_settings(self, settings_file="zappa_settings.json", session=None):

for setting in CUSTOM_SETTINGS:
if setting in self.zappa_settings[self.api_stage]:
setattr(self.zappa, setting, self.zappa_settings[
self.api_stage][setting])
setting_val = self.zappa_settings[self.api_stage][setting]
if setting.endswith('policy'):
with open(setting_val, 'r') as f:
setting_val = f.read()
setattr(self.zappa, setting, setting_val)

return self.zappa

Expand Down
35 changes: 24 additions & 11 deletions zappa/zappa.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import requests
import shutil
import string
import subprocess
import tarfile
import tempfile
import time
Expand Down Expand Up @@ -217,6 +218,8 @@ class Zappa(object):
]

role_name = "ZappaLambdaExecution"
assume_policy = ASSUME_POLICY
attach_policy = ATTACH_POLICY
aws_region = 'us-east-1'

##
Expand Down Expand Up @@ -253,9 +256,22 @@ def create_lambda_zip(self, prefix='lambda_package', handler_file=None,
print("Packaging project as zip...")

if not venv:
try:
if 'VIRTUAL_ENV' in os.environ:
venv = os.environ['VIRTUAL_ENV']
except KeyError as e: # pragma: no cover
elif os.path.exists('.python-version'): # pragma: no cover
logger.debug("Pyenv's local virtualenv detected.")
try:
subprocess.check_output('pyenv', stderr=subprocess.STDOUT)
except OSError as e:
print("This directory seems to have pyenv's local venv"
"but pyenv executable was not found.")
with open('.python-version', 'r') as f:
env_name = f.read()[:-1]
logger.debug('env name = {}'.format(env_name))
bin_path = subprocess.check_output(['pyenv', 'which', 'python']).decode('utf-8')
venv = bin_path[:bin_path.rfind(env_name)] + env_name
logger.debug('env path = {}'.format(venv))
else: # pragma: no cover
print("Zappa requires an active virtual environment.")
quit()

Expand Down Expand Up @@ -805,11 +821,8 @@ def create_iam_roles(self):
If the IAM role already exists, it will be updated if necessary.
"""
assume_policy_s = ASSUME_POLICY
attach_policy_s = ATTACH_POLICY

attach_policy_obj = json.loads(attach_policy_s)
assume_policy_obj = json.loads(assume_policy_s)
attach_policy_obj = json.loads(self.attach_policy)
assume_policy_obj = json.loads(self.assume_policy)

# Create the role if needed
role = self.iam.Role(self.role_name)
Expand All @@ -820,26 +833,26 @@ def create_iam_roles(self):
print("Creating " + self.role_name + " IAM Role...")

role = self.iam.create_role(RoleName=self.role_name,
AssumeRolePolicyDocument=assume_policy_s)
AssumeRolePolicyDocument=self.assume_policy)
self.credentials_arn = role.arn

# create or update the role's policies if needed
policy = self.iam.RolePolicy(self.role_name, 'zappa-permissions')
try:
if policy.policy_document != attach_policy_obj:
print("Updating zappa-permissions policy on " + self.role_name + " IAM Role.")
policy.put(PolicyDocument=attach_policy_s)
policy.put(PolicyDocument=self.attach_policy)

except botocore.client.ClientError:
print("Creating zappa-permissions policy on " + self.role_name + " IAM Role.")
policy.put(PolicyDocument=attach_policy_s)
policy.put(PolicyDocument=self.attach_policy)

if role.assume_role_policy_document != assume_policy_obj and \
set(role.assume_role_policy_document['Statement'][0]['Principal']['Service']) != set(assume_policy_obj['Statement'][0]['Principal']['Service']):
print("Updating assume role policy on " + self.role_name + " IAM Role.")
self.iam_client.update_assume_role_policy(
RoleName=self.role_name,
PolicyDocument=assume_policy_s
PolicyDocument=self.assume_policy
)

return self.credentials_arn
Expand Down

0 comments on commit add819c

Please sign in to comment.