Filter secrets by label
In this step, you will learn how to filter secrets based on labels. Labels are key-value pairs that you can attach to Docker objects, including secrets, to organize and categorize them. Filtering by labels is a powerful way to manage secrets in complex environments.
First, let's create a new secret and add a label to it during creation. We will create a secret named labeled_secret
and add the label environment=production
.
Run the following command to create the secret with a label:
echo "production_value" | docker secret create --label environment=production labeled_secret -
This command is similar to the previous docker secret create
commands, but we've added the --label environment=production
flag to attach a label to the secret.
Now, let's create another secret with a different label. We'll name this one dev_secret
and give it the label environment=development
.
Run the following command:
echo "development_value" | docker secret create --label environment=development dev_secret -
If you list all secrets now using docker secret ls
, you will see all three secrets:
docker secret ls
The output will show my_secret
, another_secret
, labeled_secret
, and dev_secret
.
To filter the secrets and show only those with the label environment=production
, you can use the --filter label=environment=production
option.
Run the following command:
docker secret ls --filter label=environment=production
You should see only the labeled_secret
in the output:
ID NAME CREATED
<secret_id_3> labeled_secret About a minute ago
Similarly, to filter for secrets with the label environment=development
, you would use --filter label=environment=development
.
Run the following command:
docker secret ls --filter label=environment=development
This will show only the dev_secret
:
ID NAME CREATED
<secret_id_4> dev_secret About a minute ago
You can also filter for secrets that have a specific label key, regardless of its value, by using --filter label=environment
.
Run the following command:
docker secret ls --filter label=environment
This will show both labeled_secret
and dev_secret
because they both have the environment
label key:
ID NAME CREATED
<secret_id_3> labeled_secret About 2 minutes ago
<secret_id_4> dev_secret About 2 minutes ago
Filtering by labels is a flexible way to manage and retrieve secrets based on your own defined categories.