Start/ Stop Container Using The Proxmox Web API in Bash

Start/ Stop Container Using The Proxmox Web API in Bash

Category : How-to

Get Social!

The Proxmox Web API can perform any actions available in the front end Web. By implementing a REST API, all commands have been exposed and can be used programatically.

In this example we’ll use Bash to call the Proxmox Web API with our authentication token to start and stop an existing LXC Container.

See this post for an introduction to the Proxmox Web API, including all available API commands.

To issue API requests you’ll need to ensure you have already generated an authentication ticket which is described in Parse Proxmox Web API authentication ticket and the CSRFPreventionToken in Bash.

Once you have the authentication ticket you’ll need to call the Proxmox API using curl and parse the result. Use the below scripts and substitute the values as required:

Start an LXC Container

  • TICKET is the authentication ticket that was produced in the Parse Proxmox Web API authentication ticket and the CSRFPreventionToken in Bash post. Ideally you would programatically call the authentication routine and then pass the values straight into the below API calls.
  • CSRF is produced in the same way as TICKET. It’s actually only required when writing data to the API but there is no harm in always including it.
  • HOST is the host or IP address of the Proxmox server.
  • NODE is the node name of the Proxmox server that the LXC Container resides on.
  • TARGET_VM  is the VMID of the LXC Container.
TICKET=[security-ticket]
CSRF=[csrf-token]
HOST=prox-node1
NODE=prox-node1
TARGET_VMID=100

START_TASK_DATA=`curl -s -k -b "PVEAuthCookie=$TICKET" -H "CSRFPreventionToken: $CSRF" -X POST $HOST/api2/json/nodes/$NODE/lxc/$TARGET_VMID/status/start`

START_TASK_RESULT=$(decodeDataFromJson $START_TASK_DATA 'data')

If $START_TASK_RESULT doesn’t come back with null or empty then the command has successfully executed.

Stop an LXC Container

Stopping a VM in Proxmox is very similar to starting one, with just a slight change to the API URL call. All other options are the same as the above section ‘Start an LXC Container’.

TICKET=[security-ticket]
CSRF=[csrf-token]
HOST=prox-node1
NODE=prox-node1
TARGET_VMID=100

STOP_TASK_DATA=`curl -s -k -b "PVEAuthCookie=$TICKET" -H "CSRFPreventionToken: $CSRF" -X POST $HOST/api2/json/nodes/$NODE/lxc/$TARGET_VMID/status/stop`

STOP_TASK_RESULT=$(decodeDataFromJson $STOP_TASK_DATA 'data')

If $STOP_TASK_RESULT doesn’t come back with null or empty then the command has successfully executed.


Getting Started With Proxmox HTTP API Commands

Category : How-to

Get Social!

Proxmox has 2 API access points that can be used to control your Proxmox server and virtual guests. One of the API access points is using the command line, which you’re likely already familiar with. The other is the HTTP web API which is exposed as part of the WEB GUI on port 8006.

The Proxmox uses a JSON data format for returning data that can easily be parsed programmatically. Every command available to the pvesh command line command are available to the web based API as they share the same endpoint.

The endpoint for the Web API can be called using anything that can send and receive web based requests. We’ll use curl for the below examples. The endpoint to call would be similar to below – be sure you substitute yourip for the IP or hostname of your Proxmox server.

https://yourip:8006/api2/json/

API Authentication

The next step is to authenticate your API requests with the Proxmox server. API authentication uses the same mechanism that logging into the Web GUI uses and requires a username, password and security realm.

Authentication is based on a token method which provides a ticket that must accompany all API requests except for the request that generates the token. A username and password will not be accepted for authentication with all other API requests. In addition, any requests that POST or write to the API endpoint must contain a CSRF Prevention Token.

To obtain an authentication token, run the below curl command and substitute your values as required – this example uses the root user and the default PAM realm.

curl https://yourip:8006/api2/json/access/ticket -k -d 'username=root@pam&password=PASSWORD'

Example output:

{  
  "data":{  
    "CSRFPreventionToken":"5922F2C4:e7n+eQ9Lipbga3bY00Jh79MBATk",
    "username":"root@pam"
    },
    "ticket":"PVE:J38560@AD:5922F2C4::oOAcgXvCcAdLG+B50sRZ9WeaKn3gCFEktnHtegUVEcdtYO0NE7THA7pmzKZ14MgOYrp6vrye4ZBDocpu/nhuvUUL3vZeAT7YMstBXR3YLN8IlwQl5HJdgOikdz+gMdWyfx3JxcNhaNpJlHDL8Vm7D0r7GKGsHPirB098eG7pg1MgrkW7U6R5piW66c/p3kdJvT5beD+IPOhst76SoVlFo3ZxFFcqpcD5RFsUpKl9K1/5tgPReh1sErcDhOgUeiAE5XZHFsTE/jBVeSv9O2cXb5fESRtTU3986Gtw85hPJlWDzMz+X94H0rlL25cYkIbnOx5KJi9IcNTnvTHdpaoXuQ=="
}

The two interesting parts here are the ticket value and the CSRFPreventionToken and should be parsed out for use in later requests.

A token is valid for 2 hours and should be re-requested when it expires. Alternatively each request could generate it’s own token, however this generates added overhead.

List of Proxmox API Requests

pvesh is a command line utility can be used to perform the same actions as the web based API. You can, therefore, use the pvesh command to list all the possible API calls and navigate through the API call tree.

# pvesh
entering PVE shell - type 'help' for help
pve:/> 

pve:/> ls
Dr--- access
Dr--- cluster
Dr--- nodes
Dr-c- pools
Dr-c- storage
-r--- version

pve:/>cd nodes

pve:/nodes>ls
Dr--- prox-node1

You can then list the available commands from the root of the API using ls and then change into one of the child paths using cd. You can navigate throughout the whole API tree using these two methods to see what commands are available for calling. This is often the best way to get started with the Proxmox API.

Examples of API Requests

As stated earlier, all operations available in the Proxmox Web GUI can be performed through the API. Here are a few examples of API requests using Bash:


Parse Proxmox Web API authentication ticket and the CSRFPreventionToken in Bash

Category : How-to

Get Social!

The Proxmox Web API can perform any actions available in the front end Web. By implementing a REST API, all commands have been exposed and can be used programatically.

The API is secured using a token based method which provides a ticket that must accompany all API requests except for the request that generates the token. The token is generated from an API call containing a username, password and security realm.

In this example we’ll use Bash to call the Proxmox Web API, authenticate with the root Proxmox user and parse the response for use in later API requests. Note that it’s not good practice to use the root account for API calls due to the security implications.

See this post for an introduction to the Proxmox Web API.

Add this function to the top of your Bash script. This will be used to parse the JSON using standard Bash calls to obtain the information we need.

decodeDataFromJson(){
    echo `echo $1 \
	    | sed 's/{\"data\"\:{//g' \
	    | sed 's/\\\\\//\//g' \
	    | sed 's/[{}]//g' \
            | awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}' \
	    | sed 's/\"\:\"/\|/g' \
	    | sed 's/[\,]/ /g' \
	    | sed 's/\"// g' \
	    | grep -w $2 \
	    | awk -F "|" '{print $2}'`
}

The next step is to call the Proxmox API using curl to obtain our authentication token. Use the below script and substitute the values as required:

  • PROX_USERNAME is the username and security realm used to log into the Proxmox Web front end. This must be a valid user with the required permission to make the calls you need.
  • PROX_PASSWORD is the password for the above user. You must escape any special characters as usual in Bash.
  • HOST is the host or IP address of the Proxmox server.
PROX_USERNAME=root@pam
PROX_PASSWORD=PASSWORD
HOST=proxmox-host

DATA=`curl -s -k -d "username=$PROX_USERNAME&password=$PROX_PASSWORD" $HOST/api2/json/access/ticket` 
TICKET=$(decodeDataFromJson $DATA 'ticket')
CSRF=$(decodeDataFromJson $DATA 'CSRFPreventionToken')

And that’s all there is to it! You can use the variables $TICKET and $CSRF in later requests. Keep in mind that a valid ticket is only valid for 2 hours, after that you’ll need to create a new one.


Visit our advertisers

Quick Poll

Do you use GlusterFS in your workplace?

Visit our advertisers