Create ipsets for iptables using Chef and data bags

209 Views Asked by At

I'm a little bit stuck with implementing ipsets for iptables with Chef using data bags. I know you may say that this solution is not elegant and ideal, but believe me I have my own reasons why. What I'm trying to achieve; I need to create the ip set "allowed_subnet" for future using with iptables for whitelisting some ip addresses. The "allowed" ip addresses are in the data bag. Unfortunately I could not find that Chef supports ipset resource so I have to use execute. Please correct me if I'm wrong.

Right, I have data bag with the IP list:

{
    "id": "ipset_for_iptables",
            "ip_list": [

             "1.1.1.1",                                                                                                                                                              
             "1.1.1.2",
             "1.1.1.3",
             "1.1.1.4"                                                                                                                                                
          ]                                                                                                                                                                                                   
     }

Data bag name is equal to the "id".

And I have my default recipe file default.rb where I've added the following code:

  package 'ipset'
  execute 'create timeout ipset' do
        command 'ipset create allow_selected hash:ip timeout 120'
        not_if 'ipset -L allow_selected'
  end

  execute 'create ipset' do
       command 'ipset create allowed_subnet hash:ip hashsize 8192'
       not_if 'ipset -L allowed_subnet'
  end

servers = data_bag('ipset_for_iptables' , 'ipset_for_iptables')

template "/opt/data/data_hosts.txt" do
source 'ipset.erb'
owner 'ipset'
group 'ipset'
action :create
variables :properties => servers['ip_list']
end

And now, my question is: How to add the IP addresses from the data bag to the ip set "allowed_subnet" using "execute" and "ipset" linux command.

Here is the template "ipset.erb" content:

<% @properties.each do |host|%>
<%= host['ipaddress'] %>
<% end %>

BTW, I'm not sure that this template is correct, this is legacy from a previous admin. I would really appreciate if somebody can help me and also point me to the right documentation which can help me in a future as I have a lot of inherited stuff like this in my zoo. I have tried to find how to do that reading Chef official documentation, but I guess it is something beyond the Chef itself and more Ruby stuff.

0

There are 0 best solutions below