【问题标题】:Ansible increment IP addressAnsible 增量 IP 地址
【发布时间】:2016-01-07 21:41:33
【问题描述】:

我正在使用--extra-vars "lan=10.10.10.1" 将变量传递给ansible

我现在需要增加这个 IP 地址,以便最后一个八位字节为 .2,因此它等于 10.10.10.2。

如何在 ansible 中实现这一点?

【问题讨论】:

    标签: yaml ip-address jinja2 ansible


    【解决方案1】:

    从 Ansible 2.7 开始,可以使用 IP Math

    {{ lan | ipmath(1) }}
    

    【讨论】:

    • 很好,注意 ipmath 在 Ansible/control 端需要 python netaddr 包。
    【解决方案2】:

    一行:

    - set_fact: new_ip="{{ lan | regex_replace('(^.*\.).*$', '\\1') }}{{lan.split('.')[3] | int + 1 }}"
    

    它是如何工作的?

      tasks:
      - name: Echo the passed IP
        debug: var={{lan}}
    
      - name: Extract the last octet, increment it and store it
        set_fact: octet={{lan.split('.')[3] | int + 1 }}
      - debug: var=octet
    
      - name: Append the incremented octet to the first 3 octets
        set_fact: new_ip="{{ lan | regex_replace('(^.*\.).*$', '\\1') }}{{octet}}"
      - debug: var=new_ip
    

    输出

    TASK: [Echo the passed IP] ****************************************************
    ok: [127.0.0.1] => {
        "127.0.0.1": "{{ 127.0.0.1 }}"
    }
    TASK: [Extract the last octet, increment it and store it] *********************
    ok: [127.0.0.1] => {"ansible_facts": {"octet": "2"}}
    
    TASK: [debug var=octet] *******************************************************
    ok: [127.0.0.1] => {
        "octet": "2"
    }
    TASK: [Append the incremented octet to the first 3 octets] ********************
    ok: [127.0.0.1] => {"ansible_facts": {"new_ip": "127.0.0.2"}}
    
    TASK: [debug var=new_ip] ******************************************************
    ok: [127.0.0.1] => {
        "new_ip": "127.0.0.2"
    }
    

    【讨论】:

    • 再次感谢 helloV。
    【解决方案3】:

    您可能想看看ipaddr filter

    【讨论】:

    • 我会看看这个,因为我可能需要它用于其他目的。
    【解决方案4】:

    在 Ansible 2.7 之前

    使用ipaddr filter

    {{ ((lan | ipaddr('int')) + 1) | ipaddr }}
    

    注意 Jinja2 的运算符优先级,它很时髦。

    Ansible 2.7+

    使用ipmath() filter。见the answer by Lars Francke

    【讨论】:

    • 请注意,如果您将其与 CIDR 样式地址一起使用(例如“192.0.2.0/24”并且您想将其递增 1,则需要先获取网络地址 -像这样:- set_fact:\n router_ip: "{{ (( lan | ipaddr('subnet') | ipaddr('int') ) + 1) | ipaddr }}"
    • 现在根据 Ansible 2.7 有一个更简单的解决方案。在这里查看我的答案。现在支持 IP 数学:ipmath(1)
    【解决方案5】:

    如果您想对子网执行此操作,这会很有帮助。

    - name: Give IP addresses sequentially from a subnet
      debug:
         msg: "{{ '10.10.1.48/28' | next_nth_usable(loop_index) }}" 
      loop: "{{ list }}"
      loop_control:
         index_var: loop_index
    

    在运行 playbook 之前,请不要忘记安装“netaddr” Python 库:

    pip install netaddr
    

    最后,请记住index_var0开始,所以如果你想从第一个IP地址开始,切换味精行:

    msg: "{{ '10.10.1.48/28' | next_nth_usable(loop_index |int + 1) }}"
    

    【讨论】:

      猜你喜欢
      • 2023-02-22
      • 2015-03-29
      • 2011-10-08
      • 2021-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-08
      相关资源
      最近更新 更多