Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
6.1 kB
2
Indexable
Never
import boto3
import time
from playwright.sync_api import Playwright, sync_playwright
from ec2_metadata import ec2_metadata

def fetch_tags(instance_id: str, aws_region: str) -> str:
    ec2 = boto3.client('ec2')

    # Retrieve information about the specified instance
    response = ec2.describe_instances(InstanceIds=[instance_id])

    # Extract the 'Tags' information
    tags = response['Reservations'][0]['Instances'][0].get('Tags', [])
    
    # Convert list of tags to a dictionary for easy access
    tag_dict = {tag['Key']: tag['Value'] for tag in tags}

    # Check for required tags
    required_tags = ['app_name', 'environment']
    for tag in required_tags:
        if tag not in tag_dict:
            raise ValueError(f"Tag '{tag}' not found in instance {instance_id}")

    return tag_dict

def get_ssm_parameter(parameter_name: str, aws_region: str) -> str:
    ssm_client = boto3.client('ssm', region_name=aws_region)
    response = ssm_client.get_parameter(Name=parameter_name, WithDecryption=True)
    return response['Parameter']['Value']

def deploy(playwright: Playwright, app_name: str, environment: str, aws_region: str) -> None:
    # Construct the SSM Parameter Store prefix path
    ssm_parameter_prefix = f"/{app_name}/{environment}/"

    # Define a list of parameters to be fetched from SSM Parameter Store
    ssm_parameters = [
        "admin_password",
        "admin_security_question_answer",
        "vm_minimum_heap_size",
        "vm_maximum_heap_size",
        "db_name",
        "db_hostname",
        "db_port",
        "db_username",
        "db_password"
    ]

    # Fetch the values of the parameters from SSM Parameter Store
    ssm_parameter_values = {parameter: get_ssm_parameter(ssm_parameter_prefix + parameter, aws_region) for parameter in ssm_parameters}

    print("Running automation script to deploy FlexNet Operations.")
    # Launch the Chromium browser in headless mode
    browser = playwright.chromium.launch(headless=True)
    # Create a new browser context
    context = browser.new_context()
    # Create a new page in the context
    page = context.new_page()

    # Go to the FlexNet Operations setup page
    print("Logging into the FlexNet Operations Setup WebUI...")
    page.goto("http://localhost:4321/flexnetsetup")

    # Fill in the username and password fields
    page.get_by_placeholder("Username").fill("admin")
    page.get_by_placeholder("Password").fill("admin")

    # Click the "Log in" button
    page.get_by_role("button", name="Log in").click()

    # Fill in the existing password, new password, and confirm password fields
    print("Changing password of admin user...")
    page.get_by_placeholder("Existing Password").fill("admin")
    page.get_by_placeholder("New Password").fill(ssm_parameter_values["admin_password"])
    page.get_by_placeholder("Confirm Password").fill(ssm_parameter_values["admin_password"])

    # Select a security question and provide an answer
    page.locator("#question").select_option("What was the name of your first school?")
    page.locator("input[name=\"answer\"]").fill(ssm_parameter_values["admin_security_question_answer"])

    # Click the "Change" button to change the password
    page.get_by_role("button", name="Change").click()

    print("Logged in, Configuring FlexNet Operations...")

    # Fill in the VM Heap Size and VM Size Maximum fields
    page.get_by_label("VM Heap Size (MB)").fill(ssm_parameter_values["vm_minimum_heap_size"])
    page.locator("input[name=\"vmSizeMaximum\"]").fill(ssm_parameter_values["vm_maximum_heap_size"])

    # Check the "Install as Service" and "Use Local System Account" checkboxes
    page.locator("#fnoServiceInstallAsService").check()
    page.locator("#fnoServiceUseLocalSystemAccount").check()

    # Click the "Save" button to save the configuration
    page.get_by_role("button", name="Save").click(timeout=300000)

    # Switch to the "Database" tab
    page.get_by_role("tab", name="Database").click()

    # Fill in the database related fields
    page.get_by_role("textbox", name="Schema Name :").fill(ssm_parameter_values["db_name"])
    page.get_by_role("textbox", name="Hostname :").fill(ssm_parameter_values["db_hostname"])
    page.get_by_role("textbox", name="Port :").fill(ssm_parameter_values["db_port"])
    page.get_by_role("textbox", name="Database Username :").fill(ssm_parameter_values["db_username"])
    page.get_by_role("textbox", name="Database Password :").fill(ssm_parameter_values["db_password"])
    page.get_by_role("textbox", name="Confirm Password :").fill(ssm_parameter_values["db_password"])

    # Click the "Save" button to save the database configuration
    page.get_by_role("button", name="Save").click()

    # Wait 15 seconds
    time.sleep(15)

    print("Configuration is done, deploying service...")

    # Click the "System Status" button
    page.get_by_role("button", name="System Status").click()

    # Click the "Deploy" button
    with page.expect_popup() as page1_info:
        page.get_by_role("button", name="Deploy", exact=True).click(timeout=300000)
    page1 = page1_info.value
    page1.goto("http://localhost:4321/flexnetsetup/managecomponents_FNO.action")
    page.goto("http://localhost:4321/flexnetsetup/diagnostic.action")

    # Click the "Close" button in the Deploy popup
    page1.get_by_role("button", name="Close").click(timeout=300000)

    print("Deployment is complete!")

    # Take video of automation session (for debugging purposes)
    context = browser.new_context(record_video_dir="C:\\tmp\\")

    # Close the browser context and browser
    context.close()
    browser.close()


with sync_playwright() as playwright:
    # Fetch the AWS region and tags of the EC2 instance
    aws_region = ec2_metadata.region
    tags       = fetch_tags(ec2_metadata.instance_id, aws_region)
    # Deploy FlexNet Operations using the tags provided by the EC2 instance metadata
    deploy(playwright, tags['app_name'], tags['environment'], aws_region)
Leave a Comment