ssmbak 0.0.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ssmbak-0.0.2/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 newvoll
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
ssmbak-0.0.2/PKG-INFO ADDED
@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.1
2
+ Name: ssmbak
3
+ Version: 0.0.2
4
+ Summary:
5
+ Author: Old Mouse
6
+ Author-email: github@newvoll.net
7
+ Requires-Python: >=3.9,<4.0
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.9
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Requires-Dist: boto3 (>=1.26.39,<2.0.0)
14
+ Requires-Dist: prettytable (>=3.5.0,<4.0.0)
15
+ Requires-Dist: pyyaml (>=6.0.1,<7.0.0)
16
+ Description-Content-Type: text/markdown
17
+
18
+ # Intro
19
+
20
+ The AWS SSM Parameter Store is simple and great for AWS config bits,
21
+ but it only preserves 100 versions, 0 if the parameter has been
22
+ deleted. To enable point-in-time restore, including deleted versions,
23
+ we use an s3 bucket with versioning enabled as a backend, with
24
+ timestamps in metadata for use with AWS Eventbridge and Lambda. This
25
+ project includes all the pieces to both backup and restore SSM Param
26
+ paths and keys.
27
+
ssmbak-0.0.2/README.md ADDED
@@ -0,0 +1,9 @@
1
+ # Intro
2
+
3
+ The AWS SSM Parameter Store is simple and great for AWS config bits,
4
+ but it only preserves 100 versions, 0 if the parameter has been
5
+ deleted. To enable point-in-time restore, including deleted versions,
6
+ we use an s3 bucket with versioning enabled as a backend, with
7
+ timestamps in metadata for use with AWS Eventbridge and Lambda. This
8
+ project includes all the pieces to both backup and restore SSM Param
9
+ paths and keys.
@@ -0,0 +1,42 @@
1
+ [tool.poetry]
2
+ name = "ssmbak"
3
+ version = "0.0.2"
4
+ description = ""
5
+ authors = ["Old Mouse <github@newvoll.net>"]
6
+ readme = "README.md"
7
+
8
+ [tool.poetry.dependencies]
9
+ python = "^3.9"
10
+ boto3 = "^1.26.39"
11
+ prettytable = "^3.5.0"
12
+ pyyaml = "^6.0.1"
13
+
14
+ [tool.poetry.scripts]
15
+ ssmbak = "ssmbak.cli.cli:main"
16
+ ssmbak-all = "ssmbak.cli.backup_all:main"
17
+ ssmbak-stack = "ssmbak.cli.stack:main"
18
+
19
+ [tool.poetry.group.test.dependencies]
20
+ pytest = "^8.2.1"
21
+ black = "^24.4.2"
22
+ pylint = "^3.2.2"
23
+ pre-commit = "^3.7.1"
24
+ isort = "^5.13.2"
25
+ pdoc3 = "^0.10.0"
26
+ pytype = "^2024.4.11"
27
+ requests = "^2.32.3"
28
+ pysocks = "^1.7.1"
29
+ awscli-local = "^0.22.0"
30
+
31
+ [tool.pytype]
32
+ inputs = ['ssmbak']
33
+
34
+ [build-system]
35
+ requires = ["poetry-core"]
36
+ build-backend = "poetry.core.masonry.api"
37
+
38
+ [tool.isort]
39
+ profile = "black"
40
+
41
+ [tool.pylint]
42
+ ignored-classes = "pytest"
File without changes
@@ -0,0 +1,8 @@
1
+ FROM public.ecr.aws/lambda/python:3.10
2
+
3
+ COPY requirements.txt .
4
+ RUN pip3 install -r requirements.txt
5
+
6
+ COPY ssmbak.py .
7
+
8
+ CMD ["ssmbak.handler"]
File without changes
@@ -0,0 +1 @@
1
+ boto3==1.34.124
@@ -0,0 +1,146 @@
1
+ """AWS Lambda function used to backup SSM param change events."""
2
+
3
+ import json
4
+ import logging
5
+ import os
6
+ import sys
7
+ import urllib.parse
8
+ from datetime import datetime, timezone
9
+ from typing import Union
10
+
11
+ import boto3
12
+ from botocore.exceptions import ClientError
13
+
14
+ LEVEL = os.getenv("LOGLEVEL", "INFO")
15
+ logger = logging.getLogger(__name__)
16
+ logger.setLevel(getattr(logging, LEVEL))
17
+
18
+
19
+ def process_message(body: str) -> dict[str, Union[str, datetime]]:
20
+ """Transforms a message from EventBridge (via SQS) to friendly format.
21
+
22
+ Arguments:
23
+ body: json-formatted string from the event
24
+
25
+ Returns:
26
+
27
+ A dict with the info needed for backup, including time of event.
28
+ {
29
+ "name": "/testyssmbak/023179",
30
+ "type": "SecureString",
31
+ "operation": "Create",
32
+ "time": datetime.datetime(2022, 8, 3, 21, 9, 31, tzinfo=datetime.timezone.utc),
33
+ "description": "fancy description", --OPTIONAL
34
+ }
35
+ """
36
+ logger.debug("body: %s", body)
37
+ message = json.loads(body)
38
+ logger.debug("message: %s", message)
39
+ checktime = datetime.strptime(message["time"], "%Y-%m-%dT%H:%M:%SZ").replace(
40
+ tzinfo=timezone.utc
41
+ )
42
+ action = {
43
+ "name": message["detail"]["name"],
44
+ "type": message["detail"]["type"],
45
+ "operation": message["detail"]["operation"],
46
+ "time": checktime,
47
+ }
48
+ if "description" in message["detail"]:
49
+ action["description"] = message["detail"]["description"]
50
+ return action
51
+
52
+
53
+ def backup(action: dict) -> int:
54
+ """Backs up the processed SSM event to S3, tagging with details.
55
+
56
+ If an SSM param was deleted before it could get processed, it is
57
+ logged and skipped. Tagging is used for metadata like description
58
+ and time of event.
59
+
60
+ Arguments:
61
+ action: dict as returned by process_message.
62
+
63
+ Returns:
64
+ HTTP status code of call to S3 api.
65
+
66
+ """
67
+ try:
68
+ bucketname = os.environ["SSMBAK_BUCKET"]
69
+ except KeyError:
70
+ logger.critical("SSMBAK_BUCKET env var must be set! Dying...")
71
+ sys.exit(1)
72
+ logger.debug("action: %s", action)
73
+ s3 = boto3.client("s3", endpoint_url=os.getenv("AWS_ENDPOINT"))
74
+ ssm = boto3.client("ssm", endpoint_url=os.getenv("AWS_ENDPOINT"))
75
+ kwargs = {"Bucket": bucketname, "Key": action["name"]}
76
+ if action["operation"] == "Delete":
77
+ method = "delete_object"
78
+ else:
79
+ method = "put_object"
80
+ ssm_kwargs = {"Name": action["name"], "WithDecryption": True}
81
+ try:
82
+ response = ssm.get_parameter(**ssm_kwargs)
83
+ except ClientError as e:
84
+ if e.response["Error"]["Code"] == "ParameterNotFound":
85
+ logger.warning("Skipping %s. Deleted before backup.", action["name"])
86
+ return 204
87
+ value = response["Parameter"]["Value"]
88
+ tags = {
89
+ "ssmbakTime": int(action["time"].timestamp()),
90
+ "ssmbakType": action["type"],
91
+ }
92
+ if "description" in action:
93
+ tags["ssmbakDescription"] = action["description"]
94
+ kwargs["Tagging"] = urllib.parse.urlencode(tags)
95
+ logger.debug("kwargs[Tagging]: %s", kwargs["Tagging"])
96
+ kwargs["Body"] = value
97
+ logger.info("%s %s", method, str(kwargs))
98
+ result = getattr(s3, method)(**kwargs)
99
+ return result["ResponseMetadata"]["HTTPStatusCode"]
100
+
101
+
102
+ def process_event(event: dict[str, list[dict[str, Union[str, dict]]]]) -> int:
103
+ """Extracts the body from the event for backup
104
+
105
+ Arguments:
106
+ event: dict of event coming in from EventBridge via SQS
107
+ {
108
+ "Records": [
109
+ {
110
+ "messageId": "07e34a99-5480-4c7c-bc0b-44ea9c74076b",
111
+ "receiptHandle": "XXX=",
112
+ "body": '{"version": "0", "id": "2ada935b-482a-1f19-50a1-21aa9b6b7e2c", "detail-type": "Parameter Store Change", "source": "aws.ssm", "account": "000000000000", "time": "2024-06-08T23:06:33Z", "region": "us-east-1", "resources": ["arn:aws:ssm:us-east-1:000000000000:parameter/testssmbak/bas/desctest"], "detail": {"name": "/testyssmbak/H0PTBA", "description": "fancydesc2", "type": "SecureString", "operation": "Update"}}',
113
+ "attributes": {
114
+ "ApproximateReceiveCount": "1",
115
+ "SentTimestamp": "1660007032420",
116
+ "SenderId": "AIDAJXNJGGKNS7OSV23OI",
117
+ "ApproximateFirstReceiveTimestamp": "1660007032431",
118
+ },
119
+ "messageAttributes": {},
120
+ "md5OfBody": "08a526cb73b963e532b0380646063f3b",
121
+ "eventSource": "aws:sqs",
122
+ "eventSourceARN": "arn:aws:sqs:us-east-1:000000000000:someQ",
123
+ "awsRegion": "us-east-1",
124
+ }
125
+ ]
126
+ }
127
+
128
+ Returns:
129
+ Boolean which is kind of useless.
130
+ """ # pylint: disable=line-too-long
131
+ for record in event["Records"]:
132
+ param_action = process_message(record["body"])
133
+ if param_action["operation"] in ["Create", "Update", "Delete"]:
134
+ res = backup(param_action)
135
+ else:
136
+ logger.warning(
137
+ "skipping %s %s", param_action["operation"], param_action["name"]
138
+ )
139
+ res = 205
140
+ logger.info("result: %s", res)
141
+ return res
142
+
143
+
144
+ def handler(event: dict, context) -> int: # pylint: disable=unused-argument
145
+ """Skipping module import just for context typing."""
146
+ return process_event(event)
File without changes
@@ -0,0 +1,145 @@
1
+ """This script re-updates all SSM Params with optional prefix with the
2
+ same values. Tags are automatically maintained. Its purpose is to
3
+ initialize ssmbak backup store once its Lambda function is in
4
+ place. It will process all the events and back up each reupdated SSM
5
+ Param. Advanced params are not tested.
6
+ """
7
+
8
+ import argparse
9
+ import logging
10
+ import os
11
+ import sys
12
+ from datetime import datetime
13
+
14
+ import boto3
15
+ from botocore.exceptions import ClientError, NoRegionError
16
+
17
+ from ssmbak.backup import ssmbak
18
+ from ssmbak.cli import helpers
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ # pylint: disable=duplicate-code
24
+ parser = argparse.ArgumentParser(
25
+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
26
+ )
27
+ parser.add_argument(
28
+ "-r",
29
+ "--region",
30
+ help="aws region, default same as boto/awscli",
31
+ default="",
32
+ )
33
+ parser.add_argument(
34
+ "-b",
35
+ "--bucket",
36
+ help="bucket that the lambda backs up to",
37
+ default="",
38
+ )
39
+ parser.add_argument(
40
+ "-p",
41
+ "--prefix",
42
+ help="""only perform reupdates under prefix/, still recursively.
43
+ Can have multiple, e.g. -p /this /that""",
44
+ nargs="+",
45
+ default=[],
46
+ )
47
+ parser.add_argument(
48
+ "--do-it",
49
+ help="actually perform the reupdate",
50
+ action="store_true",
51
+ default=False,
52
+ )
53
+ parser.add_argument(
54
+ "-v",
55
+ "--verbose",
56
+ action="store_true",
57
+ default=False,
58
+ help="increase logging verbosity",
59
+ )
60
+ args = parser.parse_args()
61
+ # pylint: enable=duplicate-code
62
+ ssm = boto3.client(
63
+ "ssm",
64
+ endpoint_url=os.getenv("AWS_ENDPOINT"),
65
+ region_name=helpers.sort_region(args.region),
66
+ )
67
+
68
+
69
+ def _get_params(names):
70
+ if names:
71
+ response = ssm.get_parameters(Names=names, WithDecryption=True)
72
+ params = response["Parameters"]
73
+ keyed_params = {}
74
+ for name in {x["Name"] for x in params}:
75
+ key_params = [x for x in params if x["Name"] == name]
76
+ keyed_params[name] = key_params[0]
77
+ else:
78
+ keyed_params = {}
79
+ return keyed_params
80
+
81
+
82
+ def main():
83
+ """Sorts region and bucket before backups."""
84
+ # pylint: disable=duplicate-code
85
+ if args.verbose:
86
+ logging.basicConfig(level=logging.INFO)
87
+ try:
88
+ region = helpers.sort_region(args.region)
89
+ bucketname = helpers.sort_bucket(args.bucket, region)
90
+ backup(bucketname)
91
+ except KeyboardInterrupt:
92
+ logger.fatal("Interrupted")
93
+ sys.exit(1)
94
+ except NoRegionError as e:
95
+ logger.fatal(e)
96
+ logger.fatal(
97
+ "Specify a region 1) as an argument, "
98
+ "2) using env var AWS_DEFAULT_REGION, or "
99
+ "3) region= in ~/.aws/config."
100
+ )
101
+ sys.exit(1)
102
+ except ClientError as e:
103
+ logger.fatal(
104
+ "%s: %s", e.response["Error"]["Code"], e.response["Error"]["Message"]
105
+ )
106
+ sys.exit(1)
107
+ # pylint: enable=duplicate-code
108
+
109
+
110
+ def backup(bucketname):
111
+ """Filters by path, and backs up ssm params using the same function as the lambda.
112
+
113
+ Dry run default, --do-it to actually back up. Doesn't modify any SSM params.
114
+ """
115
+ paginator = ssm.get_paginator("describe_parameters")
116
+ kwargs = {}
117
+ if args.prefix:
118
+ kwargs["ParameterFilters"] = [
119
+ {
120
+ "Key": "Name",
121
+ "Option": "BeginsWith",
122
+ "Values": args.prefix,
123
+ }
124
+ ]
125
+ for page in paginator.paginate(**kwargs):
126
+ params = page["Parameters"]
127
+ for param in params:
128
+ action = {
129
+ "name": param["Name"],
130
+ "type": param["Type"],
131
+ "operation": "Update",
132
+ "time": datetime.now(),
133
+ }
134
+ if "Description" in param:
135
+ action["description"] = param["Description"]
136
+ print(action)
137
+ if args.do_it:
138
+ os.environ["SSMBAK_BUCKET"] = bucketname # ssmbak.py requires this
139
+ ssmbak.backup(action)
140
+ if not args.do_it:
141
+ print()
142
+ print("That's what would have been backed-up. --do-it to actually perform.")
143
+ else:
144
+ print()
145
+ print("Above was backed-up (might be nothing).")
@@ -0,0 +1,194 @@
1
+ """Module to handle Cloudformation stack options for the bucket/lambda."""
2
+
3
+ import logging
4
+ import os
5
+ import re
6
+ import sys
7
+ import time
8
+
9
+ import boto3
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ class Stack:
15
+ """For manipulating cloudformation stacks"""
16
+
17
+ def __init__(self, name, region):
18
+ self.name = name
19
+ self.region = region
20
+ self.cfn = boto3.client(
21
+ "cloudformation",
22
+ endpoint_url=os.getenv("AWS_ENDPOINT"),
23
+ region_name=self.region,
24
+ )
25
+
26
+ def __repr__(self):
27
+ return f"{self.__class__.__name__} {self.name} ({self.region})"
28
+
29
+ def _slurp(self, filename):
30
+ with open(filename, encoding="utf-8") as x:
31
+ f = x.read()
32
+ return f
33
+
34
+ @property
35
+ def bucketname(self):
36
+ """Returns just the bucketname created by the stack."""
37
+ resources = self.resources()
38
+ bucketname = [
39
+ x["physical"] for x in resources if x["type"] == "AWS::S3::Bucket"
40
+ ][0]
41
+ return bucketname
42
+
43
+ @property
44
+ def lambdaname(self):
45
+ """Returns just the lambda created by the stack.
46
+
47
+ Good for logs in the awscli, e.g.
48
+ aws logs tail /aws/lambda/dev-ssmbak-resource-Function-SEmkoVs3DSgs
49
+ """
50
+ resources = self.resources()
51
+ lambdaname = [
52
+ x["physical"] for x in resources if x["type"] == "AWS::Lambda::Function"
53
+ ][0]
54
+ return lambdaname
55
+
56
+ def params(self):
57
+ """Returns a list of the stack's Parameters."""
58
+ response = self.cfn.describe_stacks(StackName=self.name)
59
+ parameters = response["Stacks"][0]["Parameters"]
60
+ for parameter in parameters:
61
+ parameter["region"] = self.region
62
+ return parameters
63
+
64
+ def resources(self, full=False):
65
+ """Returns a list of the stack's resources."""
66
+ # can't paginate
67
+ response = self.cfn.describe_stack_resources(StackName=self.name)
68
+ resources = response["StackResources"]
69
+ if full:
70
+ result = resources
71
+ else:
72
+ result = []
73
+ for resource in resources:
74
+ res = {}
75
+ res["time"] = resource["Timestamp"].strftime("%b %d %Y %H:%M:%S")
76
+ res["status"] = resource["ResourceStatus"]
77
+ res["logical"] = resource["LogicalResourceId"]
78
+ res["physical"] = resource["PhysicalResourceId"]
79
+ res["type"] = resource["ResourceType"]
80
+ result.append(res)
81
+ return result
82
+
83
+ def _kwargify_params(self, params, template_file):
84
+ parameters = [
85
+ {"ParameterKey": name, "ParameterValue": value}
86
+ for name, value in params.items()
87
+ ]
88
+ kwargs = {
89
+ "StackName": self.name,
90
+ "Parameters": parameters,
91
+ "Capabilities": ["CAPABILITY_NAMED_IAM"],
92
+ "TemplateBody": self._slurp(template_file),
93
+ }
94
+ return kwargs
95
+
96
+ def create(self, template_file, params):
97
+ """Creates the stack."""
98
+ logger.debug("params = %s", params)
99
+ kwargs = self._kwargify_params(params, template_file)
100
+ logger.debug(kwargs)
101
+ self.cfn.create_stack(**kwargs)
102
+
103
+ def update(self, template_file, params):
104
+ """Creates the stack."""
105
+ logger.debug("params = %s", params)
106
+ kwargs = self._kwargify_params(params, template_file)
107
+ logger.debug(kwargs)
108
+ self.cfn.update_stack(**kwargs)
109
+
110
+ def events(self, last=None):
111
+ """Returns a list of all stack events."""
112
+ consolidated_events = []
113
+ paginator = self.cfn.get_paginator("describe_stack_events")
114
+ paginated = paginator.paginate(StackName=self.name)
115
+ # wouldbenice: process as we go until a stack _COMPLETE
116
+ events = paginated.build_full_result()["StackEvents"]
117
+ if last:
118
+ events = [x for x in events if x["Timestamp"] > last]
119
+ for event in events:
120
+ deets = {
121
+ "time": event["Timestamp"],
122
+ "logicalId": event["LogicalResourceId"],
123
+ "type": event["ResourceType"],
124
+ "status": event["ResourceStatus"],
125
+ }
126
+ try:
127
+ deets["reason"] = event["ResourceStatusReason"]
128
+ except KeyError:
129
+ deets["reason"] = ""
130
+ consolidated_events.append(deets)
131
+ return consolidated_events
132
+
133
+ def watch(
134
+ self,
135
+ looking_for=r"(_COMPLETE|_FAILED)$",
136
+ come_back=False,
137
+ interval=10,
138
+ ):
139
+ """Will wait for stack operations to end, printing all events along the way."""
140
+ stack_complete = None
141
+ last = None
142
+ while not stack_complete:
143
+ logger.debug("last: %s", last)
144
+ events = self.events(last=last)
145
+ try:
146
+ latest = events[0]
147
+ except IndexError:
148
+ time.sleep(interval)
149
+ continue
150
+ except TypeError:
151
+ break
152
+ if not last:
153
+ events_to_show = [events[0]]
154
+ else:
155
+ events_to_show = events
156
+ try:
157
+ events.reverse()
158
+ except TypeError:
159
+ events = []
160
+ for event in events_to_show:
161
+ line = (
162
+ f"{event['time'].strftime('%m/%d/%y %H:%M:%S')} "
163
+ f"{event['status']} "
164
+ f"{event['logicalId']} "
165
+ f"{event['type']} "
166
+ f"{event['reason']}"
167
+ )
168
+ print(line)
169
+ if event["type"] == "AWS::CloudFormation::Stack" and re.search(
170
+ looking_for, event["status"]
171
+ ):
172
+ # wouldbenice: printemall first, then puke on failure
173
+ if re.search(r"(ROLLBACK_COMPLETE|FAILED)$", event["status"]):
174
+ if come_back:
175
+ return True
176
+ sys.exit(1) # don't know
177
+ return event["status"] # ugly
178
+ last = latest["time"]
179
+ time.sleep(interval)
180
+ try:
181
+ return latest
182
+ except UnboundLocalError:
183
+ return None
184
+
185
+ def status(self):
186
+ """Current operational status of the stack."""
187
+ result = None
188
+ for event in self.events():
189
+ if result:
190
+ break
191
+ if event["type"] == "AWS::CloudFormation::Stack":
192
+ result = event["status"]
193
+ break
194
+ return result