By default, VM instances created via the API are configured with dynamic public IP addresses and without a specific payload configuration to request a static IP the system assigns a dynamic IP. This article provides an example script to deploy a VM with a static public IP via the API.
Prerequisite
- Create API Security Tokens, refer managing-api-keys
- Access Key
- Secret Key
- Python installed
Instructions:
Use below example Python script to send a POST request to create an a100.2x instance with static Public IP. The script signs the request with your API credentials. You can learn more about authenticated API requests here.
- Update
api_access_key
,api_secret_key
,ssh_public_key
,project_id
. - Execute the Python script to deploy a VM with a configured static public IP.
import hmac
import hashlib
import base64
import datetime
import requests
import json
api_base_url = "https://api.crusoecloud.com"
api_version = "/v1alpha5"
api_access_key = "< insert_your_api_access_key >"
api_secret_key = "< insert_your_api_secret_key >"
project_id = "< insert_your_project_id >"
request_path = f"/projects/{project_id}/compute/vms/instances"
request_verb = "POST"
query_params = ""
payload_body = {
"name": "my-instance",
"location": "us-northcentral1-a",
"ssh_public_key": "< your_ssh_public_key >",
"type": "a100.2x", # run `crusoe compute vms types`.
"network_interfaces": [
{
"ips": [
{
"public_ipv4": {
"type": "static"
}
}
]
}
]
}
current_timestamp = datetime.datetime.utcnow().replace(microsecond=0).isoformat() + "Z"
signature_payload = f"{api_version}{request_path}\n{query_params}\n{request_verb}\n{current_timestamp}\n"
decoded_secret = base64.urlsafe_b64decode(api_secret_key + '=' * (-len(api_secret_key) % 4))
signature = base64.urlsafe_b64encode(
hmac.new(decoded_secret, msg=signature_payload.encode("utf-8"), digestmod=hashlib.sha256).digest()
).decode("utf-8").rstrip("=")
headers = {
"X-Crusoe-Timestamp": current_timestamp,
"Authorization": f"Bearer 1.0:{api_access_key}:{signature}",
"Content-Type": "application/json"
}
response = requests.post(
f"{api_base_url}{api_version}{request_path}", headers=headers, json=payload_body
)
print("Status Code:", response.status_code)
try:
print("Response:", json.dumps(response.json(), indent=4))
except json.JSONDecodeError:
print("Response:", response.text)
After the API call, a VM is deployed with a configured static public IP.
Example Payload:
payload_body = {
"name": "my-instance",
"location": "us-northcentral1-a",
"ssh_public_key": "< your_ssh_public_key >",
"type": "a100.2x", # run `crusoe compute vms types`.
"network_interfaces": [
{
"ips": [
{
"public_ipv4": {
"type": "static" }
}
]
}
]
}
This article focuses solely on setting a static public IP via the API; additional configurations may be necessary for specific customer environments.
Comments
0 comments
Please sign in to leave a comment.