hello this is my code right now its allocating the IPs using cli but if not want to use cli is there an endpoint or any method to allocate ip using API here is my code
import requests
import os
import json
import time
import subprocess
# Environment variables
FLY_API_TOKEN = os.getenv('FLY_API_TOKEN')
FLY_API_HOSTNAME = 'https://api.machines.dev'
APP_NAME = 'streamlit-hello72'
headers = {
'Authorization': f'Bearer {FLY_API_TOKEN}',
'Content-Type': 'application/json'
}
def run_fly_command(command):
"""Execute a fly CLI command and return the output"""
try:
result = subprocess.run(
command,
check=True,
text=True,
capture_output=True
)
return result.stdout
except subprocess.CalledProcessError as e:
print(f"Command failed with exit code {e.returncode}")
print(f"Error output: {e.stderr}")
return None
def create_app():
"""Create the application"""
url = f"{FLY_API_HOSTNAME}/v1/apps"
app_payload = {
"app_name": APP_NAME,
"org_slug": "personal"
}
try:
response = requests.post(url, headers=headers, json=app_payload)
response.raise_for_status()
print("App created successfully!")
return response.json()
except requests.exceptions.RequestException as e:
if hasattr(e, 'response') and e.response.status_code == 409:
print("App already exists, continuing...")
else:
print(f"Error creating app: {e}")
raise
def allocate_ips_with_cli():
"""Allocate IPs using fly CLI"""
print("Allocating IPv4...")
run_fly_command(['fly', 'ips', 'allocate-v4', '--shared', '-a', APP_NAME])
print("Allocating IPv6...")
run_fly_command(['fly', 'ips', 'allocate-v6', '-a', APP_NAME])
# Show allocated IPs
print("\nAllocated IPs:")
run_fly_command(['fly', 'ips', 'list', '-a', APP_NAME])
def deploy_machine():
"""Deploy the machine with Streamlit"""
url = f"{FLY_API_HOSTNAME}/v1/apps/{APP_NAME}/machines"
machine_config = {
"name": APP_NAME,
"config": {
"image": "registry.fly.io/muatafastreamlit-26:deployment-01JD20EHKQVH202XNMQP1SDB56@sha256:66fbb456314eddeaa297095130e347796a974e18654c7630a500dbfe578daa97",
"env": {
"PORT": "8505"
},
"services": [
{
"ports": [
{
"port": 443,
"handlers": ["tls", "http"]
},
{
"port": 80,
"handlers": ["http"]
}
],
"protocol": "tcp",
"internal_port": 8505
}
],
"guest": {
"cpu_kind": "shared",
"cpus": 2,
"memory_mb": 512
}
}
}
try:
response = requests.post(url, headers=headers, json=machine_config)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error deploying machine: {e}")
if hasattr(e, 'response'):
print(f"Response Status: {e.response.status_code}")
print(f"Response Body: {e.response.text}")
raise
def check_machine_status(machine_id):
"""Check the status of a machine"""
url = f"{FLY_API_HOSTNAME}/v1/apps/{APP_NAME}/machines/{machine_id}"
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error checking machine status: {e}")
return None
def main():
try:
# Create app
create_app()
# Allocate IPs using CLI
print("Allocating IPs using CLI...")
allocate_ips_with_cli()
# Deploy machine
print("Deploying machine...")
machine_response = deploy_machine()
machine_id = machine_response['id']
print(f"Machine deployed with ID: {machine_id}")
# Monitor deployment
print("Monitoring deployment...")
max_attempts = 20
attempt = 0
while attempt < max_attempts:
status = check_machine_status(machine_id)
if status:
state = status.get('state', '')
print(f"Current state: {state}")
if state == 'started':
print("\nDeployment successful!")
print(f"Your app should be available at: https://{APP_NAME}.fly.dev")
# Show final IP allocation using CLI
print("\nFinal IP allocation:")
run_fly_command(['fly', 'ips', 'list', '-a', APP_NAME])
break
time.sleep(2)
attempt += 1
if attempt >= max_attempts:
print("Deployment monitoring timed out")
except Exception as e:
print(f"An error occurred: {str(e)}")
if __name__ == "__main__":
main()