Learn F5 Technologies, Get Answers & Share Community Solutions Join DevCentral

Filter by:
  • Solution
  • Technology
Clear all filters
Answers

Getting the security policy associated with a VIP.

I am new to the F5 python SDK and I am trying to pull the security policy associated with a VIP. I am unable to find the security policies tied to a specific VIP through the LTM sub package and I cannot see the ASM attribute in the BigIP object.

from f5.bigip import BigIP

Connect to the BigIP

bigip = BigIP("hostname", "username", "password", token = True)

I have seen a lot of examples using the ManagementRoot class. What is the difference between the BigIP and the ManagementRoot classes ?

0
Rate this Question

Answers to this Question

placeholder+image
USER ACCEPTED ANSWER & F5 ACCEPTED ANSWER

Please go through the following links to get a better understanding of the REST API.

https://f5-sdk.readthedocs.io/en/latest/index.html

https://f5-sdk.readthedocs.io/en/latest/userguide/basics.html

As to your question regarding security policy associated with a VIP, there is currently no endpoint for this. However, you could parse policy url from the JSON returned by mgmt.tm.asm.get_collection() and then make a Request to that URL. It should return all policies which you can filter based on VIP. Here is some sample code related to a few ASM objects:

import urllib3
from f5.bigip import ManagementRoot
from uuid import uuid4
import random
import socket
import struct
import requests
import logging
from logging.handlers import RotatingFileHandler
import json

urllib3.disable_warnings()
_auth = {"_url": "https://admin:admin4@", "_host": "1.1.1.1", "_user": "admin", 
"_pswd": "admin4"}
_headers = {'accept': 'application/json', 'content-type': 'application/json'}
_config = {
            "_partition": "Common",
            "_vs_name": "test_vs_",
            "_vs_desc": "Test Virtual Server",
            "_vs_source": "0.0.0.0/0",
            "_vs_list": ["10.154.148.103:80", "10.154.148.104:8081"],
            "_vs_mask": "255.255.255.255",
            "_vs_st": {'type': 'automap'},
            "_pool_name": "test_pool",
            "_pool_desc": "This is a test pool",
            "_node_name": "Test Node",
            "_node_list": ["10.154.148.101:80", "10.154.148.101:8081"],
          }

def _bigip():
    return ManagementRoot(_auth["_host"], _auth["_user"], _auth["_pswd"])

def _configure():
    _mgmt = _bigip()
    _pool = _mgmt.tm.ltm.pools.pool.create(name=_config['_pool_name'], 
             partition=_config['_partition'])
    _pool.description = _config['_pool_desc']
    _pool.update()
    for _node in _config['_node_list']:
        _pool.members_s.members.create(partition=_config['_partition'], name=_node)
    _vs_obj = _mgmt.tm.ltm.virtuals.virtual
    for _dest in _config['_vs_list']:
        _vs = _vs_obj.create(name=_config['_vs_name']+str(uuid4()), destination=_dest, 
              source=_config['_vs_source'], mask=_config["_vs_mask"], 
              sourceAddressTranslation=_config["_vs_st"], pool=_config["_pool_name"])
        _vspr_obj = _vs.profiles_s.profiles
        _pr1 = _vspr_obj.create(partition=_config['_partition'], name='http')

def _get_virtuals():
    _mgmt = _bigip()
    _vs_collection = _mgmt.tm.ltm.virtuals.get_collection()
    for _vs in _vs_collection:
        _logger.info(_vs.name)
        _logger.info(_vs.destination)
    return _vs_collection

def _get_pools():
    _mgmt = _bigip()
    _pool_collection = _mgmt.tm.ltm.pools.get_collection()
    for _pc in _pool_collection:
        _logger.info(_pc.name)
    return _pool_collection

def _get_url(_url):
    _logger.info("in _get_url")
    return requests.get(_url, headers=_headers, auth=(_auth["_user"], 
                        _auth["_pswd"]),verify=False)

def _get_asm_policies():
    _mgmt = _bigip()
    _asm_collection = _mgmt.tm.asm.get_collection()
    _policy_url = _auth['_url']+_auth['_host']+_asm_collection[0]['reference']['link'][17:]
    _r = _get_url(_policy_url)
    _policies = json.loads(_r.text)
    _logger.info("--- Total available policies: "+str(_policies['totalItems']))
    for _item in _policies['items']:
        _logger.info("--- Policy Name: "+_item['name'])
        _logger.info("--- Policy Description: "+_item['description'])
        _logger.info("--- Policy Active?: "+str(_item['active']))
        _logger.info("--- Created by User: "+str(_item['creatorName']))
        _logger.info("--- Last Policy Change: "+str(_item['creatorName']))
        _logger.info("--- Device Host Name: "+_item['versionDeviceName'])
    return _policies

def _get_whitelisted_ips():
    _policies = _get_asm_policies()
    for _item in _policies['items']:
        _whitelistip_url = _auth['_url']+_auth['_host']+_item['whitelistIpReference']['link'][17:]
        _r = _get_url(_whitelistip_url)
        _whitelisted_ips = json.loads(_r.text)
        _logger.info("Total Whitelisted IP adresses: 
                     "+str(_whitelisted_ips['totalItems']))
        for _item in _whitelisted_ips['items']:
            _logger.info(_item['ipAddress'])

def _get_session_awareness_settings():
    _policies = _get_asm_policies()
    for _item in _policies['items']:
        _sa_url = _auth['_url'] + _auth['_host'] + \
            _item['sessionAwarenessSettingsReference']['link'][17:]
        _r = _get_url(_sa_url)
        _sa_settings = json.loads(_r.text)
        _logger.info(_sa_settings)
        _logger.info(_sa_url)

def _get_signatures():
    _policies = _get_asm_policies()
    for _item in _policies['items']:
        _signatureset_url = _auth['_url']+_auth['_host']+_item['signatureReference'] 
                            ['link'][17:]
        _r = _get_url(_signatureset_url)
        _signatures = json.loads(_r.text)
        _logger.info("Total Signatures: "+str(_signatures['totalItems'])+ " going to 
                     print first 10")
        for _item in _signatures['items'][:10]:
            _signature_url = _auth['_url']+_auth['_host']+_item['signatureReference'] 
                             ['link'][17:]
            _signature = _get_url(_signature_url)
            _logger.info("Signature Name: "+json.loads(_signature.text)['name'])

if __name__ == "__main__":
    _logger = logging.getLogger("SDK Log")
    _logger.setLevel(logging.INFO)
    _formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    _handler = RotatingFileHandler('sdk.log', maxBytes=100000, backupCount=0)
    _handler.setFormatter(_formatter)
    _logger.addHandler(_handler)

    # _configure()
    # _get_pools()
    # _get_virtuals()
    _get_asm_policies()
    # _get_whitelisted_ips()
    # _get_signatures()
    # _get_session_awareness_settings()
0