I added some rule to firewalld in centos 7 with ansible. But I must reload firewalld daemon thus service work properly. Is there any idea?
Here is my ansible code:
- name: Add port to firewalld
firewalld:
port: "{{ item }}"
permanent: yes
state: enabled
when: ansible_distribution == 'CentOS' or ansible_distribution == 'Red Hat Enterprise Linux'
loop:
- 8080/tcp
- 8000/tcp
- 8090/tcp
- 8040/tcp
6
Answers
You can use service or systemd module.
First of all use
with_items
for list of ports as below:You can also use the below code to enter ports if they are not fixed and use its as a variable:
and regarding reloading firewalld its mentioned here we can’t reload firewalld using state parameter So use systemd module as below:
I’m a bit late but given that all previous answers seem to just speculate I will give another input. Firewalld is not reloaded with ‘service’ or ‘systemctl’ commands but rather with it’s own specific command:
This is because that way you can load new rules without interrupting any active network connections as would be the case when using iptables directly.
Given this I think using service or systemctl is not a good solution.
So if you just want to create a task I suggest using the command module from ansible to execute this command. Or you could write a handler like so:
Just put the handler in the handlers/main.yml file inside your role. Then in your tasks you can call that handler with:
That way Ansible only executes the handler at the end of your Ansible run. I successfully tested this on RHEL7.
firewalld module has immediate option which is performing the same reload within firewall-cmd cli tool.
You already got a number of excellent answers. There is yet another possible approach (although the reloading part is the same as in cstoll’s answer).
If you are certain that nobody and nothing else but Ansible will ever manipulate firewalld rules, you can use a template to directly generate the zone XML files in /etc/firewalld/zones . You will still need to add
and the corresponding handler, as in cstoll’s answer.
The main advantage of this approach is that it can be dramatically faster and simpler than adding the rules one at a time.
The drawback of this approach is that it will not preserve any rules added to firewalld outside of Ansible. A second drawback is that it will not do any error checking; you can create invalid zone files easily. The firewall-cmd command (and thus the firewalld module) will verify the validity of each rule. For instance, it checks that zones do not overlap.
If you are using
permanent
conditional, you can useimmediate
option.Example:
After this rule will applied,
firewalld
will reload automatically.