Last active
March 11, 2021 12:04
-
-
Save kanghyojun/4cd6843982ee4b5b25b7ed98cd9eb2e4 to your computer and use it in GitHub Desktop.
Extract all required aws policy from terraform provider
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
# requires | |
# - https://github.com/hashicorp/terraform-provider-aws | |
# - riggrep | |
# - awk,sed,sort | |
# - your terraform code | |
# - python 3.6 + | |
pushd your-tf-directory | |
rg resource\ \"aws | sed s/\[\"{\:\.\/]//g | awk '{print "rg '\''conn\\\.([A-Za-z]*)'\'' -r '\'''\$'1'\'' -N -o aws/resource_"$2".go | sort -u | awk '\''{print \""$2"::\"$1}'\''| sed s/^aws_//g"}' > /tmp/something | |
popd | |
pushd terraform-provider-aws/ | |
bash /tmp/something > /tmp/something2 | |
popd | |
cat << EOT > /tmp/t.py | |
import sys | |
r = {} | |
form = '''statement {{ | |
actions = [ | |
{} | |
] | |
effect = "Allow" | |
resources = ["*"] | |
}}'''.format | |
# service name | |
lookup_prefix = { | |
'acm_certificate': 'acm', | |
'acm_certificate_validation': 'acm', | |
'cloudfront_distribution': 'cloudfront', | |
'cloudfront_distribution': 'cloudfront', | |
'db_instance': 'rds', | |
'db_subnet_group': 'rds', | |
'elasticache_cluster': 'elasticache', | |
'elasticache_subnet_group': 'elasticache', | |
'iam_policy': 'iam', | |
'iam_user': 'iam', | |
'iam_user_policy_attachment': 'iam', | |
'iam_role': 'iam', | |
'iam_role_policy_attachment': 'iam', | |
'internet_gateway': 'ec2', | |
'route53_record': 'route53', | |
'route53_zone': 'route53', | |
's3_bucket': 's3', | |
'secretsmanager_secret': 'secretsmanager', | |
'secretsmanager_secret_version': 'secretsmanager', | |
'security_group': 'ec2', | |
'subnet': 'ec2', | |
'vpc': 'ec2', | |
'vpc_peering_connection': 'ec2', | |
} | |
for line in sys.stdin.read().split('\n'): | |
if line.strip(): | |
service, action = line.split(':') | |
service_prefix = lookup_prefix.get(service, service) | |
r.setdefault(service_prefix, set()) | |
r[service_prefix].add('{}:{}'.format(service_prefix, action)) | |
statements = [] | |
for _, actions in sorted(r.items(), key=lambda x: x[0]): | |
delimiter = ',\n{}'.format(' ' * 8) | |
statements.append( | |
form(delimiter.join([f'"{a}"' for a in sorted(list(actions))])) | |
) | |
print(''' | |
data "aws_iam_policy_document" "out" {{ | |
{} | |
}} | |
'''.format( | |
'\n'.join([ | |
'\n'.join( | |
[ | |
'{}{}'.format(' ' * 4,v) for v in s.split('\n') | |
] | |
) | |
for s in statements | |
]) | |
)) | |
EOT | |
cat /tmp/something2 | python /tmp/t.py > out.tf | |
rm /tmp/something2 | |
rm /tmp/t.py | |
rm /tmp/something | |
echo 'out.tf created. check it out!' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment