-
Notifications
You must be signed in to change notification settings - Fork 3
/
deploy_component_version.py
executable file
·182 lines (145 loc) · 7.51 KB
/
deploy_component_version.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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Deploys a component version to the Greengrass core device target. This should be
called after "gdk component build" and "gdk component publish".
Example execution:
python3 deploy_component_version.py 1.0.0 MyCoreDeviceThingName
"""
import argparse
import json
import sys
import time
import boto3
from libs.secret import Secret
from libs.gdk_config import GdkConfig
ACCOUNT = boto3.client('sts').get_caller_identity().get('Account')
COMPONENT_DOCKER_APPLICATION_MANAGER = 'aws.greengrass.DockerApplicationManager'
COMPONENT_SECRET_MANAGER = 'aws.greengrass.SecretManager'
def get_newest_component_version(component_name):
""" Gets the newest version of a component """
component_arn = 'arn:aws:greengrass:{}:aws:components:{}'.format(gdk_config.region(), component_name)
try:
response = greengrassv2_client.list_component_versions(arn=component_arn)
except Exception as e:
print('Failed to get component versions for {}\nException: {}'.format(component_name, e))
sys.exit(1)
return response['componentVersions'][0]['componentVersion']
def get_deployment():
""" Gets the details of the existing deployment """
thing_arn = 'arn:aws:iot:{}:{}:thing/{}'.format(gdk_config.region(), ACCOUNT, args.coreDeviceThingName)
print('Searching for existing single Thing deployment for {}'.format(args.coreDeviceThingName))
try:
# Get the latest deployment for the specified core device name
response = greengrassv2_client.list_deployments(
targetArn=thing_arn,
historyFilter='LATEST_ONLY',
maxResults=1
)
except Exception as e:
print('Failed to list deployments\nException: {}'.format(e))
sys.exit(1)
# We expect to update an existing deployment, not create a new one
if len(response['deployments']) == 0:
print('No existing Thing deployment for this Core Device. Abort.')
sys.exit(1)
# We expect at most one result in the list
deployment_id = response['deployments'][0]['deploymentId']
try:
response = greengrassv2_client.get_deployment(deploymentId=deployment_id)
if 'deploymentName' in response:
print('Found existing named deployment "{}"'.format(response['deploymentName']))
else:
print('Found existing unnamed deployment {}'.format(deployment_id))
except Exception as e:
print('Failed to get deployment\nException: {}'.format(e))
sys.exit(1)
return response
def update_deployment(deployment):
""" Updates the current deplyment with the desired versions of the components """
# If Docker Application manager is not in the deployment, add the latest version
if COMPONENT_DOCKER_APPLICATION_MANAGER not in deployment['components']:
version = get_newest_component_version(COMPONENT_DOCKER_APPLICATION_MANAGER)
print('Adding {} {} to the deployment'.format(COMPONENT_DOCKER_APPLICATION_MANAGER, version))
deployment['components'].update({COMPONENT_DOCKER_APPLICATION_MANAGER: {'componentVersion': version}})
# If Secret manager is not in the deployment, add the latest version
if COMPONENT_SECRET_MANAGER not in deployment['components']:
version = get_newest_component_version(COMPONENT_SECRET_MANAGER)
print('Adding {} {} to the deployment'.format(COMPONENT_SECRET_MANAGER, version))
cloud_secrets = [{"arn": secret_value['ARN']}]
else:
# If it's already in the deployment, use the current version
version = deployment['components'][COMPONENT_SECRET_MANAGER]['componentVersion']
merge_str = deployment['components'][COMPONENT_SECRET_MANAGER]['configurationUpdate']['merge']
cloud_secrets = json.loads(merge_str)['cloudSecrets']
# Add our secret to the list of configured secrets
if secret_value['ARN'] not in merge_str:
print('Adding secret {} to Secret Manager configuration'.format(secret_value['ARN']))
cloud_secrets.append({"arn": secret_value['ARN']})
# Update Secret Manager with the appropriate version and configuration
deployment['components'].update({COMPONENT_SECRET_MANAGER: {
'componentVersion': version,
'configurationUpdate': {'merge': '{"cloudSecrets":' + json.dumps(cloud_secrets) + '}'}}
})
# Add or update our component to the specified version
if gdk_config.name() not in deployment['components']:
print('Adding {} {} to the deployment'.format(gdk_config.name(), args.version))
else:
print('Updating deployment with {} {}'.format(gdk_config.name(), args.version))
deployment['components'].update({gdk_config.name(): {'componentVersion': args.version}})
def create_deployment(deployment):
""" Creates a deployment of the component to the given Greengrass core device """
# Give the deployment a name if it doesn't already have one
if 'deploymentName' in deployment:
deployment_name = deployment['deploymentName']
else:
deployment_name = 'Deployment for {}'.format(args.coreDeviceThingName)
print('Renaming deployment to "{}"'.format(deployment_name))
try:
# We deploy to a single Thing and hence without an IoT job configuration
# Deploy with default deployment policies and no tags
response = greengrassv2_client.create_deployment(
targetArn=deployment['targetArn'],
deploymentName=deployment_name,
components=deployment['components']
)
except Exception as e:
print('Failed to create deployment\nException: {}'.format(e))
sys.exit(1)
return response['deploymentId']
def wait_for_deployment_to_finish(deploy_id):
""" Waits for the deployment to complete """
deployment_status = 'ACTIVE'
snapshot = time.time()
while deployment_status == 'ACTIVE' and (time.time() - snapshot) < 300:
try:
response = greengrassv2_client.get_deployment(deploymentId=deploy_id)
deployment_status = response['deploymentStatus']
except Exception as e:
print('Failed to get deployment\nException: {}'.format(e))
sys.exit(1)
if deployment_status == 'COMPLETED':
print('Deployment completed successfully in {:.1f} seconds'.format(time.time() - snapshot))
elif deployment_status == 'ACTIVE':
print('Deployment timed out')
sys.exit(1)
else:
print('Deployment error: {}'.format(deployment_status))
sys.exit(1)
gdk_config = GdkConfig()
parser = argparse.ArgumentParser(description='Deploy a version of the {} component'.format(gdk_config.name()))
parser.add_argument('version', help='Version of the component to be deployed (Example: 1.0.0)')
parser.add_argument('coreDeviceThingName', help='Greengrass core device to deploy to')
args = parser.parse_args()
greengrassv2_client = boto3.client('greengrassv2', region_name=gdk_config.region())
secret = Secret(gdk_config.region())
secret_value = secret.get()
print('Attempting deployment of version {} to core device {}'.format(args.version, args.coreDeviceThingName))
# Get the latest (single Thing) deployment for the specified core device
current_deployment = get_deployment()
# Update the components of the current deployment
update_deployment(current_deployment)
# Create a new deployment
new_deployment_id = create_deployment(current_deployment)
print('Deployment {} successfully created. Waiting for completion ...'.format(new_deployment_id))
wait_for_deployment_to_finish(new_deployment_id)