简体   繁体   中英

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:

current line: jenkins:x:1002:1002::/home/jenkins:/bin/bash

change to: jenkins:x:1002:1002::/var/lib/jenkins:/bin/bash

/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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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