代码之家  ›  专栏  ›  技术社区  ›  kamal

使用Ansible在/etc/hosts中添加一行“<IP address of host><FQDN of host>”

  •  1
  • kamal  · 技术社区  · 6 年前

    我有一个主机文件:

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

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

    我试过:

    - 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 回复  |  直到 6 年前
        1
  •  1
  •   mhutter    6 年前

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

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