Salt SLS remove last octect of IP address from grain

105 views Asked by At

I'm trying to match conditions based on the third octet of an IP address since Windows minions don't report the gateway. I can get the grain info for the IP and match the full IP like below but I only want to match to the third octet:


{% set subnet = salt['grains.get']('ipv4:0')  %}
user_coinfig:
  cmd.run:
    {% if subnet == '10.1.244.146' %}
    - name: |
        cmd.exe net localgroup administrators user /add
    {% elif subnet == '10.1.245.146' %}
    - name: |
        cmd.exe net localgroup administrators user /add
    {% endif %}

Desired state:

{% set subnet = salt['grains.get']('ipv4:0')  %}
user_coinfig:
  cmd.run:
    {% if subnet == '10.1.244' %}
    - name: |
        cmd.exe net localgroup administrators user /add
    {% elif subnet == '10.1.245' %}
    - name: |
        cmd.exe net localgroup administrators user /add
    {% endif %}
2

There are 2 answers

0
β.εηοιτ.βε On BEST ANSWER

Since Jinja is a templating language based on Python, you do have access to all of the string methods of Python.
And for this case, you can use the method startswith().

So, you can do:

{% if subnet.startswith('10.1.244.') %}
- name: |
    cmd.exe net localgroup administrators user /add
{% endif %}
0
OrangeDog On

For actual subnet (not just prefix) matching, there is network.in_subnet for the current host, and network.ip_in_subnet for arbitrary IP addresses.

{% if salt["network.in_subnet"]("10.1.244.0/23") %}
user_coinfig:
  cmd.run:
    - name: cmd.exe net localgroup administrators user /add
{% endif %}

You can also get the subnets of the host directly with network.subnets, if the network topology already matches what you're looking for.

{% if "10.1.244.0/23" in salt["network.subnets"]()  %}
user_coinfig:
  cmd.run:
    - name: cmd.exe net localgroup administrators user /add
{% endif %}

You could use that as a map key for more complex situations.