Search code examples
pythonlinuxfabricgoogle-cloud-platform

Fabric - Detect OS type and execute command


I am starting to experiment with Fabric as a minimal platform management tool for my GCP environment. A test use-case I want to experiment with is to get a list of hosts from the GCE API and set a dynamic host list. Based on this list I would like to apply simple minimal security update. This process differs depending on the os.

# gets running hosts in a single project across all zones
def ag_get_host():
    request = compute.instances().aggregatedList(project=project)
    response = request.execute()

    env.hosts = []
    for zone, instances in response['items'].items():
        for host in instances.get("instances", []):
            if host['status'] == 'RUNNING':
                env.hosts.append(host['name'])


# If redhat, run yum ; if ubuntu, run apt-get
def sec_update():
    if 'redhat' in platform.platform().lower():
        sudo('echo 3 > /proc/sys/vm/drop_caches')
        sudo('yum update yum -y')
        sudo('yum update-minimal --security -y')
    elif 'ubuntu' in platform.platform().lower():
        sudo('apt-get install unattended-upgrades')
        sudo('sudo unattended-upgrades –d')

I am having difficulty constructing the logic that will allow me to get the OS release details. platform.platform() gets the host os details and not the target machines.


Solution

  • Here's a possible solution:

    from fabric.api import task, sudo
    
    
    def get_platform():
        x = sudo("python -c 'import platform; print(platform.platform())'")
        if x.failed:
            raise Exception("Python not installed")
        else:
            return x
    
    
    @task
    def my_task():
        print("platform", get_platform())
    

    Be aware the requirement would be having installed python in the target boxes.