Update Variable with ENV Scope

Hi Team,

I am facing issue while updating variable using REST API via python. I need to update the variable with Scope as ENV. Can you please help me, how i can pass value with env? Please help me with it?

import json
import requests
import os
from requests.api import get, head

def get_octopus_resource(uri, headers, skip_count = 0):
items =
response = requests.get((uri + “?skip=” + str(skip_count)), headers=headers)
response.raise_for_status()

# Get results of API call
results = json.loads(response.content.decode('utf-8'))

# Store results
if 'Items' in results.keys():
    items += results['Items']

    # Check to see if there are more results
    if (len(results['Items']) > 0) and (len(results['Items']) == results['ItemsPerPage']):
        skip_count += results['ItemsPerPage']
        items += get_octopus_resource(uri, headers, skip_count)

else:
    return results


# return results
return items

Define Octopus server variables

octopus_server_uri = ‘https://URL/api
octopus_api_key = ‘Key’
headers = {‘X-Octopus-ApiKey’: octopus_api_key}
project_name = “MyApp”
space_name = “Default”
variable = {
‘Name’: ‘Test1’,
‘Value’: ‘MyValue Test’,
‘Type’: ‘String’,
‘Scope’: {‘Enviornment = Dev’},
‘IsSensitive’: False
}

uri = ‘{0}/spaces’.format(octopus_server_uri)
spaces = get_octopus_resource(uri, headers)
space = next((x for x in spaces if x[‘Name’] == space_name), None)

uri = ‘{0}/{1}/projects’.format(octopus_server_uri, space[‘Id’])
projects = get_octopus_resource(uri, headers)
project = next((x for x in projects if x[‘Name’] == project_name), None)

if project != None:
uri = ‘{0}/{1}/variables/{2}’.format(octopus_server_uri, space[‘Id’], project[‘VariableSetId’])
projectVariables = get_octopus_resource(uri, headers)
projectVariable = next((x for x in projectVariables[‘Variables’] if x[‘Name’] == variable[‘Name’]), None)

if projectVariable == None:
    projectVariables['Variables'].append(variable)
else:
    projectVariable['Value'] = variable['Value']
    projectVariable['Type'] = variable['Type']
    projectVariable['IsSensitive'] = variable ['IsSensitive']

response = requests.put(uri, headers=headers, json=projectVariables)
response.raise_for_status

Hi @pritskumar81,

Thanks for reaching out, I’d be happy to help with updating a variables scope using our REST API!

I definitely recommend checking out our swagger page for info about the data expected: https://<octopusURL>/swaggerui/index.html

Another option for confirming what data to use in the request, is to make the change in the UI and inspect the request body payload through the browsers developer tools network tab:

It looks like Enviornment is misspelled in your code, however it might also require using the EnvironmentId instead of the name:

‘Scope’: {‘Environment = ["Environments-123"]’}

Hope that helps but feel free to reach out with any questions at all!

Best Regards,

Thank Sir for helping me with details, I will try as per your suggestion.

Thanks again, Appreciate your quick guidence on it.

1 Like

Hello Sir,

I tried with the way you suggested. But that is also throwing error, not sure where i am going wrong. Also how it would be done if a variable is already exist and it has multiple values already, now I need to update the same variable with new value (old values should be intact). Hopping keeping the same value will not update the older. Sorry for basic ask but I am getting confuse with it.

TypeError: set([‘Environment = [“Environments-1”]’]) is not JSON serializable

octopus_server_uri = ‘’
octopus_api_key = os.environ[‘octo_api_key’]
headers = {‘X-Octopus-ApiKey’: octopus_api_key}
project_name = “Test_Project”
space_name = “Default”
variable = {
‘Name’: ‘NewTest1’,
‘Value’: ‘New Value’,
‘Type’: ‘String’,
‘Scope’: {‘Environment = [“Environments-1”]’},
‘IsSensitive’: False
}

uri = ‘{0}/spaces’.format(octopus_server_uri)
spaces = get_octopus_resource(uri, headers)
space = next((x for x in spaces if x[‘Name’] == space_name), None)

uri = ‘{0}/{1}/projects’.format(octopus_server_uri, space[‘Id’])
projects = get_octopus_resource(uri, headers)
project = next((x for x in projects if x[‘Name’] == project_name), None)

if project != None:
uri = ‘{0}/{1}/variables/{2}’.format(octopus_server_uri, space[‘Id’], project[‘VariableSetId’])
projectVariables = get_octopus_resource(uri, headers)
projectVariable = next((x for x in projectVariables[‘Variables’] if x[‘Name’] == variable[‘Name’]), None)

if projectVariable == None:
    projectVariables['Variables'].append(variable)
else:
    projectVariable['Value'] = variable['Value']
    projectVariable['Type'] = variable['Type']
    projectVariable['IsSensitive'] = variable ['IsSensitive']

response = requests.put(uri, headers=headers, json=projectVariables)
response.raise_for_status

Please ignore my previous comment, I am able to run it successfully now. Thanks for your help on this.

2 Likes