Probably this post as such isn’t useful to many, but I figured since it contains some OCI CLI scripting it might serve as an idea to something else for someone.

Recently I got a bunch of OCI Vault keys which had to be loaded to OCI Vault. What happened is of course the load didn’t go as planned and my next step was to delete all the keys I had loaded. Vault already contained bunch of keys so I just couldn’t go and delete everything.

What I decided to do is to take all the keys from specific compartment and look when they were created since nobody else had created any keys within last two days apart from me.

What the script does it takes all secrets with CLI from specific region and compartment. Then I parse the list via jq and get id, secret-name, lifecycle-state and time-created.

Why I take lifecycle-state? It’s because I ran into an error and had half of the keys already scheduled for deletion. So to filter only specific items you could add something like this:

if [ "$whenCreated" -gt "$createdWithin" ]  && [ "$lifecycleState" != "PENDING_DELETION" ]; then

Also with Vault, you can’t delete secrets as such but there is minimum of 24 hours time for them to be scheduled for deletion. That’s why time-of-deletion needs to be defined. It could obviously be variable +24 hours from time script is being run but it didn’t make this cut.

Whole script is below, hope it helps somebody!

#!/bin/bash
set -e
secretList=$(oci vault secret list --region us-phoenix-1 --all --compartment-id ocid1.compartment.oc1..xxxxxxx)

for i in $(echo "$secretList" | jq '.data | keys | .[]')
do
    ID=$(echo $secretList | jq -r ".data[$i].\"id\"")
    NAME=$(echo $secretList | jq -r ".data[$i].\"secret-name\"")
    lifecycleState=$(echo $secretList | jq -r ".data[$i].\"lifecycle-state\"")
    timecreated=$(echo $secretList | jq -r ".data[$i].\"time-created\"")

whenCreated=$(date -d "$timecreated" +%s)
createdWithin=$(date --date="-2 days" +%s)

if [ "$whenCreated" -gt "$createdWithin" ]; then
    echo "Deleting Secret: $NAME $timecreated"
   
    oci vault secret --region us-phoenix-1 schedule-secret-deletion \
    --secret-id $ID \
    --time-of-deletion "2021-01-13 17:30"

fi
done

Leave a Reply

Your email address will not be published.