我正在尝试使用ansible在属性文件中插入一行。我想添加一些属性,如果它不存在,但如果文件中已经存在这样的属性,则不要替换它。
我加入了我的ansible角色
- name: add couchbase host to properties
lineinfile: dest=/database.properties regexp="^couchbase.host" line="couchbase.host=127.0.0.1"
但是,如果属性值已存在于文件中,则会将属性值替换回127.0.0.1。
我做错了什么?
lineinfile
模块执行它应该执行的操作:它确保line
中定义的行存在于文件中,并且行由regexp
标识。因此,无论您的设置具有什么价值,它都会被您的新line
覆盖。
如果您不想覆盖该行,则首先需要测试内容,然后将该条件应用于lineinfile
模块。没有用于测试文件内容的模块,因此您可能需要使用grep
命令运行shell
并检查.stdout
的内容。像这样(未经测试):
- name: Test for line
shell: grep "^couchbase.host" /database.properties
register: test_grep
然后将条件应用于您的lineinfile
任务:
- name: add couchbase host to properties
lineinfile:
dest: /database.properties
line: couchbase.host=127.0.0.1
when: test_grep.stdout != ""
然后可以删除regexp
,因为你已经确定该行不存在所以它永远不会匹配。
但也许你正在做事情。文件中的那一行来自哪里?当您使用Ansible管理系统时,应该没有其他机制干扰相同的配置文件。也许你可以通过在角色中添加default
值来解决这个问题?
这是我能够让这个工作的唯一方法。
- name: checking for host
shell: cat /database.properties | grep couchbase.host | wc -l
register: test_grep
- debug: msg="{{test_grep.stdout}}"
- name: adding license server
lineinfile: dest=/database.properties line="couchbase.host=127.0.0.1"
when: test_grep.stdout == "0"
通过很长的“试验和错误”,我来到这里:
- name: check existence of line in the target file
command: grep -Fxq "ip addr add {{ item }}/32 dev lo label lo:{{ app | default('app') }}" /etc/rc.local
changed_when: false
failed_when: false
register: ip_test
with_items:
- "{{ list_of_ips }}"
- name: add autostart command
lineinfile: dest=/etc/rc.local
line="ip addr add {{ item.item }}/32 dev lo label lo:{{ app | default('app') }}"
insertbefore="exit 0"
state=present
when: item.rc == 1
with_items:
- "{{ ip_test.results }}"
与此处提出的想法相同:https://stackoverflow.com/a/40890850/7231194
步骤是:
例
# Vars
- name: Set parameters
set_fact:
ipAddress : "127.0.0.1"
lineSearched : "couchbase.host={{ ipAddress }}"
lineModified : "couchbase.host={{ ipAddress }} hello"
# Tasks
- name: Try to replace the line
replace:
dest : /dir/file
replace : '{{ lineModified }} '
regexp : '{{ lineSearched }}$'
backup : yes
register : checkIfLineIsHere
# If the line not is here, I add it
- name: Add line
lineinfile:
state : present
dest : /dir/file
line : '{{ lineSearched }}'
regexp : ''
insertafter: EOF
when: checkIfLineIsHere.changed == false
# If the line is here, I still want this line in the file, Then restore it
- name: Restore the searched line.
lineinfile:
state : present
dest : /dir/file
line : '{{ lineSearched }}'
regexp : '{{ lineModified }}$'
when: checkIfLineIsHere.changed
好的,这是我的天真解决方案......可能不是跨平台和原生的Ansible(我刚开始使用这个工具并且仍然学习它),但肯定更短:
- name: Update /path/to/some/file
shell: grep -q 'regex' /path/to/some/file && echo exists || echo 'text-to-append' >> /path/to/some/file
register: result
changed_when: result.stdout.find('exists') == -1
- name: add couchbase.host to properties, works like add or replace
lineinfile:
state: present
dest: /database.properties
regexp: '^couchbase.host'
line: 'couchbase.host=127.0.0.1'