【问题标题】:How to write multiple iptables rules in chef?如何在 Chef 中编写多个 iptables 规则?
【发布时间】:2021-03-15 11:31:45
【问题描述】:

我试图编写多个 iptables 来阻止某些子网,结果发现最后一个 iptables 规则才刚刚实施。这是我在食谱中添加的:

execute "block_ports" do
    command "iptables -A OUTPUT -p tcp -d <subnet 1> --dport <port> -j DROP"
    command "iptables -A OUTPUT -p tcp -d <subnet 2> --dport <port> -j DROP"
    command "iptables -A OUTPUT -p tcp -d <subnet 3> --dport <port> -j DROP"
    command "iptables -A OUTPUT -p tcp -d <subnet 4> --dport <port> -j DROP"
end

谁能告诉我如何编写多个 iptables 规则,以便所有规则都在 Chef 配方中执行?

【问题讨论】:

    标签: linux chef-infra


    【解决方案1】:

    execute Chef 资源只允许一个 command 变量,因此如果您多次写入它,则只会读取后一个。因此,您可以为要解决的每个规则调用一个执行 resource

    无论如何,我建议您使用 iptables 食谱的 iptables_rule Chef 资源。查看https://github.com/chef-cookbooks/iptables 的文档以获取用法示例。

    即使您可以为每个 iptables 规则调用 iptables_rule 资源,我建议改为使用包含调用它所需的所有规则的 源模板一次。 所以你可以在你的cookbook的templates/default目录下定义你的模板文件rules.erb文件如下:

    *nat
    -A OUTPUT -p tcp -d <%= @subnet1 %> --dport <%= @dest_port %> j DROP
    -A OUTPUT -p tcp -d <%= @subnet2 %> --dport <%= @dest_port %> j DROP
    -A OUTPUT -p tcp -d <%= @subnet3 %> --dport <%= @dest_port %> j DROP
    -A OUTPUT -p tcp -d <%= @subnet4 %> --dport <%= @dest_port %> j DROP
    

    然后调用一次资源指定模板变量如下:

    iptables_rule "rules.erb" do
              action [:disable, :enable] #If a rule already exists it isn't added again creating a duplicate
              variables(
                 :port => d_port,
                 :subnet1 => subnet_1,
                 :subnet2 => subnet_2,
                 :subnet3 => subnet_3,
                 :subnet4 => subnet_4
              )
    end
    

    请注意,默认情况下,rebuild-iptables 在整个 Chef 进程结束时“延迟”。如果您需要在添加规则后立即激活规则,您可以通过 :immediate 属性集通知手动调用rebuild-iptables 命令的execute 资源

    【讨论】:

      【解决方案2】:

      您之前似乎曾问过这个问题,并且它与此question 相关联。

      如果您想从 一个 Chef 资源运行多个 iptables 命令,您可以使用 bash 资源。

      例子:

      bash 'block_ports' do
        code <<-EOH
          iptables -A OUTPUT -p tcp -d <subnet 1> --dport <port> -j DROP
          iptables -A OUTPUT -p tcp -d <subnet 2> --dport <port> -j DROP
          iptables -A OUTPUT -p tcp -d <subnet 3> --dport <port> -j DROP
          iptables -A OUTPUT -p tcp -d <subnet 4> --dport <port> -j DROP
        EOH
      end
      

      【讨论】:

      • 这不是幂等的,因为如果发生不同的 Chef 执行会添加重复的规则
      猜你喜欢
      • 2014-01-11
      • 2012-04-02
      • 2016-02-01
      • 1970-01-01
      • 2016-07-07
      • 2011-09-17
      • 2014-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多