Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save inceabdullah/024219958b6be61dcf3502fd02d447c3 to your computer and use it in GitHub Desktop.
Save inceabdullah/024219958b6be61dcf3502fd02d447c3 to your computer and use it in GitHub Desktop.
Ansible Netplan Set Static IP with Default Gateway from Iface of Connecting IP

Ansible Netplan Set Static IP with Default Gateway from Iface of Connecting IP

- name: set default route with connecting ipv4
  hosts: nodes
  tasks:
   - name: make default gw
     command: sudo bash -c "export IP={{ IP }}; ip r | grep $IP |grep -Po 'dev \K\S+' |xargs -I{} bash -c \"DEV={};GW=`echo '${IP%.*}.1'`;ip r r default via \${GW} dev \${DEV}; ip r\""
     vars:
       IP: "{{ ansible_facts['env'].SSH_CONNECTION.split(' ')[2] }}"
     register: output
   - name: debug
     debug:
       msg: "{{ output }}"        

- name: disable all netconf related to iface
  hosts: nodes
  tasks:
   - name: disable netconf
     command: bash -c "sudo ls -A1 /etc/netplan/*.y{a,}ml |sudo xargs -I{} grep -nlr \"$IFACE\" {} |sudo xargs -I{} bash -c 'SHA1SUM=`sha1sum {} |cut -d\" \" -f1`; mv -v {} {}.$SHA1SUM'"
     vars:
       IFACE: "{{ ansible_default_ipv4.interface }}"
     register: output
   - name: debug
     debug:
       msg: "{{ output }}"

- name: net plan
  hosts: nodes
  any_errors_fatal: true
  roles:
    - role: ansible-netplan # https://github.com/mrlesmithjr/ansible-netplan
      become: yes
      netplan_enabled: true
      netplan_config_file: /etc/netplan/static-ip-from-current.yaml
      netplan_renderer: networkd
      netplan_configuration:
        network:
          version: 2
          ethernets: "{
            '{{ ansible_default_ipv4.interface }}': {
              'addresses': [ '{{ ansible_default_ipv4.address }}/24' ],
              'gateway4': '{{ ansible_default_ipv4.gateway }}'
                }
            }"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment