简体   繁体   English

ansible-替换现有行中的字符串或单词,而不替换所有行

[英]ansible - replace a string or word in existing line without replace all the line

I want to replace only the home directory for jenkins user in passwd, I guess lineinfile not good for this, because it will replace all the line and I need to keep the User ID and Group ID, for example: 我只想替换passwd中jenkins用户的主目录,我想lineinfile对此不好,因为它将替换所有行,并且我需要保留用户ID和组ID,例如:

current line: jenkins:x:1002:1002::/home/jenkins:/bin/bash 当前行: jenkins:x:1002:1002::/home/jenkins:/bin/bash

change to: jenkins:x:1002:1002::/var/lib/jenkins:/bin/bash 更改为: jenkins:x:1002:1002::/var/lib/jenkins:/bin/bash

/home/jenkins -> /var/lib/jenkins / home / jenkins-> / var / lib / jenkins

- name: Set the Jenkins home directory in passwd
  lineinfile:
    dest: /etc/passwd
    regexp: '^jenkins=.*'
    line: '?'
  register: jenkins_passwd
  notify: restart jenkins

Match 比赛

^(jenkins:.:\d+:\d+::)[^:]*

Replace by 替换为

\1/var/lib/jenkins

This matches the start of a correctly formatted line of /etc/passwd up to its home directory. 这与/etc/passwd正确格式化的行的起始行与其原始目录匹配。 The informations we wish to keep are grouped in a capturing group, which stops before the current home directory definition. 我们希望保留的信息被分组在一个捕获组中,该捕获组在当前主目录定义之前停止。 To replace, we reference that group then add our new home directory definition. 要进行替换,我们引用该组,然后添加新的主目录定义。 The end of the line is left unchanged. 该行的末尾保持不变。

Match 比赛

::.*jenkins ::。*詹金斯

Replace with 用。。。来代替

::/var/lib/jenkins :: / var / lib / jenkins

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM