| 1 | #!/usr/bin/env bash |
| 2 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 3 | # SPDX-License-Identifier: Apache-2.0 |
| 4 | set -euo pipefail |
| 5 | |
| 6 | display_usage() { |
| 7 | cat <<EOF |
| 8 | Usage: $0 [OPTIONS] |
| 9 | |
| 10 | Sets up an AWS EC2 instance for CodeBuild fleets by: |
| 11 | 1) Installing Nix package manager on a bare EC2 instance |
| 12 | 2) Configuring Nix to be usable by the root user for CodeBuild compatibility |
| 13 | (Note: This is not officially supported by Nix) |
| 14 | |
| 15 | Options: |
| 16 | -h, --help Display this help message and exit |
| 17 | EOF |
| 18 | } |
| 19 | |
| 20 | setup_nix() { |
| 21 | echo "=== Setting up nix user, groups and permissions ===" |
| 22 | sudo groupadd nixbld |
| 23 | sudo useradd -m -g nixbld -G nixbld nix |
| 24 | # Give everyone on the system read access to the nix user homedir. |
| 25 | sudo chmod 755 /home/nix |
| 26 | echo "Both $HOME and $USER need to be set for the nix installer to work." |
| 27 | echo "=== Installing Nix ===" |
| 28 | sudo -u nix bash -c "sh <(curl --proto '=https' --tlsv1.2 -L https://nixos.org/nix/install) --no-daemon" |
| 29 | echo "=== Enabling Nix flakes ===" |
| 30 | sudo -u nix bash -c 'mkdir -p ~/.config/nix; echo "experimental-features = nix-command flakes" >> ~/.config/nix/nix.conf' |
| 31 | # This sidesteps the need to update PATH for every user. |
| 32 | sudo ln -s /home/nix/.nix-profile/bin/nix /usr/local/bin |
| 33 | echo "=== Setting up Nix configs for the root user ===" |
| 34 | sudo -u root bash -c "ln -s /home/nix/.nix-profile ~/" |
| 35 | sudo -u root bash -c "ln -s /home/nix/.config ~/" |
| 36 | } |
| 37 | |
| 38 | setup_sudo() { |
| 39 | echo "=== Setting up sudo for the nix user, needed for installation ===" |
| 40 | # The nix installer refuses to install as root, so we need to set up sudo for the nix user. |
| 41 | sudo bash -c "echo 'nix ALL=NOPASSWD: ALL' > /etc/sudoers.d/nix" |
| 42 | } |
| 43 | |
| 44 | check_gnutls_config() { |
| 45 | if [[ -f "/etc/gnutls/config" ]]; then |
| 46 | echo "Turning off gnuTLS overrides" |
| 47 | sudo rm -f /etc/gnutls/config |
| 48 | fi |
| 49 | } |
| 50 | |
| 51 | update_ubuntu_packages() { |
| 52 | sudo apt update |
| 53 | sudo apt upgrade -y |
| 54 | } |
| 55 | # main |
| 56 | for arg in "$@"; do |
| 57 | case $arg in |
| 58 | -h|--help) |
| 59 | display_usage |
| 60 | exit 0 |
| 61 | ;; |
| 62 | esac |
| 63 | done |
| 64 | check_gnutls_config |
| 65 | update_ubuntu_packages |
| 66 | setup_sudo |
| 67 | setup_nix |