简体   繁体   中英

Ansible convert subnet mask to wildcard mask

I have a subnet mask in ansible and I want to convert it to a wildcard mask (255 - current) for each octet as so http://wintelguy.com/2009/20090410_subnets.html

I know I will need to use set_fact with this but I am unsure how to split the mask up and convert each octet.

255.255.255.224

255 - 255 = 0 255 - 224 = 31

So it equals 0.0.0.31

Thanks

Doing this with Ansible tasks would get quite complicated. In a template it would get easier. But the best thing you can do is to create a custom lookup plugin.

Something like this:

import ansible.errors as errors

class LookupModule(object):

    def __init__(self, basedir=None, **kwargs):
        self.basedir = basedir

    def run(self, terms, inject=None, **kwargs):

        if not isinstance(terms, basestring):
            raise errors.AnsibleError("lookup expects a string (IP address)")

        parts = terms.split(".")
        l = map(lambda x: str(255-int(x)), parts)
        return [".".join(l)]

Save this in your project as plugins/lookup/wildcard_mask.py , then call it as

{{ lookup('wildcard_mask', '255.255.255.224') }}

Should work with Ansible 1.x - probably needs changes for Ansible 2.x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM