Ansible как скачать правила iptables
Перейти к содержимому

Ansible как скачать правила iptables

  • автор:

ansible.builtin.iptables – Изменить правила iptables

Этот модуль является частью ansible-core и включен во все установки Ansible. В большинстве случаев можно использовать короткое имя модуля iptables даже без указания ключевого слова collections: . Тем не менее, мы рекомендуем вам использовать FQCN, чтобы упростить ссылку на документацию модуля и избежать конфликтов с другими коллекциями, которые могут иметь такое же имя модуля.

Новое в версии 2.0: ansible.builtin

Synopsis

  • iptables используется для настройки, обслуживания и проверки таблиц правил фильтрации IP-пакетов в ядре Linux.
  • Этот модуль не обрабатывает сохраняющую загрузку правил and/or, а только манипулирует текущими правилами, которые присутствуют в памяти. Это то же самое, что и поведение команд iptables и ip6tables , которые этот модуль использует внутри.

Parameters

добавлено в 2.2 из ansible.builtin
append
Должно ли правило добавляться внизу или вставляться вверху.
Если правило уже существует, цепочка не будет изменена.
Укажите цепочку iptables для изменения.

Это может быть пользовательская цепочка или одна из стандартных цепочек iptables, например INPUT , FORWARD , OUTPUT , PREROUTING , POSTROUTING , SECMARK или CONNSECMARK .

Указывает комментарий, который будет добавлен к правилу.
список / elements=string
Список состояний соединения для сопоставления в модуле conntrack.
Возможные значения: INVALID , NEW , ESTABLISHED , RELATED , UNTRACKED , SNAT , DNAT .
Destination specification.
Адрес может быть сетевым именем, именем хоста, сетевым IP-адресом (с /mask), или обычным IP-адресом.

Имена хостов будут разрешены только один раз, прежде чем правило будет отправлено в ядро. Обратите внимание, что указание любого имени для разрешения с помощью удаленного запроса, такого как DNS, является очень плохой идеей.

Маска может быть маской сети или простым числом, указывающим количество единиц слева от маски сети. Таким образом, маска 24 эквивалентна аргументу 255.255.255.0. ! до того, как спецификация адреса инвертирует смысл адреса.

Спецификация порта назначения или диапазона портов. Это может быть имя службы или номер порта. Также можно указать включающий диапазон, используя формат first:last.. Если первый порт опущен, предполагается ‘0’; если последний опущен, предполагается ‘65535’. Если первый порт больше второго, они будут заменены. Это действительно только в том случае, если в правиле также указан один из следующих протоколов: tcp, udp, dccp или sctp.

список / elements=string
добавлено в 2.11 из ansible.builtin

Это указывает несколько номеров портов назначения или диапазонов портов, которые должны совпадать в многопортовом модуле.

Его можно использовать только совместно с протоколами tcp, udp, udplite, dccp и sctp.
добавлено в 2.8 из ansible.builtin
Указывает диапазон IP-адресов назначения для соответствия в модуле iprange.
добавлено в 2.2 из ansible.builtin
Сбрасывает указанную таблицу и цепочку всех правил.
Если цепочка не указана, очищается вся таблица.
Игнорирует все остальные параметры.

Это означает, что правило касается только второго и последующих фрагментов фрагментированных пакетов.

Поскольку невозможно указать порты источника или получателя такого пакета (или ICMP type),), такой пакет не будет соответствовать каким-либо правилам, которые его определяют.

Когда «!» аргумент предшествует аргументу фрагмента, правило будет соответствовать только головным фрагментам или нефрагментированным пакетам.

добавлено в 2.8 из ansible.builtin
Это указывает IP-адрес хоста для отправки клонированных пакетов.
Эта опция действительна, только если для jump установлено значение TEE .
добавлено в 2.9 из ansible.builtin
Указывает GID или группу для использования в соответствии с правилом владельца.
Это указывает, что обработка должна продолжаться в заданной пользователем цепочке.

В отличие от аргумента перехода, return продолжит обработку не в этой цепочке, а в цепочке, вызвавшей нас через переход.

добавлено в 2.2 из ansible.builtin

Это позволяет указать тип ICMP, который может быть числовым типом ICMP, парой type/code или одним из имен типа ICMP, отображаемых командой «iptables -p icmp -h».

Имя интерфейса, через который был получен пакет (только для пакетов, поступающих на INPUT , FORWARD и PREROUTING chains).

Когда аргумент ! используется перед именем интерфейса, смысл инвертируется.

Если имя интерфейса заканчивается на + , то будет соответствовать любой интерфейс, начинающийся с этого имени.

Если этот параметр опущен, любое имя интерфейса будет соответствовать.
К какой версии IP-протокола должно применяться это правило.
Это указывает цель правила; i.e., что делать, если пакет совпадает с ним.

Целью может быть цепочка, определяемая пользователем (кроме той, для которой это правило — in),, одна из специальных встроенных целей, которая немедленно решает судьбу пакета, или расширение (см. EXTENSIONS below).

Если этот параметр опущен в правиле (и параметр goto не равен used),, то совпадение с правилом не повлияет на судьбу пакета, но счетчики правила будут увеличены.

Определяет максимальное среднее количество совпадений, допустимое в секунду.

Номер может указывать блоки явно, используя `/second’, `/minute’, `/hour’ или `/day’, или их части (таким образом, `5/second’ совпадает с `5/s’).).

добавлено в 2.1 из ansible.builtin
Определяет максимальный пакет до того, как сработает указанный выше предел.
добавлено в 2.8 из ansible.builtin
Уровень ведения журнала в соответствии с приоритетами, определенными syslogd.
Значение может быть строкой или числом от 1 до 8.
Этот параметр применим, только если jump установлен на LOG .
добавлено в 2.5 ansible.builtin
Указывает текст журнала для правила. Имеет смысл только с прыжком LOG.
список / elements=string

Указывает соответствие для использования, то есть модуль расширения, который проверяет определенное свойство.

Набор совпадений составляет условие, при котором вызывается цель.

Совпадения оцениваются от первого до последнего, если они указаны в виде массива и работают в режиме короткого замыкания, i.e., если одно расширение дает false, оценка останавливается.

добавлено в 2.11 из ansible.builtin
Указывает имя набора, которое может быть определено ipset.
Должен использоваться вместе с параметром match_set_flags.
Когда аргумент ! добавляется в начало, правило инвертируется.
Использует расширение набора iptables.
добавлено в 2.11 из ansible.builtin
Указывает необходимые флаги для параметра match_set.
Должен использоваться вместе с параметром match_set.
Использует расширение набора iptables.

Имя интерфейса, через который будет отправлен пакет (для пакетов, поступающих на FORWARD , OUTPUT и POSTROUTING chains).

Когда аргумент ! используется перед именем интерфейса, смысл инвертируется.

Если имя интерфейса заканчивается на + , то будет соответствовать любой интерфейс, начинающийся с этого имени.

Если этот параметр опущен, любое имя интерфейса будет соответствовать.
добавлено в 2.2 из ansible.builtin
Установите политику для цепочки на указанную цель.
Только встроенные цепочки могут иметь политики.
Для этого параметра требуется параметр chain .
Если вы укажете этот параметр, все остальные параметры будут проигнорированы.

Этот параметр используется для установки политики по умолчанию для данного chain . Не путайте с параметром jump .

Протокол правила или пакета для проверки.

Указанный протокол может быть одним из tcp , udp , udplite , icmp , ipv6-icmp или icmpv6 , esp , ah , sctp или специальным ключевым словом all , или это может быть числовое значение, представляющее один из этих протоколов или другой.

Также разрешено имя протокола от /etc/protocols.
Аргумент ! перед тем, как протокол инвертирует тест.
Число ноль эквивалентно всем.
all будет соответствовать всем протоколам и используется по умолчанию, если этот параметр опущен.
добавлено в 2.1 из ansible.builtin

Указывает тип пакета ошибки, который будет возвращен при отклонении. Это подразумевает «прыжок: REJECT».

добавлено в 2.5 ansible.builtin
Вставьте правило под заданным номером правила.
Это работает только с action=insert .

Это позволяет администратору инициализировать счетчики пакетов и байтов правила (во время INSERT , APPEND , REPLACE operations).

добавлено в 2.1 из ansible.builtin

Это позволяет указать метку DSCP для добавления к пакетам. Он принимает целое или шестнадцатеричное значение.

Взаимоисключающий с set_dscp_mark_class .
добавлено в 2.1 из ansible.builtin

Это позволяет указать предопределенный класс DiffServ, который будет преобразован в соответствующую метку DSCP.

Взаимоисключающий с set_dscp_mark .
Source specification.
Адрес может быть сетевым именем, именем хоста, сетевым IP-адресом (с /mask), или обычным IP-адресом.

Имена хостов будут разрешены только один раз, прежде чем правило будет отправлено в ядро. Обратите внимание, что указание любого имени для разрешения с помощью удаленного запроса, такого как DNS, является очень плохой идеей.

Маска может быть маской сети или простым числом, указывающим количество единиц слева от маски сети. Таким образом, маска 24 эквивалентна аргументу 255.255.255.0. ! до того, как спецификация адреса инвертирует смысл адреса.

Исходный порт или спецификация диапазона портов.
Это может быть имя службы или номер порта.
Также можно указать включающий диапазон, используя формат first:last .
Если первый порт не указан, предполагается 0 ; если последний опущен, предполагается 65535 .
Если первый порт больше второго, они будут заменены.
добавлено в 2.8 из ansible.builtin
Указывает исходный диапазон IP-адресов для соответствия в модуле iprange.
present
Должно ли правило отсутствовать или присутствовать.
добавлено в 2.5 ansible.builtin
ignore
Это позволяет сопоставлять пакеты с установленным битом SYN и неустановленными битами ACK и RST.
При отрицании это соответствует всем пакетам с установленными битами RST или ACK.
filter
Эта опция указывает таблицу сопоставления пакетов, с которой должна работать команда.

Если ядро настроено на автоматическую загрузку модулей, будет предпринята попытка загрузить соответствующий модуль для этой таблицы, если его еще нет.

dictionary
добавлено в 2.4 из ansible.builtin
Спецификация флагов TCP.
tcp_flags ожидает дикт с двумя ключами flags и flags_set .
список / elements=string
Список флагов, которые вы хотите изучить.
список / elements=string
Флаги, которые нужно установить.
добавлено в 2.1 из ansible.builtin
Это указывает адрес назначения для использования с DNAT .
Без этого адрес назначения никогда не изменяется.

Это указывает порт назначения или диапазон портов для использования, без этого порт назначения никогда не изменяется.

Это допустимо только в том случае, если в правиле также указан один из протоколов tcp , udp , dccp или sctp .

добавлено в 2.2 из ansible.builtin
Это указывает исходный адрес для использования с SNAT .
Без этого исходный адрес никогда не изменяется.
добавлено в 2.1 из ansible.builtin
Указывает UID или имя пользователя для использования в правиле сопоставления по владельцу.

Начиная с Ansible 2.6, когда аргумент ! добавляется в начале, правило инвертируется и применяется ко всем пользователям, кроме указанного.

добавлено в 2.10 из ansible.builtin

Подождите N секунд, пока xtables заблокируется, чтобы предотвратить одновременный запуск нескольких экземпляров программы.

Notes

  • Этот модуль работает только с отдельными rules.If, вам нужна расширенная цепочка правил, рекомендуемый способ — создать шаблон файла восстановления iptables.

Examples

- name: Block specific IP ansible.builtin.iptables: chain: INPUT source: 8.8.8.8 jump: DROP become: yes - name: Forward port 80 to 8600 ansible.builtin.iptables: table: nat chain: PREROUTING in_interface: eth0 protocol: tcp match: tcp destination_port: 80 jump: REDIRECT to_ports: 8600 comment: Redirect web traffic to port 8600 become: yes - name: Allow related and established connections ansible.builtin.iptables: chain: INPUT ctstate: ESTABLISHED,RELATED jump: ACCEPT become: yes - name: Allow new incoming SYN packets on TCP port 22 (SSH) ansible.builtin.iptables: chain: INPUT protocol: tcp destination_port: 22 ctstate: NEW syn: match jump: ACCEPT comment: Accept new SSH connections. - name: Match on IP ranges ansible.builtin.iptables: chain: FORWARD src_range: 192.168.1.100-192.168.1.199 dst_range: 10.0.0.1-10.0.0.50 jump: ACCEPT - name: Allow source IPs defined in ipset "admin_hosts" on port 22 ansible.builtin.iptables: chain: INPUT match_set: admin_hosts match_set_flags: src destination_port: 22 jump: ALLOW - name: Tag all outbound tcp packets with DSCP mark 8 ansible.builtin.iptables: chain: OUTPUT jump: DSCP table: mangle set_dscp_mark: 8 protocol: tcp - name: Tag all outbound tcp packets with DSCP DiffServ class CS1 ansible.builtin.iptables: chain: OUTPUT jump: DSCP table: mangle set_dscp_mark_class: CS1 protocol: tcp - name: Insert a rule on line 5 ansible.builtin.iptables: chain: INPUT protocol: tcp destination_port: 8080 jump: ACCEPT action: insert rule_num: 5 # Подумайте дважды, прежде чем запускать следующую задачу, так как это может заблокировать целевую систему - name: Set the policy for the INPUT chain to DROP ansible.builtin.iptables: chain: INPUT policy: DROP - name: Reject tcp with tcp-reset ansible.builtin.iptables: chain: INPUT protocol: tcp reject_with: tcp-reset ip_version: ipv4 - name: Set tcp flags ansible.builtin.iptables: chain: OUTPUT jump: DROP protocol: tcp tcp_flags: flags: ALL flags_set: - ACK - RST - SYN - FIN - name: Iptables flush filter ansible.builtin.iptables: chain: ">" flush: yes with_items: [ 'INPUT', 'FORWARD', 'OUTPUT' ] - name: Iptables flush nat ansible.builtin.iptables: table: nat chain: '>' flush: yes with_items: [ 'INPUT', 'OUTPUT', 'PREROUTING', 'POSTROUTING' ] - name: Log packets arriving into an user-defined chain ansible.builtin.iptables: chain: LOGGING action: append state: present limit: 2/second limit_burst: 20 log_prefix: "IPTABLES:INFO: " log_level: info - name: Allow connections on multiple ports ansible.builtin.iptables: chain: INPUT protocol: tcp destination_ports: - "80" - "443" - "8081:8083" jump: ACCEPT 

Authors

  • Линус Уннебек (@LinusU) < [email protected] >
  • Себастьен Д.А. ROCHA (@sebastiendarocha)

ansible.builtin.iptables module – Modify iptables rules

This module is part of ansible-core and included in all Ansible installations. In most cases, you can use the short module name iptables even without specifying the collections keyword . However, we recommend you use the Fully Qualified Collection Name (FQCN) ansible.builtin.iptables for easy linking to the module documentation and to avoid conflicting with other collections that may have the same module name.

Synopsis

  • iptables is used to set up, maintain, and inspect the tables of IP packet filter rules in the Linux kernel.
  • This module does not handle the saving and/or loading of rules, but rather only manipulates the current rules that are present in memory. This is the same as the behaviour of the iptables and ip6tables command which this module uses internally.

Parameters

action

Whether the rule should be appended at the bottom or inserted at the top.

If the rule already exists the chain will not be modified.

Choices:

chain

Specify the iptables chain to modify.

This could be a user-defined chain or one of the standard iptables chains, like INPUT , FORWARD , OUTPUT , PREROUTING , POSTROUTING , SECMARK or CONNSECMARK .

chain_management

added in ansible-core 2.13

If true and state is present , the chain will be created if needed.

If true and state is absent , the chain will be deleted if the only other parameter passed are chain and optionally table .

Choices:

comment

This specifies a comment that will be added to the rule.

ctstate

A list of the connection states to match in the conntrack module.

Possible values are INVALID , NEW , ESTABLISHED , RELATED , UNTRACKED , SNAT , DNAT .

Default: []

destination

Address can be either a network name, a hostname, a network IP address (with /mask), or a plain IP address.

Hostnames will be resolved once only, before the rule is submitted to the kernel. Please note that specifying any name to be resolved with a remote query such as DNS is a really bad idea.

The mask can be either a network mask or a plain number, specifying the number of 1’s at the left side of the network mask. Thus, a mask of 24 is equivalent to 255.255.255.0. A ! argument before the address specification inverts the sense of the address.

destination_port

Destination port or port range specification. This can either be a service name or a port number. An inclusive range can also be specified, using the format first:last. If the first port is omitted, ‘0’ is assumed; if the last is omitted, ‘65535’ is assumed. If the first port is greater than the second one they will be swapped. This is only valid if the rule also specifies one of the following protocols: tcp, udp, dccp or sctp.

destination_ports

added in ansible-core 2.11

This specifies multiple destination port numbers or port ranges to match in the multiport module.

It can only be used in conjunction with the protocols tcp, udp, udplite, dccp and sctp.

Default: []

dst_range

added in Ansible 2.8

Specifies the destination IP range to match in the iprange module.

flush

Flushes the specified table and chain of all rules.

If no chain is specified then the entire table is purged.

Ignores all other parameters.

Choices:

fragment

This means that the rule only refers to second and further fragments of fragmented packets.

Since there is no way to tell the source or destination ports of such a packet (or ICMP type), such a packet will not match any rules which specify them.

When the “!” argument precedes fragment argument, the rule will only match head fragments, or unfragmented packets.

gateway

added in Ansible 2.8

This specifies the IP address of host to send the cloned packets.

This option is only valid when jump is set to TEE .

gid_owner

added in Ansible 2.9

Specifies the GID or group to use in match by owner rule.

goto

This specifies that the processing should continue in a user specified chain.

Unlike the jump argument return will not continue processing in this chain but instead in the chain that called us via jump.

icmp_type

This allows specification of the ICMP type, which can be a numeric ICMP type, type/code pair, or one of the ICMP type names shown by the command ‘iptables -p icmp -h’

in_interface

Name of an interface via which a packet was received (only for packets entering the INPUT , FORWARD and PREROUTING chains).

When the ! argument is used before the interface name, the sense is inverted.

If the interface name ends in a + , then any interface which begins with this name will match.

If this option is omitted, any interface name will match.

ip_version

Which version of the IP protocol this rule should apply to.

Choices:

jump

This specifies the target of the rule; i.e., what to do if the packet matches it.

The target can be a user-defined chain (other than the one this rule is in), one of the special builtin targets which decide the fate of the packet immediately, or an extension (see EXTENSIONS below).

If this option is omitted in a rule (and the goto parameter is not used), then matching the rule will have no effect on the packet’s fate, but the counters on the rule will be incremented.

limit

Specifies the maximum average number of matches to allow per second.

The number can specify units explicitly, using /second , /minute , /hour or /day , or parts of them (so 5/second is the same as 5/s ).

limit_burst

Specifies the maximum burst before the above limit kicks in.

log_level

added in Ansible 2.8

Logging level according to the syslogd-defined priorities.

The value can be strings or numbers from 1-8.

This parameter is only applicable if jump is set to LOG .

Choices:

log_prefix

Specifies a log text for the rule. Only make sense with a LOG jump.

match

Specifies a match to use, that is, an extension module that tests for a specific property.

The set of matches make up the condition under which a target is invoked.

Matches are evaluated first to last if specified as an array and work in short-circuit fashion, i.e. if one extension yields false, evaluation will stop.

Default: []

match_set

added in ansible-core 2.11

Specifies a set name which can be defined by ipset.

Must be used together with the match_set_flags parameter.

When the ! argument is prepended then it inverts the rule.

Uses the iptables set extension.

match_set_flags

added in ansible-core 2.11

Specifies the necessary flags for the match_set parameter.

Must be used together with the match_set parameter.

Uses the iptables set extension.

Choices:

numeric

added in ansible-core 2.15

This parameter controls the running of the list -action of iptables, which is used internally by the module

Does not affect the actual functionality. Use this if iptables hangs when creating chain or altering policy

If true , then iptables skips the DNS-lookup of the IP addresses in a chain when it uses the list -action

Listing is used internally for example when setting a policy or creting of a chain

Choices:

out_interface

Name of an interface via which a packet is going to be sent (for packets entering the FORWARD , OUTPUT and POSTROUTING chains).

When the ! argument is used before the interface name, the sense is inverted.

If the interface name ends in a + , then any interface which begins with this name will match.

If this option is omitted, any interface name will match.

policy

Set the policy for the chain to the given target.

Only built-in chains can have policies.

This parameter requires the chain parameter.

If you specify this parameter, all other parameters will be ignored.

This parameter is used to set default policy for the given chain . Do not confuse this with jump parameter.

Choices:

protocol

The protocol of the rule or of the packet to check.

The specified protocol can be one of tcp , udp , udplite , icmp , ipv6-icmp or icmpv6 , esp , ah , sctp or the special keyword all , or it can be a numeric value, representing one of these protocols or a different one.

A protocol name from /etc/protocols is also allowed.

A ! argument before the protocol inverts the test.

The number zero is equivalent to all.

all will match with all protocols and is taken as default when this option is omitted.

reject_with

Specifies the error packet type to return while rejecting. It implies “jump: REJECT”.

rule_num

Insert the rule as the given rule number.

This works only with action=insert .

set_counters

This enables the administrator to initialize the packet and byte counters of a rule (during INSERT , APPEND , REPLACE operations).

set_dscp_mark

This allows specifying a DSCP mark to be added to packets. It takes either an integer or hex value.

Mutually exclusive with set_dscp_mark_class .

set_dscp_mark_class

This allows specifying a predefined DiffServ class which will be translated to the corresponding DSCP mark.

Mutually exclusive with set_dscp_mark .

source

Address can be either a network name, a hostname, a network IP address (with /mask), or a plain IP address.

Hostnames will be resolved once only, before the rule is submitted to the kernel. Please note that specifying any name to be resolved with a remote query such as DNS is a really bad idea.

The mask can be either a network mask or a plain number, specifying the number of 1’s at the left side of the network mask. Thus, a mask of 24 is equivalent to 255.255.255.0. A ! argument before the address specification inverts the sense of the address.

source_port

Source port or port range specification.

This can either be a service name or a port number.

An inclusive range can also be specified, using the format first:last .

If the first port is omitted, 0 is assumed; if the last is omitted, 65535 is assumed.

If the first port is greater than the second one they will be swapped.

src_range

added in Ansible 2.8

Specifies the source IP range to match in the iprange module.

state

Whether the rule should be absent or present.

Choices:

syn

This allows matching packets that have the SYN bit set and the ACK and RST bits unset.

When negated, this matches all packets with the RST or the ACK bits set.

Choices:

table

This option specifies the packet matching table which the command should operate on.

If the kernel is configured with automatic module loading, an attempt will be made to load the appropriate module for that table if it is not already there.

Choices:

tcp_flags

TCP flags specification.

tcp_flags expects a dict with the two keys flags and flags_set .

flags

List of flags you want to examine.

flags_set

Flags to be set.

to_destination

This specifies a destination address to use with DNAT .

Without this, the destination address is never altered.

to_ports

This specifies a destination port or range of ports to use, without this, the destination port is never altered.

This is only valid if the rule also specifies one of the protocol tcp , udp , dccp or sctp .

to_source

This specifies a source address to use with SNAT .

Without this, the source address is never altered.

uid_owner

Specifies the UID or username to use in match by owner rule.

From Ansible 2.6 when the ! argument is prepended then the it inverts the rule to apply instead to all users except that one specified.

wait

added in ansible-base 2.10

Wait N seconds for the xtables lock to prevent multiple instances of the program from running concurrently.

Attributes

check_mode

Support: full

Can run in check_mode and return changed status prediction without modifying target

diff_mode

Support: none

Will return details on what has changed (or possibly needs changing in check_mode), when in diff mode

platform

Platform: linux

Target OS/families that can be operated against

Notes

  • This module just deals with individual rules. If you need advanced chaining of rules the recommended way is to template the iptables restore file.

Examples

- name: Block specific IP ansible.builtin.iptables: chain: INPUT source: 8.8.8.8 jump: DROP become: yes - name: Forward port 80 to 8600 ansible.builtin.iptables: table: nat chain: PREROUTING in_interface: eth0 protocol: tcp match: tcp destination_port: 80 jump: REDIRECT to_ports: 8600 comment: Redirect web traffic to port 8600 become: yes - name: Allow related and established connections ansible.builtin.iptables: chain: INPUT ctstate: ESTABLISHED,RELATED jump: ACCEPT become: yes - name: Allow new incoming SYN packets on TCP port 22 (SSH) ansible.builtin.iptables: chain: INPUT protocol: tcp destination_port: 22 ctstate: NEW syn: match jump: ACCEPT comment: Accept new SSH connections. - name: Match on IP ranges ansible.builtin.iptables: chain: FORWARD src_range: 192.168.1.100-192.168.1.199 dst_range: 10.0.0.1-10.0.0.50 jump: ACCEPT - name: Allow source IPs defined in ipset "admin_hosts" on port 22 ansible.builtin.iptables: chain: INPUT match_set: admin_hosts match_set_flags: src destination_port: 22 jump: ALLOW - name: Tag all outbound tcp packets with DSCP mark 8 ansible.builtin.iptables: chain: OUTPUT jump: DSCP table: mangle set_dscp_mark: 8 protocol: tcp - name: Tag all outbound tcp packets with DSCP DiffServ class CS1 ansible.builtin.iptables: chain: OUTPUT jump: DSCP table: mangle set_dscp_mark_class: CS1 protocol: tcp # Create the user-defined chain ALLOWLIST - iptables: chain: ALLOWLIST chain_management: true # Delete the user-defined chain ALLOWLIST - iptables: chain: ALLOWLIST chain_management: true state: absent - name: Insert a rule on line 5 ansible.builtin.iptables: chain: INPUT protocol: tcp destination_port: 8080 jump: ACCEPT action: insert rule_num: 5 # Think twice before running following task as this may lock target system - name: Set the policy for the INPUT chain to DROP ansible.builtin.iptables: chain: INPUT policy: DROP - name: Reject tcp with tcp-reset ansible.builtin.iptables: chain: INPUT protocol: tcp reject_with: tcp-reset ip_version: ipv4 - name: Set tcp flags ansible.builtin.iptables: chain: OUTPUT jump: DROP protocol: tcp tcp_flags: flags: ALL flags_set: - ACK - RST - SYN - FIN - name: Iptables flush filter ansible.builtin.iptables: chain: " item >>" flush: yes with_items: [ 'INPUT', 'FORWARD', 'OUTPUT' ] - name: Iptables flush nat ansible.builtin.iptables: table: nat chain: ' item >>' flush: yes with_items: [ 'INPUT', 'OUTPUT', 'PREROUTING', 'POSTROUTING' ] - name: Log packets arriving into an user-defined chain ansible.builtin.iptables: chain: LOGGING action: append state: present limit: 2/second limit_burst: 20 log_prefix: "IPTABLES:INFO: " log_level: info - name: Allow connections on multiple ports ansible.builtin.iptables: chain: INPUT protocol: tcp destination_ports: - "80" - "443" - "8081:8083" jump: ACCEPT 

Authors

  • Linus Unnebäck (@LinusU)
  • Sébastien DA ROCHA (@sebastiendarocha)

Collection links

  • Issue Tracker
  • Repository (Sources)
  • Communication

© Copyright Ansible project contributors. Last updated on Oct 26, 2023.

community.general.iptables_state module – Save iptables state into a file or restore it from a file

This module is part of the community.general collection (version 7.5.0).

You might already have this collection installed if you are using the ansible package. It is not included in ansible-core . To check whether it is installed, run ansible-galaxy collection list .

To install it, use: ansible-galaxy collection install community.general . You need further requirements to be able to use this module, see Requirements for details.

To use it in a playbook, specify: community.general.iptables_state .

New in community.general 1.1.0

Synopsis

  • iptables is used to set up, maintain, and inspect the tables of IP packet filter rules in the Linux kernel.
  • This module handles the saving and/or loading of rules. This is the same as the behaviour of the iptables-save and iptables-restore (or ip6tables-save and ip6tables-restore for IPv6) commands which this module uses internally.
  • Modifying the state of the firewall remotely may lead to loose access to the host in case of mistake in new ruleset. This module embeds a rollback feature to avoid this, by telling the host to restore previous rules if a cookie is still there after a given delay, and all this time telling the controller to try to remove this cookie on the host through a new connection.

This module has a corresponding action plugin .

Requirements

The below requirements are needed on the host that executes this module.

Parameters

counters

Save or restore the values of all packet and byte counters.

When true , the module is not idempotent.

Choices:

ip_version

Which version of the IP protocol this module should apply to.

Choices:

modprobe

Specify the path to the modprobe program internally used by iptables related commands to load kernel modules.

By default, /proc/sys/kernel/modprobe is inspected to determine the executable’s path.

noflush

For state=restored , ignored otherwise.

If false , restoring iptables rules from a file flushes (deletes) all previous contents of the respective table(s). If true , the previous rules are left untouched (but policies are updated anyway, for all built-in chains).

Choices:

path

The file the iptables state should be saved to.

The file the iptables state should be restored from.

state

Whether the firewall state should be saved (into a file) or restored (from a file).

Choices:

table

When state=restored , restore only the named table even if the input file contains other tables. Fail if the named table is not declared in the file.

When state=saved , restrict output to the specified table. If not specified, output includes all active tables.

Choices:

  • «filter»
  • «nat»
  • «mangle»
  • «raw»
  • «security»

wait

Wait N seconds for the xtables lock to prevent instant failure in case multiple instances of the program are running concurrently.

Attributes

action

Support: full

Indicates this has a corresponding action plugin so some parts of the options can be executed on the controller.

async

Support: full

Supports being used with the async keyword.

check_mode

Support: full

Can run in check_mode and return changed status prediction without modifying target.

diff_mode

Support: none

Will return details on what has changed (or possibly needs changing in check_mode ), when in diff mode.

Notes

  • The rollback feature is not a module option and depends on task’s attributes. To enable it, the module must be played asynchronously, i.e. by setting task attributes poll to 0 , and async to a value less or equal to ANSIBLE_TIMEOUT . If async is greater, the rollback will still happen if it shall happen, but you will experience a connection timeout instead of more relevant info returned by the module after its failure.

Examples

# This will apply to all loaded/active IPv4 tables. - name: Save current state of the firewall in system file community.general.iptables_state: state: saved path: /etc/sysconfig/iptables # This will apply only to IPv6 filter table. - name: save current state of the firewall in system file community.general.iptables_state: ip_version: ipv6 table: filter state: saved path: /etc/iptables/rules.v6 # This will load a state from a file, with a rollback in case of access loss - name: restore firewall state from a file community.general.iptables_state: state: restored path: /run/iptables.apply async: " ansible_timeout >>" poll: 0 # This will load new rules by appending them to the current ones - name: restore firewall state from a file community.general.iptables_state: state: restored path: /run/iptables.apply noflush: true async: " ansible_timeout >>" poll: 0 # This will only retrieve information - name: get current state of the firewall community.general.iptables_state: state: saved path: /tmp/iptables check_mode: true changed_when: false register: iptables_state - name: show current state of the firewall ansible.builtin.debug: var: iptables_state.initial_state 

Return Values

Common return values are documented here , the following are the fields unique to this module:

community.general.iptables_state — Сохранение состояния iptables в файл или восстановление его из файла

Этот плагин является частью community.general collection (версия 3.8.1).).

Возможно, у вас уже установлена эта коллекция, если вы используете пакет ansible . Он не включен в ansible-core . Чтобы проверить, установлен ли он, запустите ansible-galaxy collection list .

Для его установки используйте: ansible-galaxy collection install community.general .

Чтобы использовать его в плейбуке, укажите: community.general.iptables_state .

Новое в версии 1.1.0: community.general

Synopsis

  • iptables используется для настройки, обслуживания и проверки таблиц правил фильтрации IP-пакетов в ядре Linux.
  • Этот модуль обрабатывает сохраняющую загрузку правил and/or. Это то же самое, что и поведение iptables-save и iptables-restore (или ip6tables-save и ip6tables-restore для команд IPv6), которые этот модуль использует внутри.
  • Удаленное изменение состояния брандмауэра может привести к потере доступа к хосту в случае ошибки в новом наборе правил. Этот модуль включает функцию отката, чтобы избежать этого, сообщая хосту восстановить предыдущие правила, если файл cookie все еще существует после заданной задержки, и все это время сообщая контроллеру, чтобы он попытался удалить этот файл cookie на хосте через новое соединение.

Этому модулю соответствует action plugin .

Requirements

Следующие требования необходимы для хоста, на котором выполняется этот модуль.

Parameters

Сохраните или восстановите значения всех счетчиков пакетов и байтов.
Когда true модуль не является идемпотентным.
К какой версии IP-протокола должен применяться этот модуль.

Укажите путь к программе modprobe , которая используется командами, связанными с iptables, для загрузки модулей ядра.

По умолчанию проверяется /proc/sys/kernel/modprobe для определения пути к исполняемому файлу.
Для state=restored в противном случае игнорируется.

Если false , восстановление правил iptables из файла сбрасывает (удаляет) все предыдущее содержимое соответствующего table(s).. Если true , предыдущие правила остаются нетронутыми (но политики все равно обновляются для всех встроенных chains).).

путь / требуется
Файл, в котором должно быть сохранено состояние iptables.
Файл, из которого нужно восстановить состояние iptables.
строка / обязательный
Следует ли сохранять состояние брандмауэра (в файл) или восстанавливать (из file).).

При state=restored восстанавливать только именованную таблицу, даже если входной файл содержит другие таблицы. Сбой, если именованная таблица не объявлена в файле.

При state=saved ограничить вывод указанной таблицей. Если не указано, выходные данные включают все активные таблицы.

Подождите N секунд до блокировки xtables, чтобы предотвратить мгновенный сбой в случае одновременного запуска нескольких экземпляров программы.

Notes

  • Функция отката не является опцией модуля и зависит от атрибутов задачи. Чтобы включить его, необходимо воспроизвести модуль asynchronly, i.e., установив опрос атрибутов задачи на 0 и async на значение, меньшее или равное ANSIBLE_TIMEOUT . Если async больше, откат все равно произойдет, если он произойдет, но вы получите тайм-аут соединения вместо более релевантной информации, возвращаемой модулем после его сбоя.
  • Этот модуль поддерживает check_mode.

Examples

# Это применимо ко всем таблицам loaded/active IPv4. - name: Save current state of the firewall in system file community.general.iptables_state: state: saved path: /etc/sysconfig/iptables # Это применимо только к таблице фильтров IPv6. - name: save current state of the firewall in system file community.general.iptables_state: ip_version: ipv6 table: filter state: saved path: /etc/iptables/rules.v6 # Это загрузит состояние из файла, с откатом в случае потери доступа - name: restore firewall state from a file community.general.iptables_state: state: restored path: /run/iptables.apply async: ">" poll: 0 # Это загрузит новые правила, добавив их к текущим - name: restore firewall state from a file community.general.iptables_state: state: restored path: /run/iptables.apply noflush: true async: ">" poll: 0 # Будет получена только информация - name: get current state of the firewall community.general.iptables_state: state: saved path: /tmp/iptables check_mode: yes changed_when: false register: iptables_state - name: show current state of the firewall ansible.builtin.debug: var: iptables_state.initial_state 

Return Values

Общие возвращаемые значения задокументированы here , следующие поля являются уникальными для этого модуля:

Было ли успешно восстановлено состояние розыска.
Sample:
список / elements=string
Текущее состояние брандмауэра при запуске модуля.
Sample:

[‘# Сгенерировано xtables-save v1.8.2’, ‘*filter’, ‘:INPUT ACCEPT [0:0]’, ‘:FORWARD ACCEPT [0:0]’, ‘:OUTPUT ACCEPT [0:0]’, ‘COMMIT’, ‘# Completed’]

список / elements=string

Состояние, которое восстанавливает модуль, вне зависимости от того, применяется он окончательно или нет.

Sample:

[‘# Сгенерировано xtables-save v1.8.2’, ‘*filter’, ‘:INPUT DROP [0:0]’, ‘:FORWARD DROP [0:0]’, ‘:OUTPUT ACCEPT [0:0]’, ‘-A INPUT -m conntrack —ctstate RELATED,ESTABLISHED -j ACCEPT’, ‘-A Z8531 Z -m conntrack —ctstate INVALID -j DROP’, ‘-A INPUT -i lo -j ACCEPT’, ‘-A INPUT -p icmp -j ACCEPT’, ‘-A INPUT -p tcp -m tcp —dport 22 -j ACCEPT’, ‘COMMIT’, ‘# Завершено’ ]

список / elements=string
В iptables указано, что модуль сохранен.
Sample:

[‘# Сгенерировано xtables-save v1.8.2’, ‘*filter’, ‘:INPUT ACCEPT [0:0]’, ‘:FORWARD DROP [0:0]’, ‘:OUTPUT ACCEPT [0:0]’, ‘COMMIT’, ‘# Completed’]

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *