【问题标题】:ansible read ip address from hostsansible 从主机读取 IP 地址
【发布时间】:2020-01-10 15:40:58
【问题描述】:

我需要为远程主机设置日期,所以我读取本地主机日期然后需要获取ansible的hosts文件中定义的otherhost“ipv4_address”。

- hosts: localhost
  become_user : root
  tasks:

    - name: align datetime
      shell: |
                 data="$(date +'%Y/%m/%d +%H:%m:00')"
                 ssh  user@{{ otherhost.ipv4_address }} "sudo date -s $data"

- hosts: otherhost
  become: true
his tasks....

但这似乎不是获取 ipv4 的正确方法:

致命:[127.0.0.1]:失败! => {"msg": "任务包含一个选项 带有未定义的变量。错误是:“otherhost.ipv4_address”是 未定义\n\n错误似乎在

ansible --version
ansible 2.9.2
  config file = None
  configured module search path = ['/home/tec1/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /home/tec1/.local/share/virtualenvs/sniperx-EdPGXWMw/lib/python3.7/site-packages/ansible
  executable location = /home/tec1/.local/share/virtualenvs/sniperx-EdPGXWMw/bin/ansible
  python version = 3.7.3 (default, Apr  3 2019, 05:39:12) [GCC 8.3.0]

【问题讨论】:

    标签: ansible


    【解决方案1】:

    问题在于 {{ otherhost.ipv4_address }} 在您使用它时不可用,因为 ansible 尚未收集有关 otherhost 的事实。

    您可以使用以下几个选项:

    1. 在开始使用数据之前收集事实,例如
    ---
    - hosts: all
      gather_facts: true
      # here you gather facts about otherhost
    
    - hosts: localhost
      tasks:
        - debug: var=hostvars["otherhost"].ansible_all_ipv4_addresses
          # and here you can access those facts about 
    
    1. 在远程主机上运行 playbook 并预先委托本地主机时间,例如
    - hosts: otherhost
      tasks:
      - name: get localhost time
        shell: date +'%Y/%m/%d +%H:%m:00'
        become: false
        register: local_date
      - name: set the date on the server
        shell: sudo date -s '{{ local_date.stdout_lines[0] }}'
    

    这利用了 ansibles 自动 ssh 进入目标框的方式,您不必手动 ssh

    【讨论】:

      猜你喜欢
      • 2021-01-18
      • 2017-02-10
      • 2012-05-31
      • 2018-08-26
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      • 1970-01-01
      相关资源
      最近更新 更多