|
| 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 botocore |
| 29 | +import boto3 |
| 30 | +# |
| 31 | +# Create a table of secret names and keys for the username and password for each of the FSxIds. |
| 32 | +secretsTable = [ |
| 33 | + {"id": "fs-0e8d9172fa545ef3b", "secretName": "mon-fsxn-credentials", "usernameKey": "mon-fsxn-username", "passwordKey": "mon-fsxn-password"}, |
| 34 | + {"id": "fs-020de2687bd98ccf7", "secretName": "mon-fsxn-credentials", "usernameKey": "mon-fsxn-username", "passwordKey": "mon-fsxn-password"}, |
| 35 | + {"id": "fs-07bcb7ad84ac75e43", "secretName": "mon-fsxn-credentials", "usernameKey": "mon-fsxn-username", "passwordKey": "mon-fsxn-password"}, |
| 36 | + {"id": "fs-077b5ff41951c57b2", "secretName": "mon-fsxn-credentials", "usernameKey": "mon-fsxn-username", "passwordKey": "mon-fsxn-password"} |
| 37 | + ] |
| 38 | +# |
| 39 | +# Set the region where the secrets are stored. |
| 40 | +secretsManagerRegion="us-west-2" |
| 41 | + |
| 42 | +################################################################################ |
| 43 | +# This function is used to obtain the username and password from AWS's Secrets |
| 44 | +# Manager for the fsxnId passed in. It returns empty strings if it can't |
| 45 | +# find the credentials. |
| 46 | +################################################################################ |
| 47 | +def getCredentials(secretsManagerClient, fsxnId): |
| 48 | + |
| 49 | + for secretItem in secretsTable: |
| 50 | + if secretItem['id'] == fsxnId: |
| 51 | + secretsInfo = secretsManagerClient.get_secret_value(SecretId=secretItem['secretName']) |
| 52 | + secrets = json.loads(secretsInfo['SecretString']) |
| 53 | + username = secrets[secretItem['usernameKey']] |
| 54 | + password = secrets[secretItem['passwordKey']] |
| 55 | + return (username, password) |
| 56 | + return ("", "") |
| 57 | + |
| 58 | +################################################################################ |
| 59 | +# This function returns the UUID of the volume that has the ARN passed in. It |
| 60 | +# tries a few times, sleeping 1 second between attempts, since the UUID |
| 61 | +# doesn't exist until the volume has been created on the ONTAP side. |
| 62 | +# It returns an empty string if the ARN is not found. |
| 63 | +################################################################################ |
| 64 | +def getVolumeUUID(fsxClient, volumeId, volumeARN): |
| 65 | + |
| 66 | + global logger |
| 67 | + |
| 68 | + cnt = 0 |
| 69 | + while cnt < 3: |
| 70 | + awsVolume = fsxClient.describe_volumes(VolumeIds=[volumeId])['Volumes'][0] |
| 71 | + if awsVolume['ResourceARN'] == volumeARN: |
| 72 | + return awsVolume['OntapConfiguration']['UUID'] |
| 73 | + logger.debug(f'Looping, getting the UUID {cnt}') |
| 74 | + cnt += 1 |
| 75 | + time.sleep(1) |
| 76 | + |
| 77 | + return "" |
| 78 | + |
| 79 | +################################################################################ |
| 80 | +################################################################################ |
| 81 | +def lambda_handler(event, context): |
| 82 | + |
| 83 | + global logger |
| 84 | + # |
| 85 | + # Set up "logging" to appropriately display messages. It can be set it up |
| 86 | + # to send messages to a syslog server. |
| 87 | + logging.basicConfig(datefmt='%Y-%m-%d_%H:%M:%S', format='%(asctime)s:%(name)s:%(levelname)s:%(message)s', encoding='utf-8') |
| 88 | + logger = logging.getLogger("scan_create_sm_relationships") |
| 89 | +# logger.setLevel(logging.DEBUG) |
| 90 | + logger.setLevel(logging.INFO) |
| 91 | + # |
| 92 | + # Set the logging level higher for these noisy modules to mute thier messages. |
| 93 | + logging.getLogger("botocore").setLevel(logging.WARNING) |
| 94 | + logging.getLogger("boto3").setLevel(logging.WARNING) |
| 95 | + logging.getLogger("urllib3").setLevel(logging.WARNING) |
| 96 | + # |
| 97 | + # Create a Secrets Manager client. |
| 98 | + session = boto3.session.Session() |
| 99 | + secretsManagerClient = session.client(service_name='secretsmanager', region_name=secretsManagerRegion) |
| 100 | + # |
| 101 | + # Disable warning about connecting to servers with self-signed SSL certificates. |
| 102 | + urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) |
| 103 | + # |
| 104 | + # Set the https retries to 1. |
| 105 | + retries = Retry(total=None, connect=1, read=1, redirect=10, status=0, other=0) # pylint: disable=E1123 |
| 106 | + http = urllib3.PoolManager(cert_reqs='CERT_NONE', retries=retries) |
| 107 | + # |
| 108 | + # Get the FSxN ID, region, volume name, volume ID, and volume ARN from the CloudWatch event. |
| 109 | + fsxId = event['detail']['responseElements']['volume']['fileSystemId'] |
| 110 | + regionName = event['detail']['awsRegion'] |
| 111 | + volumeName = event['detail']['requestParameters']['name'] |
| 112 | + volumeId = event['detail']['responseElements']['volume']['volumeId'] |
| 113 | + volumeARN = event['detail']['responseElements']['volume']['resourceARN'] |
| 114 | + if fsxId == "" or regionName == "" or volumeId == "" or volumeName == "" or volumeARN == "": |
| 115 | + message = f"Couldn't obtain the fsxId, region, volume name, volume ID or volume ARN from the CloudWatch evevnt." |
| 116 | + logger.critcal(message) |
| 117 | + raise Exception(mmessage) |
| 118 | + |
| 119 | + logger.debug(f'Data from CloudWatch event: FSxID={fsxId}, Region={regionName}, VolumeName={volumeName}, volumeId={volumeId}.') |
| 120 | + # |
| 121 | + # Get the username and password for the FSxN ID. |
| 122 | + (username, password) = getCredentials(secretsManagerClient, fsxId) |
| 123 | + if username == "" or password == "": |
| 124 | + message = f'No credentials for FSxN ID: {fsxId}.' |
| 125 | + logger.critical(message) |
| 126 | + raise Exception(message) |
| 127 | + # |
| 128 | + # Build a header that is used for all the ONTAP API requests. |
| 129 | + auth = urllib3.make_headers(basic_auth=f'{username}:{password}') |
| 130 | + headers = { **auth } |
| 131 | + # |
| 132 | + # Get the management IP of the FSxN file system. |
| 133 | + fsxClient = boto3.client('fsx', region_name = regionName) |
| 134 | + fs = fsxClient.describe_file_systems(FileSystemIds = [fsxId])['FileSystems'][0] |
| 135 | + fsxnIp = fs['OntapConfiguration']['Endpoints']['Management']['IpAddresses'][0] |
| 136 | + if fsxnIp == "": |
| 137 | + message = f"Can't find manament IP for FSxN file system with an ID of '{fsxId}'." |
| 138 | + logger.critical(message) |
| 139 | + raise Exception(message) |
| 140 | + |
| 141 | + volumeUUID = getVolumeUUID(fsxClient, volumeId, volumeARN) |
| 142 | + if volumeUUID == "": |
| 143 | + message = f"Can't find the volumeUUID based on the volume ARN {volumeARN}." |
| 144 | + logger.critical(message) |
| 145 | + raise Exception(message) |
| 146 | + # |
| 147 | + # Set the auto grow feature. |
| 148 | + try: |
| 149 | + endpoint = f'https://{fsxnIp}/api/storage/volumes/{volumeUUID}' |
| 150 | + data = '{"autosize": {"mode": "grow"}}' |
| 151 | + logger.debug(f'Trying {endpoint} with {data}.') |
| 152 | + response = http.request('PATCH', endpoint, headers=headers, timeout=5.0, body=data) |
| 153 | + if response.status >= 200 and response.status <= 299: |
| 154 | + logger.info(f"Updated the auto grow flag for volume name {volumeName}.") |
| 155 | + else: |
| 156 | + logger.error(f'API call to {endpoint} failed. HTTP status code: {response.status}.') |
| 157 | + except Exception as err: |
| 158 | + logger.critical(f'Failed to issue API against {fsxnIp}. The error messages received: "{err}".') |
0 commit comments