Python create Confluence Pages
Python script to create confluence page (+ child pages) from confluence markup .txt files. Handles page name collisions.
#!/usr/bin/python ################################################################################### # Name : awrConfluence.py # Purpose : Create confluence page (+ child pages) from confluence markup .txt files # Based on https://stackoverflow.com/questions/33168060/how-can-i-create-a-new-page-to-confluence-with-python # Parameters : 1 = p_test_description free text description field passed in by e.g. jenkins job ################################################################################### # initialize import requests import json import argparse import datetime import sys from requests.auth import HTTPBasicAuth # Global variables: set auth token and get the basic auth code auth_token = 'myAuthToken' basic_auth = HTTPBasicAuth('myConfluenceUser', auth_token) space_key = 'myconfluencespace' url = 'https://confluenceserver.mydomain/rest/api/content/' parser = argparse.ArgumentParser() parser.add_argument('p_test_description') args = parser.parse_args() ################################################################################### def pageExists(page_title): # checks if confluence page already exists # Request Headers headers = { 'Content-Type': 'application/json;charset=iso-8859-1', } # Request body data = { 'type': 'page', 'title': page_title, 'space': {'key':space_key} } try: r = requests.get(url=url, params=data, headers=headers, auth=basic_auth) # Consider any status other than 2xx an error if not r.status_code // 100 == 2: print("Error: Unexpected response {}".format(r)) sys.exit() else: if 'id' in r.text and r.json()['results'][0]['id'].isdigit(): return True else: return False except requests.exceptions.RequestException as e: # A serious problem happened, like an SSLError or InvalidURL print("Error: {}".format(e)) sys.exit() ################################################################################### def createPage(page_title, parent_page_id, inputTextFile): # creates a confluence page, returns the new page ID. # Set the title and content of the page to create. Utf8 encoding is needed to deal with 201a low-9 quotation mark symbol in activity charts. with open(inputTextFile, 'r', encoding='utf8') as text_file: page_html = text_file.read() # Request Headers headers = { 'Content-Type': 'application/json;charset=iso-8859-1', } # Request body data = { 'type': 'page', 'title': page_title, 'ancestors': [{'id':parent_page_id}], 'space': {'key':space_key}, 'body': { 'storage':{ 'value': page_html, 'representation':'wiki', } } } try: r = requests.post(url=url, data=json.dumps(data), headers=headers, auth=basic_auth) # Consider any status other than 2xx an error if not r.status_code // 100 == 2: print("Error: Unexpected response {}".format(r)) print(r.text) return('Error') else: return r.json()['id'] except requests.exceptions.RequestException as e: # A serious problem happened, like an SSLError or InvalidURL print("Error: {}".format(e)) return('Error') ################################################################################### # main block page_name = " ".join(args.p_test_description.split()) # strip out extra space characters (if any) if page_name == '': page_name = '{:%Y%m%d%H%M%S}'.format(datetime.datetime.now()) elif pageExists("DB Analysis " + page_name) or pageExists("Load Comparison " + page_name) or pageExists("All SQL Comparison " + page_name) or pageExists("Sql Analysis " + page_name) or pageExists("Database Activity " + page_name): page_name = page_name + ' {:%Y%m%d%H%M%S}'.format(datetime.datetime.now()) page_id = createPage("DB Analysis " + page_name, 999999999, 'dbAnalysis.txt') # 999999999 is confluence id of ultimate parent holding page. if page_id != 'Error': child_page_id = createPage("Database Activity " + page_name, page_id, 'databaseActivity.txt') child_page_id = createPage("Load Comparison " + page_name, page_id, 'load_comp.txt') child_page_id = createPage("Sql Analysis " + page_name, page_id, 'sql_comp.txt') child_page_id = createPage("All SQL Comparison " + page_name, page_id, 'all_sql_comp.txt') print(f"Confluence page created as https://confluenceserver.mydomain/display/myconfluencespace/DB+Analysis+{page_name.replace(' ', '+')} ") ###################################################################################
Can be called from Jenkins “windows batch command” with:
python awrConfluence.py "%p_test_description%"
H/t J. Antunes and Somaiah Kumbera at https://stackoverflow.com/questions/33168060/how-can-i-create-a-new-page-to-confluence-with-python
Leave a Reply