-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathCloud-Init.txt
More file actions
2789 lines (2322 loc) · 77.9 KB
/
Cloud-Init.txt
File metadata and controls
2789 lines (2322 loc) · 77.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# CLOUD-INIT - Cloud Instance Initialization Reference - by Richard Rembert
# Cloud-init is the industry standard multi-distribution method for cross-platform cloud instance initialization
# Handles early initialization of cloud instances including networking, storage, SSH keys, packages, and arbitrary scripts
# INSTALLATION AND SETUP
# Cloud-init is pre-installed on most cloud images
# Check if cloud-init is installed
which cloud-init
cloud-init --version
# Install cloud-init (if needed)
# Ubuntu/Debian
sudo apt update
sudo apt install cloud-init
# CentOS/RHEL/Rocky Linux
sudo yum install cloud-init
# or
sudo dnf install cloud-init
# Enable cloud-init services
sudo systemctl enable cloud-init-local
sudo systemctl enable cloud-init
sudo systemctl enable cloud-config
sudo systemctl enable cloud-final
# Check service status
sudo systemctl status cloud-init
# Verify installation
cloud-init status
cloud-init --help
# CLOUD-INIT BASICS AND CONCEPTS
# Key Concepts:
# - User Data: Configuration passed to cloud-init at instance launch
# - Cloud Config: YAML-formatted configuration for cloud-init
# - Modules: Individual components that perform specific tasks
# - Stages: Different phases of cloud-init execution
# - Data Sources: Sources of configuration data (metadata service, user data, etc.)
# Execution Stages:
# 1. Generator: Early boot, before networking
# 2. Local: Early boot, with basic networking
# 3. Network: After networking is configured
# 4. Config: User configuration stage
# 5. Final: Late boot, system is mostly ready
# File Locations:
# /var/lib/cloud/ - Cloud-init working directory
# /var/log/cloud-init.log - Main log file
# /var/log/cloud-init-output.log - Output from user scripts
# /etc/cloud/cloud.cfg - Main configuration file
# /etc/cloud/cloud.cfg.d/ - Additional configuration files
# Data Sources (in order of preference):
# - NoCloud: Local data source (ISO, filesystem)
# - ConfigDrive: OpenStack config drive
# - OpenStack: OpenStack metadata service
# - Ec2: Amazon EC2 metadata service
# - Azure: Microsoft Azure metadata service
# - GCE: Google Compute Engine metadata service
# BASIC CLOUD-CONFIG STRUCTURE
# Basic cloud-config YAML format
#cloud-config
# System identification
hostname: web-server-01
fqdn: web-server-01.example.com
manage_etc_hosts: true
# Timezone and locale
timezone: UTC
locale: en_US.UTF-8
# Package management
package_update: true
package_upgrade: true
packages:
- curl
- wget
- git
- vim
# Simple user creation
users:
- name: ubuntu
sudo: ALL=(ALL) NOPASSWD:ALL
shell: /bin/bash
ssh_authorized_keys:
- ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC... user@example.com
# Basic file creation
write_files:
- path: /etc/motd
content: |
Welcome to the server!
Configured by cloud-init
owner: root:root
permissions: '0644'
# Simple commands
runcmd:
- echo "Cloud-init setup complete" | tee /var/log/setup.log
- systemctl enable nginx
- systemctl start nginx
# Final message
final_message: "Cloud-init setup completed at $TIMESTAMP"
# USER MANAGEMENT
# Creating users with various configurations
users:
# Standard user with sudo access
- name: ubuntu
gecos: Ubuntu User
sudo: ALL=(ALL) NOPASSWD:ALL
groups: users, admin, docker
shell: /bin/bash
lock_passwd: false
ssh_authorized_keys:
- ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC... user@laptop
- ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... user@desktop
ssh_import_id:
- gh:username # Import from GitHub
- lp:username # Import from Launchpad
# Service user (system account)
- name: webapp
system: true
shell: /bin/false
home: /opt/webapp
create_home: true
no_user_group: false
# User with password (hashed)
- name: developer
passwd: $6$rounds=4096$salt$hash... # Use: mkpasswd --method=SHA-512
lock_passwd: false
shell: /bin/bash
groups: developers, docker
sudo: ["ALL=(ALL) NOPASSWD: /usr/bin/docker", "/usr/bin/systemctl"]
# Disable default user
- name: root
lock_passwd: true
# SSH configuration
ssh_pwauth: false # Disable password authentication
disable_root: true # Disable root login
ssh_deletekeys: true # Delete existing SSH host keys
ssh_genkeytypes: ['rsa', 'dsa', 'ecdsa', 'ed25519']
# SSH key management
ssh_keys:
rsa_private: |
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA...
-----END RSA PRIVATE KEY-----
rsa_public: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC...
ed25519_private: |
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmU...
-----END OPENSSH PRIVATE KEY-----
ed25519_public: ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI...
# Global SSH authorized keys
ssh_authorized_keys:
- ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC... admin@example.com
- ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... backup@example.com
# PACKAGE MANAGEMENT
# Basic package operations
package_update: true # Update package cache
package_upgrade: true # Upgrade all packages
package_reboot_if_required: true # Reboot if kernel updated
# Install packages
packages:
# System utilities
- curl
- wget
- git
- vim
- htop
- tree
- unzip
- jq
# Development tools
- build-essential
- python3
- python3-pip
- nodejs
- npm
# System administration
- ufw
- fail2ban
- logrotate
- rsync
# Monitoring tools
- htop
- iotop
- netstat-persistent
- lsof
# Advanced package repository management
apt:
preserve_sources_list: false
sources:
# Docker repository
docker:
source: "deb [arch=amd64] https://download.docker.com/linux/ubuntu $RELEASE stable"
keyid: 9DC858229FC7DD38854AE2D88D81803C0EBFCD88
filename: docker.list
# Node.js repository
nodejs:
source: "deb https://deb.nodesource.com/node_18.x $RELEASE main"
keyid: 68576280
filename: nodejs.list
# Kubernetes repository
kubernetes:
source: "deb https://apt.kubernetes.io/ kubernetes-xenial main"
keyid: BA07F4FB
filename: kubernetes.list
# Custom repository with GPG key
custom:
source: "deb https://packages.example.com/ubuntu $RELEASE main"
key: |
-----BEGIN PGP PUBLIC KEY BLOCK-----
mQENBFJu...
-----END PGP PUBLIC KEY BLOCK-----
# Snap package management
snap:
commands:
- snap install docker
- snap install kubectl --classic
- snap install helm --classic
- snap install code --classic
# YUM/DNF configuration (CentOS/RHEL)
yum_repos:
epel:
name: Extra Packages for Enterprise Linux 8
baseurl: https://download.fedoraproject.org/pub/epel/8/Everything/$basearch
enabled: true
gpgcheck: true
gpgkey: https://download.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-8
# Python package management
pip:
- ansible
- docker-compose
- awscli
- azure-cli
- requests
- pyyaml
# Ruby gems
gem:
- bundler
- rails
# Node.js packages
npm:
- pm2
- nodemon
- "@angular/cli"
- create-react-app
# FILE AND DIRECTORY MANAGEMENT
# Write files to the filesystem
write_files:
# Simple text file
- path: /etc/motd
content: |
================================================
Welcome to {{ ansible_hostname }}
Environment: Production
Managed by: Cloud-Init
Last Updated: $(date)
================================================
owner: root:root
permissions: '0644'
# Configuration file with variables
- path: /etc/nginx/sites-available/default
content: |
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name _;
location / {
try_files $uri $uri/ =404;
}
location /health {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
}
owner: root:root
permissions: '0644'
# Environment configuration
- path: /etc/environment
content: |
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
EDITOR="vim"
LANG="en_US.UTF-8"
LC_ALL="en_US.UTF-8"
append: true
# Shell script
- path: /usr/local/bin/health-check.sh
content: |
#!/bin/bash
# Health check script
set -e
# Check if services are running
check_service() {
local service=$1
if systemctl is-active --quiet $service; then
echo "✓ $service: OK"
else
echo "✗ $service: FAILED"
return 1
fi
}
# Check disk space
check_disk() {
local usage=$(df / | awk 'NR==2 {print $5}' | sed 's/%//')
if [ $usage -gt 90 ]; then
echo "✗ Disk: CRITICAL - ${usage}% used"
return 1
elif [ $usage -gt 80 ]; then
echo "⚠ Disk: WARNING - ${usage}% used"
else
echo "✓ Disk: OK - ${usage}% used"
fi
}
# Run checks
echo "Health Check Report - $(date)"
echo "================================"
check_service nginx
check_service ssh
check_disk
echo "Health check completed"
owner: root:root
permissions: '0755'
# JSON configuration file
- path: /opt/app/config.json
content: |
{
"database": {
"host": "localhost",
"port": 5432,
"name": "myapp",
"ssl": true
},
"redis": {
"host": "localhost",
"port": 6379,
"db": 0
},
"logging": {
"level": "info",
"format": "json",
"file": "/var/log/app.log"
},
"features": {
"authentication": true,
"monitoring": true,
"debug": false
}
}
owner: app:app
permissions: '0640'
# Systemd service file
- path: /etc/systemd/system/webapp.service
content: |
[Unit]
Description=Web Application
Documentation=https://docs.example.com
After=network.target postgresql.service redis.service
Wants=network.target
Requires=postgresql.service
[Service]
Type=simple
User=webapp
Group=webapp
WorkingDirectory=/opt/webapp
Environment=NODE_ENV=production
Environment=PORT=3000
ExecStart=/opt/webapp/bin/start.sh
ExecReload=/bin/kill -HUP $MAINPID
ExecStop=/bin/kill -TERM $MAINPID
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal
SyslogIdentifier=webapp
KillMode=mixed
TimeoutStopSec=30
# Security settings
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/opt/webapp/data /var/log
[Install]
WantedBy=multi-user.target
owner: root:root
permissions: '0644'
# Binary content (base64 encoded)
- path: /etc/ssl/certs/ca-certificate.crt
content: !!binary |
LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUNhakNDQWZPZ0F3SUJBZ0lKQUt...
owner: root:root
permissions: '0644'
encoding: b64
# Directory creation (via runcmd)
runcmd:
# Create application directories
- mkdir -p /opt/app/{data,logs,config,tmp}
- mkdir -p /var/lib/app
- mkdir -p /etc/app/conf.d
# Set proper ownership and permissions
- chown -R app:app /opt/app
- chmod 755 /opt/app
- chmod 750 /opt/app/data
- chmod 755 /opt/app/logs
- chmod 700 /opt/app/config
# STORAGE AND FILESYSTEM CONFIGURATION
# Disk partitioning and setup
disk_setup:
# Setup additional disk
/dev/nvme1n1:
table_type: gpt
layout:
- [50, 83] # 50% for partition 1, type 83 (Linux)
- [50, 83] # 50% for partition 2, type 83 (Linux)
overwrite: false
# Use entire disk
/dev/sdb:
table_type: mbr
layout: true
overwrite: false
# Filesystem creation
fs_setup:
- label: app-data
filesystem: ext4
device: /dev/nvme1n1p1
partition: auto
- label: app-logs
filesystem: ext4
device: /dev/nvme1n1p2
partition: auto
- label: backup
filesystem: xfs
device: /dev/sdb1
partition: auto
# Mount configuration
mounts:
- ["/dev/nvme1n1p1", "/opt/app/data", "ext4", "defaults,nofail", "0", "2"]
- ["/dev/nvme1n1p2", "/var/log/app", "ext4", "defaults,nofail", "0", "2"]
- ["/dev/sdb1", "/backup", "xfs", "defaults,nofail", "0", "2"]
- ["tmpfs", "/tmp", "tmpfs", "defaults,nodev,nosuid,size=2G", "0", "0"]
# Swap configuration
swap:
filename: /swapfile
size: 2G
maxsize: 4G
# LVM configuration (if needed)
runcmd:
# LVM setup commands
- pvcreate /dev/nvme2n1
- vgcreate data-vg /dev/nvme2n1
- lvcreate -L 50G -n app-lv data-vg
- lvcreate -L 30G -n logs-lv data-vg
- mkfs.ext4 /dev/data-vg/app-lv
- mkfs.ext4 /dev/data-vg/logs-lv
- mkdir -p /opt/app /opt/logs
- mount /dev/data-vg/app-lv /opt/app
- mount /dev/data-vg/logs-lv /opt/logs
# Add to fstab
- echo "/dev/data-vg/app-lv /opt/app ext4 defaults 0 2" >> /etc/fstab
- echo "/dev/data-vg/logs-lv /opt/logs ext4 defaults 0 2" >> /etc/fstab
# NETWORK CONFIGURATION
# Basic hostname and domain setup
hostname: web-server-01
fqdn: web-server-01.example.com
prefer_fqdn_over_hostname: true
manage_etc_hosts: true
# DNS resolver configuration
manage_resolv_conf: true
resolv_conf:
nameservers:
- 8.8.8.8
- 8.8.4.4
- 1.1.1.1
searchdomains:
- example.com
- internal.example.com
domain: example.com
options:
rotate: true
timeout: 1
# Static network configuration (Netplan for Ubuntu)
write_files:
- path: /etc/netplan/01-static.yaml
content: |
network:
version: 2
renderer: networkd
ethernets:
eth0:
dhcp4: false
addresses:
- 192.168.1.100/24
gateway4: 192.168.1.1
nameservers:
addresses:
- 8.8.8.8
- 8.8.4.4
search:
- example.com
eth1:
dhcp4: true
permissions: '0644'
# Network configuration for older systems
write_files:
- path: /etc/network/interfaces
content: |
# Network configuration
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet static
address 192.168.1.100
netmask 255.255.255.0
gateway 192.168.1.1
dns-nameservers 8.8.8.8 8.8.4.4
dns-search example.com
permissions: '0644'
# Custom hosts entries
write_files:
- path: /etc/hosts
content: |
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
# Infrastructure hosts
192.168.1.10 database.internal db.internal
192.168.1.20 cache.internal redis.internal
192.168.1.30 api.internal
192.168.1.40 monitor.internal
append: true
# Apply network configuration
runcmd:
- netplan apply # For Ubuntu with Netplan
# - systemctl restart networking # For Debian/Ubuntu with interfaces
# - systemctl restart network # For CentOS/RHEL
# SYSTEM CONFIGURATION
# Timezone and locale settings
timezone: UTC
locale: en_US.UTF-8
locale_configfile: /etc/default/locale
# NTP time synchronization
ntp:
enabled: true
ntp_client: chrony
servers:
- 0.pool.ntp.org
- 1.pool.ntp.org
- 2.pool.ntp.org
- 3.pool.ntp.org
pools:
- 0.ubuntu.pool.ntp.org
- 1.ubuntu.pool.ntp.org
# Kernel modules
write_files:
- path: /etc/modules-load.d/custom.conf
content: |
# Custom kernel modules
overlay
br_netfilter
ip_vs
ip_vs_rr
ip_vs_wrr
ip_vs_sh
owner: root:root
permissions: '0644'
# System limits configuration
write_files:
- path: /etc/security/limits.conf
content: |
# Custom system limits
* soft nofile 65536
* hard nofile 65536
* soft nproc 32768
* hard nproc 32768
# Application specific limits
webapp soft nofile 100000
webapp hard nofile 100000
webapp soft nproc 50000
webapp hard nproc 50000
append: true
# Sysctl kernel parameters
write_files:
- path: /etc/sysctl.d/99-custom.conf
content: |
# Network optimization
net.core.rmem_max = 134217728
net.core.wmem_max = 134217728
net.ipv4.tcp_rmem = 4096 65536 134217728
net.ipv4.tcp_wmem = 4096 65536 134217728
net.core.netdev_max_backlog = 5000
# Security settings
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1
# Performance tuning
vm.swappiness = 10
vm.dirty_ratio = 15
vm.dirty_background_ratio = 5
vm.vfs_cache_pressure = 50
# File system
fs.file-max = 2097152
fs.inotify.max_user_watches = 524288
owner: root:root
permissions: '0644'
# System services configuration
services:
enabled:
- nginx
- ssh
- fail2ban
- ufw
- chrony
disabled:
- snapd
- apport
# Bootloader configuration (if needed)
bootcmd:
- echo 'Cloud-init starting...' > /var/log/cloud-init-start.log
- mount -a
- swapon -a
# Apply system configuration
runcmd:
# Load kernel modules
- modprobe overlay
- modprobe br_netfilter
# Apply sysctl settings
- sysctl -p /etc/sysctl.d/99-custom.conf
# Reload systemd
- systemctl daemon-reload
# SECURITY CONFIGURATION
# SSH hardening
write_files:
- path: /etc/ssh/sshd_config.d/99-custom.conf
content: |
# Custom SSH security configuration
Port 2222
Protocol 2
# Authentication
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PermitEmptyPasswords no
ChallengeResponseAuthentication no
UsePAM yes
# Security settings
MaxAuthTries 3
MaxSessions 4
MaxStartups 10:30:60
LoginGraceTime 30
ClientAliveInterval 300
ClientAliveCountMax 2
# Logging
SyslogFacility AUTH
LogLevel VERBOSE
# User restrictions
AllowUsers ubuntu webapp
DenyUsers root
# Protocol settings
X11Forwarding no
AllowTcpForwarding no
AllowAgentForwarding no
PermitTunnel no
# Modern cryptography
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com
MACs hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com
KexAlgorithms curve25519-sha256@libssh.org,diffie-hellman-group16-sha512
owner: root:root
permissions: '0644'
# Firewall configuration
write_files:
- path: /etc/ufw/applications.d/custom
content: |
[Nginx Full]
title=Web Server (Nginx, HTTP + HTTPS)
description=Small, but very powerful and efficient web server
ports=80,443/tcp
[SSH Custom]
title=Secure shell server (custom port)
description=OpenSSH server on custom port
ports=2222/tcp
[Web Application]
title=Custom web application
description=Node.js/Python web application
ports=3000/tcp
owner: root:root
permissions: '0644'
# Fail2ban configuration
write_files:
- path: /etc/fail2ban/jail.local
content: |
[DEFAULT]
# Ban settings
bantime = 1h
findtime = 10m
maxretry = 5
backend = systemd
# Email notifications (optional)
destemail = admin@example.com
sendername = Fail2Ban
sender = fail2ban@example.com
action = %(action_mw)s
# SSH protection
[sshd]
enabled = true
port = 2222
logpath = %(sshd_log)s
backend = %(sshd_backend)s
maxretry = 3
# Nginx protection
[nginx-http-auth]
enabled = true
filter = nginx-http-auth
logpath = /var/log/nginx/error.log
maxretry = 5
[nginx-limit-req]
enabled = true
filter = nginx-limit-req
logpath = /var/log/nginx/error.log
maxretry = 10
[nginx-botsearch]
enabled = true
filter = nginx-botsearch
logpath = /var/log/nginx/access.log
maxretry = 2
owner: root:root
permissions: '0644'
# System security hardening
runcmd:
# Configure UFW firewall
- ufw --force reset
- ufw default deny incoming
- ufw default allow outgoing
- ufw allow 2222/tcp # SSH
- ufw allow 80/tcp # HTTP
- ufw allow 443/tcp # HTTPS
- ufw logging on
- ufw --force enable
# Restart SSH with new configuration
- systemctl restart ssh
# Start and enable security services
- systemctl enable fail2ban
- systemctl start fail2ban
# Set secure file permissions
- chmod 700 /home/*/
- chmod 600 /home/*/.ssh/authorized_keys
- chmod 700 /home/*/.ssh/
# Remove unnecessary packages
- apt-get autoremove -y
- apt-get autoclean
# APPLICATION DEPLOYMENT
# Docker installation and configuration
write_files:
- path: /etc/docker/daemon.json
content: |
{
"log-driver": "json-file",
"log-opts": {
"max-size": "10m",
"max-file": "3"
},
"storage-driver": "overlay2",
"live-restore": true,
"userland-proxy": false,
"experimental": false,
"metrics-addr": "127.0.0.1:9323",
"log-level": "info",
"default-ulimits": {
"nofile": {
"Hard": 64000,
"Name": "nofile",
"Soft": 64000
}
}
}
owner: root:root
permissions: '0644'
# Application configuration
write_files:
- path: /opt/webapp/start.sh
content: |
#!/bin/bash
set -e
# Environment setup
export NODE_ENV=production
export PORT=3000
export LOG_LEVEL=info
# Wait for dependencies
echo "Waiting for database connection..."
until nc -z database.internal 5432; do
echo "Database not ready, waiting..."
sleep 2
done
echo "Waiting for Redis connection..."
until nc -z cache.internal 6379; do
echo "Redis not ready, waiting..."
sleep 2
done
# Start application
echo "Starting application..."
cd /opt/webapp
npm start
owner: webapp:webapp
permissions: '0755'
- path: /opt/webapp/package.json
content: |
{
"name": "myapp",
"version": "1.0.0",
"description": "My Web Application",
"main": "server.js",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js",
"test": "jest",
"lint": "eslint .",
"build": "webpack --mode production"
},
"dependencies": {
"express": "^4.18.0",
"pg": "^8.8.0",
"redis": "^4.3.0",
"bcryptjs": "^2.4.3",
"jsonwebtoken": "^8.5.1"
},
"engines": {
"node": ">=18.0.0"
}
}
owner: webapp:webapp
permissions: '0644'
# Database setup
write_files:
- path: /opt/scripts/setup-database.sh
content: |
#!/bin/bash
set -e
echo "Setting up PostgreSQL database..."
# Install PostgreSQL
apt-get update
apt-get install -y postgresql postgresql-contrib
# Configure PostgreSQL
sudo -u postgres createuser --superuser webapp || true
sudo -u postgres createdb myapp || true
# Set up database schema
sudo -u postgres psql -d myapp -c "
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,