这是我的group_vars
:
services:
service_csmsaga:
service_name: "service_csmsaga"
port: "21100/tcp"
service_csmsagatcp:
service_name: "service_csmsagatcp"
port: "21200/tcp"
我想使用以下内容将这些行添加到/etc/services
中
- name: Add saga services to /etc/services
lineinfile: dest=/etc/services regexp='^{{ item.value.service_name }}'
line="{{ item.value.service_name}} {{ item.value.port }}"
with_dict: services
这些行已添加到/etc/services
,如下所示:
service_csmsaga 21100/tcp
service_csmsaga 21100/tcp
service_csmsaga 21100/tcp
service_csmsagatcp 21200/tcp
但它仍然继续添加这一行:
TASK [db_server : Add saga services to /etc/services] **************************
changed: [172.17.0.2] => (item={'value': {u'service_name': u'service_csmsaga', u'port': u'21100/tcp'}, 'key': u'service_csmsaga'}) => {"backup": "", "changed": true, "item": {"key": "service_csmsaga", "value": {"port": "21100/tcp", "service_name": "service_csmsaga"}}, "msg": "line replaced"}
changed: [172.17.0.2] => (item={'value': {u'service_name': u'service_csmsagatcp', u'port': u'21200/tcp'}, 'key': u'service_csmsagatcp'}) => {"backup": "", "changed": true, "item": {"key": "service_csmsagatcp", "value": {"port": "21200/tcp", "service_name": "service_csmsagatcp"}}, "msg": "line added"}
我在这里缺少什么?
答案 0 :(得分:1)
查看您的regexp
参数,然后查看您的数据。
第一次迭代(service_csmsaga
)将匹配两条线,因此将用第一条线替换两条线。然后第二次迭代将在末尾添加一个新行,因为service_csmsagatcp
不存在。然后当你再次运行你的剧本时,你的第一次迭代将取代所有三行,依此类推。依此类推。
要解决此问题,您需要更改数据(更改服务名称)或在正则表达式中更具体。
这样的事情应该有效:
- name: Add saga services to /etc/services
lineinfile: dest=/etc/services regexp='^{{ item.value.service_name }}\s'
line="{{ item.value.service_name}} {{ item.value.port }}"
with_dict: services
这样可以确保它在替换之前仅匹配service_name
后跟一些空格,以便您的服务名称不会重叠。