Ansible:使用blockinfile注释掉一个已定义的python代码块?

时间:2016-03-08 14:38:26

标签: ansible ansible-playbook ansible-2.x

尝试使用Ansible对服务器上的文件(websocket.py)中的几行进行注释,但由于某些原因,我的代码在OPCODE_CONTINUATION之前没有添加第二个注释块。

想法是在“slot”行之前添加三行引号,在“OPCODE_CONTINUATION”行之前添加三个引号。我当前的解决方案试图找到具有正则表达式的行,但显然有些错误,因为只添加了第一个注释块。

Ansible版本2.0.1.0(2016/02/22 11:04:54)

websocket.py的片段:

__slots__ = ('utf8validator', 'utf8validate_last', 'environ', 'closed',
             'stream', 'raw_write', 'raw_read', 'handler')

OPCODE_CONTINUATION = 0x00

Ansible playbooks脚本:

---
- name: First comment
  blockinfile:
    dest: /usr/local/lib/python2.7/site-packages/geventwebsocket/websocket.py
    insertbefore: '\w{9}\s\W\s\W{2}\w{13}'
    state: present
    block: |
      """

- name: Second comment
  blockinfile:
    dest: /usr/local/lib/python2.7/site-packages/geventwebsocket/websocket.py
    insertbefore: '\s{4}\w{19}\s\W\s\d\w\d\d'
    state: present
    block: |
      """     

结果

# BEGIN ANSIBLE MANAGED BLOCK
"""
# END ANSIBLE MANAGED BLOCK
__slots__ = ('utf8validator', 'utf8validate_last', 'environ', 'closed',
             'stream', 'raw_write', 'raw_read', 'handler')

OPCODE_CONTINUATION = 0x00

文件:Websocket.py

1 个答案:

答案 0 :(得分:1)

标记blockinfile模块的主要标识符。请参阅docs中的marker选项。

制作者默认为# {mark} ANSIBLE MANAGED BLOCK,这是您在修改后的文件中看到的内容。在第二个任务Ansible在文件中找到那些确切的标记并假定该块存在。

如果您在每个任务上提供唯一标记,它应该有效:

- name: First comment
  blockinfile:
    dest: /usr/local/lib/python2.7/site-packages/geventwebsocket/websocket.py
    insertbefore: '\w{9}\s\W\s\W{2}\w{13}'
    state: present
    marker: "# {mark} FIRST COMMENT"
    block: '    """'

- name: Second comment
  blockinfile:
    dest: /usr/local/lib/python2.7/site-packages/geventwebsocket/websocket.py
    insertbefore: '\s{4}\w{19}\s\W\s\d\w\d\d'
    state: present
    marker: "# {mark} SECOND COMMENT"
    block: '    """'