<jupyter_start><jupyter_text>AWS Secret Management

 Prerequisite tasks

To set up and run this example, you must first set up the following:

1. Install AWS CLI 2 as described in the **"1.0.AWS_CLI_2_Installation"** notebook.
2. Configure your AWS credentials, as described in [Quickstart](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html) using the AWS CLI or the AWS Console IAM Manager.
3. Run locally the "aws configure" from the console to store locally your credentials to connect to AWS using the CLI.
   - Input your "AWS Access Key ID" and "AWS Secret Access Key" and "Default region name".
   - This will create a directory ".aws" and the files "config" and "credentials" (you must edit later if required).
4. Create a secret with the AWS Secrets Manager, as described in the [AWS Secrets Manager Developer Guide](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_create-basic-secret.html) and it has been described in the Lab.
5. Install boto3 library in your environment as described in the **"1.1.AWS_Boto3_Installation"** notebook (if it is not already done)
6. Modify the parameters "secret_name" and "region_name" to set your own data in the next cell code for this example.
  
**NOTE**: Boto3 will also search the ~/.aws/config file when looking for configuration values. You can change the location of this file by setting the AWS_CONFIG_FILE environment variable.
**NOTE**: The credential file has your AWS Keys so must not be located in a public source control repository.
  Retrieve the secret value The following example shows how to:Retrieve a secret value using [get_secret_value](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/secretsmanager.htmlSecretsManager.Client.get_secret_value) funtion<jupyter_code>import boto3
from botocore.exceptions import ClientError
def get_secret():
    secret_name = "my_secret_name"
    region_name = "my_region_name"
    
    session = boto3.session.Session()
    client = session.client(
        service_name='secretsmanager',
        region_name=region_name,
    )

    try:
        get_secret_value_response = client.get_secret_value(
            SecretId=secret_name)
    except ClientError as e:
        if e.response['Error']['Code'] == 'DecryptionFailureException':
            # Secrets Manager can't decrypt the protected secret text using the provided KMS key.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
        elif e.response['Error']['Code'] == 'InternalServiceErrorException':
            # An error occurred on the server side.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
        elif e.response['Error']['Code'] == 'InvalidParameterException':
            # You provided an invalid value for a parameter.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
        elif e.response['Error']['Code'] == 'InvalidRequestException':
            # You provided a parameter value that is not valid for the current state of the resource.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
        elif e.response['Error']['Code'] == 'ResourceNotFoundException':
            # We can't find the resource that you asked for.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
    else:
        # Decrypts secret using the associated KMS CMK.
        # Depending on whether the secret is a string or binary, one of these fields will be populated.
        if 'SecretString' in get_secret_value_response:
            secret = get_secret_value_response['SecretString']
        else:
            decoded_binary_secret = base64.b64decode(get_secret_value_response['SecretBinary'])
            
    # Your code goes here. 

        print ("The Secret that has been retrieved and can be used is: ", secret)
get_secret()<jupyter_output><empty_output><jupyter_text>That it is the same as executing with the CLI<jupyter_code>!aws secretsmanager get-secret-value --secret-id prod/api/devopslab/miclavesecreta<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.07548054383497421, 'fraction_numerical': 0.005860290670417253, 'mean_word_length': 3.2080867850098618, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 3, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '524702', 'license': 'Apache-2.0', 'n_tokens_mistral': 1154, 'n_tokens_neox': 1116, 'n_words': 448, 'path': 'runbooks/DevSecOps runbooks/1.2.AWS_SecretManager_GetSecret_Example.ipynb', 'repo_name': 'JuanLuisGozaloFdez/DevOpsLab4-Jupyter', 'size': '4266'}