Sub topic 7
Retrieving parameters and secrets from the CLI and SDK
This chapter assumes you have already created parameters and secrets, and that your IAM identity can read them. It also assumes you can run AWS CLI commands and read short Python scripts. Here you read values back out. You will compare the retrieval calls, see what each returns, and handle the errors you are most likely to hit.
The retrieval calls at a glance
Parameter Store and Secrets Manager have separate APIs. Each takes the name of a value and returns the value plus metadata.
| Call | Service | Returns | Notes |
|---|---|---|---|
| `GetParameter` | Parameter Store | One parameter | Add `WithDecryption` for SecureString |
| `GetParameters` | Parameter Store | Up to 10 named parameters | Reports missing names in `InvalidParameters` |
| `GetParametersByPath` | Parameter Store | All parameters under a path | Paginated, optional recursion |
| `GetSecretValue` | Secrets Manager | One secret version | Decrypts automatically |
| `BatchGetSecretValue` | Secrets Manager | Up to 20 secrets | Needs permission for each secret |
Parameter Store only decrypts SecureString values when you ask for it. Secrets Manager always decrypts, so it has no equivalent flag.
Two permission checks happen on every encrypted read. The caller needs the service action (for example ssm:GetParameter) and kms:Decrypt on the key. A missing KMS permission is the most common cause of an AccessDeniedException on a read that looks correctly permitted.
Reading from the CLI
Parameter Store
The default output of get-parameter is a JSON document with metadata. Use --query and --output text to get only the value.
aws ssm get-parameter \
--name /myapp/prod/db/host \
--query Parameter.Value \
--output textFor a SecureString, add --with-decryption. Without it, the CLI returns the ciphertext, which is not an error and is easy to mistake for a bad value.
aws ssm get-parameter \
--name /myapp/prod/db/password \
--with-decryption \
--query Parameter.Value \
--output textTo load a whole environment at once, use a path. This is the call shown earlier for startup configuration.
aws ssm get-parameters-by-path \
--path /myapp/prod \
--recursive \
--with-decryptionThree behaviors of get-parameters-by-path surprise people:
- Recursion is off by default. Without
--recursive, you get only parameters exactly one level below the path./myapp/prod/db/hostis not returned for--path /myapp/prod. - Results are paginated. The API returns at most 10 parameters per page. The CLI follows the pages for you unless you pass
--no-paginate. - The path must start with
/and should not end with one.
You can read an older version or a labeled version by appending a selector to the name: /myapp/prod/db/host:3 for version 3, or /myapp/prod/db/host:blue for the label blue.
Secrets Manager
aws secretsmanager get-secret-value \
--secret-id myapp/prod/db \
--query SecretString \
--output textThe result for a JSON secret is a string containing JSON. To extract one field in a script, pipe it to a JSON tool. This example assumes jq is installed.
aws secretsmanager get-secret-value \
--secret-id myapp/prod/db \
--query SecretString \
--output text | jq -r .usernameBy default you get the version labeled AWSCURRENT. Pass --version-stage AWSPREVIOUS or --version-id to read a different version. Binary secrets come back in SecretBinary instead of SecretString, and a given secret version has only one of the two.
Reading from the SDK
The CLI is useful for scripts and debugging. Applications read through an SDK. The example below uses boto3 and covers the three common patterns: load a path, fetch several named parameters, and read a JSON secret.
import json
import boto3
from botocore.exceptions import ClientError
ssm = boto3.client("ssm")
secrets = boto3.client("secretsmanager")
def load_path(path):
"""Return every parameter under path as {relative_name: value}."""
config = {}
paginator = ssm.get_paginator("get_parameters_by_path")
pages = paginator.paginate(Path=path, Recursive=True, WithDecryption=True)
for page in pages:
for param in page["Parameters"]:
relative = param["Name"][len(path):].lstrip("/")
config[relative] = param["Value"]
return config
def load_named(names):
"""Fetch up to 10 parameters by name and fail loudly on missing ones."""
response = ssm.get_parameters(Names=names, WithDecryption=True)
if response["InvalidParameters"]:
raise KeyError(f"Missing parameters: {response['InvalidParameters']}")
return {p["Name"]: p["Value"] for p in response["Parameters"]}
def load_secret_json(secret_id):
"""Return a JSON secret as a dictionary."""
try:
response = secrets.get_secret_value(SecretId=secret_id)
except ClientError as error:
code = error.response["Error"]["Code"]
if code == "ResourceNotFoundException":
raise KeyError(f"Secret {secret_id} does not exist") from error
raise
return json.loads(response["SecretString"])
if __name__ == "__main__":
settings = load_path("/myapp/prod")
print(sorted(settings)) # print names only, never values
creds = load_secret_json("myapp/prod/db")
print(creds["username"])Several details in this code matter in practice.
- Use the paginator. Calling
get_parameters_by_pathdirectly returns only the first page. Code that skips the paginator works in a test with five parameters and silently drops values in production. - Check
InvalidParameters.GetParametersdoes not raise an error for a name that does not exist. It returns the name inInvalidParameters. It also lists names you are not allowed to read there, so a typo and a permission gap look the same. - Never print values. The script prints parameter names and the username only.
- Parse the secret once.
SecretStringis plain text. The JSON structure is a convention you create, so the SDK does not parse it for you.
Errors you will see
| Error | Typical cause | Fix |
|---|---|---|
| `ParameterNotFound` | Wrong name, wrong Region, or missing leading `/` | Check the name and the `--region` or `AWS_REGION` value |
| `ResourceNotFoundException` | Secret name or Region is wrong, or the secret is scheduled for deletion | Check name and Region, and check the console for a pending deletion |
| `AccessDeniedException` on the read | The role lacks the service action for that resource ARN | Fix the identity policy resource |
| `AccessDeniedException` mentioning KMS | The role lacks `kms:Decrypt` on the key | Add the key to the policy, and check the key policy |
| `ThrottlingException` or `TooManyRequestsException` | Too many calls per second | Cache values, and rely on SDK retries |
| `InvalidRequestException` on a secret | The secret is scheduled for deletion, or the request is malformed | Restore the secret or fix the call |
The Region is the most common cause of "not found" errors. Both services are Regional, so the same name in us-east-1 and eu-west-1 refers to two unrelated values. Set the Region explicitly in the client with boto3.client("ssm", region_name="us-east-1") when you cannot trust the environment.
Choosing the right call
- Use
GetParameterwhen the code needs one known value. - Use
GetParametersfor a small fixed list, such as three settings needed together. - Use
GetParametersByPathwhen a whole environment should load at startup. The hierarchy you design earlier pays off here, because one path selects one environment. - Use
GetSecretValuefor a single secret. UseBatchGetSecretValueonly when you truly need many secrets in one step, and give the rolesecretsmanager:GetSecretValueon each secret as well.
Exercise
A startup script runs aws ssm get-parameters-by-path --path /myapp/prod --with-decryption and returns an empty list, although /myapp/prod/db/host and /myapp/prod/db/password exist and the role is allowed to read them. What is the most likely cause, and what change fixes it?
Show answer
The command does not pass --recursive. Without it, the call returns only parameters exactly one level below /myapp/prod, and both parameters sit two levels down under /myapp/prod/db/. Adding --recursive returns them. In SDK code, pass Recursive=True and use a paginator so results beyond the first page are not lost.
Exercise
You call GetParameters for three names and the response contains two parameters and one entry in InvalidParameters. Name two possible reasons, and say why your code should treat this as an error.
Show answer
The name may not exist (a typo, or the wrong Region), or the caller may lack permission to read it. The API reports both in InvalidParameters instead of raising an exception. The code should raise an error because it would otherwise continue with an incomplete configuration, and a missing database host or password would show up later as a confusing failure.