lineinfile模块无法与Ansible变量字典配合使用 [英] lineinfile module not acting appropriately with Ansible variable dictionary

查看:128
本文介绍了lineinfile模块无法与Ansible变量字典配合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码是删除my.cnf文件中所有套接字变量的实例,然后使用正确的变量和文件位置重新填充文件.

My code is removing all instances of socket variables in my.cnf file and then repopulating the file with the correct variable and file location.

删除部分工作正常,但是插入内容在第一行之后退出.因此它将直接在[mysqladmin]下插入正确的'socket'行,但不会添加到文件的其余部分.

The deletion portion is working correctly, however the insert quits after the first line. So it will insert the correct 'socket' line directly under [mysqladmin] but it won't add to the remaining sections of the file.

- name: modify my.cnf setting
  hosts: dbservers
  remote_user: dbuser
  become: yes

  tasks:
  - name: delete old socket definitions
    lineinfile:
      dest: /etc/mysql/my.cnf
      regexp: "^socket "
      state: absent

  - name: add new socket variable
    lineinfile:
      dest: /etc/mysql/my.cnf
      line: "{{ item.line }}"
      insertafter: "{{ item.insertafter }}"
    with_items:
      - { line: 'socket = /mysql/run/mysqld.sock', insertafter: '^\[mysqladmin\]' }
      - { line: 'socket = /mysql/run/mysqld.sock', insertafter: '^\[mysql\]' }
      - { line: 'socket = /mysql/run/mysqld.sock', insertafter: '^\[mysqldump\]' }
      - { line: 'socket = /mysql/run/mysqld.sock', insertafter: '^\[mysqld\]' }

还有一点,我希望报头和新的套接字声明之间尽可能有一行空格.

On an additional note, I'd like there to be a line of space between the header and the new socket declaration if that is at all possible.

我已经尝试使用2.0.2和2.2.0版本,但都没有达到预期的效果.

I've tried with version 2.0.2 and 2.2.0 and neither are behaving as intended.

推荐答案

lineinfile可以正常工作(请参阅 @techraf的答案).

The lineinfile works as it should (see @techraf's answer).

您的任务是:

我的代码正在删除my.cnf文件中的所有实例套接字变量,然后使用正确的变量和文件位置重新填充文件.

My code is removing all instances of socket variables in my.cnf file and then repopulating the file with the correct variable and file location.

为什么不使用替换呢?

- replace:
    dest: /etc/mysql/my.cnf
    regexp: '^socket.*$'
    replace: 'socket = /mysql/run/mysqld.sock'

请紧记:

由用户决定是否保持幂等,以确保相同的模式永远不会与进行的任何替换相匹配.

It is up to the user to maintain idempotence by ensuring that the same pattern would never match any replacements made.

因此,您可能希望将regexp ^socket.*$更改为仅与错误"值匹配的值,应将其替换以防止不必要的任务状态更改.

So you may want to change regexp ^socket.*$ to something that matches only "wrong" values that should be replaced to prevent unnecessary changed state of the task.

这篇关于lineinfile模块无法与Ansible变量字典配合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆