Skip to content

Commit 7de1989

Browse files
committed
Added the ability to retrieve the secretsTable from a DynamoDB.
1 parent 2f5fae5 commit 7de1989

File tree

3 files changed

+255
-6
lines changed

3 files changed

+255
-6
lines changed

Management-Utilities/auto_set_fsxn_auto_grow/README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ The Lambda function doesn't leverage that many AWS services, so only a few permi
2727
| Allow:logs:CreateLogGroup | arn:aws:logs:<LAMBDA_REGION>:<ACCOUNT_ID>:* | This is required so you can get logs from the Lambda function. |
2828
| Allow:logs:CreateLogStream<BR>Allow:logs:PutLogEvents | arn:aws:logs:<LAMBDA_REGION>:<ACCOUNT_ID>:/aws/lambda/<LAMBDA_FUNCTION_NAME>:* | This is required so you can get logs from the Lambda function. |
2929
| Allow:secretsmanager:GetSecretValue | <ARN_OF_SECRET_WITHIN_SECRETS_MANAGER> | This is required so the Lambda function can get the credentials for the FSxN file system. |
30+
| Allow:dynamodb:Scan | <ARN_OF_DYNAMODB_TABLE> | This is optional, depending on if you put your secretsTable in a DynamoDB. |
3031
| Allow:fsx:DescribeFileSystems<BR>Allow:fsx:DescribeVolumes | * | You can't limit these API. They are required to get information regarding the file system and volumes. |
3132
| Allow:ec2:CreateNetworkInterface<BR>Allow:ec2:DeleteNetworkInterface<BR>Allow:ec2:DescribeNetworkInterfaces | * | Since the Lambda function is going to run within your VPC, it has to be able to create a network interface to communicate with the FSxn file system API. |
3233

@@ -40,6 +41,7 @@ FSxN file system is attached to.
4041

4142
- FSx
4243
- SecretsManager
44+
- DynamoDB - This one can be a Gateway endpoint.
4345

4446
### Create the Lambda Function
4547
Create a Lambda function with the following parameters:
@@ -60,6 +62,12 @@ is a dictionary with the following keys:
6062
- secretName - The name of the secret in Secrets Manager.
6163
- usernameKey - The name of the key in the secret that contains the username.
6264
- passwordKey - The name of the key in the secret that contains the password.
65+
66+
**NOTE:** Instead of defining the secretsTable in the script, you can define
67+
dynamodbSecretsTableName and dynamodbRegion and the script will read in the
68+
secretsTable information from the specified DynamoDB table. The table should have
69+
the same fields as the secretsTable defined above.
70+
6371
- secretsManagerRegion - Defines the region where your secrets are stored.
6472
- autoSizeMode - Defines the auto size mode you want to set the volume to. Valid values are:
6573
- grow - The volume will automatically grow when it reaches the grow threshold.
Lines changed: 218 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,218 @@
1+
################################################################################
2+
# THIS SOFTWARE IS PROVIDED BY NETAPP "AS IS" AND ANY EXPRESS OR IMPLIED
3+
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
4+
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
5+
# EVENT SHALL NETAPP BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
6+
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
7+
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
8+
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
9+
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR'
10+
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
11+
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
12+
################################################################################
13+
14+
################################################################################
15+
# This Lambda function is used to set the auto size feature to 'grow' on a
16+
# volume that was created in an AWS FSx for NetApp ONTAP file system. It is
17+
# expected to be triggered by a CloudWatch event that is generated when a
18+
# volume is created. The function uses the ONTAP API to set the auto size
19+
# mode to 'grow' on the volume therefore it most run within the VPC where the
20+
# FSx for ONTAP file system is located.
21+
################################################################################
22+
23+
import json
24+
import time
25+
import urllib3
26+
from urllib3.util import Retry
27+
import logging
28+
import boto3
29+
#
30+
# Create a table of secret names and keys for the username and password for
31+
# each of the FSxIds. In the example below, it shows using the same
32+
# secret for four differnt FSxIds, but you can set it up to use
33+
# a different secret and/or keys for the username and password for each
34+
# of the FSxId.
35+
#secretsTable = [
36+
# {"fsxId": "fs-0e8d9172fa5XXXXXX", "secretName": "fsxn-credentials", "usernameKey": "fsxn-username", "passwordKey": "fsxn-password"},
37+
# {"fsxId": "fs-020de2687bdXXXXXX", "secretName": "fsxn-credentials", "usernameKey": "fsxn-username", "passwordKey": "fsxn-password"},
38+
# {"fsxId": "fs-07bcb7ad84aXXXXXX", "secretName": "fsxn-credentials", "usernameKey": "fsxn-username", "passwordKey": "fsxn-password"},
39+
# {"fsxId": "fs-077b5ff4195XXXXXX", "secretName": "fsxn-credentials", "usernameKey": "fsxn-username", "passwordKey": "fsxn-password"}
40+
# ]
41+
#
42+
# If you don't want to define the secretsTable in this script, you can
43+
# define the following variables to use a DynamoDB table to get the
44+
# secret information.
45+
#
46+
# NOTE: If both the secretsTable, and dynamodbSecretsTableName are defined,
47+
# the secretsTable will be used.
48+
dynamodbRegion="us-west-2"
49+
dynamodbSecretsTableName="keith_secrets"
50+
#
51+
# Set the region where the secrets are stored.
52+
secretsManagerRegion="us-west-2"
53+
#
54+
# Set the auto size mode. Supported values are "grow", "grow_shrink", and "off".
55+
autoSizeMode = "grow"
56+
#
57+
# Set the grow-threshold-percentage for the volume. This is the percentage of the volume that must be used before it grows.
58+
growThresholdPercentage = 85
59+
#
60+
# Set the maximum grow size for the volume in terms of the percentage of the provisioned size.
61+
maxGrowSizePercentage = 200
62+
#
63+
# Set the shrink-threshold-percentage for the volume. This is the percentage of the volume that must be free before it shrinks.
64+
shrinkThresholdPercentage = 50
65+
#
66+
# Set the minimum shirtk size for the volume in terms of the percentage of the provisioned size.
67+
minShrinkSizePercentage = 100
68+
#
69+
# Set the iime to wait for a volume to get created. This Lambda function will
70+
# loop waiting for the volume to be created on the ONTAP side so it can set
71+
# the auto size parameters. It will wait up to the number of seconds specified
72+
# below before giving up. NOTE: You must set the timeout of this function
73+
# to at least the number of seconds specified here, and probably two times
74+
# the number to account for the time it takes to do the API calls,
75+
# otherwise the Lambda timeout feature will kill it before it is able to
76+
# wait as long you want it to. Also note that the main reason for
77+
# it to take a while for a volume to get created is when multiple are being
78+
# created at the same time. So, if you have automation that might create a lot of
79+
# volumes at the same time, you might need to either adjust this number really
80+
# high, or come up with another way to get the auto size mode.
81+
maxWaitTime=60
82+
83+
################################################################################
84+
# This function is used to obtain the username and password from AWS's Secrets
85+
# Manager for the fsxnId passed in. It returns empty strings if it can't
86+
# find the credentials.
87+
################################################################################
88+
def getCredentials(secretsManagerClient, fsxnId):
89+
90+
for secretItem in secretsTable:
91+
if secretItem['fsxId'] == fsxnId:
92+
secretsInfo = secretsManagerClient.get_secret_value(SecretId=secretItem['secretName'])
93+
secrets = json.loads(secretsInfo['SecretString'])
94+
username = secrets[secretItem['usernameKey']]
95+
password = secrets[secretItem['passwordKey']]
96+
return (username, password)
97+
return ("", "")
98+
99+
################################################################################
100+
# This function returns the AWS structure for a FSxN volume based on the
101+
# volumeId passed it. It confirms that the volume has been created on the ONTAP
102+
# side by checking that the ResourceARN field equals the volumeARN passed in
103+
# that came from the volume creation event and that the UUID field has been
104+
# populated. It returns None if it can't find the volume.
105+
################################################################################
106+
def getVolumeData(fsxClient, volumeId, volumeARN):
107+
108+
global logger
109+
110+
cnt = 0
111+
while cnt < maxWaitTime:
112+
awsVolume = fsxClient.describe_volumes(VolumeIds=[volumeId])['Volumes'][0]
113+
if awsVolume['ResourceARN'] == volumeARN and awsVolume['OntapConfiguration'].get("UUID") != None:
114+
return awsVolume
115+
logger.debug(f'Looping, getting the UUID {cnt}')
116+
cnt += 1
117+
time.sleep(1)
118+
119+
return None
120+
121+
################################################################################
122+
################################################################################
123+
def lambda_handler(event, context):
124+
125+
global logger, secretsTable
126+
#
127+
# Set up "logging" to appropriately display messages. It can be set it up
128+
# to send messages to a syslog server.
129+
logging.basicConfig(datefmt='%Y-%m-%d_%H:%M:%S', format='%(asctime)s:%(name)s:%(levelname)s:%(message)s', encoding='utf-8')
130+
logger = logging.getLogger("set_fsxn_volume_auto_size")
131+
# logger.setLevel(logging.DEBUG)
132+
logger.setLevel(logging.INFO)
133+
#
134+
# Set the logging level higher for these noisy modules to mute thier messages.
135+
logging.getLogger("botocore").setLevel(logging.WARNING)
136+
logging.getLogger("boto3").setLevel(logging.WARNING)
137+
logging.getLogger("urllib3").setLevel(logging.WARNING)
138+
#
139+
# Create a Secrets Manager client.
140+
session = boto3.session.Session()
141+
secretsManagerClient = session.client(service_name='secretsmanager', region_name=secretsManagerRegion)
142+
#
143+
# Disable warning about connecting to servers with self-signed SSL certificates.
144+
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
145+
#
146+
# Set the https retries to 1.
147+
retries = Retry(total=None, connect=1, read=1, redirect=10, status=0, other=0) # pylint: disable=E1123
148+
http = urllib3.PoolManager(cert_reqs='CERT_NONE', retries=retries)
149+
#
150+
# Read in the secretTable if it is not already defined.
151+
if 'dynamodbRegion' in globals():
152+
dynamodbClient = boto3.resource("dynamodb", region_name=dynamodbRegion) # pylint: disable=E0602
153+
154+
if 'secretsTable' not in globals():
155+
if 'dynamodbRegion' not in globals() or 'dynamodbSecretsTableName' not in globals():
156+
raise Exception('Error, you must either define the secretsTable array at the top of this script, or define dynamodbRegion and dynamodbSecretsTableName')
157+
158+
table = dynamodbClient.Table(dynamodbSecretsTableName) # pylint: disable=E0602
159+
160+
response = table.scan()
161+
secretsTable = response["Items"]
162+
#
163+
# Get the FSxN ID, region, volume name, volume ID, and volume ARN from the CloudWatch event.
164+
fsxId = event['detail']['responseElements']['volume']['fileSystemId']
165+
regionName = event['detail']['awsRegion']
166+
volumeName = event['detail']['requestParameters']['name']
167+
volumeId = event['detail']['responseElements']['volume']['volumeId']
168+
volumeARN = event['detail']['responseElements']['volume']['resourceARN']
169+
if fsxId == "" or regionName == "" or volumeId == "" or volumeName == "" or volumeARN == "":
170+
message = "Couldn't obtain the fsxId, region, volume name, volume ID or volume ARN from the CloudWatch evevnt."
171+
logger.critcal(message)
172+
raise Exception(message)
173+
174+
logger.debug(f'Data from CloudWatch event: FSxID={fsxId}, Region={regionName}, VolumeName={volumeName}, volumeId={volumeId}.')
175+
#
176+
# Get the username and password for the FSxN ID.
177+
(username, password) = getCredentials(secretsManagerClient, fsxId)
178+
if username == "" or password == "":
179+
message = f'No credentials for FSxN ID: {fsxId}.'
180+
logger.critical(message)
181+
raise Exception(message)
182+
#
183+
# Build a header that is used for all the ONTAP API requests.
184+
auth = urllib3.make_headers(basic_auth=f'{username}:{password}')
185+
headers = { **auth }
186+
#
187+
# Get the management IP of the FSxN file system.
188+
fsxClient = boto3.client('fsx', region_name = regionName)
189+
fs = fsxClient.describe_file_systems(FileSystemIds = [fsxId])['FileSystems'][0]
190+
fsxnIp = fs['OntapConfiguration']['Endpoints']['Management']['IpAddresses'][0]
191+
if fsxnIp == "":
192+
message = f"Can't find management IP for FSxN file system with an ID of '{fsxId}'."
193+
logger.critical(message)
194+
raise Exception(message)
195+
#
196+
# Get the volume UUID and volume size based on the volume ID.
197+
volumeData = getVolumeData(fsxClient, volumeId, volumeARN)
198+
if volumeData == None:
199+
message=f'Failed to get volume information for volumeID: {volumeId}.'
200+
logger.critical(message)
201+
raise Exception(message)
202+
volumeUUID = volumeData["OntapConfiguration"]["UUID"]
203+
volumeSizeInMegabytes = volumeData["OntapConfiguration"]["SizeInMegabytes"]
204+
#
205+
# Set the auto grow feature.
206+
try:
207+
endpoint = f'https://{fsxnIp}/api/storage/volumes/{volumeUUID}'
208+
maximum = volumeSizeInMegabytes * maxGrowSizePercentage / 100 * 1024 * 1024
209+
minimum = volumeSizeInMegabytes * minShrinkSizePercentage / 100 * 1024 * 1024
210+
data = json.dumps({"autosize": {"mode": autoSizeMode, "grow_threshold": growThresholdPercentage, "maximum": maximum, "minimum": minimum, "shrink_threshold": shrinkThresholdPercentage}})
211+
logger.debug(f'Trying {endpoint} with {data}.')
212+
response = http.request('PATCH', endpoint, headers=headers, timeout=5.0, body=data)
213+
if response.status >= 200 and response.status <= 299:
214+
logger.info(f"Updated the auto size parameters for volume name {volumeName}.")
215+
else:
216+
logger.error(f'API call to {endpoint} failed. HTTP status code: {response.status}. Error message: {response.data}.')
217+
except Exception as err:
218+
logger.critical(f'Failed to issue API against {fsxnIp}. The error messages received: "{err}".')

Management-Utilities/auto_set_fsxn_auto_grow/set_fsxn_volume_auto_grow.py

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,21 @@
3333
# a different secret and/or keys for the username and password for each
3434
# of the FSxId.
3535
secretsTable = [
36-
{"id": "fs-0e8d9172fa5XXXXXX", "secretName": "fsxn-credentials", "usernameKey": "fsxn-username", "passwordKey": "fsxn-password"},
37-
{"id": "fs-020de2687bdXXXXXX", "secretName": "fsxn-credentials", "usernameKey": "fsxn-username", "passwordKey": "fsxn-password"},
38-
{"id": "fs-07bcb7ad84aXXXXXX", "secretName": "fsxn-credentials", "usernameKey": "fsxn-username", "passwordKey": "fsxn-password"},
39-
{"id": "fs-077b5ff4195XXXXXX", "secretName": "fsxn-credentials", "usernameKey": "fsxn-username", "passwordKey": "fsxn-password"}
36+
{"fsxId": "fs-0e8d9172fa5XXXXXX", "secretName": "fsxn-credentials", "usernameKey": "fsxn-username", "passwordKey": "fsxn-password"},
37+
{"fsxId": "fs-020de2687bdXXXXXX", "secretName": "fsxn-credentials", "usernameKey": "fsxn-username", "passwordKey": "fsxn-password"},
38+
{"fsxId": "fs-07bcb7ad84aXXXXXX", "secretName": "fsxn-credentials", "usernameKey": "fsxn-username", "passwordKey": "fsxn-password"},
39+
{"fsxId": "fs-077b5ff4195XXXXXX", "secretName": "fsxn-credentials", "usernameKey": "fsxn-username", "passwordKey": "fsxn-password"}
4040
]
4141
#
42+
# If you don't want to define the secretsTable in this script, you can
43+
# define the following variables to use a DynamoDB table to get the
44+
# secret information.
45+
#
46+
# NOTE: If both the secretsTable, and dynamodbSecretsTableName are defined,
47+
# then the secretsTable will be used.
48+
#dynamodbRegion="us-west-2"
49+
#dynamodbSecretsTableName="fsx_secrets"
50+
#
4251
# Set the region where the secrets are stored.
4352
secretsManagerRegion="us-west-2"
4453
#
@@ -77,9 +86,10 @@
7786
# find the credentials.
7887
################################################################################
7988
def getCredentials(secretsManagerClient, fsxnId):
89+
global secretsTable
8090

8191
for secretItem in secretsTable:
82-
if secretItem['id'] == fsxnId:
92+
if secretItem['fsxId'] == fsxnId:
8393
secretsInfo = secretsManagerClient.get_secret_value(SecretId=secretItem['secretName'])
8494
secrets = json.loads(secretsInfo['SecretString'])
8595
username = secrets[secretItem['usernameKey']]
@@ -113,7 +123,7 @@ def getVolumeData(fsxClient, volumeId, volumeARN):
113123
################################################################################
114124
def lambda_handler(event, context):
115125

116-
global logger
126+
global logger, secretsTable
117127
#
118128
# Set up "logging" to appropriately display messages. It can be set it up
119129
# to send messages to a syslog server.
@@ -138,6 +148,19 @@ def lambda_handler(event, context):
138148
retries = Retry(total=None, connect=1, read=1, redirect=10, status=0, other=0) # pylint: disable=E1123
139149
http = urllib3.PoolManager(cert_reqs='CERT_NONE', retries=retries)
140150
#
151+
# Read in the secretTable if it is not already defined.
152+
if 'dynamodbRegion' in globals():
153+
dynamodbClient = boto3.resource("dynamodb", region_name=dynamodbRegion) # pylint: disable=E0602
154+
155+
if 'secretsTable' not in globals():
156+
if 'dynamodbRegion' not in globals() or 'dynamodbSecretsTableName' not in globals():
157+
raise Exception('Error, you must either define the secretsTable array at the top of this script, or define dynamodbRegion and dynamodbSecretsTableName.')
158+
159+
table = dynamodbClient.Table(dynamodbSecretsTableName) # pylint: disable=E0602
160+
161+
response = table.scan()
162+
secretsTable = response["Items"]
163+
#
141164
# Get the FSxN ID, region, volume name, volume ID, and volume ARN from the CloudWatch event.
142165
fsxId = event['detail']['responseElements']['volume']['fileSystemId']
143166
regionName = event['detail']['awsRegion']

0 commit comments

Comments
 (0)