mirror of
https://gitlab.sectorq.eu/jaydee/portainer.git
synced 2025-12-14 10:44:52 +01:00
build
This commit is contained in:
147
portainer.py
147
portainer.py
@@ -3,15 +3,11 @@ import os
|
||||
import sys
|
||||
import requests
|
||||
import json
|
||||
import uuid
|
||||
import argparse
|
||||
import shutil
|
||||
import time
|
||||
from tabulate import tabulate
|
||||
from git import Repo # pip install gitpython
|
||||
from port import Portainer
|
||||
import logging
|
||||
VERSION="0.0.1"
|
||||
VERSION = "0.0.1"
|
||||
|
||||
defaults = {
|
||||
"endpoint_id": "vm01",
|
||||
@@ -24,18 +20,21 @@ defaults = {
|
||||
|
||||
|
||||
parser = argparse.ArgumentParser(description="Portainer helper - use env vars or pass credentials.")
|
||||
parser.add_argument("--base", "-b", default=os.getenv("PORTAINER_URL", \
|
||||
"https://portainer.example.com"),help="Base URL for Portainer (ENV: PORTAINER_URL)")
|
||||
parser.add_argument("--base",
|
||||
"-b",
|
||||
default=os.getenv("PORTAINER_URL", "https://portainer.example.com"),
|
||||
help="Base URL for Portainer (ENV: PORTAINER_URL)"
|
||||
)
|
||||
parser.add_argument("--site", "-t", type=str, default=None, help="Site")
|
||||
parser.add_argument("--endpoint-id", "-e", type=str, default=None, help="Endpoint ID to limit stack operations")
|
||||
parser.add_argument("--refresh-environment", "-R", action="store_true", help="List endpoints")
|
||||
parser.add_argument("--list-endpoints","-E", action="store_true", help="List endpoints")
|
||||
parser.add_argument("--list-endpoints", "-E", action="store_true", help="List endpoints")
|
||||
parser.add_argument("--list-stacks", "-l", action="store_true", help="List stacks")
|
||||
parser.add_argument("--print-all-data", "-A", action="store_true", help="List stacks")
|
||||
parser.add_argument("--list-containers", "-c", action="store_true", help="List containers")
|
||||
parser.add_argument("--update-stack", "-U", action="store_true", help="Update stacls")
|
||||
parser.add_argument("--update-stack", "-U", action="store_true", help="Update stacks")
|
||||
parser.add_argument("--stop-containers", "-O", action="store_true", help="Stop containers")
|
||||
parser.add_argument("--start-containers", "-X", action="store_true", help="Stop containers")
|
||||
parser.add_argument("--start-containers", "-X", action="store_true", help="Start containers")
|
||||
parser.add_argument("--update-status", "-S", action="store_true", help="Update status")
|
||||
parser.add_argument("--get-stack", metavar="NAME_OR_ID", help="Get stack by name or numeric id")
|
||||
parser.add_argument("--action", "-a", type=str, default=None, help="Action to perform")
|
||||
@@ -44,17 +43,17 @@ parser.add_argument("--start-stack", "-x", action='store_true')
|
||||
parser.add_argument("--stop-stack", "-o", action='store_true')
|
||||
parser.add_argument("--secrets", "-q", action='store_true')
|
||||
parser.add_argument("--debug", "-D", action='store_true')
|
||||
parser.add_argument("--create-stack","-n", action='store_true')
|
||||
parser.add_argument("--create-stack_new2","-N", action='store_true')
|
||||
parser.add_argument("--gpu","-g", action='store_true')
|
||||
parser.add_argument("--create-stacks","-C", action='store_true')
|
||||
parser.add_argument("--refresh-status","-r", action='store_true')
|
||||
parser.add_argument("--create-stack", "-n", action='store_true')
|
||||
parser.add_argument("--create-stack_new2", "-N", action='store_true')
|
||||
parser.add_argument("--gpu", "-g", action='store_true')
|
||||
parser.add_argument("--create-stacks", "-C", action='store_true')
|
||||
parser.add_argument("--refresh-status", "-r", action='store_true')
|
||||
|
||||
parser.add_argument("--stack", "-s", type=str, help="Stack ID for operations")
|
||||
parser.add_argument("--token-only", action="store_true", help="Print auth token and exit")
|
||||
parser.add_argument("--timeout", type=int, default=10, help="Request timeout seconds")
|
||||
parser.add_argument("--deploy-mode","-m", type=str, default="git", help="Deploy mode")
|
||||
parser.add_argument("--stack-mode","-w", default=None, help="Stack mode")
|
||||
parser.add_argument("--deploy-mode", "-m", type=str, default="git", help="Deploy mode")
|
||||
parser.add_argument("--stack-mode", "-w", default=None, help="Stack mode")
|
||||
args = parser.parse_args()
|
||||
print("Running version:", VERSION)
|
||||
print("Environment:", args.site)
|
||||
@@ -62,19 +61,39 @@ print("Environment:", args.site)
|
||||
_LOG_LEVEL = "INFO"
|
||||
LOG_FILE = "/tmp/portainer.log"
|
||||
if _LOG_LEVEL == "DEBUG":
|
||||
logging.basicConfig(filename=LOG_FILE, level=logging.DEBUG, format='%(asctime)s : %(levelname)s : %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
|
||||
logging.debug('using debug loging')
|
||||
logging.basicConfig(
|
||||
filename=LOG_FILE,
|
||||
level=logging.DEBUG,
|
||||
format='%(asctime)s : %(levelname)s : %(message)s',
|
||||
datefmt='%m/%d/%Y %I:%M:%S %p'
|
||||
)
|
||||
logging.debug('using debug logging')
|
||||
elif _LOG_LEVEL == "ERROR":
|
||||
logging.basicConfig(filename=LOG_FILE, level=logging.ERROR, format='%(asctime)s : %(levelname)s : %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
|
||||
logging.info('using error loging')
|
||||
logging.basicConfig(
|
||||
filename=LOG_FILE,
|
||||
level=logging.ERROR,
|
||||
format='%(asctime)s : %(levelname)s : %(message)s',
|
||||
datefmt='%m/%d/%Y %I:%M:%S %p'
|
||||
)
|
||||
logging.info('using error logging')
|
||||
elif _LOG_LEVEL == "SCAN":
|
||||
logging.basicConfig(filename=LOG_FILE, level=logging.DEBUG, format='%(asctime)s : %(levelname)s : %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
|
||||
logging.info('using error loging')
|
||||
logging.basicConfig(
|
||||
filename=LOG_FILE,
|
||||
level=logging.DEBUG,
|
||||
format='%(asctime)s : %(levelname)s : %(message)s',
|
||||
datefmt='%m/%d/%Y %I:%M:%S %p'
|
||||
)
|
||||
logging.info('using scan logging')
|
||||
else:
|
||||
logging.basicConfig(filename=LOG_FILE, level=logging.INFO, format='%(asctime)s : %(levelname)s : %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
|
||||
logging.info("script started")
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.basicConfig(
|
||||
filename=LOG_FILE,
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s : %(levelname)s : %(message)s',
|
||||
datefmt='%m/%d/%Y %I:%M:%S %p'
|
||||
)
|
||||
logging.info("script started")
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
if args.site == "portainer":
|
||||
base = os.getenv("PORTAINER_URL", "https://portainer.sectorq.eu/api")
|
||||
@@ -82,10 +101,13 @@ if args.site == "portainer":
|
||||
else:
|
||||
base = os.getenv("PORTAINER_URL", "https://port.sectorq.eu/api")
|
||||
portainer_api_key = "ptr_/5RkMCT/j3BTaL32vMSDtXFi76yOXRKVFOrUtzMsl5Y="
|
||||
|
||||
|
||||
|
||||
def wl(msg):
|
||||
if args.debug:
|
||||
print(msg)
|
||||
|
||||
|
||||
def is_number(s):
|
||||
"""Check if the input string is a number."""
|
||||
try:
|
||||
@@ -95,7 +117,6 @@ def is_number(s):
|
||||
return False
|
||||
|
||||
|
||||
|
||||
def get_portainer_token(base_url, username=None, password=None, timeout=10):
|
||||
"""
|
||||
Authenticate to Portainer and return a JWT token.
|
||||
@@ -114,6 +135,8 @@ def get_portainer_token(base_url, username=None, password=None, timeout=10):
|
||||
if not token:
|
||||
raise ValueError(f"No token found in response: {data}")
|
||||
return token
|
||||
|
||||
|
||||
def prompt_missing_args(args, defaults, fields):
|
||||
"""
|
||||
fields = [("arg_name", "Prompt text")]
|
||||
@@ -132,11 +155,27 @@ def prompt_missing_args(args, defaults, fields):
|
||||
setattr(args, field, value)
|
||||
|
||||
return args
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Example usage: set PORTAINER_USER and PORTAINER_PASS in env, or pass literals below.
|
||||
#token = get_portainer_token(base,"admin","l4c1j4yd33Du5lo") # or get_portainer_token(base, "admin", "secret")
|
||||
if args.action == None:
|
||||
actions = ["delete_stack","create_stack","stop_stack","start_stack","list_stacks","update_stack","secrets","print_all_data","list_endpoints","list_containers","stop_containers","start_containers","refresh_environment","refresh_status","update_status"]
|
||||
# token = get_portainer_token(base,"admin","l4c1j4yd33Du5lo") # or get_portainer_token(base, "admin", "secret")
|
||||
if args.action is None:
|
||||
actions = ["delete_stack",
|
||||
"create_stack",
|
||||
"stop_stack",
|
||||
"start_stack",
|
||||
"list_stacks",
|
||||
"update_stack",
|
||||
"secrets",
|
||||
"print_all_data",
|
||||
"list_endpoints",
|
||||
"list_containers",
|
||||
"stop_containers",
|
||||
"start_containers",
|
||||
"refresh_environment",
|
||||
"refresh_status",
|
||||
"update_status"]
|
||||
print("Possible actions: ")
|
||||
i = 1
|
||||
for a in actions:
|
||||
@@ -144,15 +183,15 @@ if __name__ == "__main__":
|
||||
i += 1
|
||||
ans = input("\nSelect action to perform: ")
|
||||
args.action = actions[int(ans)-1]
|
||||
|
||||
|
||||
token = portainer_api_key
|
||||
# Example: list endpoints
|
||||
por = Portainer(base, token)
|
||||
|
||||
if args.action == "secrets":
|
||||
if args.endpoint_id == None:
|
||||
args.endpoint_id = input("Endpoint ID is required for creating secrets : ")
|
||||
|
||||
if args.endpoint_id is None:
|
||||
args.endpoint_id = input("Endpoint ID is required for creating secrets : ")
|
||||
|
||||
secrets = {
|
||||
"gitea_runner_registration_token": "8nmKqJhkvYwltmNfF2o9vs0tzo70ufHSQpVg6ymb",
|
||||
"influxdb2-admin-token": "l4c1j4yd33Du5lo",
|
||||
@@ -182,42 +221,40 @@ if __name__ == "__main__":
|
||||
("stack_mode", "Stack mode (swarm or compose)"),
|
||||
("deploy_mode", "Deploy mode (git or upload)")
|
||||
])
|
||||
|
||||
|
||||
por.create_stack(args.endpoint_id,args.stack, args.deploy_mode, args.autostart, args.stack_mode)
|
||||
por.create_stack(args.endpoint_id, args.stack, args.deploy_mode, args.autostart, args.stack_mode)
|
||||
sys.exit()
|
||||
|
||||
if args.action == "stop_stack":
|
||||
if args.endpoint_id == None:
|
||||
args.endpoint_id = input("Endpoint ID is required for stopping stacks : ")
|
||||
if args.stack == None:
|
||||
args.stack = input("Stack name or ID is required for stopping stacks : ")
|
||||
por.stop_stack(args.stack,args.endpoint_id)
|
||||
if args.endpoint_id is None:
|
||||
args.endpoint_id = input("Endpoint ID is required for stopping stacks : ")
|
||||
if args.stack is None:
|
||||
args.stack = input("Stack name or ID is required for stopping stacks : ")
|
||||
por.stop_stack(args.stack, args.endpoint_id)
|
||||
sys.exit()
|
||||
|
||||
|
||||
if args.action == "start_stack":
|
||||
if args.endpoint_id == None:
|
||||
args.endpoint_id = input("Endpoint ID is required for starting stacks : ")
|
||||
if args.stack == None:
|
||||
args.stack = input("Stack name or ID is required for starting stacks : ")
|
||||
if args.endpoint_id is None:
|
||||
args.endpoint_id = input("Endpoint ID is required for starting stacks : ")
|
||||
if args.stack is None:
|
||||
args.stack = input("Stack name or ID is required for starting stacks : ")
|
||||
por.start_stack(args.stack, args.endpoint_id)
|
||||
sys.exit()
|
||||
|
||||
if args.action == "list_stacks":
|
||||
por.print_stacks(args.endpoint_id)
|
||||
print(json.dumps(por.all_data,indent=2))
|
||||
print(json.dumps(por.all_data, indent=2))
|
||||
sys.exit()
|
||||
|
||||
|
||||
if args.action == "list_containers":
|
||||
print("Getting containers")
|
||||
por.get_containers(args.endpoint_id,args.stack)
|
||||
por.get_containers(args.endpoint_id, args.stack)
|
||||
sys.exit()
|
||||
|
||||
if args.action == "update_stack":
|
||||
print("Updating stacks")
|
||||
autostart=True if args.autostart else False
|
||||
por.update_stack(args.endpoint_id,args.stack,autostart)
|
||||
sys.exit()
|
||||
autostart = True if args.autostart else False
|
||||
por.update_stack(args.endpoint_id, args.stack, autostart)
|
||||
sys.exit()
|
||||
if args.action == "print_all_data":
|
||||
print(json.dumps(por.all_data, indent=2))
|
||||
sys.exit()
|
||||
|
||||
Reference in New Issue
Block a user