示例#1
0
def lambda_handler(event, context):
    invalidation_items = event['invalidation_items']
    if event['source'] == "Akamai":
        import requests, json
        from http_calls import EdgeGridHttpCaller
        from akamai.edgegrid import EdgeGridAuth
        creds = event['credentials']

        session = requests.Session()
        debug = False
        verbose = False
        section_name = "default"

        # Set the config options
        session.auth = EdgeGridAuth(client_token=creds['client_token'],
                                    client_secret=creds['client_secret'],
                                    access_token=creds['access_token'])

        baseurl = '%s://%s/' % ('https', creds['host'])
        httpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl)

        purge_obj = {
            "objects": invalidation_items,
            "hostname": "",
            "action": "remove",
            "type": "arl",
            "domain": "production"
        }
        purge_post_result = httpCaller.postResult('/ccu/v3/invalidate/url',
                                                  json.dumps(purge_obj))
        return {"success": True, "message": purge_post_result}

    else:
        if "distribution_id" in event and "credentials" in event:
            distribution_id = event['distribution_id']
            quantity = event['quantity']

            creds = event['credentials']

            if distribution_id:
                client = boto3.client(
                    'cloudfront',
                    aws_access_key_id=creds["aws_access_key_id"],
                    aws_secret_access_key=creds['aws_secret_access_key'])
                invalidation = client.create_invalidation(
                    DistributionId=distribution_id,
                    InvalidationBatch={
                        'Paths': {
                            'Quantity': quantity,
                            'Items': invalidation_items
                        },
                        'CallerReference': str(time.time())
                    })
        return {"success": True, "message": invalidation}
        #	"capabilities": [
        #	  "View", 
        #	  "Edit", 
        #	  "Activate", 
        #	  "Internal", 
        #	  "AdvancedEdit"
        #	]
      	#	}, 

	sample_post_body = {
		  "cloudletId": 0,
		  "groupId": 77649,
		  "name": "APIBootcampERv6",
		  "description": "Testing the creation of a policy"
	}
	sample_post_result = httpCaller.postResult('/cloudlets/api/v2/policies', json.dumps(sample_post_body))
	policyId = sample_post_result['policyId']
#{
  #"cloudletCode": "SA", 
  #"cloudletId": 2, 
  #"name": "APIBootcampEdgeRedirect", 
  #"propertyName": null, 
  #"deleted": false, 
  #"lastModifiedDate": 1458765299155, 
  #"description": "Testing the creation of a policy", 
  #"apiVersion": "2.0", 
  #"lastModifiedBy": "advocate2", 
  #"serviceVersion": null, 
  #"createDate": 1458765299155, 
  #"location": "/cloudlets/api/v2/policies/11434", 
  #"createdBy": "advocate2", 
    newCase = {}

    # Set severity to the default value for the case
    newCase["severity"] = attributes_result["severity"]["value"]
    newCase["userDetail"] = {}
    for userField in ("userName", "userEmail", "userPhone", "userCompany"):
        newCase["userDetail"][userField] = attributes_result["userDetail"][
            userField]["value"]
    newCase["categoryType"] = testCategory
    newCase["subCategories"] = testSubCategories
    newCase["subject"] = "This is a test case from the Case Management API"

    print json.dumps(newCase, indent=2)

    case_create_result = httpCaller.postResult('/case-management/v2/cases',
                                               json.dumps(newCase))

    print json.dumps(case_create_result, indent=2)
    caseId = case_create_result["caseId"]

    files = {'file': open('case_management_create.py', 'rb')}
    case_upload_file_result = httpCaller.postFiles(
        '/case-management/v2/cases/%s/files' % caseId, files)

    print json.dumps(case_upload_file_result)
    # List the active cases in the system
    case_list_result = httpCaller.getResult('/case-management/v2/cases')
    print json.dumps(case_list_result, indent=2)

    closeComments = {"comment": "Closing API Generated case"}
    case_close_results = httpCaller.postResult(
示例#4
0
    #	"capabilities": [
    #	  "View",
    #	  "Edit",
    #	  "Activate",
    #	  "Internal",
    #	  "AdvancedEdit"
    #	]
    #	},

    sample_post_body = {
        "cloudletId": 0,
        "groupId": 77649,
        "name": "APIBootcampERv6",
        "description": "Testing the creation of a policy"
    }
    sample_post_result = httpCaller.postResult('/cloudlets/api/v2/policies',
                                               json.dumps(sample_post_body))
    policyId = sample_post_result['policyId']
    #{
    #"cloudletCode": "SA",
    #"cloudletId": 2,
    #"name": "APIBootcampEdgeRedirect",
    #"propertyName": null,
    #"deleted": false,
    #"lastModifiedDate": 1458765299155,
    #"description": "Testing the creation of a policy",
    #"apiVersion": "2.0",
    #"lastModifiedBy": "advocate2",
    #"serviceVersion": null,
    #"createDate": 1458765299155,
    #"location": "/cloudlets/api/v2/policies/11434",
    #"createdBy": "advocate2",
# Set the baseurl based on config.host
baseurl = '%s://%s/' % ('https', config.host)
httpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl)

if __name__ == "__main__":
    # Get the list of cloudlets to pick the one we want to use

    if version == "CREATE":
        new_version_info = {
            "description": "Adding a new version for match rules",
            "matchRuleFormat": "1.0",
            "matchRules": []
        }
        create_path = "/cloudlets/api/v2/policies/%s/versions" % policy
        create_result = httpCaller.postResult(create_path,
                                              json.dumps(new_version_info))

    if version == "CREATE" or version == "LATEST":
        version_path = "/cloudlets/api/v2/policies/%s/versions" % policy
        version_result = httpCaller.getResult(version_path)
        version = version_result[0]["version"]

    # Now we know which version (and we've set the policy)

    # Open the JSON filename with mappings
    with open(filename) as data_file:
        data = json.load(data_file)

    for rule in data:
        rule_path = "/cloudlets/api/v2/policies/%s/versions/%s/rules" % (
            policy, version)
示例#6
0
print "[*] process to resolve %s from country %s" % ("junchen.sandbox",
                                                     location)

dig_parameters = {"hostName": "junchen.sandbox.akamaideveloper.com"}

dig_result = httpCaller.getResult(
    "/diagnostic-tools/v2/ghost-locations/%s/dig-info" % location,
    dig_parameters)

# Display the results from dig
print(dig_result['digInfo']['result'])

#config_t = EdgeGridConfig({"verbose":False},section_ccu)
#baseurl = '%s://%s/' % ('https', config.host)
baseurl_t = 'https://%s' % edgerc.get(section_ccu, 'host')

t.auth = EdgeGridAuth.from_edgerc(edgerc, section_ccu)

httpCaller_t = EdgeGridHttpCaller(t, debug, verbose, baseurl_t)

purge_obj = {
    "objects": ["https://khunter.sandbox.akamaideveloper.com/index.html"]
}

print("Adding invalidate request to queue - %s" % (json.dumps(purge_obj)))

purge_post_result = httpCaller_t.postResult('/ccu/v3/invalidate/url',
                                            json.dumps(purge_obj))

print purge_post_result
示例#7
0
# Get a rule tree for latest version on Production
ruleTree = httpCaller.getResult(
    "/papi/v0/properties/" + propertyDeets['propertyId'] + "/versions/" +
    str(propertyDeets['productionVersion']) + "/rules/", requestParams)

# Update Origin server in local rule tree
for behavior in ruleTree['rules']['behaviors']:
    if behavior['name'] == "origin":
        oldOrigin = behavior['options']['hostname']
        behavior['options']['hostname'] = newOrigin

# Create a new version
requestPayload = {"createFromVersion": propertyDeets['productionVersion']}
createVersion = httpCaller.postResult(
    "/papi/v0/properties/" + propertyDeets['propertyId'] + "/versions/",
    json.dumps(requestPayload), requestParams)

# List versions
propertyVersions = httpCaller.getResult(
    "/papi/v0/properties/" + propertyDeets['propertyId'] + "/versions/",
    requestParams)

# find the most recent version in the list
newVersion = propertyVersions['versions']['items'][0]['propertyVersion']

# PUT Rule tree
# path = "/papi/v0/properties/"+ propertyDeets['propertyId'] + "/versions/" + str(propertyDeets['productionVersion']) + "/rules/"
path = "/papi/v0/properties/" + propertyDeets[
    'propertyId'] + "/versions/" + str(newVersion) + "/rules/"
updateRules = httpCaller.putResult(path, json.dumps(ruleTree), requestParams)
示例#8
0
# Set the baseurl based on config.host
baseurl = '%s://%s/' % ('https', config.host)
httpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl)

if __name__ == "__main__":
	# Get the list of cloudlets to pick the one we want to use

	if version == "CREATE":
		new_version_info = {
				"description":"Adding a new version for match rules",
				"matchRuleFormat":"1.0",
				"matchRules": []
		}
		create_path = "/cloudlets/api/v2/policies/%s/versions" % policy
		create_result = httpCaller.postResult(create_path, 
							json.dumps(new_version_info))

	if version == "CREATE" or version == "LATEST":
		version_path = "/cloudlets/api/v2/policies/%s/versions" % policy
		version_result = httpCaller.getResult(version_path)
		version = version_result[0]["version"]

	# Now we know which version (and we've set the policy)

	# Open the JSON filename with mappings
	with open(filename) as data_file:
		data = json.load(data_file)

	for rule in data:
		rule_path = "/cloudlets/api/v2/policies/%s/versions/%s/rules" % (policy, version)
		rule_result = httpCaller.postResult(rule_path, json.dumps(rule))
class Cloudlet(object):
    def __init__(self, config):
        self.http_caller = EdgeGridHttpCaller(config, False, False)


    def list_cloudlet_groups(self):
        """
        Returns information about the Cloudlet types associated with the groups you have edit privileges for.

        Parameters
        -----------
            None

        Returns
        -------
            (result) Object with cloudlet types associated with the groups
        """
        endpoint = '/cloudlets/api/v2/group-info'
        result = self.http_caller.getResult(endpoint)
        return (result)


    def list_policies(
            self,
            group_id = None,
            cloudlet_id = None):
        """
        Returns cloudlet policies associated with group_id

        Parameters
        -----------
            group Id,
            cloudlet Id
        Returns
        -------
            (result) Policies of cloudlet Id
        """
        endpoint = '/cloudlets/api/v2/policies'
        result = self.http_caller.getResult(endpoint, {"gid": group_id, "cloudletId": cloudlet_id})
        return (result)


    def get_cloudlet_policy(self, policy_id, version = None):
        endpoint = '/cloudlets/api/v2/policies/' + str(policy_id)
        if version:
            endpoint += '/versions/' + version
        
        result = self.http_caller.getResult(endpoint, {})
        return (result)

        # if version == 'optional':
        #     cloudlet_policy_url = 'https://' + self.access_hostname + \
        #                           '/cloudlets/api/v2/policies/' + str(policy_id)
        # else:
        #     cloudlet_policy_url = 'https://' + self.access_hostname + '/cloudlets/api/v2/policies/' + \
        #                           str(policy_id) + '/versions/' + str(version) + '?omitRules=false'
        # cloudlet_policy_response = session.get(cloudlet_policy_url)
        
        return result


    def create_policy_version(
            self,
            policy_id,
            clone_version = None,
            policy_data = {}):
        
        endpoint = '/cloudlets/api/v2/policies/' + str(policy_id) + '/versions'
        result = self.http_caller.postResult(endpoint, policy_data, {'includeRules': 'true', 'cloneVersion': clone_version})
        return (result)


    def update_policy_version(
            self,
            policy_id,
            policy_details,
            version):
        
        endpoint = '/cloudlets/api/v2/policies/' + str(policy_id) + '/versions/' + str(version) + '?omitRules=false'
        # refactoring not finished
        cloudlet_policy_update_response = session.put(
            cloudlet_policy_update_url, data=policy_details, headers=headers)
        return cloudlet_policy_update_response


    def activate_policy_version(
            self,
            policy_id,
            version,
            network='staging'):
        """
        Function to activate a policy version
        """

        data = """{
            "network" : "%s"
        }""" % network

        endpoint = '/cloudlets/api/v2/policies/' + str(policy_id) + '/versions/' + str(version) + '/activations'
        result = self.http_caller.postResult(endpoint, data, {})
        return (result)
        

    def add_rule(
            self,
            policy_id,
            version,
            index = None,
            rule_data = {}):
        
        endpoint = '/cloudlets/api/v2/policies/' + str(policy_id) + '/versions/'+ str(version) +'/rules'
        result = self.http_caller.postResult(endpoint, rule_data, {'index': index})
        return (result)

    def modify_rule(
            self,
            policy_id,
            version,
            rule_id,
            # index = None,
            rule_data = {}):
        
        endpoint = '/cloudlets/api/v2/policies/' + str(policy_id) + '/versions/'+ str(version) +'/rules/' + str(rule_id)
        result = self.http_caller.putResult(endpoint, rule_data, {})
        return (result)