Skip to content

Instantly share code, notes, and snippets.

@lotyp
Forked from danew/ses-smtp-password.py
Last active October 15, 2023 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lotyp/e06c709e07f1cd92575a001dc8c0a282 to your computer and use it in GitHub Desktop.
Save lotyp/e06c709e07f1cd92575a001dc8c0a282 to your computer and use it in GitHub Desktop.
Ansible filter to create AWS SES SMTP password from aws access secret
#!/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)

Usage:

- name: 🔐 AWS -> Secrets | Generate customer secret
  ansible.builtin.set_fact:
    customer_secrets:
      smtp_password: "{{ iam_customer_access_secret | smtp_password(ses_region) }}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment