ドルヲタ系インフラエンジニア じーふーの備忘録

クラウドをメインに扱うインフラエンジニアが書くメモやら雑感、たまにドルヲタ的活動記録残します。最近の推しはAzureのData Factory(V2)です。

【linux】 ユーザーをグループに追加する際は gpasswd -a か usermod -aG を使う方がいい

ユーザーをあるグループに追加する場合はusermod -aGコマンドかgpasswd -aを利用した方がいいという話です。

ユーザーをグループに追加する手段

ユーザーを作成する場合に、そのユーザーをグループに所属させる方法として主に以下の手段が考えられる

  • user作成時にオプションで所属させるグループを指定する
# useradd -g [主グループ名 or gid] -G [サブグループ名 or gid] [ユーザー名]
  • usermodコマンドで所属グループ指定
# usermod -g [主グループ名 or gid] -G [サブグループ名 or gid] [ユーザー名]
  • usermodコマンドに -aG オプションを付けて追加グループ指定
# usermod -aG [グループ名] [ユーザー名]
  • gpasswdコマンドで特定のグループに指定ユーザーを追加する
# gpasswd -a [ユーザー名] [グループ名]

usermodを使用する場合の注意点

usermodコマンドを使用する際、-aオプションをつけない状態で-Gオプションで所属グループを指定した場合、指定したグループにのみ所属する状態に変更されます。そのため、指定によっては元々所属していたグループから外れる恐れがありますので注意が必要です。

マニュアル

# man usermod
       -a, --append
           Add the user to the supplementary group(s). Use only with the -G option.

       -G, --groups GROUP1[,GROUP2,...[,GROUPN]]]
           A list of supplementary groups which the user is also a member of. Each
           group is separated from the next by a comma, with no intervening
           whitespace. The groups are subject to the same restrictions as the group
           given with the -g option.

           If the user is currently a member of a group which is not listed, the user
           will be removed from the group. This behaviour can be changed via the -a
           option, which appends the user to the current supplementary group list.

実行ログ

わかり辛いかもですが、redmine というユーザーに対して gpasswd -ausermod -Gusermod -aGでグループ追加操作を行った操作ログです。

[root@vagrant-centos65 ~]#
[root@vagrant-centos65 ~]# id redmine
uid=502(redmine) gid=502(redmine) groups=502(redmine)
[root@vagrant-centos65 ~]#
[root@vagrant-centos65 ~]#
[root@vagrant-centos65 ~]# gpasswd -a redmine wheel
Adding user redmine to group wheel
[root@vagrant-centos65 ~]#
[root@vagrant-centos65 ~]#
[root@vagrant-centos65 ~]#
[root@vagrant-centos65 ~]#
[root@vagrant-centos65 ~]# id redmine
uid=502(redmine) gid=502(redmine) groups=502(redmine),10(wheel)
[root@vagrant-centos65 ~]#
[root@vagrant-centos65 ~]#
[root@vagrant-centos65 ~]#
[root@vagrant-centos65 ~]# usermod -G redmine redmine
[root@vagrant-centos65 ~]#
[root@vagrant-centos65 ~]#
[root@vagrant-centos65 ~]#
[root@vagrant-centos65 ~]#
[root@vagrant-centos65 ~]# id redmine
[uid=502(redmine) gid=502(redmine) groups=502(redmine)
[root@vagrant-centos65 ~]#
[root@vagrant-centos65 ~]#
[root@vagrant-centos65 ~]#
[root@vagrant-centos65 ~]#
[root@vagrant-centos65 ~]# usermod -aG wheel redmine
[root@vagrant-centos65 ~]#
[root@vagrant-centos65 ~]#
[root@vagrant-centos65 ~]# id redmine
uid=502(redmine) gid=502(redmine) groups=502(redmine),10(wheel)