使用Ansible在/ etc / hosts中添加一行“ <ip address =”“ of =”“ host =”“> <fqdn of =”“ host =”“>

时间:2018-09-13 11:03:23

标签: 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

1 个答案:

答案 0 :(得分:1)

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

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

参考文献: