コード例 #1
0
 def test_env(self):
     os.environ[AtlasEnv.ATLAS_PUBLIC_KEY.value] = "123456789"
     os.environ[AtlasEnv.ATLAS_PRIVATE_KEY.value] = "987654321"
     key = AtlasKey.get_from_env()
     self.assertEqual(str(key), "AtlasKey(public_key='xxxxx1234', private_key='xxxxx9876')")
     del os.environ[AtlasEnv.ATLAS_PUBLIC_KEY.value]
     del os.environ[AtlasEnv.ATLAS_PRIVATE_KEY.value]
コード例 #2
0
    def __init__(self,
                 api_key: AtlasKey=None,
                 page_size: int = 100):

        self._api_key: AtlasKey = api_key
        self._auth = None
        self._log = logging.getLogger(__name__)
        self._page_size = page_size

        if self._page_size < 1 or self._page_size > 500 :
            raise AtlasInitialisationError("'page_size' must be between 1 and 500")

        if not self._api_key:
            self._api_key = AtlasKey.get_from_env()

        # print(self._username)
        # print(self._api_key)
        self._auth = HTTPDigestAuth(self._api_key.public_key, self._api_key.private_key)
コード例 #3
0
def main():

    parser = argparse.ArgumentParser()

    parser.add_argument("--publickey", help="MongoDB Atlas public API key")
    parser.add_argument("--privatekey", help="MongoDB Atlas private API key")

    parser.add_argument(
        "--atlasop",
        type=AtlasOperation,
        default=None,
        choices=list(AtlasOperation),
        help="Which Atlas operation do you want to run create, modify, delete")

    parser.add_argument("--resource",
                        type=AtlasResource,
                        default=None,
                        choices=list(AtlasResource),
                        help="Which resource type are we operating on:"
                        "organization, project or cluster?")

    parser.add_argument(
        "--data",
        help="Arguments for create and modify arguments (Python dict)")

    parser.add_argument("--orgid", help="ID for an AtlasOrganization")

    parser.add_argument("--projectid",
                        nargs="+",
                        help="Project ID for an AtlasProject")

    parser.add_argument("--projectname",
                        help="Project name for an AtlasProject")

    parser.add_argument("--clustername", help="name  for an AltasCluster")

    parser.add_argument("--org",
                        action="store_true",
                        default=False,
                        help="Get the organisation associated with the "
                        "current API key pair [default: %(default)s]")

    parser.add_argument(
        "--pause",
        default=[],
        dest="pause_cluster",
        action="append",
        help="pause named cluster in project specified by project_id "
        "Note that clusters that have been resumed cannot be paused"
        "for the next 60 minutes")
    parser.add_argument(
        "--resume",
        default=[],
        dest="resume_cluster",
        action="append",
        help="resume named cluster in project specified by project_id")
    parser.add_argument(
        "--list",
        type=AtlasResource,
        default=None,
        choices=list(AtlasResource),
        action="append",
        help="List all of the reachable categories [default: %(default)s]")

    parser.add_argument(
        '--cluster',
        default=[],
        action="append",
        help="list all elements for for project_id:cluster_name")
    parser.add_argument(
        "--project_id",
        default=[],
        dest="project_detail",
        action="append",
        help="specify project for cluster that is to be paused")
    parser.add_argument(
        '--format',
        type=OutputFormat,
        default=OutputFormat.SUMMARY,
        choices=list(OutputFormat),
        help="The format to output data either in a single line "
        "summary or a full JSON document [default: %(default)s]")
    parser.add_argument("--debug",
                        default=False,
                        action="store_true",
                        help="Turn on logging at debug level")
    parser.add_argument("--http",
                        type=HTTPOperation,
                        choices=list(HTTPOperation),
                        help="do a http operation")
    parser.add_argument("--url", help="URL for HTTP operation")
    parser.add_argument(
        "--itemsperpage",
        type=int,
        default=100,
        help="No of items to return per page [default: %(default)s]")
    parser.add_argument("--pagenum",
                        type=int,
                        default=1,
                        help="Page to return [default: %(default)s]")
    args = parser.parse_args()

    if args.debug:
        logging.basicConfig(
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            level=logging.DEBUG)
    else:
        logging.basicConfig(
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            level=logging.INFO)

    logging.debug("logging is on at DEBUG level")

    if args.publickey:
        public_key = args.publickey
    else:
        public_key = os.getenv("ATLAS_PUBLIC_KEY")
        if public_key is None:
            print("you must specify an ATLAS public key via --publickey arg "
                  "or the environment variable ATLAS_PUBLIC_KEY")
            sys.exit(10)

    if args.privatekey:
        private_key = args.privatekey
    else:
        private_key = os.getenv("ATLAS_PRIVATE_KEY")
        if private_key is None:
            print("you must specify an an ATLAS private key via --privatekey"
                  "arg or the environment variable ATLAS_PRIVATE_KEY")
            sys.exit(1)

    api = API(AtlasKey(public_key, private_key))
    org = api.get_this_organization()

    data = None
    if args.data:
        try:
            data = json.loads(args.data)
        except json.JSONDecodeError as e:
            print("Error decoding:")
            print(f"{args.data}")
            print(f"error:{e}")
            sys.exit(1)

    if args.atlasop is AtlasOperation.CREATE:
        if args.resource is AtlasResource.ORGANIZATION:
            print(
                'No support for organization creation at the moment use the UI'
            )
        elif args.resource is AtlasResource.PROJECT:
            if args.projectname:
                project = api.create_project(org.id, args.projectname)
                project.print_resource(args.format)
            else:
                print("You must specify a project name via --projectname")
        else:  # Cluster
            if args.projectid:
                if data:
                    cluster = api.create_cluster(args.project_id, args.data)
                    cluster.print_resource(args.format)
                else:
                    print("You must specify a JSON data object via --data")
    elif args.atlasop is AtlasOperation.PATCH:
        if args.resource is AtlasResource.ORGANIZATION:
            print("No support for modifying organizations in this release")
        elif args.resource is AtlasResource.PROJECT:
            print(
                "There is not modify capability for projects in MongoDB Atlas")
        else:  # Cluster
            if args.projectid:
                if args.clustername:
                    cluster = api.modify_cluster(args.projectid,
                                                 args.clustername, args.data)
                    cluster.print_resource(args.format)
                else:
                    print(f"You must specify a cluster name via --clustername")
            else:
                print(f"You must specify a project id via --projectid")
    elif args.atlasop is AtlasOperation.DELETE:
        if args.resource is AtlasResource.ORGANIZATION:
            print("You cannot delete organisations via atlascli at this time")
        elif args.resource is AtlasResource.PROJECT:
            if args.projectid:
                project = api.get_one_project(args.projectid)
                api.delete_project(args.projectid)
                print(f"Deleted project: {project.summary_string()}")
        elif args.resource is AtlasResource.CLUSTER:
            if args.projectid:
                if args.clustername:
                    cluster = api.get_one_cluster(args.projectid,
                                                  args.clustername)
                    api.delete_cluster(args.projectid, args.clustername)
                    print(f"Deleted cluster: {cluster.summary_string()}")
                else:
                    print(
                        "You must specify a a cluster name via --clustername")
            else:
                print("You must specify a project id via --projectid")

    elif args.atlasop is AtlasOperation.LIST:
        if args.resource is AtlasResource.ORGANIZATION:
            if args.orgid:
                org = api.get_one_organization(args.orgid)
                org.print_resource(args.format)
            else:
                org.print_resource(args.format)
        elif args.resource is AtlasResource.PROJECT:
            if args.projectid:
                AtlasResource.iter_print(args.projectid, api.get_one_project,
                                         args.format)
            else:
                for i in api.get_projects():
                    i.print_resource(args.format)

    elif args.atlasop is AtlasOperation.PAUSE:
        pass
    elif args.atlasop is AtlasOperation.RESUME:
        pass
コード例 #4
0
def main():
    parser = argparse.ArgumentParser(description=
                                     f"A command line program to list organizations,"
                                     f"projects and clusters on a MongoDB Atlas organization."
                                     f"You need to enable programmatic keys for this program"
                                     f" to work. See https://docs.atlas.mongodb.com/reference/api/apiKeys/ ",
                                     epilog=f"Version: {__VERSION__}")

    parser.add_argument("--publickey", help="MongoDB Atlas public API key."
                                            "Can be read from the environment variable ATLAS_PUBLIC_KEY")
    parser.add_argument("--privatekey", help="MongoDB Atlas private API key."
                                             "Can be read from the environment variable ATLAS_PRIVATE_KEY")

    # parser.add_argument("--atlasop",
    #                     type=AtlasOperationName,
    #                     default=None,
    #                     choices=list(AtlasOperationName),
    #                     help="Which Atlas operation do you want to run create, modify, delete, list, pause, resume"
    #                     )
    #
    # parser.add_argument("--resource",
    #                     type=AtlasResourceName, default=None,
    #                     choices=list(AtlasResourceName),
    #                     help="Which resource type are we operating on:"
    #                          "organization, project or cluster?")

    # parser.add_argument("--data",
    #                     help="Arguments for create and modify arguments (Python dict)")

    # parser.add_argument("--orgid",
    #                     help="ID for an AtlasOrganization")

    # parser.add_argument("--projectname",
    #                     help="Project name for an AtlasProject")
    #
    # parser.add_argument("--clustername",
    #                     help="name  for an AltasCluster")

    # parser.add_argument("--org", action="store_true", default=False,
    #                     help="Get the organisation associated with the "
    #                          "current API key pair [default: %(default)s]")

    parser.add_argument("-p", "--pause", default=[], dest="pause_cluster",
                        action="append",
                        help="pause named cluster in project specified by project_id "
                             "Note that clusters that have been resumed cannot be paused "
                             "for the next 60 minutes")

    parser.add_argument("-r", "--resume", default=[],
                        dest="resume_cluster", action="append",
                        help="resume named cluster in project specified by project_id")

    parser.add_argument("-l", "--list",
                        action="store_true",
                        default=False,
                        help="List everything in the organization")

    parser.add_argument("-lp", "--listproj",
                        action="store_true",
                        default=False,
                        help="List all projects")

    parser.add_argument("-lc", "--listcluster",
                        action="store_true",
                        default=False,
                        help="List all clusters")

    parser.add_argument("-pid", "--project_id", default=[], dest="project_id_list",
                        action="append",
                        help="specify the project ID for cluster that is to be paused")
    # parser.add_argument('--format', type=OutputFormat,
    #                     default=OutputFormat.SUMMARY, choices=list(OutputFormat),
    #                     help="The format to output data either in a single line "
    #                          "summary or a full JSON document [default: %(default)s]")
    parser.add_argument("-d", "--debug", default=False, action="store_true",
                        help="Turn on logging at debug level")
    # parser.add_argument("--http", type=HTTPOperationName, choices=list(HTTPOperationName),
    #                     help="do a http operation")
    # parser.add_argument("--url", help="URL for HTTP operation")
    # parser.add_argument("--itemsperpage", type=int, default=100,
    #                     help="No of items to return per page [default: %(default)s]")
    # parser.add_argument("--pagenum", type=int, default=1,
    #                     help="Page to return [default: %(default)s]")

    args = parser.parse_args()

    if args.debug:
        logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                            level=logging.DEBUG)
    else:
        logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                            level=logging.INFO)

    logging.debug("logging is on at DEBUG level")

    # Stop noisy urllib3 info logs
    logging.getLogger("requests").setLevel(logging.WARNING)
    if args.publickey:
        public_key = args.publickey
    else:
        public_key = os.getenv("ATLAS_PUBLIC_KEY")
        if public_key is None:
            print("you must specify an ATLAS public key via --publickey arg "
                  "or the environment variable ATLAS_PUBLIC_KEY")
            sys.exit(10)

    if args.privatekey:
        private_key = args.privatekey
    else:
        private_key = os.getenv("ATLAS_PRIVATE_KEY")
        if private_key is None:
            print("you must specify an an ATLAS private key via --privatekey"
                  "arg or the environment variable ATLAS_PRIVATE_KEY")
            sys.exit(1)

    api = OPCAPI(AtlasKey(public_key, private_key))
    org = api.get_this_organization()

    # data = None
    # if args.data:
    #     try:
    #         data = json.loads(args.data)
    #     except json.JSONDecodeError as e:
    #         print("Error decoding:")
    #         print(f"{args.data}")
    #         print(f"error:{e}")
    #         sys.exit(1)

    # if args.atlasop is AtlasOperationName.CREATE:
    #     if args.resource is AtlasResourceName.ORGANIZATION:
    #         print('No support for organization creation at the moment use the UI')
    #     elif args.resource is AtlasResourceName.PROJECT:
    #         if args.projectname:
    #             project = api.create_project(org.id, args.projectname)
    #             project.print_resource(args.format)
    #         else:
    #             print("You must specify a project name via --projectname")
    #     else:  # Cluster
    #         if args.projectid:
    #             if data:
    #                 cluster = api.create_cluster(args.project_id, args.data)
    #                 cluster.print_resource(args.format)
    #             else:
    #                 print("You must specify a JSON data object via --data")
    # elif args.atlasop is AtlasOperationName.PATCH:
    #     if args.resource is AtlasResourceName.ORGANIZATION:
    #         print("No support for modifying organizations in this release")
    #     elif args.resource is AtlasResourceName.PROJECT:
    #         print("There is no modify capability for projects in MongoDB Atlas")
    #     else:  # Cluster
    #         if args.projectid:
    #             if args.clustername:
    #                 cluster = api.modify_cluster(args.projectid,
    #                                              args.clustername,
    #                                              args.data)
    #                 cluster.print_resource(args.format)
    #             else:
    #                 print(f"You must specify a cluster name via --clustername")
    #         else:
    #             print(f"You must specify a project id via --projectid")
    # elif args.atlasop is AtlasOperationName.DELETE:
    #     if args.resource is AtlasResourceName.ORGANIZATION:
    #         print("You cannot delete organisations via atlascli at this time")
    #     elif args.resource is AtlasResourceName.PROJECT:
    #         if args.projectid:
    #             project = api.get_one_project(args.projectid)
    #             api.delete_project(args.projectid)
    #             print(f"Deleted project: {project.summary_string()}")
    #     elif args.resource is AtlasResourceName.CLUSTER:
    #         if args.projectid:
    #             if args.clustername:
    #                 cluster = api.get_one_cluster(args.project_id[0], args.clustername)
    #                 api.delete_cluster(args.projectid, args.clustername)
    #                 print(f"Deleted cluster: {cluster.summary_string()}")
    #             else:
    #                 print("You must specify a a cluster name via --clustername")
    #         else:
    #             print("You must specify a project id via --projectid")

    if args.list:
        org = api.get_organization_and_clusters()
        print(org)
        org.pprint()
    if args.listproj :
        if args.project_id_list:
            for project_id in args.project_id_list:
                print(api.get_one_project(project_id))
        else:
            for project in api.get_projects():
                print(f"\nProject: '{project.name}'")
                print(project)
    if args.listcluster:
        if args.project_id_list:
            for project_id in args.project_id_list:
                clusters = api.get_clusters(project_id)

                for cluster in clusters:
                    print(f"\nProject: '{project_id}' Cluster: '{cluster.name}'")
                    print(cluster)
        else:
            for project in api.get_projects():
                clusters = api.get_clusters(project.id)
                for cluster in clusters:
                    print(f"\nProject: '{project.id}' Cluster: '{cluster.name}'")
                    print(cluster)

    if args.pause_cluster or args.resume_cluster:
        if args.project_id_list:
            for cluster_name in args.pause_cluster:
                print(f"Pausing '{cluster_name}'")
                cluster = api.get_one_cluster(args.project_id_list[0], cluster_name)
                if cluster.resource['paused']:
                    print(f"'cluster_name' is already paused, nothing to do")
                else:
                    result = api.pause_cluster(args.project_id_list[0], cluster_name)
                    print(f"Paused cluster '{cluster_name}'")
                    # pprint.pprint(result)

            if args.resume_cluster:
                for cluster_name in args.resume_cluster:
                    print(f"Resuming cluster '{cluster_name}'")
                    cluster=api.get_one_cluster(args.project_id_list[0], cluster_name)
                    if cluster.resource['paused']:
                        result = api.resume_cluster(args.project_id_list[0], cluster_name)
                        print(f"Resumed cluster '{cluster_name}'")
                    else:
                        print(f"'cluster_name' is already resumed, nothing to do")
                    #pprint.pprint(result)
        else:
            print(f"You must specify a --project_id for the cluster to be paused or resumed")
コード例 #5
0
 def setUp(self):
     key = AtlasKey.get_from_env()
     self._api = AtlasRequests(api_key=key, debug=1)
コード例 #6
0
 def setUp(self):
     key = AtlasKey.get_from_env()
     self._api = APIMixin(api_key=key, debug=1)
コード例 #7
0
 def test_no_env(self):
     del os.environ[AtlasEnv.ATLAS_PUBLIC_KEY.value]
     del os.environ[AtlasEnv.ATLAS_PRIVATE_KEY.value]
     with self.assertRaises(AtlasEnvironmentError):
         _=AtlasKey.get_from_env()
コード例 #8
0
    def test_atlaskey(self):

        key = AtlasKey(private_key="AAAAAAAAAA", public_key="BBBBBBBBBBB")
        self.assertEqual(str(key), "AtlasKey(public_key='xxxxxxxBBBB', private_key='xxxxxxAAAA')")
コード例 #9
0
import requests
from requests.auth import HTTPDigestAuth
from mongodbatlas.atlaskey import AtlasKey

key = AtlasKey.get_from_env()

try:
    r = requests.get("https://cloud.mongodb.com/api/atlas/v1.0/groups",
                     headers={
                         "Accept": "application/json",
                         "Content-Type": "application/json"
                     },
                     auth=HTTPDigestAuth(key.public_key, key.private_key))
    print(r.json())
    r.raise_for_status()
except requests.exceptions.HTTPError as e:
    print(e)
    print(e.response)