0

Want to execute the second task (task2) when the first task (task1) successfully added lines in the file (blockinfile).

 - name: nodes ip server configuration
   hosts: "{{ hostname }}"
   become: true
   become_user: root
   tasks:
     - include_tasks: step1_iptables.yaml
     - include_tasks: step2_script_firewall.yaml

======= more step1_iptables.yaml =========

- name: ip firewall configuration
  blockinfile:
    path: /etc/init.d/test
    marker: "# {mark} Customer {{ admin_code }}-{{ ipadd }}-{{ ip }}-{{ rg1 }}-{{ rg2 }}"
    insertbefore: "## TO HERE"
    block: |
      $IPTABLES -A LOCALLY_MANAGED_RULES_INPUT -p udp -s {{ ipadd }} --sport 5060 -d $ip_SERVER_{{ ip }}_IP_ADDRESS --dport $ip_PORT -j ACCEPT
      $IPTABLES -A LOCALLY_MANAGED_RULES_OUTPUT -p udp -s $ip_SERVER_{{ ip }}_IP_ADDRESS --sport $ip_PORT -d {{ ipadd }} -j ACCEPT
    backup: yes

======= more step2_script_firewall.yaml =========

- name: Run script to save iptables
  command: sh /etc/init.d/firewall_node_local
  register: myoutput
- debug: var=myoutput.stdout_lines

=======================================================================

task2 only runs when lines in task1 added in file. if duplication then task2 related to script run skip.

   tasks:
      - include_tasks: step1_iptables.yaml
      - include_tasks: step2_script_firewall.yaml
        when: step1_iptables.yaml is changed

=======================================================================

Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
  • You'll be better off with [iptables](https://docs.ansible.com/ansible/latest/modules/iptables_module.html#iptables-modify-iptables-rules), or [ufw](https://docs.ansible.com/ansible/latest/modules/ufw_module.html#ufw-manage-firewall-with-ufw). – Vladimir Botka Jun 12 '19 at 03:35

1 Answers1

0

That's what handlers are for. Add notify to the 1st task

- name: ip firewall configuration
  blockinfile:
    path: /etc/init.d/test
    ...
    backup: yes
  notify: script_firewall

and create handlers section with the handler

handlers:
- name: script_firewall
  command: sh /etc/init.d/firewall_node_local
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
  • One question, its not showing debug command output. register: myoutput - debug: var=myoutput.stdout_lines – ahmedrathore Jun 12 '19 at 04:30
  • See [How do I write an Ansible handler with multiple tasks?](https://stackoverflow.com/questions/31618967/how-do-i-write-an-ansible-handler-with-multiple-tasks). – Vladimir Botka Jun 12 '19 at 07:55