-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdynamodb-sync.py
160 lines (129 loc) · 5.1 KB
/
dynamodb-sync.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
from __future__ import print_function
import json
import boto3
import traceback
from boto3.session import Session
import zipfile
import tempfile
import botocore
import decimal
objmapping = None
code_pipeline = boto3.client('codepipeline')
dynamodb_client = boto3.client('dynamodb')
tablename = 'custom-lookup'
hashkey = 'teamname-environment'
rangekey = 'appname'
def handler(event,context):
try:
job_id = event['CodePipeline.job']['id']
job_data = event['CodePipeline.job']['data']
artifact_data = job_data['inputArtifacts'][0]
params = get_user_params(job_id, job_data)
artifact = params['file_to_sync']
s3 = setup_s3_client(job_data)
objartifact = get_file_from_artifact(s3, artifact_data, artifact)
sampledata = load_data(objartifact)
for item in sampledata:
insert_update_data(item)
put_job_success(job_id, "Success")
except Exception as e:
print('Function failed due to exception.')
print(e)
traceback.print_exc()
put_job_failure(job_id, 'Function exception: ' + str(e))
def load_data(objfile):
mappings = json.loads(objfile, parse_float=decimal.Decimal)
return mappings
def insert_update_data(response):
createtable()
dynamodb_client.put_item(
TableName=tablename,
Item={
hashkey: {'S': response[hashkey]},
rangekey: {'S': response[rangekey]},
'mappings': {'S': str(response['mappings'])}
}
)
def createtable():
try:
dynamodb_client.describe_table(TableName=tablename)
except Exception:
dynamodb_client.create_table(
TableName=tablename,
KeySchema=[
{'AttributeName': hashkey, 'KeyType': 'HASH'},
{'AttributeName': rangekey, 'KeyType': 'RANGE'}
],
AttributeDefinitions=[
{'AttributeName': hashkey, 'AttributeType': 'S'},
{'AttributeName': rangekey, 'AttributeType': 'S'}
],
ProvisionedThroughput={'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5}
)
dynamodb_client.get_waiter('table_exists').wait(TableName=tablename)
def get_file_from_artifact(s3, artifact, file_in_zip):
bucket = artifact['location']['s3Location']['bucketName']
key = artifact['location']['s3Location']['objectKey']
with tempfile.NamedTemporaryFile() as tmp_file:
s3.download_file(bucket, key, tmp_file.name)
with zipfile.ZipFile(tmp_file.name, 'r') as zip:
print(zip.read(file_in_zip))
return zip.read(file_in_zip)
def setup_s3_client(job_data):
key_id = job_data['artifactCredentials']['accessKeyId']
key_secret = job_data['artifactCredentials']['secretAccessKey']
session_token = job_data['artifactCredentials']['sessionToken']
session = Session(aws_access_key_id=key_id,
aws_secret_access_key=key_secret,
aws_session_token=session_token)
return session.client('s3', config=botocore.client.Config(signature_version='s3v4'))
def put_job_success(job, message):
"""Notify CodePipeline of a successful job
Args:
job: The CodePipeline job ID
message: A message to be logged relating to the job status
Raises:
Exception: Any exception thrown by .put_job_success_result()
"""
print('Putting job success')
print(message)
code_pipeline.put_job_success_result(jobId=job)
def put_job_failure(job, message):
"""Notify CodePipeline of a failed job
Args:
job: The CodePipeline job ID
message: A message to be logged relating to the job status
Raises:
Exception: Any exception thrown by .put_job_failure_result()
"""
print('Putting job failure')
print(message)
code_pipeline.put_job_failure_result(jobId=job, failureDetails={'message': message, 'type': 'JobFailed'})
def continue_job_later(job, message):
"""Notify CodePipeline of a continuing job
This will cause CodePipeline to invoke the function again with the
supplied continuation token.
Args:
job: The JobID
message: A message to be logged relating to the job status
continuation_token: The continuation token
Raises:
Exception: Any exception thrown by .put_job_success_result()
"""
# Use the continuation token to keep track of any job execution state
# This data will be available when a new job is scheduled to continue the current execution
continuation_token = json.dumps({'previous_job_id': job})
print('Putting job continuation')
print(message)
code_pipeline.put_job_success_result(jobId=job, continuationToken=continuation_token)
def get_user_params(job_id,job_data):
try:
user_parameters = job_data['actionConfiguration']['configuration']['UserParameters']
decoded_parameters = json.loads(user_parameters)
print(decoded_parameters)
except Exception as e:
put_job_failure(job_id,e)
raise Exception('UserParameters could not be decoded as JSON')
return decoded_parameters
if __name__ == "__main__":
handler(None, None)