Setting hostname in CentOS 7 and RHEL 7

Setting the hostname in CentOS 6 used to done with:

hostname foobar.example.com

This would only set the hostname until server restart though. To get the hostname to stick, the file: /etc/sysconfig/network would need to be edited. The line HOSTNAME= needs to be updated from (localhost.localdomain is the default value):

HOSTNAME=localhost.localdomain

to:

HOSTNAME=foobar.example.com

In CentOS 7 everything is done with the command hostnamectl.

For a temporary setting of the hostname

hostnamectl set-hostname foobar.example.com

And to make it stick, use the flag --static:

hostnamectl set-hostname --static foobar.example.com