Usage:
- name: 🔐 AWS -> Secrets | Generate customer secret
ansible.builtin.set_fact:
customer_secrets:
smtp_password: "{{ iam_customer_access_secret | smtp_password(ses_region) }}"| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| import base64 | |
| import hmac | |
| import hashlib | |
| SMTP_REGIONS = [ | |
| 'us-east-2', # US East (Ohio) | |
| 'us-east-1', # US East (N. Virginia) | |
| 'us-west-2', # US West (Oregon) | |
| 'ca-central-1', # Canada (Central) | |
| 'eu-central-1', # Europe (Frankfurt) | |
| 'eu-west-1', # Europe (Ireland) | |
| 'eu-west-2', # Europe (London) | |
| ] | |
| DATE = "11111111" | |
| SERVICE = "ses" | |
| MESSAGE = "SendRawEmail" | |
| TERMINAL = "aws4_request" | |
| VERSION = 0x04 | |
| class PasswordEncoder: | |
| def calculate_key(self, secret_access_key, region): | |
| if region not in SMTP_REGIONS: | |
| raise ValueError(f"The {region} Region doesn't have an SMTP endpoint.") | |
| signature = self.sign(("AWS4" + secret_access_key).encode('utf-8'), DATE) | |
| signature = self.sign(signature, region) | |
| signature = self.sign(signature, SERVICE) | |
| signature = self.sign(signature, TERMINAL) | |
| signature = self.sign(signature, MESSAGE) | |
| signature_and_version = bytes([VERSION]) + signature | |
| smtp_password = base64.b64encode(signature_and_version) | |
| return smtp_password.decode('utf-8') | |
| def sign(self, key, msg): | |
| if isinstance(msg, str): | |
| msg = msg.encode('utf-8') | |
| return hmac.new(key, msg, hashlib.sha256).digest() | |
| class FilterModule(object): | |
| def filters(self): | |
| return { | |
| 'smtp_password': self._smtp_password | |
| } | |
| def _smtp_password(self, aws_access_secret, region): | |
| return PasswordEncoder().calculate_key(aws_access_secret, region) |