在 Ansible 中,如何使用 regex_replace 模块将新的 EC2 服务器 IP 更改为 NATed IP

问题描述 投票:0回答:1

我正在将新的 EC2 服务器部署到只能通过 NAT 的 IP 访问的 AWS VPC 中。例如,如果 IP 192.168.131.11 已分配给新的 EC2 服务器,则 Ansible 必须使用 IP 10.144.192.11 来连接到新服务器。因此,我尝试使用 Ansible

created_instance.instances.0.private_ip_address
模块更改
regex_replace
返回的 IP。这是我的 Ansible 代码:

- name: Print Private IP Address
  debug:
    msg: "Private IPv4 Address: {{ created_instance.instances.0.private_ip_address }}"

- name: Assign IP Address
  set_fact:
    ec2_ip_address: "{{ created_instance.instances.0.private_ip_address }}"

- name: Reassign IP Address to NATed IP
  set_fact:
    ec2_ip_address: "{{ hostvars[inventory_hostname][ec2_ip_address] | regex_replace('\\b(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\b', '10.144.192.\\4') }}"
  when: (buildenv == "nat-vpc")

- name: Add Host to Inventory
  add_host:
    ansible_host: "{{ ec2_ip_address }}"
    ...

此 Ansible 代码会产生此错误:

TASK [Print Private IP Address] ************************************************
ok: [localhost] => {
    "msg": "Private IPv4 Address: 192.168.131.24"
}

TASK [Assign IP Address] *******************************************************
ok: [localhost] => {"ansible_facts": {"ec2_ip_address": "192.168.131.24"}, "changed": false}

TASK [Reassign IP Address to NATed IP] *****************************************
fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'ansible.vars.hostvars.HostVarsVars object' has no attribute '192.168.131.24'. 'ansible.vars.hostvars.HostVarsVars object' has no attribute '192.168.131.24'\n\nThe error appears to be in '/runner/project/osbuildlinux.yml': line 117, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Reassign IP Address to NATed IP\n  ^ here\n"}

有什么想法可以实现这一点吗?

ansible ansible-inventory
1个回答
0
投票

我找到了解决方案。

hostvars[inventory_hostname][ec2_ip_address]
应该是:

hostvars[inventory_hostname]['ec2_ip_address']
hostvars[inventory_hostname].ec2_ip_address

© www.soinside.com 2019 - 2024. All rights reserved.