Ansible 可更换库存:更换问题

Ansible 可更换库存:更换问题,ansible,Ansible,我有这样一份清单: [all:vars] env_cidr_prefix='172.25' antother_var="foo" [VPN_SERVER] vpn-server ansible_host="{{ env_cidr_prefix}}.0.1" vpn-server ansible_host="{{ env_cidr_prefix}}.0.1" 在ansible playbook期间,资源清册只保存私有ip地址。 我不想用公共ip替换“ansible\u host=“”的内

我有这样一份清单:

[all:vars]
env_cidr_prefix='172.25'
antother_var="foo"

[VPN_SERVER]
vpn-server ansible_host="{{ env_cidr_prefix}}.0.1" 
vpn-server ansible_host="{{ env_cidr_prefix}}.0.1" 
在ansible playbook期间,资源清册只保存私有ip地址。 我不想用公共ip替换
“ansible\u host=“
”的内容

剧本示例:

- name: grab the vpn public_ip
  set_fact: PUBLIC_IP="{{ instance_eip.public_ip }}"
  when: inventory_hostname |search("vpn-server")

- name: update inventory with the vpn public ip
  replace:
     path: "{{ inventory_file }}"
     regexp: "{{ ansible_host }}"
     replace: "{{ PUBLIC_IP }}"
  when: inventory_hostname |search("vpn-server")
如果

更换模块将正常工作

但这失败了

ansible_host="{{ env_cidr_prefix}}.0.1" 
调试输出:

ok: [vpn-server] => {
    "changed": false,
    "invocation": {
        "module_args": {
            "after": null,
            "attributes": null,
            "backup": false,
            "before": null,
            "content": null,
            "delimiter": null,
            "directory_mode": null,
            "encoding": "utf-8",
            "follow": false,
            "force": null,
            "group": null,
            "mode": null,
            "owner": null,
            "path": "/home/toluna/ansible/openvpn/env.properties",
            "regexp": "172.25.0.11",
            "remote_src": null,
            "replace": "1.1.1.1",
            "selevel": null,
            "serole": null,
            "setype": null,
            "seuser": null,
            "src": null,
            "unsafe_writes": null,
            "validate": null
        }
    },
    "msg": ""
}
注意,我不能使用添加主机模块,因为剧本在不同的阶段运行

有更好的方法吗?
谢谢

好的,经过测试,我想我明白你想要实现什么

这里有几个部分:

清单文件如下所示:

[all:vars]
env_cidr_prefix='172.25'
antother_var="foo"

[VPN_SERVER]
vpn-server ansible_host="{{ env_cidr_prefix}}.0.1" 
vpn-server ansible_host="{{ env_cidr_prefix}}.0.1" 
您正在尝试替换文件中不存在的
172.25.0.1
literal。您有
“{{env\u cidr\u prefix}.0.1”
而不是
172.25.0.1

选项:

  • 如果您希望以这种方式替换,可以在您的角色中使用Jinja2文件,以您尝试的相同方式替换变量和库存文件

  • 覆盖Jenkins的/etc/hosts文件(我真的不太喜欢)并使用主机名

  • 在剧本中使用主机变量,如:

  • 主办剧本:

    - name : Test
      hosts: "{{ variable_vpn_ip | default('vpn-server') }}"
    
    并将其称为从变量读取,您将临时更改该变量,或者:

    ansible-playbook play.yml -e "variable_vpn_ip=172.25.0.1"
    

    对不起,我不完全理解这个场景。为什么用add_主机替换资源清册不是一个选项,而是以您想要的方式替换ip地址?如果您有不同的阶段,为什么不使用不同的库存文件?@imjoseangel我为每个阶段使用不同的角色。创建aws实例是一个角色,vpn服务器是另一个角色。所有这些阶段都是通过詹金斯进行的。