Skip to content

Instantly share code, notes, and snippets.

@pkdone
Last active April 24, 2022 08:31
Show Gist options
  • Save pkdone/0c3a2181864d789138948be254644c38 to your computer and use it in GitHub Desktop.
Save pkdone/0c3a2181864d789138948be254644c38 to your computer and use it in GitHub Desktop.

Hashicorp Vault Secrets For MongoDB Atlas Programmatic Admin API Keys Creation

Assumptions

  • You have a MongoDB Atlas project already created and you have made a note of its project/group ID
  • You have already created an Atlas org-level Admin API key which has an Access List configured to be accessible from your workstation and you have made a note of its public and private key values
  • You have Hashicorp Vault installed

Start Vault in Development Mode

From a terminal, execute:

vault server -dev

Keep this Vault server process running in the current terminal - do not terminate it.

Configure Vault to Create Atas Admin API Keys and Create One Key

From a NEW separate terminal, execute the code below after first:

  • Changing PROJECT_ID to match the id of your Atlas project/group you want Admin API Keys created in
  • Changing PUBLIC_KEY to match the public key of your pre-existing Atlas org-level Admin API Key
  • Changing PRIVATE_KEY to match the public key of your pre-existing Atlas org-level Admin API Key
export PROJECT_ID="abcdef1234567890abcdef12"
export PUBLIC_KEY="abcdefgh"
export PRIVATE_KEY="fedcba12-3456-7890-abcd-ef0987654345"
export ROLE_NAME="myapp-proj-owners"

# Clean out previously created file, if any
rm -f my-public-ip-address

# Get current workstation's public IP address
curl --no-progress-meter http://checkip.dyndns.org/ | sed -e 's/.*: //' -e 's/<.*//' > my-public-ip-address
cat my-public-ip-address

# Set address of Vault server
export VAULT_ADDR='http://localhost:8200'

# Enable the Atlas secrets engine for Vault
vault secrets enable mongodbatlas

# Configure Vault's Atlas secrets engine with the existing Atlas org-level Admin API key
vault write mongodbatlas/config \
  public_key="${PUBLIC_KEY}" \
  private_key="${PRIVATE_KEY}"

# Configure a new Vault role to map to the creation of a project-level API key's credentials in Atlas:
vault write "mongodbatlas/roles/${ROLE_NAME}" \
  project_id="${PROJECT_ID}" \
  roles="GROUP_OWNER" \
  ip_addresses="$(< my-public-ip-address)" \
  ttl="2h" \
  max_ttl="48h"

# Show the newly configured Vault role 
vault read "mongodbatlas/roles/${ROLE_NAME}"

# Induce creation of new project API key
vault read "mongodbatlas/creds/${ROLE_NAME}"

Via the Atlas Console, you should now be able to see the newly created project-level Admin API key.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment