添加一行“&书信电报;主机的IP地址>&书信电报;主机的FQDN>;在/etc/hosts中使用Ansible

添加一行“&书信电报;主机的IP地址>&书信电报;主机的FQDN>;在/etc/hosts中使用Ansible,ansible,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 }}"

我有一个主机文件:

[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的帮助下)

文件“主机”:


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

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


此操作有效,但会附加IP地址。如果IP地址已经存在,正则表达式不应该考虑不附加的条件吗?还没有详细研究这一部分,但它的工作原理是:1)查找
regexp
2)如果它匹配,用
替换整行(没有其他内容)。那么,您想要的是为清单中的每个主机提供一个主机条目?还要注意的是,
对整个任务进行评估,而不是对循环的每个迭代进行评估时,有一种方法可以进行反向操作。i、 e.如果有管线,不要更换。对于regex,我们可以传递regexp={{hostvars[groups['chef_be1_cluster'][0]]吗?be1_ip}@kamal我已经更新了答案,以包括
lineinfle
部分。该任务现在执行您在问题中描述的任务
[cluster_be1]
10.10.10.10 be1_dns=chef-be1-tnp.a.b.c.d be1_ip=10.10.10.10
- lineinfile:
    dest: /tmp/hosts
    line: "{{ hostvars[item].inventory_hostname }} {{ hostvars[item].be1_dns }}"
    state: present
  loop: "{{ play_hosts }}"