lineinfile 模块与 Ansible 变量字典的作用不正确 [英] lineinfile module not acting appropriately with Ansible variable dictionary
问题描述
我的代码正在删除 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.
因此,您可能希望将正则表达式 ^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屋!