从文件中加载变量并进行比较

时间:2019-06-21 11:37:42

标签: ansible

我正在编写一个Ansible脚本,通过检查规则是否已存在来添加iptable规则。

在脚本中,我将所有iptables结果保存到变量“ ipall”。然后,我在“ rules.txt”中阅读新规则,并将其保存到rules变量。现在,我尝试从“ rules.txt”中获取第一条规则,并验证规则是否存在于ipall中,如果不存在,则将其添加到iptables中。

  tasks:
    - name: fetch iptable
      shell: iptables-save
      register: ipall

    - debug: var=ipall

    - name: load variables
      command: cat rules.txt
      register: rules

    - debug: var=rules

    - name: search a rule
      debug:
        msg: "iptables {{ item }}"
      loop: rules.stdout_lines
      when: item not in ipall.stdout_lines
[root@localhost myplaybooks]# cat rules.txt 
-A TESTCHAIN -p tcp -m tcp --dport 100 -j ACCEPT
-A TESTCHAIN -p tcp -m tcp --dport 101 -j ACCEPT
-A TESTCHAIN -p tcp -m tcp --dport 102 -j ACCEPT

我希望脚本将规则添加到rules.txt中,但出现以下错误。

ok: [localhost] => (item=rules.stdout_lines) => {
    "msg": "iptables rules.stdout_lines"
}

2 个答案:

答案 0 :(得分:1)

首先,让我们看看会发生什么

- name: Print commands to apply missing rules
  debug:
     msg: "iptables {{ item }}"
  loop: rules.stdout_lines
  when: item not in ipall.stdout_lines

然后尝试下面的任务(当然要先使用TESTCHAIN)

- name: Search and apply missing rules
  command: "iptables {{ item }}"
  loop: rules.stdout_lines
  when: item not in ipall.stdout_lines

(未经测试)

答案 1 :(得分:1)

以下内容正在工作:

---
- hosts: localhost
  vars:
    rules: "{{ lookup('file', 'rules.txt') }}"
  tasks:
    - name: fetch iptable
      shell: iptables-save
      register: ipall
    - debug:
        var: ipall.stdout_lines
    - debug:
        var: rules
    - name: search a rule
      debug:
        msg: "{{ item }}"
      with_items:
        - "{{ ipall.stdout_lines }}"
      when: item not in rules

文件->

-A TESTCHAIN -p tcp -m tcp --dport 100 -j ACCEPT
-A TESTCHAIN -p tcp -m tcp --dport 101 -j ACCEPT
-A TESTCHAIN -p tcp -m tcp --dport 102 -j ACCEPT
-A DOCKER-ISOLATION-STAGE-2 -j RETURN

部分输出->

}
ok: [localhost] => (item=-A DOCKER-ISOLATION-STAGE-2 -o docker0 -j DROP) => {
    "msg": "-A DOCKER-ISOLATION-STAGE-2 -o docker0 -j DROP"
}
skipping: [localhost] => (item=-A DOCKER-ISOLATION-STAGE-2 -j RETURN)
ok: [localhost] => (item=-A DOCKER-USER -j RETURN) => {
    "msg": "-A DOCKER-USER -j RETURN"
}
ok: [localhost] => (item=COMMIT) => {
    "msg": "COMMIT"
}
ok: [localhost] => (item=# Completed on Fri Jun 21 17:07:15 2019) => {
    "msg": "# Completed on Fri Jun 21 17:07:15 2019"
}

PLAY RECAP ********************************************************************************************************************
localhost                  : ok=5    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0