Introduction
This article will provide steps on how to authenticate to Hashicorp Cloud Platform (HCP) using curl method and how to obtain the required access token for consuming HCP APIs.
Currently, only the HCP Packer API endpoints are available. We plan to expand the API documentation in the future for other HCP products.
Steps:
- Create a service principal credential guide.
- Set an environment variable for the client ID and client secret.
export HCP_CLIENT_ID=
export HCP_CLIENT_SECRET=
- HCP_API_URL=https://api.cloud.hashicorp.com/ (Audience is the same across all products)
- Retrieve access token
curl --silent --request POST --header "Content-Type: application/json" \
--data '{
"audience": "https://api.hashicorp.cloud",
"grant_type": "client_credentials",
"client_id": "'"$HCP_CLIENT_ID"'",
"client_secret": "'"$HCP_CLIENT_SECRET"'"
}' \
https://auth.hashicorp.com/oauth/token | jq
Output
{
"access_token": "access token here",
"expires_in": 3600,
"token_type": "Bearer"
}
- Call APIs using that access token by sending an authorization request header
-H 'Authorization: Bearer <your_access_token>'
Example: Get a list of vault clusters in an HCP organization and information on each cluster.
curl \
--header "Authorization: Bearer $HCP_ACCESS_TOKEN" \
"https://api.cloud.hashicorp.com/vault/2020-11-25/organizations/${HCP_ORGANIZATION_ID}/projects/${HCP_PROJECT_ID}/clusters" | jq
Sample output
"clusters": [
{
"id": "vault-cluster-2",
"location": {
"organization_id": "",
"project_id": "",
"region": {
"provider": "aws",
"region": "us-west-2"
}
},
"state": "RUNNING",
"config": {
"vault_config": {
"namespace": "",
"initial_version": "v1.9.2",
"max_lease_ttl": ""
},
.........truncated
Additional Information
The above examples assume organization_id and project_id are set as environment variables.
You can retrieve organization_id
and project_id
by visiting the HCP Portal and clicking on "Overview" in the left panel which will then display the organization_id and project_id as part of the URL in the address bar of your browser, similar to a format like this
https://portal.cloud.hashicorp.com/orgs/01f34945-65f4-439e/projects/6aed8bf5-203e-4f27-9016
in this example organization_id
is next to orgs 01f34945-65f4-439e and project_id
is next to projects 6aed8bf5-203e-4f27-9016