获取本地主机 ip 地址并在目标文件中替换为值的 Ansible 任务

Ansible task to to get the localhost ip address and replace in the destination file with value

我在 运行 任务下方并用 ip 地址替换目标文件中的全部内容

---
- hosts: localhost
  connection: local
  tasks:
    - debug: var=ansible_all_ipv4_addresses
    - debug: var=ansible_default_ipv4.address
    - copy: content="{{ ansible_all_ipv4_addresses }}" dest=/root/curator.yml

我在 curator.yml 中有变量,我想用 IP 地址更新变量 {{ ansible_default_ipv4.address }}。

---
client:
  hosts:
    - {{ ansible_default_ipv4.address }}
  port: 9200
  url_prefix:
  use_ssl: False
  ssl_no_validate: False
  http_auth:
  timeout: 30
  master_only: False

logging:
  loglevel: INFO
  logfile:
  logformat: default
  blacklist: ['elasticsearch', 'urllib3']

当我执行上面的剧本任务时,它会用调试输出中的 ip 地址替换 curator.yml 中的全部信息

播放 [localhost] ***************************************** ****************************************************** *********************

任务 [收集事实] **************************************** ****************************************************** ******************* 好的:[本地主机]

任务 [调试] ****************************************** ****************************************************** **************************** 好的:[本地主机] => { "ansible_all_ipv4_addresses": [ “10.0.0.5” ] }

任务 [调试] ****************************************** ****************************************************** **************************** 好的:[本地主机] => { "ansible_default_ipv4.address": "10.0.0.5" }

任务 [复制] ***************************************** ****************************************************** *************************** 更改:[本地主机]

播放回顾 ******************************************* ****************************************************** **************************** localhost : ok=4 changed=1 unreachable=0 failed=0

我也被包含在任务下面,但看起来它不起作用

#- name: rewrite
#  vars:
#    ansible_default_ipv4.address: "{{ ansible_default_ipv4.address[0] }}"
#  template:
#    src: templates/curator.yml.j2
#    dest: /root/curator.yml

您的复制和模板任务存在问题:

  1. 复制任务 - 当您使用 content 参数时,它将 "set the contents of a file directly to the specified value" copy_module

  2. 模板任务 - 你不能用 .("dot") 符号 define/update 变量(甚至 set_fact),你甚至不需要,因为已经定义了 ansible_default_ipv4.address 变量并且设置了值。

这会起作用:

---
- name: Update ip
  hosts: 127.0.0.1
  connection: local
  tasks:
    - debug: var=ansible_all_ipv4_addresses
    - debug: var=ansible_default_ipv4.address
    - name: Template file with ip
      template:
        src: templates/curator.yml.j2
        dest: /root/curator.yml
...