ansible - 使用 Ansible 在/etc/hosts 中添加一行“<主机的 IP 地址> <主机的 FQDN>

标签 ansible

我有一个主机文件:

[cluster_be1]
10.10.10.10 be1_dns=c-be1.a.b.c.d

我希望能够填充/etc/hosts(附加在顶部)

10.10.10.10 c-be1.a.b.c.d

我尝试过:

- name:  build hosts file
    lineinfile: dest=/etc/hosts regexp='.*{{ item }}$' line="{{ hostvars[groups['cluster_be1'][0]].be1_ip }}"  state=present
    when: "{{ hostvars[groups['cluster_be1'][0]] }}" is defined
    with_items: play_hosts

但出现错误:

The error appears to have been in '/home/ec2-user/ANSIBLE/clusterOps/roles/cluster-be1/defaults/main.yml': line 36, column 59, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

    lineinfile: dest=/etc/hosts regexp='.*{{ item }}$' line="{{ hostvars[groups['chef_be1_cluster'][0]].be1_ip }}"  state=present
    when: "{{ hostvars[groups['cluster_be1'][0]] }}" is defined
                                                          ^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes.  Always quote template expression brackets when they
start a value. For instance:

    with_items:
      - {{ foo }}

Should be written as:

    with_items:
      - "{{ foo }}"

回答(在mhutter的帮助下)

- name:  build hosts file
    lineinfile: dest=/etc/hosts regexp={{ hostvars[groups['cluster_be1'][0]].be1_ip }} line="{{ hostvars[groups['cluster_be1'][0]].be1_ip }} {{ hostvars[groups['cluster_be1'][0]].be1_dns }}"  state=present
    when: hostvars[groups['cluster_be1'][0]] is defined
    with_items: "{{ play_hosts }}"

文件“主机”:

[cluster_be1]
10.10.10.10 be1_dns=chef-be1-tnp.a.b.c.d be1_ip=10.10.10.10

最佳答案

Ansible 与何时必须使用 jinja 语法以及何时不使用有点不一致。我认为正确的标记应该是:

- lineinfile:
    dest: /tmp/hosts
    line: "{{ hostvars[item].inventory_hostname }} {{ hostvars[item].be1_dns }}"
    state: present
  loop: "{{ play_hosts }}"

引用文献:

关于ansible - 使用 Ansible 在/etc/hosts 中添加一行“<主机的 IP 地址> <主机的 FQDN>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52312358/

相关文章:

ansible - 错误!在主处理程序列表和监听处理程序列表中都找不到请求的处理程序 'restart nginx'

ansible - 检查 Ansible 流水线是否启用/工作

ssh - 使用密码和私钥进行 Ansible SSH 身份验证

ansible - 剧本中ansible主机的默认值?

list - 将列表转换为字典 - Ansible YAML

Ansible 迄今为止的 Actor 阵容

ansible - 如何检查 Ansible 中是否存在文件?

ansible - 如果一场比赛失败,如何停止剧本

json - Ansible - 将环境中的 JSON 字符串传递给 shell 模块

ansible - 在 ansible 中,何时使用 shell vs 脚本模块来运行 shell 脚本