Report this

What is the reason for this report?

How to change the root password with the cloud-init program on CentOS 7

Posted on January 27, 2022

As I was following through the introduction to Cloud-Config Scripting, I noticed there were no examples of tasks that I usually use on Linux machines.

Is it possible to change the root password with cloud-init?



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hi there,

Yes, this should be doable with the following:

#cloud-config
chpasswd:
  list: |
    root:your_secure_password_here
  expire: False

Hope that this helps! Best, Bobby

Yes, you can use cloud-init to change the root password, but you need to be cautious about doing so for security reasons. If you’re setting this on a public cloud or a place where the cloud-config is visible, it’s generally not recommended to hardcode passwords in the cloud-config due to security concerns. Instead, it’s better to use SSH key-based authentication.

That said, if you are in a controlled environment where this makes sense, you can use the chpasswd and ssh_pwauth modules.

Here’s an example cloud-config:

#cloud-config

chpasswd:
  list: |
    root:<YOUR_NEW_PASSWORD>
  expire: False

ssh_pwauth: True

Replace <YOUR_NEW_PASSWORD> with your desired root password.

  • The chpasswd section sets passwords for specified users. The expire option, when set to False, means the password won’t be forced to change on the next login.

  • The ssh_pwauth option allows password authentication via SSH. If you’re enabling the root password, you might want to control if SSH password authentication is permitted. In most cases, for security, password authentication via SSH should be disabled.

Again, I can’t stress this enough: be very cautious with this, especially in public or multi-tenant environments. The safest approach is to disable root login altogether and use sudo-enabled users for administrative tasks.

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.