将以太网接口传递给 ansible playbook 中的 iptables 规则

将以太网接口传递给 ansible playbook 中的 iptables 规则

我正在编写一个非常简单的 ansible 剧本,用于在 centos 中设置我们的 iptables 防火墙。这是我写的剧本:

---
- hosts: test
  remote_user: deploy
  sudo: True
  tasks:
  - name: Get iptables rules
    shell: /sbin/iptables -L
    register: iptablesrules
    always_run: yes
  - name: Add nginx iptables rule
    command: /sbin/iptables -I INPUT -p tcp --dport 80 -j ACCEPT -m comment --comment "Nginx_HTTP"
    when: iptablesrules.stdout.find("Nginx_HTTP") == -1
  - name: Add nginx ssl iptables rule
    command: /sbin/iptables -I INPUT -p tcp --dport 443 -j ACCEPT -m comment --comment "Nginx_SSL"
    when: iptablesrules.stdout.find("Nginx_SSL") == -1
  - name: Add postgres rule on ham0 interface
    command: /sbin/iptables -I INPUT -p tcp -s 0/0 --sport 1024:65535 -d 0.0.0.0/0 --dport 5432 -m state --state NEW,ESTABLISHED -j ACCEPT -m comment --comment "Postgres"
    when: iptablesrules.stdout.find("Postgres") == -1
  - name: save iptables
    command: service iptables save
  - name: ensure iptables is set to start at boot
    action: command /sbin/chkconfig iptables on

一切都按预期进行,尽管我确信它可以做得更好。但我的问题是关于 Postgres 规则的。我想动态地将目标地址 0.0.0.0/0 替换为目标框上特定接口 (ham0) 的 IP。我假设我可以执行类似 ansible_ham0.ipv4.address 的操作来获取 IP 地址。但我不确定如何将其作为变量传递到 Postgress 规则中。

我正在阅读文档,但遇到了一些困难。我会继续研究,但在此期间,如果有人知道如何做到这一点,我将不胜感激。

答案1

抱歉,问答时间太短,但我稍加调整就解决了这个问题。

这是我更新的剧本。希望它能帮助别人!

---
- hosts: test
  remote_user: deploy
  sudo: True
  tasks:
  - name: Get iptables rules
    shell: /sbin/iptables -L
    register: iptablesrules
    always_run: yes
  - name: Add nginx iptables rule
    command: /sbin/iptables -I INPUT -p tcp --dport 80 -j ACCEPT -m comment --comment "Nginx_HTTP"
    when: iptablesrules.stdout.find("Nginx_HTTP") == -1
  - name: Add nginx ssl iptables rule
    command: /sbin/iptables -I INPUT -p tcp --dport 443 -j ACCEPT -m comment --comment "Nginx_SSL"
    when: iptablesrules.stdout.find("Nginx_SSL") == -1
  - name: Add postgres rule on ham0 interface
    command: /sbin/iptables -I INPUT -p tcp -s 0/0 --sport 1024:65535 -d {{ansible_ham0.ipv4.address }}  --dport 5432 -m state --state NEW,ESTABLISHED -j ACCEPT -m comment --comment "Postgres"
    when: iptablesrules.stdout.find("Postgres") == -1
  - name: save iptables
    command: service iptables save
  - name: ensure iptables is set to start at boot
    action: command /sbin/chkconfig iptables on

相关内容