用iptables从Ansible中提取网络信息的指定形式

- set_fact:
    interfaces: "{{ansible_interfaces | map('regex_search', 'en.+') | select('string') | list}}"

- set_fact:
    network: "{{vars['ansible_' + item]['ipv4']['network']}}/{{vars['ansible_' + item]['ipv4']['netmask']}}"
  with_items: "{{interfaces}}"
  register: networks

- set_fact:
    networks: "{{networks.results | map(attribute='ansible_facts.network') | list}}"

- debug:
    msg: "{{networks}}"

- shell: iptables -A INPUT -s {{item}} -j ACCEPT
  with_items: "{{networks}}"



TASK [set_fact] *******************************************************
ok: [127.0.0.1]

TASK [set_fact] *******************************************************
ok: [127.0.0.1] => (item=enp0s3)
ok: [127.0.0.1] => (item=enp0s8)

TASK [set_fact] *******************************************************
ok: [127.0.0.1]

TASK [debug] **********************************************************
ok: [127.0.0.1] => {
    "msg": [
        "192.168.1.0/255.255.255.0",
        "192.168.2.0/255.255.255.0"
    ]
}

TASK [command] ********************************************************
changed: [127.0.0.1] => (item=192.168.1.0/255.255.255.0)
changed: [127.0.0.1] => (item=192.168.2.0/255.255.255.0)

重点有两个

获取动态变量的变量名

Ansible接口的变量名是动态的,例如ansible_enp0s3,因此从ansible_interfaces中提取接口名称并构建变量名。

vars['ansible_' + 変数名]

您可以从中取出。

获取循环执行结果

- set_fact:
    network: "{{vars['ansible_' + item]['ipv4']['network']}}/{{vars['ansible_' + item]['ipv4']['netmask']}}"
  with_items: "{{interfaces}}"
  register: networks

通过注册`register`,可以获取`set_fact`的执行结果。

"changed": false,
"msg": "All items completed",
"results": [
    {
        "_ansible_item_result": true,
        "_ansible_no_log": false,
        "ansible_facts": {
            "network": "192.168.1.0/255.255.255.0"
        },
        "changed": false,
        "invocation": {
            "module_args": {
                "network": "192.168.1.0/255.255.255.0"
            },
            "module_name": "set_fact"
        },
        "item": "enp0s3"
    },
    {
        "_ansible_item_result": true,
        "_ansible_no_log": false,
        "ansible_facts": {
            "network": "192.168.2.0/255.255.255.0"
        },
        "changed": false,
        "invocation": {
            "module_args": {
                "network": "192.168.2.0/255.255.255.0"
            },
            "module_name": "set_fact"
        },
        "item": "enp0s8"
    }
]

有一个结果称为”results”。
通过循环遍历它,
从 “ansible_facts” 的变量名为 “network” (由 “set_fact” 指定)以下的内容中提取map。

- set_fact:
    networks: "{{networks.results | map(attribute='ansible_facts.network') | list}}"

最后

[
        "192.168.1.0/255.255.255.0",
        "192.168.2.0/255.255.255.0"
]

可以获得。

广告
将在 10 秒后关闭
bannerAds