Octopus and python

Hey,

I’m currently writing Octopus API scripts using python and need to update variables, any ideas on how to do this?

my current error

Hi, thanks for reaching out.

We have an example script that demonstrates how to update variables via the API at https://github.com/OctopusDeploy/OctopusDeploy-Api/blob/master/Octopus.Client/LINQPad/ImportExportUpdateVariables.linq#L32.

Specifically you need to make sure that the Version field is defined correctly or you will receive errors like the one you have supplied in the screenshot.

Regards
Matt C

I have picked this up again, I notice that it now asks me to do https instead http.
I’m passing in the version, name and value into the data is there anything else I’m missing?

Hi,

Can you please paste in the script you are trying to run. That will help us diagnose the issue.

Regards
Matt C

import requests
import json
import time
from robot.libraries.BuiltIn import BuiltIn
import warnings

warnings.filterwarnings(“once”)
key = “API-XXXXXXXXXXXXXXXXXXXXX”

class Octopus_API_Library:

def __init__(self):
    self.url = "url here"
    self.session = None
    self.project = None
    self.header = "X-Octopus-ApiKey"

def _create_octo_session(self):
    self.session = None
    if not self.session:
        self.session = requests.session()

def _login_to_octo(self, key, url):

    self._create_octo_session()
    header = {self.header: key}
    response = self.session.get(url, headers=header)

    success = 200
    success_create = 201
    try:
        if response != success_create or response != success:
            response.raise_for_status()

    except Exception, e:
        BuiltIn().log("************************************************************************************\n"
                      "                    " + self.project + "\n"
                      "                     failed to Deploy with a FATAL ERROR of %s \n" % (str(e)) +
                      "                    " + response.text + "\n"
                      "************************************************************************************"
                      , "WARN")

    return response.text


def _deploy_release_with_value(self, key):
    #formvalue = 'SqlScriptListParameter': value
    data = {
        'Version': 'version number',
        'Name': 'variable name',
        'Value': 'new value',
    }

    self._create_octo_session()
    header = {self.header: key}
    url = self.url + "/variables/variableset-Projects-###"
    print data
    data = json.dumps(data)
    print data
    response = self.session.put(url, headers=header, data=data)
    print response
    print response.text

x= Octopus_API_Library()
x._deploy_release_with_value(key)

Hi,

This is an example of the variable set data structure:

{
  "OwnerId": "Projects-61",
  "Version": 4,
  "Variables": [
    {
      "Id": "bcb36f5c-9589-95ca-9180-1bbdc8163536",
      "Name": "MyVariable",
      "Value": "test",
      "Type": 0,
      "Scope": {
        "Environment": [
          "Environments-61"
        ]
      },
      "IsEditable": true,
      "Prompt": null,
      "IsSensitive": false
    }
  ],
  "ScopeValues": {
    "Environments": [
      {
        "Id": "Environments-1",
        "Name": "Windows"
      },
      {
        "Id": "Environments-21",
        "Name": "Linux"
      },
      {
        "Id": "Environments-41",
        "Name": "Azure"
      },
      {
        "Id": "Environments-61",
        "Name": "Local"
      }
    ],
    "Machines": [
      {
        "Id": "Machines-222",
        "Name": "54.163.42.238"
      },
      {
        "Id": "Machines-221",
        "Name": "54.227.102.12"
      },
      {
        "Id": "Machines-101",
        "Name": "Azure"
      },
      {
        "Id": "Machines-201",
        "Name": "Local"
      },
      {
        "Id": "Machines-241",
        "Name": "Windows 2016"
      }
    ],
    "Actions": [
      {
        "Id": "07b84dd6-8d80-4622-a660-bd9abac85594",
        "Name": "1. a"
      }
    ],
    "Roles": [
      {
        "Id": "cloud",
        "Name": "cloud"
      },
      {
        "Id": "web",
        "Name": "web"
      }
    ],
    "Channels": [
      {
        "Id": "Channels-61",
        "Name": "Default"
      }
    ],
    "TenantTags": []
  },
  "Id": "variableset-Projects-61",
  "LastModifiedOn": null,
  "LastModifiedBy": null,
  "Links": {
    "Self": {}
  }
}

To update it you will need to send the same structure back:

import requests
import json
import time
from robot.libraries.BuiltIn import BuiltIn
import warnings

warnings.filterwarnings("once")
key = "API-Whatever"

class Octopus_API_Library:

    def __init__(self):
        self.url = "http://localhost:8065/api"
        self.session = None
        self.project = None
        self.header = "X-Octopus-ApiKey"

    def _create_octo_session(self):
        self.session = None
        if not self.session:
            self.session = requests.session()

    def _login_to_octo(self, key, url):

        self._create_octo_session()
        header = {self.header: key}
        response = self.session.get(url, headers=header)

        success = 200
        success_create = 201
        try:
            if response != success_create or response != success:
                response.raise_for_status()

        except Exception, e:
            BuiltIn().log("************************************************************************************\n"
                          " " + self.project + "\n"
                          " failed to Deploy with a FATAL ERROR of %s \n" % (str(e)) +
                          " " + response.text + "\n"
                          "************************************************************************************"
                          , "WARN")

        return response.text

    def _deploy_release_with_value(self, key):
        #formvalue = 'SqlScriptListParameter': value
        data = {
            'Version': 5,
            'Variables': [{
                "Id": "bcb36f5c-9589-95ca-9180-1bbdc8163536",
                'Name': 'MyVariable',
                'Value': 'new value',
                "Type": 0,
                "Scope": {
                    "Environment": [
                        "Environments-61"
                    ]
                },
                "IsEditable": True,
                "IsSensitive": False
            }],
            "ScopeValues": {
                "Environments": [
                    {
                        "Id": "Environments-1",
                        "Name": "Windows"
                    },
                    {
                        "Id": "Environments-21",
                        "Name": "Linux"
                    },
                    {
                        "Id": "Environments-41",
                        "Name": "Azure"
                    },
                    {
                        "Id": "Environments-61",
                        "Name": "Local"
                    }
                ]
            }
        }

        self._create_octo_session()
        header = {self.header: key}
        url = self.url + "/variables/variableset-Projects-61"
        print data
        data = json.dumps(data)
        print data
        response = self.session.put(url, headers=header, data=data)
        print response
        print response.text

x= Octopus_API_Library()
x._deploy_release_with_value(key)

That will allow you to update the variables.

Regards
Matt C