Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
5.1k views
in Technique[技术] by (71.8m points)

jinja2 - How to skip or ignore a config within j2 template if it's already in the running config (declared in a variable) of a Network Switch using Ansible?

running-config on the switch:

switch-1#
interface Ethernet1/1
  ip dhcp relay address 1.1.1.2

j2 template:

{% for ip in dhcp_servers %}
interface Ethernet1/1
  ip dhcp relay address {{ ip }}
{% endfor %}

variables defined:

dhcp_servers:
 - 1.1.1.2
 - 1.1.1.3
 - 1.1.1.4

expected config created with j2, later to be added on the switch:

interface Ethernet1/1
  ip dhcp relay address 1.1.1.3
  ip dhcp relay address 1.1.1.4

Only creating configs which are not present in the running config without needing to delete the ip from variable list (dhcp_servers)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From the "running-config on the switch" parse the list of present DHCP servers. For example

dhcp_servers_present: [1.1.1.2]

Then the task below

    - debug:
        msg: |
          interface Ethernet1/1
          {% for ip in dhcp_servers|difference(dhcp_servers_present) %}
            ip dhcp relay address {{ ip }}
          {% endfor %}

gives the expected config

  msg: |-
    interface Ethernet1/1
      ip dhcp relay address 1.1.1.3
      ip dhcp relay address 1.1.1.4

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...