Dandelion
Dandelion

Reputation: 61

Ansible playbook block ALL IP exclude one or more IP

I'm starting to use Ansible to develop a playbook that perform some actions on the system iptables. I have a server and I want to block ALL IP except one or more IP.

I really don't know how to write the iptables rules using the ansible modules. I need to:

  1. Drop all incoming traffic (iptables -P INPUT DROP)
  2. Drop all incoming traffic (iptables -P INPUT DROP)
  3. Drop all forwarded traffic (iptables -P FORWARD DROP)
  4. Allow all outgoing traffic (iptables -P OUTPUT ACCEPT)
  5. iptables -A INPUT -p tcp -m tcp -s ipaddress --dport 22 -j ACCEPT

So far, I've created this Playbook:

---

  - hosts: localhost
    remote_user: sysadmin
    become: true

    vars:
      host_name: localhost

    tasks:

  # Drop all incoming traffic
  # iptables -P INPUT DROP
     - iptables:
         chain: INPUT
         protocol: all
         jump: DROP
       become: yes


  # Drop all forwarded traffic
  # iptables -P FORWARD DROP
     - iptables:
         chain: FORWARD
         source: all
         jump: DROP
       become: yes

  # Allow all outgoing traffic
  #iptables -P OUTPUT ACCEPT
     - iptables:
         chain: OUTPUT
         source: all
         jump: ACCEPT
       become: yes

  # Allow all outgoing traffic
  # iptables -A INPUT -p tcp -m tcp -s xx.xx.xx.xx/32 --dport 22 -j ACCEPT
     - iptables:
         action: append
         chain: INPUT
         protocol: tcp
         source: ip_address
         destination_port: 22
         jump: ACCEPT
       become: yes  

Upvotes: 2

Views: 4812

Answers (1)

Dandelion
Dandelion

Reputation: 61

I solved taking different steps:

  1. iptables -A INPUT -s 2.228.104.210 -j ACCEPT
  2. iptables -A OUTPUT -d 2.228.104.210 -j ACCEPT
  3. iptables -P INPUT DROP
  4. iptables -P OUTPUT DROP

And the working playbook:

---

  - hosts: localhost
    remote_user: sysadmin
    become: true

    vars:
      host_name: localhost

    tasks:

     - iptables:
         chain: INPUT
         source: 192.168.1.1
         jump: ACCEPT
       become: yes


     - iptables:
         chain: OUTPUT
         destination: 192.168.1.1
         jump: ACCEPT
       become: yes


     - iptables:
         chain: INPUT
         policy: DROP
       become: yes


     - iptables:
         chain: OUTPUT
         policy: DROP
       become: yes

Upvotes: 2

Related Questions