Created
November 20, 2015 02:50
-
-
Save graphaelli/3a1e43cb94b3e7e36ce5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from awacs.aws import Action, Condition, Policy, Principal, Statement | |
from awacs.aws import Deny, Everybody, StringNotEquals | |
from awacs.s3 import ARN as S3_ARN | |
import troposphere | |
import troposphere.s3 | |
def resource_namify(resource_name): | |
"""Convert resource name into cloudformation acceptable identifier. | |
>>> resource_namify('a') | |
'A' | |
>>> resource_namify('aa-bb') | |
'AaBb' | |
>>> resource_namify('aa_bb') | |
'AaBb' | |
>>> resource_namify('aa bb') | |
'AaBb' | |
""" | |
return resource_name.replace('-', ' ').replace('_', ' ').title().replace(' ', '') | |
def sse_required(bucket_name): | |
"""Generate IAM Policy statement requiring SSE for S3 buckets.""" | |
return Statement( | |
Sid='DenyUnEncryptedObjectUploads', | |
Effect=Deny, | |
Principal=Principal(Everybody), | |
Action=[Action('s3', 'PutObject')], | |
Resource=[S3_ARN(bucket_name + '/*'),], | |
Condition=Condition( | |
StringNotEquals('s3:x-amz-server-side-encryption', ['AES256']) | |
), | |
) | |
def main(): | |
"""Cloudformation template for bucket policies.""" | |
bucket_policies = { | |
'docker-registry': Policy( | |
Version='2012-10-17', | |
Id=resource_namify('docker-registry bucket policy'), | |
Statement=[ | |
sse_required('docker-registry') | |
] | |
), | |
} | |
t = troposphere.Template() | |
for bucket_name, policy in bucket_policies.items(): | |
t.add_resource( | |
troposphere.s3.BucketPolicy( | |
resource_namify(bucket_name + ' bucket'), | |
Bucket=bucket_name, | |
PolicyDocument=policy, | |
) | |
) | |
print(t.to_json()) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment