Ansible регулярное выражение для поиска и замены IP-адреса в строке - PullRequest
1 голос
/ 09 июля 2020

У меня есть плейбук Ansible, где мне нужно изменить Server Name в одной строке и Specific IP address в другой, так как в этой строке есть набор IP-адресов, разделенных запятой.

У меня есть игра ниже, которая работает абсолютно нормально, если мне нужно изменить всю строку IP-адреса с определенным набором IP-адресов, но я ищу конкретный c IP-адрес, т.е. 191.168.1.4, чтобы посмотреть после, и если он найден, просто замените только его и оставьте остальной IP как есть.

---
- name: Playbook to replace line in zabbix_agentd.conf
  hosts: all
  #remote_user: root
  gather_facts: False

  tasks:
  - name: Changing the zabbix-agent configuration on the client
    lineinfile:
      path: /tmp/zabbix_agentd.conf
      ### line to be searched & matched
      regexp: '{{ item.From }}'
      ### new line to be replaced with the old matched one
      line: '{{ item.To }}'
      state: present
      backup: yes
      backrefs: yes

    with_items:
    - { From: '#ServerActive=myzabbix1.example.com', To: 'ServerActive=myzabbix2.example.com'}
    - { From: 'Server=192.168.1.1,192.168.1.2,192.168.1.3,192.168.1.4,192.168.1.5', To: 'Server=192.168.1.1,192.168.1.2,192.168.1.3,192.168.1.10,192.168.1.5'}
    # Actions will be triggered at the end of each block of task and notifies a handler.
    notify: restart_zabbix_service

  handlers:
  - name: restart_zabbix_service
    # referenced by a globally unique name and are notified by notifiers.
    service:
      name: zabbix-agentd
      state: restarted

1 Ответ

1 голос
/ 11 июля 2020

Вот полный MCVE, который направит вас на правильный путь. На основе приведенного выше содержания:

---
- name: Replace demo
  hosts: localhost
  gather_facts: false

  vars:
    demo_file_content: |-
      #ServerActive=myzabbix1.example.com
      Server=192.168.1.1,192.168.1.2,192.168.1.3,192.168.1.4,192.168.1.5
      SomeOtherTestForDemo: toto 192.168.1.4 pipo bingo
    demo_file_destination: /tmp/replace_demo.conf

  tasks:
    - name: Start our test from scratch with a fresh file
      copy:
        dest: "{{ demo_file_destination }}"
        content: "{{ demo_file_content }}"

    - name: Check file content before demo
      slurp:
        path: "{{ demo_file_destination }}"
      register: demo_start
    - debug:
        msg: "{{ (demo_start.content | b64decode).split('\n') }}"

    - name: Replace elements in file
      replace:
        path: "{{ demo_file_destination }}"
        regexp: "{{ item.regexp }}"
        replace: "{{ item.replace }}"
      loop:
        # Replace active server and remove comment if exists
        - regexp: "^#?(ServerActive=)myzabbix1.example.com$"
          replace: "\\g<1>myzabbix2.example.com"
        # Replace all occurences of a specific IP anywhere
        - regexp: "^(.*)192\\.168\\.1\\.4(.*)$"
          replace: "\\g<1>192.168.1.10\\g<2>"

    - name: Check file content after demo
      slurp:
        path: "{{ demo_file_destination }}"
      register: demo_end
    - debug:
        msg: "{{ (demo_end.content | b64decode).split('\n') }}"


    - name: Cleanup (unless you pass `-e keep_demo_file=true` to ansible-playbook)
      file:
        path: "{{ demo_file_destination }}"
        state: absent
      when: not keep_demo_file | default(false) | bool

Что дает:

$ ansible-playbook test.yml

PLAY [Replace demo] ***************************************************************************************

TASK [Start our test from scratch with a fresh file] ******************************************************
changed: [localhost]

TASK [Check file content before demo] *********************************************************************
ok: [localhost]

TASK [debug] **********************************************************************************************
ok: [localhost] => {
    "msg": [
        "#ServerActive=myzabbix1.example.com",
        "Server=192.168.1.1,192.168.1.2,192.168.1.3,192.168.1.4,192.168.1.5",
        "SomeOtherTestForDemo: toto 192.168.1.4 pipo bingo"
    ]
}

TASK [Replace elements in file] ***************************************************************************
changed: [localhost] => (item={'regexp': '^#?(ServerActive=)myzabbix1.example.com$', 'replace': '\\g<1>myzabbix2.example.com'})
changed: [localhost] => (item={'regexp': '^(.*)192\\.168\\.1\\.4(.*)$', 'replace': '\\g<1>192.168.1.10\\g<2>'})

TASK [Check file content after demo] **********************************************************************
ok: [localhost]

TASK [debug] **********************************************************************************************
ok: [localhost] => {
    "msg": [
        "ServerActive=myzabbix2.example.com",
        "Server=192.168.1.1,192.168.1.2,192.168.1.3,192.168.1.10,192.168.1.5",
        "SomeOtherTestForDemo: toto 192.168.1.10 pipo bingo"
    ]
}

TASK [Cleanup (unless you pass `-e keep_demo_file=true` to ansible-playbook)] *****************************
changed: [localhost]

PLAY RECAP ************************************************************************************************
localhost                  : ok=7    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
...