Skip to content

Instantly share code, notes, and snippets.

@RobinBeismann
Created August 11, 2025 06:45
Show Gist options
  • Save RobinBeismann/bf561426031b3ecbca0f0a84d3e82540 to your computer and use it in GitHub Desktop.
Save RobinBeismann/bf561426031b3ecbca0f0a84d3e82540 to your computer and use it in GitHub Desktop.
Ansible: copy macros onto switches
- name: "Copy NAC macros onto switches"
hosts: all
gather_facts: no
vars:
macro_files: [
"nac-mab-access-wap.txt",
"nac-mab-access-data-voice.txt",
"nac-mab-access-data-only.txt",
"nac-mab-access-switch.txt",
"nac-mab-access-authfailed.txt"
]
config_lines: [
"ip scp server enable", # Enable SFTP Server
]
tasks:
# Check reachability and skip host if not pingable
- name: Test reachability
wait_for:
port: 22
timeout: 2
host: '{{ ansible_host }}'
state: present
ignore_errors: true
register: output
changed_when: false
- name: Exit if switch is not reachable
meta: end_host
when: output.failed != 0
# Set facts
- name: Set VLAN Facts
ansible.builtin.set_fact:
NAC_FALLBACK_VLAN: "{{ hostvars[inventory_hostname].vars.NAC_FALLBACK_VLAN if hostvars[inventory_hostname].vars.NAC_FALLBACK_VLAN is defined and hostvars[inventory_hostname].vars.NAC_FALLBACK_VLAN != None else '6' }}"
# Check OS
- name: Exit if switch OS is not ios
meta: end_host
when: ansible_network_os != 'ios'
changed_when: false
# Check reachability and skip host if not pingable
- name: Test reachability
wait_for:
port: 22
timeout: 2
host: '{{ ansible_host }}'
state: present
ignore_errors: true
register: output
changed_when: false
- name: Exit if switch is not reachable
meta: end_host
when: output.failed != 0
- name: "Gather device facts"
when: inventory_hostname in groups['ios']
ios_facts:
register: device_facts
- name: Insert Config Lines
when: inventory_hostname in groups['ios']
notify: "save ios"
ios_config:
lines: "{{ config_lines }}"
vars:
ansible_command_timeout: 2000
- name: Retrieve file systems via CLI
ios_command:
commands: "show file systems | include flash"
register: filesystemresult
- name: Extract flash file systems via regex
set_fact:
useable_filesystems: "{{ filesystemresult.stdout[0] | regex_findall('^.*\\s(?P<flash>flash-\\d:|flash\\d:|flash:).*', multiline=True, ignorecase=True) }}"
- name: Copy File to Switch
when: inventory_hostname in groups['ios']
net_put:
src: "macro-files/{{ item[1] }}"
protocol: scp
mode: text
dest : "{{ item[0] }}/{{ item[1] }}"
with_nested:
- "{{ useable_filesystems }}"
- "{{ macro_files }}"
loop_control:
extended: yes
vars:
ansible_command_timeout: 2000
handlers:
- name: save ios
ios_command:
commands: "write memory"
when: not ansible_check_mode
- name: save nxos
ios_command:
commands: "copy running-config startup-config"
when: not ansible_check_mode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment