Ejemplo n.º 1
0
def createProject(server, project):
    projectObj = Project(name=project, connector=server)
    #print(projectObj.status)
    # if projectObj.status == "opened":
    #     print("Closing the current project...", end="")
    #     projectObj.close()
    #     print("OK")

    getProject = next((project
                       for project in server.projects_summary(is_print=False)
                       if project[0] == projectObj.name), "Project not found")
    if getProject[0] == projectObj.name:
        print("Project name existed, re-creating the project...", end="")
        deleteProject(getProject[1])
    #else:
    #    print("Creating the project...", end="")
    projectObj.create()
    print("Project " + projectObj.name + " created. ID: " +
          projectObj.project_id + "...",
          end="")
    return projectObj
def main():
    module = AnsibleModule(
        argument_spec=dict(
            url=dict(type="str", required=True),
            port=dict(type="int", default=3080),
            user=dict(type="str", default=None),
            password=dict(type="str", default=None, no_log=True),
            state=dict(
                type="str",
                required=True,
                choices=["opened", "closed", "present", "absent"],
            ),
            project_name=dict(type="str", default=None),
            project_id=dict(type="str", default=None),
            nodes_state=dict(type="str", choices=["started", "stopped"]),
            nodes_strategy=dict(type="str",
                                choices=["all", "one_by_one"],
                                default="all"),
            nodes_delay=dict(type="int", default=10),
            poll_wait_time=dict(type="int", default=5),
            nodes_spec=dict(type="list"),
            links_spec=dict(type="list"),
        ),
        supports_check_mode=True,
        required_one_of=[["project_name", "project_id"]],
        required_if=[["nodes_strategy", "one_by_one", ["nodes_delay"]]],
    )
    result = dict(changed=False)
    if not HAS_GNS3FY:
        module.fail_json(msg=missing_required_lib("gns3fy"),
                         exception=GNS3FY_IMP_ERR)
    if module.check_mode:
        module.exit_json(**result)

    server_url = module.params["url"]
    server_port = module.params["port"]
    server_user = module.params["user"]
    server_password = module.params["password"]
    state = module.params["state"]
    project_name = module.params["project_name"]
    project_id = module.params["project_id"]
    nodes_state = module.params["nodes_state"]
    nodes_strategy = module.params["nodes_strategy"]
    nodes_delay = module.params["nodes_delay"]
    poll_wait_time = module.params["poll_wait_time"]
    nodes_spec = module.params["nodes_spec"]
    links_spec = module.params["links_spec"]

    try:
        # Create server session
        server = Gns3Connector(url=f"{server_url}:{server_port}",
                               user=server_user,
                               cred=server_password)
        # Define the project
        if project_name is not None:
            project = Project(name=project_name, connector=server)
        elif project_id is not None:
            project = Project(project_id=project_id, connector=server)
    except Exception as err:
        module.fail_json(msg=str(err), **result)

    #  Retrieve project information
    try:
        project.get()
        pr_exists = True
    except Exception as err:
        pr_exists = False
        reason = str(err)

    if state == "opened":
        if pr_exists:
            if project.status != "opened":
                # Open project
                project.open()

                # Now verify nodes
                if nodes_state is not None:

                    # Change flag based on the nodes state
                    result["changed"] = nodes_state_verification(
                        expected_nodes_state=nodes_state,
                        nodes_strategy=nodes_strategy,
                        nodes_delay=nodes_delay,
                        poll_wait_time=poll_wait_time,
                        project=project,
                    )
                else:
                    # Means that nodes are not taken into account for idempotency
                    result["changed"] = True
            # Even if the project is open if nodes_state has been set, check it
            else:
                if nodes_state is not None:
                    result["changed"] = nodes_state_verification(
                        expected_nodes_state=nodes_state,
                        nodes_strategy=nodes_strategy,
                        nodes_delay=nodes_delay,
                        poll_wait_time=poll_wait_time,
                        project=project,
                    )

        else:
            module.fail_json(msg=reason, **result)

    elif state == "closed":
        if pr_exists:
            if project.status != "closed":
                # Close project
                project.close()
                result["changed"] = True
        else:
            module.fail_json(msg=reason, **result)

    elif state == "present":
        if pr_exists:
            if nodes_spec is not None:
                # Need to verify if nodes exist
                _nodes_already_created = [node.name for node in project.nodes]
                for node_spec in nodes_spec:
                    if node_spec["name"] not in _nodes_already_created:
                        # Open the project in case it was closed
                        project.open()
                        create_node(node_spec, project, module)
                        result["changed"] = True
            if links_spec is not None:
                for link_spec in links_spec:
                    project.open()
                    # Trigger another get to refresh nodes attributes
                    project.get()
                    # Link verification is already built in the library
                    created = create_link(link_spec, project, module)
                    if created:
                        result["changed"] = True
        else:
            # Create project
            project.create()
            # Nodes section
            if nodes_spec is not None:
                for node_spec in nodes_spec:
                    create_node(node_spec, project, module)
            # Links section
            if links_spec is not None:
                for link_spec in links_spec:
                    create_link(link_spec, project, module)
            result["changed"] = True
    elif state == "absent":
        if pr_exists:
            # Stop nodes and close project to perform delete gracefully
            if project.status != "opened":
                # Project needs to be opened in order to be deleted...
                project.open()
            project.stop_nodes(poll_wait_time=0)
            project.delete()
            result["changed"] = True
        else:
            module.exit_json(**result)

    # Return the project data
    result["project"] = return_project_data(project)
    module.exit_json(**result)
Ejemplo n.º 3
0
def main():
    # Parse the arguments
    args = parse_args()
    topology_data = load_yaml(args.topology)

    # Collect lab name
    print(heading("Collecting topology data"))
    lab_name: str = topology_data["title"]["text"]
    print(f"The lab name would be: {lab_name}")

    # Collect nodes specs
    nodes_spec = get_nodes_spec(topology_data["icons"])

    # Collect connections specs
    links_spec = get_links_spec(topology_data["connections"])

    # Create Gns3Connector
    print(heading(f"Configuring lab on GNS3 server"))
    server = Gns3Connector(f"{args.protocol}://{args.server}:{args.port}")

    # Verify lab is not already created
    lab_project = server.get_project(name=lab_name)
    if lab_project:
        delete_lab = input(
            f"\nLab already created, do you want to delete it? (y/n): ")
        if delete_lab == "y":
            server.delete_project(lab_project["project_id"])
        else:
            sys.exit("Exiting...")

    # Create the lab
    lab = Project(name=lab_name, connector=server)
    lab.create()
    print(f"Project created: {lab.name}\n")

    # Create the nodes
    for device in nodes_spec:
        node = Node(
            project_id=lab.project_id,
            connector=server,
            name=device["name"],
            template=device["template"],
            x=parsed_x(device["x"] - 10),
            y=parsed_y(device["y"] - 5),
        )
        node.create()
        time.sleep(3)
        print(f"Device created: {node.name}")

    # Create the links
    for link in links_spec:
        lab.create_link(*link)

    # Summary
    print(heading("Nodes Summary"))
    nodes_summary: str = lab.nodes_summary(is_print=False)
    print(
        tabulate(nodes_summary,
                 headers=["Device", "Status", "Console Port", "ID"]))
    print(heading("Links Summary"))
    links_summary: str = lab.links_summary(is_print=False)
    print(
        tabulate(links_summary,
                 headers=["Device A", "Port A", "Device B", "Port B"]))

    return