-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcloudformation.yaml
More file actions
594 lines (541 loc) · 28.4 KB
/
cloudformation.yaml
File metadata and controls
594 lines (541 loc) · 28.4 KB
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
Description: "Deploy auto-set-fsxn-auto-grow"
#
# This just formats the page that prompts for the parameters when using the AWS Console to deploy your stack.
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: "Deployment Parameters"
Parameters:
- subNetIds
- vpcId
- securityGroupIds
- dynamoDbSecretsTableName
- dynamoDbRegion
- secretsManagerRegion
- createWatchdogAlarm
- snsTopicArn
- createSecretManagerEndpoint
- createFSxEndpoint
- createDynamoDbEndpoint
- routeTableIds
- endpointSecurityGroupIds
- Label:
default: "Auto Size Parameters"
Parameters:
- autoSizeMode
- growThresholdPrecentage
- maxGrowSizePercentage
- shrinkThresholdPrecentage
- minShrinkSizePercentage
- maxWaitTime
Parameters:
subNetIds:
Description: "The subnet IDs where you want the Lambda function to run from. These subnets must have access to management end points of all the FSxNs you want it to manage."
Type: "List<AWS::EC2::Subnet::Id>"
securityGroupIds:
Description: "The security group IDs to associate with the Lambda function. Just needs to allow outbound traffic to port 443 to the AWS API endpoints as well as the FSxNs."
Type: "List<AWS::EC2::SecurityGroup::Id>"
vpcId:
Description: "The VPC ID of the subnets where the Lambda function is run from. This is only needed if you are creating an AWS service VPC endpoint."
Type: String
Default: ""
dynamoDbSecretsTableName:
Description: "The name of the DynamoDB table that contains the list of AWS secrets use to authenicate to the FSxNs with."
Type: String
Default: ""
dynamoDbRegion:
Description: "The region where the DynamoDB table is located."
Type: String
Default: ""
secretsManagerRegion:
Description: "The region where the AWS Secrets are located."
Type: String
Default: ""
createWatchdogAlarm:
Description: "Create a CloudWatch alarm to monitor the this Lambda function."
Type: String
Default: "true"
AllowedValues: ["true", "false"]
snsTopicArn:
Description: "The ARN of the SNS topic to send watchdog alerts to. Only needed if createWatchdogAlarm is set to 'true'."
Type: String
Default: ""
createSecretManagerEndpoint:
Description: "Create a secret manager endpoint."
Type: String
Default: "false"
AllowedValues: ["true", "false"]
createFSxEndpoint:
Description: "Create an FSx endpoint."
Type: String
Default: "false"
AllowedValues: ["true", "false"]
createDynamoDbEndpoint:
Description: "Create a DynamoDB endpoint."
Type: String
Default: "false"
AllowedValues: ["true", "false"]
endpointSecurityGroupIds:
Description: "The security group IDs to associate with the AWS service VPC endpoints. Must allow traffic from from the Lambda function over TCP port 443. This parameter is only needed if you are creating the AWS service VPC endpoints."
Type: CommaDelimitedList
Default: ""
routeTableIds:
Description: "The route table IDs to update to use the DynamoDB endpoint. Since the DynamoDB endpoint is of type 'Gateway' route tables must be updated to use it. This parameter is only needed if createDynamoDbEndpoint is set to 'true'."
Type: CommaDelimitedList
Default: ""
autoSizeMode:
Description: "Defines the mode you want auto size run in. Allowed values are grow, grow and shrink, off."
Type: String
Default: "grow"
AllowedValues: ["grow", "grow_and_shrink", "off"]
growThresholdPrecentage:
Description: "The percentage of the volume that must be used before the volume will grow."
Type: Number
Default: 85
MinValue: 1
MaxValue: 100
shrinkThresholdPrecentage:
Description: "The percentage of the volume that must be in use before the volume will shrink."
Type: Number
Default: 50
MinValue: 1
MaxValue: 100
maxGrowSizePercentage:
Description: "The maximum size the volume can auto grow to expressed in terms of a percentage of the volume size."
Type: Number
Default: 200
MinValue: 1
minShrinkSizePercentage:
Description: "The minimum size the volume can auto shrink to expressed in terms of a percentage of the volume size."
Type: Number
Default: 50
MinValue: 1
maxWaitTime:
Description: "The maximum time, in minutes, to wait for a volume to be created before it will give up and exit."
Type: Number
Default: 60
MinValue: 10
Conditions:
CreateSecretManagerEndpoint: !Equals [!Ref createSecretManagerEndpoint, "true"]
CreateFSxEndpoint: !Equals [!Ref createFSxEndpoint, "true"]
CreateDynamoDbEndpoint: !Equals [!Ref createDynamoDbEndpoint, "true"]
CreateWatchdogAlarm: !Equals [!Ref createWatchdogAlarm, "true"]
Resources:
SecretManagerEndpoint:
Type: AWS::EC2::VPCEndpoint
Condition: CreateSecretManagerEndpoint
Properties:
VpcId: !Ref vpcId
ServiceName: !Sub "com.amazonaws.${AWS::Region}.secretsmanager"
VpcEndpointType: 'Interface'
PrivateDnsEnabled: true
SubnetIds: !Ref subNetIds
SecurityGroupIds: !Ref endpointSecurityGroupIds
FSxEndpoint:
Type: AWS::EC2::VPCEndpoint
Condition: CreateFSxEndpoint
Properties:
VpcId: !Ref vpcId
ServiceName: !Sub "com.amazonaws.${AWS::Region}.fsx"
VpcEndpointType: 'Interface'
PrivateDnsEnabled: true
SubnetIds: !Ref subNetIds
SecurityGroupIds: !Ref endpointSecurityGroupIds
DynamoDbEndpoint:
Type: AWS::EC2::VPCEndpoint
Condition: CreateDynamoDbEndpoint
Properties:
VpcId: !Ref vpcId
ServiceName: !Sub "com.amazonaws.${AWS::Region}.dynamodb"
VpcEndpointType: 'Gateway'
RouteTableIds: !Ref routeTableIds
watchDogAlarm:
Type: "AWS::CloudWatch::Alarm"
Condition: CreateWatchdogAlarm
Properties:
AlarmName: !Sub "auto-set-auto-grow-${AWS::StackName}"
AlarmDescription: !Sub "Watchdog alarm for the auto-set-auto-grow-${AWS::StackName} Lambda function."
Namespace: "AWS/Lambda"
MetricName: "Errors"
Dimensions:
- Name: "FunctionName"
Value: !Sub "auto-set-fsxn-auto-grow-${AWS::StackName}"
Statistic: "Maximum"
Period: 300
EvaluationPeriods: 1
TreatMissingData: "ignore"
Threshold: 0.5
ComparisonOperator: "GreaterThanThreshold"
AlarmActions:
- !Ref snsTopicArn
LambdaRole:
Type: "AWS::IAM::Role"
Properties:
RoleName: !Sub "auto-set-fsxn-auto-grow-${AWS::StackName}"
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Principal:
Service: "lambda.amazonaws.com"
Action: "sts:AssumeRole"
ManagedPolicyArns:
- "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
Policies:
- PolicyName: "LambdaPolicy"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Action:
- "secretsManager:GetSecretValue"
Resource:
- !Sub "arn:aws:secretsmanager:${secretsManagerRegion}:${AWS::AccountId}:secret:*"
- Effect: "Allow"
Action:
- "dynamodb:Scan"
Resource:
- !Sub "arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${dynamoDbSecretsTableName}"
- Effect: "Allow"
Action:
- "fsx:DescribeFileSystems"
- "fsx:DescribeVolumes"
Resource: "*"
- Effect: "Allow"
Action:
- "ec2:CreateNetworkInterface"
- "ec2:DeleteNetworkInterface"
- "ec2:DescribeNetworkInterfaces"
Resource: "*"
LambdaInvokePermission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !GetAtt LambdaFunction.Arn
Action: "lambda:InvokeFunction"
Principal: "events.amazonaws.com"
SourceArn: !GetAtt EventBridgeCreateVolumeRule.Arn
EventBridgeCreateVolumeRule:
Type: "AWS::Events::Rule"
Properties:
Description: "Triggered when a FSx volume is created."
Name: !Sub "auto-set-fsxn-auto-grow-${AWS::StackName}"
EventBusName: "default"
EventPattern:
detail-type:
- "AWS API Call via CloudTrail"
detail:
eventSource:
- "fsx.amazonaws.com"
eventName:
- "CreateVolume"
Targets:
- Arn: !GetAtt LambdaFunction.Arn
Id: "Target_1"
LambdaFunction:
Type: "AWS::Lambda::Function"
Properties:
FunctionName: !Sub "auto-set-fsxn-auto-grow-${AWS::StackName}"
Role: !GetAtt LambdaRole.Arn
VpcConfig:
SecurityGroupIds: !Ref securityGroupIds
SubnetIds: !Ref subNetIds
PackageType: "Zip"
Runtime: "python3.12"
Handler: "index.lambda_handler"
Timeout: !Ref maxWaitTime
Environment:
Variables:
dynamoDbRegion: !Ref dynamoDbRegion
dynamoDbSecretsTableName: !Ref dynamoDbSecretsTableName
secretsManagerRegion: !Ref secretsManagerRegion
autoSizeMode: !Ref autoSizeMode
growThresholdPrecentage: !Ref growThresholdPrecentage
maxGrowSizePercentage: !Ref maxGrowSizePercentage
shrinkThresholdPrecentage: !Ref shrinkThresholdPrecentage
minShrinkSizePercentage: !Ref minShrinkSizePercentage
maxWaitTime: !Ref maxWaitTime
Code:
ZipFile: |
################################################################################
# THIS SOFTWARE IS PROVIDED BY NETAPP "AS IS" AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
# EVENT SHALL NETAPP BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR'
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
################################################################################
################################################################################
# This Lambda function is used to set the auto size feature to 'grow' on a
# volume that was created in an AWS FSx for NetApp ONTAP file system. It is
# expected to be triggered by a CloudWatch event that is generated when a
# volume is created. The function uses the ONTAP API to set the auto size
# mode to 'grow' on the volume therefore it most run within the VPC where the
# FSx for ONTAP file system is located.
#
# Version: v1.1
# Date: 2024-12-06-20:30:19
################################################################################
import json
import time
import urllib3
from urllib3.util import Retry
import logging
import boto3
import os
#
################################################################################
# Configuration settings.
#
# You can either set the variables in the code below, or set environment variables
# with the same name as the variables below. Except for the secretsTable, you must
# set that in the code if you are not going to use DynamoDb to hold your secrets
# table.
#
# NOTE: The environment variables will take precedence over the variables
# set in the code.
#
################################################################################
#
# Create a table of secret names and keys for the username and password for
# each of the FSxIds. In the example below, it shows using the same
# secret for four different FSxIds, but you can set it up to use
# a different secret and/or keys for the username and password for each
# of the FSxId.
#secretsTable = [
# {"fsxId": "fs-0e8d9172fa5XXXXXX", "secretName": "fsxn-credentials", "usernameKey": "username", "passwordKey": "password"},
# {"fsxId": "fs-020de2687bdXXXXXX", "secretName": "fsxn-credentials", "usernameKey": "username", "passwordKey": "password"},
# {"fsxId": "fs-07bcb7ad84aXXXXXX", "secretName": "fsxn-credentials", "usernameKey": "username", "passwordKey": "password"},
# {"fsxId": "fs-077b5ff4195XXXXXX", "secretName": "fsxn-credentials", "usernameKey": "username", "passwordKey": "password"}
# ]
#
# If you don't want to define the secretsTable in this script, you can
# define the following variables to use a DynamoDB table to get the
# secret information.
#
# NOTE: If both the secretsTable, and dynamodbSecretsTableName are defined,
# then the secretsTable will be used.
dynamoDbRegion=None
dynamoDbSecretsTableName=None
#
# Set the region where the secrets are stored.
secretsManagerRegion=None
#
# Set the auto size mode. Supported values are "grow", "grow_shrink", and "off".
autoSizeMode = "grow"
#
# Set the grow-threshold-percentage for the volume. This is the percentage of the volume that must be used before it grows.
growThresholdPercentage = 85
#
# Set the maximum grow size for the volume in terms of the percentage of the provisioned size.
maxGrowSizePercentage = 200
#
# Set the shrink-threshold-percentage for the volume. This is the percentage of the volume that must be free before it shrinks.
shrinkThresholdPercentage = 50
#
# Set the minimum shirtk size for the volume in terms of the percentage of the provisioned size.
minShrinkSizePercentage = 100
#
# Set the time to wait for a volume to get created. This Lambda function will
# loop waiting for the volume to be created on the ONTAP side so it can set
# the auto size parameters. It will wait up to the number of seconds specified
# below before giving up. NOTE: You must set the timeout of this function
# to at least the number of seconds specified here, and probably two times
# the number to account for the time it takes to do the API calls,
# otherwise the Lambda timeout feature will kill it before it is able to
# wait as long you want it to. Also note that the main reason for
# it to take a while for a volume to get created is when multiple are being
# created at the same time. So, if you have automation that might create a lot of
# volumes at the same time, you might need to either adjust this number really
# high, or come up with another way to get the auto size mode.
maxWaitTime=60
################################################################################
# This function sets the configuration variables from environment variables if
# they are defined.
################################################################################
def setConfigurationVariables():
global secretsTable, secretsManagerRegion, autoSizeMode, growThresholdPercentage
global maxGrowSizePercentage, shrinkThresholdPercentage, minShrinkSizePercentage
global dynamoDbRegion, dynamoDbSecretsTableName, secretsTable, maxWaitTime, logger
if os.environ.get('dynamoDbRegion') != None:
dynamoDbRegion = os.environ['dynamoDbRegion']
if os.environ.get('dynamoDbSecretsTableName') != None:
dynamoDbSecretsTableName = os.environ['dynamoDbSecretsTableName']
if os.environ.get('secretsManagerRegion') != None:
secretsManagerRegion = os.environ['secretsManagerRegion']
if os.environ.get('autoSizeMode') != None:
autoSizeMode = os.environ['autoSizeMode']
if os.environ.get('growThresholdPercentage') != None:
growThresholdPercentage = int(os.environ['growThresholdPercentage'])
if os.environ.get('maxGrowSizePercentage') != None:
maxGrowSizePercentage = int(os.environ['maxGrowSizePercentage'])
if os.environ.get('shrinkThresholdPercentage') != None:
shrinkThresholdPercentage = int(os.environ['shrinkThresholdPercentage'])
if os.environ.get('minShrinkSizePercentage') != None:
minShrinkSizePercentage = int(os.environ['minShrinkSizePercentage'])
if os.environ.get('maxWaitTime') != None:
maxWaitTime = int(os.environ['maxWaitTime'])
#
# Check that all the required variables are set.
message = ""
if dynamoDbRegion == None and dynamoDbSecretsTableName == None and 'secretsTable' not in globals():
message += 'Error, you must either define the secretsTable array at the top of this script, or define dynamodbRegion and dynamoDbSecretsTableName environment variables.\n'
if secretsManagerRegion == None:
message += 'Error, you must define the secretsManagerRegion environment variable.\n'
if autoSizeMode == None or autoSizeMode not in ['grow', 'grow_shrink', 'off']:
message += 'Error, you must define the autoSizeMode environment variable to either "grow", "grow_shrink", or "off".\n'
if growThresholdPercentage == None or isinstance(growThresholdPercentage, int) == False or growThresholdPercentage < 0 or growThresholdPercentage > 100:
message += 'Error, you must define the growThresholdPercentage environment variable between 0 and 100.\n'
if maxGrowSizePercentage == None or isinstance(maxGrowSizePercentage, int) == False or maxGrowSizePercentage < 0 or maxGrowSizePercentage > 1000:
message += 'Error, you must define the maxGrowSizePercentage environment variable between 0 and 1000.\n'
if shrinkThresholdPercentage == None or isinstance(shrinkThresholdPercentage, int) == False or shrinkThresholdPercentage < 0 or shrinkThresholdPercentage > 100:
message += 'Error, you must define the shrinkThresholdPercentage environment variable between 0 and 100.\n'
if minShrinkSizePercentage == None or isinstance(minShrinkSizePercentage, int) == False or minShrinkSizePercentage < 0 or minShrinkSizePercentage > 100:
message += 'Error, you must define the minShrinkSizePercentage environment variable between 0 and 100.\n'
if maxWaitTime == None or isinstance(maxWaitTime, int) == False or maxWaitTime < 0 or maxWaitTime > 600:
message += 'Error, you must define the maxWaitTime environment variable between 0 and 600.\n'
if message != "":
logger.critical(message)
raise Exception(message)
################################################################################
# This function is used to obtain the username and password from AWS's Secrets
# Manager for the fsxnId passed in. It returns empty strings if it can't
# find the credentials.
################################################################################
def getCredentials(secretsManagerClient, fsxnId):
global secretsTable
for secretItem in secretsTable:
if secretItem['fsxId'] == fsxnId:
secretsInfo = secretsManagerClient.get_secret_value(SecretId=secretItem['secretName'])
secrets = json.loads(secretsInfo['SecretString'])
username = secrets[secretItem['usernameKey']]
password = secrets[secretItem['passwordKey']]
return (username, password)
return ("", "")
################################################################################
# This function returns the AWS structure for a FSxN volume based on the
# volumeId passed it. It confirms that the volume has been created on the ONTAP
# side by checking that the ResourceARN field equals the volumeARN passed in
# that came from the volume creation event and that the UUID field has been
# populated. It returns None if it can't find the volume.
################################################################################
def getVolumeData(fsxClient, volumeId, volumeARN):
global logger
cnt = 0
while cnt < maxWaitTime:
awsVolume = fsxClient.describe_volumes(VolumeIds=[volumeId])['Volumes'][0]
if awsVolume['ResourceARN'] == volumeARN and awsVolume['OntapConfiguration'].get("UUID") != None:
return awsVolume
logger.debug(f'Looping, getting the UUID {cnt}')
cnt += 1
time.sleep(1)
return None
################################################################################
################################################################################
def lambda_handler(event, context):
global logger, secretsTable
#
# Set up "logging" to appropriately display messages. It can be set it up
# to send messages to a syslog server.
logging.basicConfig(datefmt='%Y-%m-%d_%H:%M:%S', format='%(asctime)s:%(name)s:%(levelname)s:%(message)s', encoding='utf-8')
logger = logging.getLogger("set_fsxn_volume_auto_size")
# logger.setLevel(logging.DEBUG)
logger.setLevel(logging.INFO)
#
# Set the logging level higher for these noisy modules to mute thier messages.
logging.getLogger("botocore").setLevel(logging.WARNING)
logging.getLogger("boto3").setLevel(logging.WARNING)
logging.getLogger("urllib3").setLevel(logging.WARNING)
#
# Set the configuration variables from environment variables if they are defined.
setConfigurationVariables()
#
# If this is an event from a failed call. Report that and return.
if event['detail'].get('errorCode') != None:
logger.warning(f"This is reporting on a error event. Error Code: {event['detail']['errorCode']}. Error Message: {event['detail']['errorMessage']}.")
return
#
# Create a Secrets Manager client.
session = boto3.session.Session()
secretsManagerClient = session.client(service_name='secretsmanager', region_name=secretsManagerRegion)
#
# Disable warning about connecting to servers with self-signed SSL certificates.
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
#
# Set the https retries to 1.
retries = Retry(total=None, connect=1, read=1, redirect=10, status=0, other=0)
http = urllib3.PoolManager(cert_reqs='CERT_NONE', retries=retries)
#
# Read in the secretTable if it is not already defined.
# It is safe to assume dynamoDbRegion and dynamoDbSecretsTableName are defined
# because the setConfigurationVariables function would have errored out if they
# were not.
if 'secretsTable' not in globals():
dynamodbClient = boto3.resource("dynamodb", region_name=dynamoDbRegion)
table = dynamodbClient.Table(dynamoDbSecretsTableName)
response = table.scan()
secretsTable = response["Items"]
#
# Get the FSxN ID, region, volume name, volume ID, and volume ARN from the CloudWatch event.
fsxId = event['detail']['responseElements']['volume']['fileSystemId']
regionName = event['detail']['awsRegion']
volumeName = event['detail']['requestParameters']['name']
volumeId = event['detail']['responseElements']['volume']['volumeId']
volumeARN = event['detail']['responseElements']['volume']['resourceARN']
if fsxId == "" or regionName == "" or volumeId == "" or volumeName == "" or volumeARN == "":
message = "Couldn't obtain the fsxId, region, volume name, volume ID or volume ARN from the CloudWatch evevnt."
logger.critical(message)
return
logger.debug(f'Data from CloudWatch event: FSxID={fsxId}, Region={regionName}, VolumeName={volumeName}, volumeId={volumeId}.')
#
# Get the username and password for the FSxN ID.
(username, password) = getCredentials(secretsManagerClient, fsxId)
if username == "" or password == "":
message = f'No credentials for FSxN ID: {fsxId}.'
logger.critical(message)
return
#
# Build a header that is used for all the ONTAP API requests.
auth = urllib3.make_headers(basic_auth=f'{username}:{password}')
headers = { **auth }
#
# Get the management IP of the FSxN file system.
fsxClient = boto3.client('fsx', region_name = regionName)
fs = fsxClient.describe_file_systems(FileSystemIds = [fsxId])['FileSystems'][0]
fsxnIp = fs['OntapConfiguration']['Endpoints']['Management']['IpAddresses'][0]
if fsxnIp == "":
message = f"Can't find management IP for FSxN file system with an ID of '{fsxId}'."
logger.critical(message)
return
#
# Get the volume UUID and volume size based on the volume ID.
volumeData = getVolumeData(fsxClient, volumeId, volumeARN)
if volumeData == None:
message=f'Failed to get volume information for volumeID: {volumeId}.'
logger.critical(message)
return
volumeUUID = volumeData["OntapConfiguration"]["UUID"]
volumeSizeInMegabytes = volumeData["OntapConfiguration"]["SizeInMegabytes"]
#
# Set the auto grow feature.
try:
endpoint = f'https://{fsxnIp}/api/storage/volumes/{volumeUUID}'
maximum = volumeSizeInMegabytes * maxGrowSizePercentage / 100 * 1024 * 1024
minimum = volumeSizeInMegabytes * minShrinkSizePercentage / 100 * 1024 * 1024
#
# Make sure the minimum is at least 20MB.
if minimum < 20 * 1024 * 1024:
minimum = 20 * 1024 * 1024
data = json.dumps({"autosize": {"mode": autoSizeMode, "grow_threshold": growThresholdPercentage, "maximum": maximum, "minimum": minimum, "shrink_threshold": shrinkThresholdPercentage}})
logger.debug(f'Trying {endpoint} with {data}.')
response = http.request('PATCH', endpoint, headers=headers, timeout=5.0, body=data)
if response.status >= 200 and response.status <= 299:
logger.info(f"Updated the auto size parameters for volume name {volumeName}.")
else:
logger.error(f'API call to {endpoint} failed. HTTP status code: {response.status}. Error message: {response.data}.')
except Exception as err:
logger.critical(f'Failed to issue API against {fsxnIp}. The error messages received: "{err}".')