ssmbak 0.0.2__py3-none-any.whl
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/__init__.py +0 -0
- ssmbak/backup/Dockerfile +8 -0
- ssmbak/backup/__init__.py +0 -0
- ssmbak/backup/requirements.txt +1 -0
- ssmbak/backup/ssmbak.py +146 -0
- ssmbak/cli/__init__.py +0 -0
- ssmbak/cli/backup_all.py +145 -0
- ssmbak/cli/cfn.py +194 -0
- ssmbak/cli/cli.py +124 -0
- ssmbak/cli/helpers.py +59 -0
- ssmbak/cli/stack.py +94 -0
- ssmbak/data/cfn.yml +209 -0
- ssmbak/restore/__init__.py +0 -0
- ssmbak/restore/actions.py +277 -0
- ssmbak/restore/aws.py +341 -0
- ssmbak/typing.py +9 -0
- ssmbak-0.0.2.dist-info/LICENSE +21 -0
- ssmbak-0.0.2.dist-info/METADATA +27 -0
- ssmbak-0.0.2.dist-info/RECORD +21 -0
- ssmbak-0.0.2.dist-info/WHEEL +4 -0
- ssmbak-0.0.2.dist-info/entry_points.txt +5 -0
ssmbak/__init__.py
ADDED
|
File without changes
|
ssmbak/backup/Dockerfile
ADDED
|
File without changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
boto3==1.34.124
|
ssmbak/backup/ssmbak.py
ADDED
|
@@ -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)
|
ssmbak/cli/__init__.py
ADDED
|
File without changes
|
ssmbak/cli/backup_all.py
ADDED
|
@@ -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).")
|
ssmbak/cli/cfn.py
ADDED
|
@@ -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
|
ssmbak/cli/cli.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""A CLI interface to the ssmbak library. It's barely a CLI interface
|
|
2
|
+
and more of a wrapper to the ssmbak lib. Its main function is to
|
|
3
|
+
restore an ssm path, either key or path (recursive or not) to their
|
|
4
|
+
state at a point in time (checktime).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import logging
|
|
9
|
+
import pprint
|
|
10
|
+
import sys
|
|
11
|
+
from datetime import datetime, timezone
|
|
12
|
+
from textwrap import wrap
|
|
13
|
+
|
|
14
|
+
from botocore.exceptions import ClientError, NoRegionError
|
|
15
|
+
from prettytable import PrettyTable
|
|
16
|
+
|
|
17
|
+
from ssmbak.cli import helpers
|
|
18
|
+
from ssmbak.restore.actions import Path
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
pp = pprint.PrettyPrinter(indent=4)
|
|
22
|
+
parser = argparse.ArgumentParser(
|
|
23
|
+
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
|
|
24
|
+
)
|
|
25
|
+
parser.add_argument("command", help="one of preview or restore")
|
|
26
|
+
parser.add_argument(
|
|
27
|
+
"path",
|
|
28
|
+
help="ssm/s3 path/ or key",
|
|
29
|
+
)
|
|
30
|
+
parser.add_argument(
|
|
31
|
+
"checktime",
|
|
32
|
+
help="""point-in-time (UTC) to retrieve latest values, e.g. 2022-08-03T21:10:00""",
|
|
33
|
+
)
|
|
34
|
+
parser.add_argument(
|
|
35
|
+
"-r",
|
|
36
|
+
"--region",
|
|
37
|
+
help="aws region, default same as boto/awscli",
|
|
38
|
+
default="",
|
|
39
|
+
)
|
|
40
|
+
parser.add_argument(
|
|
41
|
+
"-b",
|
|
42
|
+
"--bucket",
|
|
43
|
+
help="bucket that the lambda backs up to",
|
|
44
|
+
default="",
|
|
45
|
+
)
|
|
46
|
+
parser.add_argument(
|
|
47
|
+
"-R",
|
|
48
|
+
"--recursive",
|
|
49
|
+
action="store_true",
|
|
50
|
+
default=False,
|
|
51
|
+
help="recursive, only for actual path not key",
|
|
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
|
+
checktime = datetime.strptime(args.checktime, "%Y-%m-%dT%H:%M:%S").replace(
|
|
62
|
+
tzinfo=timezone.utc
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def main():
|
|
67
|
+
"""Checks for necessary confs, invokes ssmbak method Path.command,
|
|
68
|
+
and tries to print out a nice table of results..
|
|
69
|
+
"""
|
|
70
|
+
if args.verbose:
|
|
71
|
+
logging.basicConfig(level=logging.INFO)
|
|
72
|
+
try:
|
|
73
|
+
region = helpers.sort_region(args.region)
|
|
74
|
+
bucketname = helpers.sort_bucket(args.bucket, region)
|
|
75
|
+
result = _do_path(bucketname, region)
|
|
76
|
+
_print_outs(result)
|
|
77
|
+
except KeyboardInterrupt:
|
|
78
|
+
logger.fatal("Interrupted")
|
|
79
|
+
sys.exit(1)
|
|
80
|
+
except ClientError as e:
|
|
81
|
+
logger.fatal(
|
|
82
|
+
"%s: %s", e.response["Error"]["Code"], e.response["Error"]["Message"]
|
|
83
|
+
)
|
|
84
|
+
if e.response["Error"]["Code"] == "ParameterNotFound":
|
|
85
|
+
logger.fatal("Couldn't find SSM bucket param set by the stack.")
|
|
86
|
+
sys.exit(1)
|
|
87
|
+
except NoRegionError as e:
|
|
88
|
+
logger.fatal(e)
|
|
89
|
+
logger.fatal(
|
|
90
|
+
"Specify a region 1) as an argument, "
|
|
91
|
+
"2) using env var AWS_DEFAULT_REGION, or "
|
|
92
|
+
"3) region= in ~/.aws/config."
|
|
93
|
+
)
|
|
94
|
+
sys.exit(1)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _do_path(bucketname, region):
|
|
98
|
+
path = Path(args.path, checktime, region, bucketname, recurse=args.recursive)
|
|
99
|
+
return getattr(path, args.command)()
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _limit_string(val, limit=40):
|
|
103
|
+
return "\n".join(wrap(str(val), limit))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _print_outs(outs):
|
|
107
|
+
try:
|
|
108
|
+
keys = set().union(*outs)
|
|
109
|
+
for out in outs:
|
|
110
|
+
for key in keys - out.keys():
|
|
111
|
+
out[key] = ""
|
|
112
|
+
table = PrettyTable()
|
|
113
|
+
headings = list(outs[0])
|
|
114
|
+
table.field_names = headings
|
|
115
|
+
table.align = "l"
|
|
116
|
+
for out in outs:
|
|
117
|
+
if out:
|
|
118
|
+
table.add_row([_limit_string(out[x]) for x in headings])
|
|
119
|
+
if len(table.rows) > 0:
|
|
120
|
+
print(table)
|
|
121
|
+
except (TypeError, AttributeError): # pprint if table trouble
|
|
122
|
+
pp.pprint(outs)
|
|
123
|
+
except (KeyError, IndexError): # for none
|
|
124
|
+
pass
|
ssmbak/cli/helpers.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""shared functions"""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import boto3
|
|
8
|
+
import yaml
|
|
9
|
+
|
|
10
|
+
logger = logging.getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _slurp(filename):
|
|
14
|
+
with open(filename, encoding="utf-8") as x:
|
|
15
|
+
f = x.read()
|
|
16
|
+
return f
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _any_constructor(loader, tag_suffix, node): # pylint: disable=unused-argument
|
|
20
|
+
if isinstance(node, yaml.MappingNode):
|
|
21
|
+
return loader.construct_mapping(node)
|
|
22
|
+
if isinstance(node, yaml.SequenceNode):
|
|
23
|
+
return loader.construct_sequence(node)
|
|
24
|
+
return loader.construct_scalar(node)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def sort_bucket(bucketname, region):
|
|
28
|
+
"""Figures out where the backup bucket is, first by arg then by SSM Param.
|
|
29
|
+
|
|
30
|
+
The stack created by ssmbak-stack create <STACKNAME> will write that param.
|
|
31
|
+
"""
|
|
32
|
+
if bucketname:
|
|
33
|
+
res = bucketname
|
|
34
|
+
logger.info("%s set by arg", res)
|
|
35
|
+
else:
|
|
36
|
+
template_dir = Path(__file__).parent.parent
|
|
37
|
+
template_file = f"{template_dir}/data/cfn.yml"
|
|
38
|
+
yaml.add_multi_constructor("", _any_constructor, Loader=yaml.SafeLoader)
|
|
39
|
+
template = yaml.safe_load(_slurp(template_file))
|
|
40
|
+
key = template["Resources"]["BucketParam"]["Properties"]["Name"]
|
|
41
|
+
ssm = boto3.client(
|
|
42
|
+
"ssm", endpoint_url=os.getenv("AWS_ENDPOINT"), region_name=region
|
|
43
|
+
)
|
|
44
|
+
bucket_param = ssm.get_parameter(Name=key)
|
|
45
|
+
res = bucket_param["Parameter"]["Value"]
|
|
46
|
+
logger.info("%s set by SSM param %s", res, bucket_param["Parameter"]["Name"])
|
|
47
|
+
return res
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def sort_region(region):
|
|
51
|
+
"""Set region if provided, see if boto can figure it out otherwise."""
|
|
52
|
+
if region:
|
|
53
|
+
logger.info("%s set by arg", region)
|
|
54
|
+
return region
|
|
55
|
+
session = boto3.session.Session()
|
|
56
|
+
if session.region_name:
|
|
57
|
+
logger.info("%s set by session", session.region_name)
|
|
58
|
+
return session.region_name
|
|
59
|
+
return None
|