0

Can we use a Chef resource to change the GID from 101 to 100(or any other number) in /etc/passwd file?libuuid:x:100:101::/var/lib/libuuid:

For all the GID's with 101 in /etc/passwd if one needs to change the GID, what is the way to do it using Chef resources?

blueowl
  • 35
  • 6

2 Answers2

1

Before suggesting a solution for this, I would like point out 2 things:

  1. Hand/scripted editing of /etc/passwd file is best avoided as it can lead to issues.
  2. Chef is not the tool for editing files. Chef resources are converged on the node they run, and bring the state of the resource to state defined in the recipe.

If you would still like to use Chef, you could use Ruby code inside ruby_block resource.

However, the cleanest way to handle this would be identify the users (separately) and use the user resource.

Example:

# This will set gid as 1001 for user1, user2, user3
%w(
  user1
  user2
  user3
).each do |u|
  user u do
    # add any other properties as required
    gid '1001'
  end
end

Update:

A sample file /tmp/userlist with below contents:

john:x:100:101::/bin/bash:
david:x:207:100::/bin/bash:
joe:x:100:101::/bin/nologin:
mike:x:101:100::/bin/bash:
rich:x:103:207::/bin/bash:
fred:x:105:111::/bin/nologin:

Not an expert at Ruby, but here it goes. The following ruby_block will read lines from a file, and create a new file with the lines with GID 101 replaced:

ruby_block "Write file" do
  block do
    puts
    userlist = File.readlines('/tmp/userlist')
    fp = File.open('/tmp/newuserlist', mode='w')
    userlist.each do |line|
      gid = line.split(':')[3]
      if gid == '101'
        fp.write line.sub(/.*\K101/, '1001')
      else
        fp.write line
      end
    end
    fp.close
  end
end

Note: There may be a cleaner and easier way to do this with Ruby, or with some other language or even Shell script. Do consider the same.

seshadri_c
  • 6,906
  • 2
  • 10
  • 24
  • Thank you @Seshadri C. I was trying to find if for all the users or any user whose GID is 101 in /etc/passwd how to get it changed to 100 using Chef resources? I can use 'user' resource only when I know the specific list of users beforehand whose GID is 101. – blueowl Jul 27 '20 at 11:20
  • As I mentioned, editing the file like how you want is more of a "scripty" operation than what Chef resources are designed to do. If you still want to achieve it with Chef, you would have to write some Ruby code to find and replace lines in file within a `ruby_block` resource. I will update my answer with a sample. – seshadri_c Jul 27 '20 at 16:04
0

utilize the user resource

user 'a user' do
  comment 'A random user'
  uid 1234
  gid 'groupname'
  home '/home/random'
  shell '/bin/bash'
  password '$1$JJsvHslasdfjVEroftprNn4JHtDi'
end
Mr.
  • 9,429
  • 13
  • 58
  • 82