def main():

    # Get and log the config from the Env variable
    config = json.loads(os.environ["CUSTOM_SCRIPT_CONFIG"])
    print(config)

    # Get PC info from the config dict
    pc_info = config.get("tdaas_pc")
    pc_external_ip = pc_info.get("ips")[0][0]
    pc_internal_ip = pc_info.get("ips")[0][1]
    pc_password = pc_info.get("prism_password")

    try:

        # Get marketplace items
        mp_items = body_via_v3_post(pc_external_ip, "calm_marketplace_items",
                                    pc_password, None).json

        # Loop through our items
        for item in mp_items["entities"]:

            # We only care about those PENDING
            if item["status"]["app_state"] == "PENDING":

                # Get and modify the body
                body = body_via_v3_get(
                    pc_external_ip,
                    "calm_marketplace_items",
                    pc_password,
                    item["metadata"]["uuid"],
                ).json
                del body["status"]
                body["spec"]["resources"]["app_state"] = "ACCEPTED"

                # Update the item
                resp = update_via_v3_put(
                    pc_external_ip,
                    "calm_marketplace_items",
                    pc_password,
                    item["metadata"]["uuid"],
                    body,
                )

                # Log appropriately based on response
                if resp.code == 200 or resp.code == 202:
                    print(
                        f"{item['status']['name']} bp approved successfully.")
                else:
                    raise Exception(
                        f"{item['status']['name']} bp approved failed with:\n"
                        + f"Resp: {resp}\n" + f"Error Code: {resp.code}\n" +
                        f"Error Message: {resp.message}")

    except Exception as ex:
        print(traceback.format_exc())
        sys.exit(1)
Exemple #2
0
def main():

    # Get and log the config from the Env variable
    config = json.loads(os.environ["CUSTOM_SCRIPT_CONFIG"])
    INFO(config)

    # Get PC info from the config dict
    pc_info = config.get("tdaas_pc")
    pc_external_ip = pc_info.get("ips")[0][0]
    pc_internal_ip = pc_info.get("ips")[0][1]
    pc_password = pc_info.get("prism_password")

    try:

        # Convert our spec to dict
        apps_spec = file_to_dict("specs/calm_bp_publish.json")

        # Get our non-default projects before the loop
        projects_payload = {"filter": "name!=default"}
        projects_resp = body_via_v3_post(pc_external_ip, "projects",
                                         pc_password, projects_payload)

        # Loop through our to-be-published apps
        for app in apps_spec["entities"]:

            # Construct payload and make call
            mp_payload = {"filter": f"name=={app['mp_name']}"}
            mp_post = body_via_v3_post(pc_external_ip,
                                       "calm_marketplace_items", pc_password,
                                       mp_payload)

            # Loop through our response to find matching version
            for mp_item in mp_post.json["entities"]:
                if (mp_item["status"]["app_state"] == "ACCEPTED"
                        and mp_item["status"]["version"] == app["bp_version"]
                        and mp_item["status"]["app_source"]
                        == app["app_source"]):

                    # Make a GET with our UUID
                    mp_get = body_via_v3_get(
                        pc_external_ip,
                        "calm_marketplace_items",
                        pc_password,
                        mp_item["metadata"]["uuid"],
                    )

                    # Modify the response body
                    mp_body = mp_get.json
                    del mp_body["status"]
                    mp_body["spec"]["resources"]["app_state"] = "PUBLISHED"
                    for project in projects_resp.json["entities"]:
                        mp_body["spec"]["resources"][
                            "project_reference_list"].append(
                                project["metadata"]["project_reference"])

                    # Publish the blueprint
                    pub_resp = update_via_v3_put(
                        pc_external_ip,
                        "calm_marketplace_items",
                        pc_password,
                        mp_body["metadata"]["uuid"],
                        mp_body,
                    )

                    # Log appropriately based on response
                    if pub_resp.code == 200 or pub_resp.code == 202:
                        INFO(
                            f"{mp_body['spec']['name']} MP item published successfully."
                        )
                    else:
                        raise Exception(
                            f"{mp_body['spec']['name']} MP App Publish failed with:\n"
                            + f"Resp: {resp}\n" +
                            f"Error Code: {pub_resp.code}\n" +
                            f"Error Message: {pub_resp.message}")

    except Exception as ex:
        ERROR(traceback.format_exc())
Exemple #3
0
def main():

    # Get and log the config from the Env variable
    config = json.loads(os.environ["CUSTOM_SCRIPT_CONFIG"])
    INFO(config)

    # Get PC info from the config dict
    pc_info = config.get("tdaas_pc")
    pc_external_ip = pc_info.get("ips")[0][0]
    pc_internal_ip = pc_info.get("ips")[0][1]
    pc_password = pc_info.get("prism_password")

    try:

        # Read in the spec files and conver to dicts
        subnet_spec = file_to_dict("specs/calm_subnet.spec")
        INFO(f"subnet_spec: {subnet_spec}")
        secret_spec = file_to_dict("specs/calm_secrets.spec")
        INFO(f"secret_spec: {secret_spec}")

        # Get our subnet and image info from the infra
        subnet_info = get_subnet_info(pc_external_ip, pc_password,
                                      subnet_spec["vlan"])
        image_info = body_via_v3_post(pc_external_ip, "images", pc_password,
                                      None).json

        # Get a list of DRAFT blueprints
        payload = {"filter": "state==DRAFT"}
        draft_resp = body_via_v3_post(pc_external_ip, "blueprints",
                                      pc_password, payload).json

        # Loop through the blueprints to modify
        for bp in draft_resp["entities"]:

            # Get the body of our blueprint
            bp_body = body_via_v3_get(pc_external_ip, "blueprints",
                                      pc_password, bp["metadata"]["uuid"]).json

            # Remove unneeded status
            del bp_body["status"]

            # Configure secrets
            for secret in bp_body["spec"]["resources"]\
                                 ["credential_definition_list"]:
                secret["secret"]["attrs"]["is_secret_modified"] = True
                # Find a matching type/username from our secret_spec
                for ss in secret_spec["entities"]:
                    if secret["type"] == ss["type"] and\
                       secret["username"] == ss["username"]:
                        secret["secret"]["value"] = ss["secret"]
                print(json.dumps(secret, sort_keys=True, indent=4))

            # Configure NICs and Images
            for substrate in bp_body["spec"]["resources"][
                    "substrate_definition_list"]:
                if substrate["type"] == "AHV_VM":
                    for nic in substrate["create_spec"]["resources"][
                            "nic_list"]:
                        nic["subnet_reference"]["uuid"] = subnet_info["uuid"]
                        nic["subnet_reference"]["name"] = subnet_info["name"]
                        print(json.dumps(nic, sort_keys=True, indent=4))
                    for disk in substrate["create_spec"]["resources"][
                            "disk_list"]:
                        if disk["data_source_reference"] is not None and\
                           disk["data_source_reference"]["kind"] == "image":
                            for image in image_info["entities"]:
                                if image["status"]["name"] == disk[
                                        "data_source_reference"]["name"]:
                                    disk["data_source_reference"][
                                        "uuid"] = image["metadata"]["uuid"]
                                    print(
                                        json.dumps(disk,
                                                   sort_keys=True,
                                                   indent=4))

            # Update our blueprint
            resp = update_via_v3_put(pc_external_ip, "blueprints", pc_password,
                                     bp["metadata"]["uuid"], bp_body)

            # Log appropriately based on response
            if (resp.code == 200 or resp.code == 202):
                INFO(
                    f"{bp['metadata']['name']} blueprint updated successfully."
                )
            else:
                raise Exception(f"{bp['metadata']['name']} blueprint update" +
                                f" failed with:\n" +
                                f"Error Code: {resp.code}\n" +
                                f"Error Message: {resp.message}")

    except Exception as ex:
        INFO(ex)
def main():

    # Get and log the config from the Env variable
    config = json.loads(os.environ["CUSTOM_SCRIPT_CONFIG"])
    INFO(config)

    # Get PC info from the config dict
    pc_info = config.get("tdaas_pc")
    pc_external_ip = pc_info.get("ips")[0][0]
    pc_internal_ip = pc_info.get("ips")[0][1]
    pc_password = pc_info.get("prism_password")

    try:

        # Convert our spec to dict
        subnet_spec = file_to_dict("specs/calm_subnet.json")

        # Get our info from the infra
        subnet_info = get_subnet_info(
            pc_external_ip, pc_password, subnet_spec["entities"][0]["vlan"]
        )
        if "proxy_vm" in config:
            public_subnet_info = get_subnet_info(
                pc_external_ip, pc_password, subnet_spec["entities"][1]["vlan"]
            )
        account_info = body_via_v3_post(pc_external_ip, "accounts", pc_password, None)
        env_uuid = uuid_via_v3_post(pc_external_ip, "environments", pc_password, "")

        # Get the pojects body
        project_resp = body_via_v3_post(pc_external_ip, "projects", pc_password, None)

        # Loop through each project to add the env
        for project in project_resp.json["entities"]:

            # Delete the unneeded "status"
            del project["status"]

            # If default project, add subnet_ref_list
            if project["spec"]["name"] == "default":

                # add subnet if not present
                if len(project["spec"]["resources"]["subnet_reference_list"]) == 0:
                    project["spec"]["resources"]["subnet_reference_list"].append(
                        {
                            "kind": "subnet",
                            "name": subnet_info["name"],
                            "uuid": subnet_info["uuid"],
                        }
                    )
                    if "proxy_vm" in config:
                        project["spec"]["resources"]["subnet_reference_list"].append(
                            {
                                "kind": "subnet",
                                "name": public_subnet_info["name"],
                                "uuid": public_subnet_info["uuid"],
                            }
                        )

                # Add account if not present
                if len(project["spec"]["resources"]["account_reference_list"]) == 0:
                    for account in account_info.json["entities"]:
                        if account["status"]["resources"]["type"] == "nutanix_pc":
                            project["spec"]["resources"][
                                "account_reference_list"
                            ].append(
                                {
                                    "kind": "account",
                                    "name": account["metadata"]["name"],
                                    "uuid": account["metadata"]["uuid"],
                                }
                            )

            # Add env if not present
            if len(project["spec"]["resources"]["environment_reference_list"]) == 0:
                project["spec"]["resources"]["environment_reference_list"].append(
                    {"kind": "environment", "uuid": env_uuid}
                )

            # Make the API call to update the Project
            INFO(f"project: {project}")
            resp = update_via_v3_put(
                pc_external_ip,
                "projects",
                pc_password,
                project["metadata"]["uuid"],
                project,
            )

            # Log appropriately based on response
            if resp.code == 202 or resp.code == 200:
                INFO(f"{project['spec']['name']} Project updated successfully.")
            else:
                raise Exception(
                    f"{project['spec']['name']} Project update failed with:\n"
                    + f"Resp: {resp}\n"
                    + f"Error Code: {resp.code}\n"
                    + f"Error Message: {resp.message}"
                )

    except Exception as ex:
        ERROR(traceback.format_exc())
Exemple #5
0
def main():

    # Get and log the config from the Env variable
    config = json.loads(os.environ["CUSTOM_SCRIPT_CONFIG"])
    print(config)

    # Get PC info from the config dict
    pc_info = config.get("tdaas_pc")
    pc_external_ip = pc_info.get("ips")[0][0]
    pc_internal_ip = pc_info.get("ips")[0][1]
    pc_password = pc_info.get("prism_password")

    # Get PE info from the config dict
    pe_info = config.get("tdaas_cluster")
    pe_external_ip = pe_info.get("ips")[0][0]
    pe_internal_ip = pe_info.get("ips")[0][1]
    pe_password = pe_info.get("prism_password")

    try:

        # Read in the spec files and conver to dicts
        subnet_spec = file_to_dict("specs/calm_subnet.json")
        print(f"subnet_spec: {subnet_spec}")
        secret_spec = file_to_dict("specs/calm_secrets.json")
        print(f"secret_spec: {secret_spec}")

        # Get our subnet and image info from the infra
        subnet_info = get_subnet_info(pc_external_ip, pc_password,
                                      subnet_spec["entities"][0]["vlan"])
        infra_subnet_info = get_subnet_info(pc_external_ip, pc_password,
                                            subnet_spec["entities"][1]["vlan"])
        image_info = body_via_v3_post(pc_external_ip, "images", pc_password,
                                      None).json

        # If we have Public UVMs / Proxy IPs, then get our array
        proxy_array = []
        if "proxy_vm" in config:
            proxy_array = create_proxy_array(config["proxy_vm"])

        # Get a list of DRAFT blueprints
        payload = {"filter": "state==DRAFT"}
        draft_resp = body_via_v3_post(pc_external_ip, "blueprints",
                                      pc_password, payload).json

        # Loop through the blueprints to modify
        for bp in draft_resp["entities"]:

            # Get the body of our blueprint
            bp_body = body_via_v3_get(pc_external_ip, "blueprints",
                                      pc_password, bp["metadata"]["uuid"]).json

            # Remove unneeded status
            del bp_body["status"]

            # Configure secrets
            for secret in bp_body["spec"]["resources"][
                    "credential_definition_list"]:
                secret["secret"]["attrs"]["is_secret_modified"] = True
                # Handle PE and PC Creds which are unique
                if secret["name"].lower() == "pc_creds":
                    secret["secret"]["username"] = "******"
                    secret["secret"]["value"] = pc_password
                elif secret["name"].lower() == "pe_creds":
                    secret["secret"]["username"] = "******"
                    secret["secret"]["value"] = pe_password
                # Find a matching type/username from our secret_spec
                else:
                    for ss in secret_spec["entities"]:
                        if (secret["type"] == ss["type"]
                                and secret["username"] == ss["username"]):
                            secret["secret"]["value"] = ss["secret"]
                print(f"secret: {secret}")

            # Configure NICs and Images
            for substrate in bp_body["spec"]["resources"][
                    "substrate_definition_list"]:
                if substrate["type"] == "AHV_VM":

                    # For NICs, determine if it's an infra or user VM based blueprint
                    for nic in substrate["create_spec"]["resources"][
                            "nic_list"]:
                        if "infra" in bp_body["metadata"]["name"].lower():
                            # Ensure we have a proxy_vm config
                            if len(proxy_array) > 0:
                                nic["subnet_reference"][
                                    "uuid"] = infra_subnet_info["uuid"]
                                nic["subnet_reference"][
                                    "name"] = infra_subnet_info["name"]
                                proxy_ips = proxy_array.pop()
                                nic["ip_endpoint_list"][0]["ip"] = proxy_ips[1]
                            else:
                                print(
                                    f'Blueprint "{bp_body["metadata"]["name"]}" has '
                                    +
                                    f'"infra" in the name, but there were not enough '
                                    + f" proxy IPs configured: {config}. If" +
                                    f" this application needs external access, "
                                    +
                                    f"please ensure enough proxy IPs are in your GCP "
                                    +
                                    f'cluster.  Otherwise, remove "infra" from the '
                                    + f"blueprint name.")
                        else:
                            nic["subnet_reference"]["uuid"] = subnet_info[
                                "uuid"]
                            nic["subnet_reference"]["name"] = subnet_info[
                                "name"]
                        print(json.dumps(nic, sort_keys=True, indent=4))

                    for disk in substrate["create_spec"]["resources"][
                            "disk_list"]:
                        if (disk["data_source_reference"] is not None
                                and disk["data_source_reference"]["kind"]
                                == "image"):
                            for image in image_info["entities"]:
                                if (image["status"]["name"] ==
                                        disk["data_source_reference"]["name"]):
                                    disk["data_source_reference"][
                                        "uuid"] = image["metadata"]["uuid"]
                                    print(
                                        json.dumps(disk,
                                                   sort_keys=True,
                                                   indent=4))

            # Update our blueprint
            resp = update_via_v3_put(
                pc_external_ip,
                "blueprints",
                pc_password,
                bp["metadata"]["uuid"],
                bp_body,
            )

            # Log appropriately based on response
            if resp.code == 200 or resp.code == 202:
                print(
                    f"{bp['metadata']['name']} blueprint updated successfully."
                )
            else:
                raise Exception(
                    f"{bp['metadata']['name']} blueprint update failed with:\n"
                    + f"Resp: {resp}\n" + f"Error Code: {resp.code}\n" +
                    f"Error Message: {resp.message}")

    except Exception as ex:
        print(traceback.format_exc())
        sys.exit(1)