Ansible正则表达式从/ etc / hosts中删除匹配的IP

时间:2017-01-12 10:22:02

标签: regex linux ansible devops

我正在尝试更改远程节点的主机名,此部分有效:

- name: Change the hostname
  lineinfile: dest=/etc/hosts
              regexp='.*{{ item }}$'
              line="{{ hostvars[item].ansible_default_ipv4.address }} {{ LOCAL_HOSTNAME }} {{ LOCAL_HOSTNAME }}.{{ LOCAL_DOMAIN_NAME }}"
              state=present
  when: hostvars[item].ansible_default_ipv4.address is defined
  with_items: "{{ groups['dbservers'] }}"

这样做,它会将IP hostname FQDN附加到/etc/hosts文件的末尾。

我想要实现的是删除现有条目然后添加此部分,这是我尝试过的:

    - name: Change the hostname
      lineinfile: dest=/etc/hosts
#                  regexp='.*{{ item }}$'
                  regexp='{{ hostvars[item].ansible_default_ipv4.address }}'
                  state=absent
#                  line="{{ hostvars[item].ansible_default_ipv4.address }} {{ LOCAL_HOSTNAME }} {{ LOCAL_HOSTNAME }}.{{ LOCAL_DOMAIN_NAME }}"
#                  state=present
      when: hostvars[item].ansible_default_ipv4.address is defined
      with_items: "{{ groups['dbservers'] }}"

但是,这会一直显示以下错误:

The offending line appears to be:
#                  regexp='.*{{ item }}$'
                  regexp="{{ hostvars[item].ansible_default_ipv4.address }}"
                  ^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes.

将引号从''更改为""似乎不起作用。我的问题是:

  • 这是查询IP的正确方法,以便删除 在hosts文件中输入?
  • 如果是这样,有人可以指出错误 句法?
  • 是否有更有效的方法来完成删除任务 (全部)现有条目,然后在/etc/hosts
  • 中添加该行

2 个答案:

答案 0 :(得分:2)

你不能使用Ansible符号(带有相同的符号)并将其视为YAML。

您的代码的问题不是引用,而是您在不应该的位置插入注释的事实。

以下语法有效,您的语法不是:

- name: Change the hostname
  lineinfile:
    dest: /etc/hosts
    # regexp: '.*{{ item }}$'
    regexp: '{{ hostvars[item].ansible_default_ipv4.address }}'
    state: absent
    # line: "{{ hostvars[item].ansible_default_ipv4.address }} {{ LOCAL_HOSTNAME }} {{ LOCAL_HOSTNAME }}.{{ LOCAL_DOMAIN_NAME }}"
    # state: present
  when: hostvars[item].ansible_default_ipv4.address is defined
  with_items: "{{ groups['dbservers'] }}"

答案 1 :(得分:0)

Here you go..
---
- name: host trick
  hosts: dev
  gather_facts: yes
  become: true
  pre_tasks:
    - name: Include fixed env variables
      include_vars: "group_vars/dev.yml"


  tasks:

  - debug: var=hostvars[groups['app'][0]].ansible_host
  
  - name: Update the /etc/hosts file with node name
    vars: 
         remove_host: "hostname.domain.com"
    tags: etchostsupdate
    become: yes
    become_user: root
    lineinfile:
      dest: /etc/hosts
      regexp: "{{ remove_host }}"
      line: "{{ hostvars[item]['ansible_default_ipv4']['address'] }} {{item}}"
      state: absent
      backup: yes
    register: etchostsupdate
    when: hostvars[item]['ansible_facts']['default_ipv4'] is defined
    with_items:
      - "{{ groups['dev'] }}"



#ansible-playbook -i dev/hosts dev/remove_etc_hosts.yml -e "remove_host=hostname.domain.com"