Skip to content

Instantly share code, notes, and snippets.

@halberom
Last active September 6, 2022 08:03
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save halberom/a5aebb34da179fdce91a1bd018ec2805 to your computer and use it in GitHub Desktop.
Save halberom/a5aebb34da179fdce91a1bd018ec2805 to your computer and use it in GitHub Desktop.
ansible - example of parsing a url
---
- hosts: localhost
gather_facts: False
connection: local
vars:
myvar: 'http://www.example.domain.com:9090'
tasks:
- name: not as good as a custom filter
debug:
msg: "{{ myvar.rpartition('//')[2].split(':') }}"
- name: use a custom filter
debug:
msg: "{{ myvar | parse_url }}"
[defaults]
filter_plugins = plugins/filter
# plugins/filter/custom.py
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from urlparse import urlparse
def parse_url(url):
"""return a dict, of the parsed elements"""
result = {}
o = urlparse(url)
result['scheme'] = o.scheme
result['port'] = o.port
result['url'] = o.geturl()
result['path'] = o.path
result['netloc'] = o.netloc
result['query'] = o.query
result['hostname'] = o.hostname
return result
class FilterModule(object):
def filters(self):
return {
"parse_url": parse_url
}
PLAY [localhost] ***************************************************************************************************************************************************************************************************************************************************************
TASK [not as good as a custom filter] ******************************************************************************************************************************************************************************************************************************************
ok: [localhost] => {
"changed": false,
"msg": [
"www.example.domain.com",
"9090"
]
}
TASK [use a custom filter] *****************************************************************************************************************************************************************************************************************************************************
ok: [localhost] => {
"changed": false,
"msg": {
"hostname": "www.example.domain.com",
"netloc": "www.example.domain.com:9090",
"path": "",
"port": 9090,
"query": "",
"scheme": "http",
"url": "http://www.example.domain.com:9090"
}
}
PLAY RECAP *********************************************************************************************************************************************************************************************************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0
@tamlyn
Copy link

tamlyn commented May 15, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment