raspi-config automated

Posted by ads' corner on Wednesday, 2020-06-17
Posted in [Ansible][Linux][Raspberry-Pi]

While I installed the Raspberry Pi with the Raspbee board on it, I had to modify the settings for the serial device. That’s done using the raspi-config tool on Raspbian.

However since I’m into automation, I don’t want to start raspi-config manually, but had to figure out how to do that in an automated way.

Turns out, raspi-config can be started with parameters, which basically guide the tool what to do. For every change a new run is necessary, it’s not possible to do two changes at once. And there is really no feedback if something was changed or not. Plus there is not much documentation at all for this mode. But oh well, better than nothing.

In my case, I had to enable the serial console, but disable the login over the serial port. The Raspbee is using that channel to communicate with the Pi.

By default, the login over the serial bus is enabled, and that results in one of the two following strings in /boot/cmdline.txt: console=serial0 or console=console=ttyAMA0. In my Ansible Playbook, I first read in the file:

1
2
3
4
5
6
7
8
- name: Retrieve /boot/cmdline.txt
  slurp:
    src: "/boot/cmdline.txt"
  register: boot_cmdline_txt_retrieve

- name: Extract /boot/cmdline.txt
  set_fact:
    boot_cmdline_txt: "{{ boot_cmdline_txt_retrieve.content | b64decode }}"

This fetches the file /boot/cmdline.txt from the remote host (the Raspberry Pi) and stores it in a variable. The content is base64 encoded, and needs to be decoded first. The plain text content is then stored in $boot_cmdline_txt. Now I can use the content of that file (variable) and figure out if I have to run raspi-config:

1
2
3
4
5
6
7
8
9
- block:
  - name: Enable hardware serial port
    # "2" will disable the login on the serial port,
    # but will enable the port itself
    shell: raspi-config nonint do_serial 2
    notify:
      - restart Pi

  when: boot_cmdline_txt is search("console=serial0") or boot_cmdline_txt is search("console=console=ttyAMA0")

When I find one of the two strings in the file, I run raspi-config. That was the easy part.

It was more complicated to figure out what exact parameters are required. First raspi-config expects nonint for non interactive mode. After that, the command which is to be executed. In my case that’s do_serial for changing the serial settings. Since it’s nowhere documented, I looked into /usr/bin/raspi-config - which is just a long shell script. And finally the remaining parameters are used for the command. In this case there are two parameters encoded into one: the setting 2 will first disable the login shell over the serial port, but then enable the serial port itself.

In the same way one can manage the other commands in raspi-config, but some source code surfing might be necessary.


Categories: [Ansible] [Linux] [Raspberry-Pi]