diff --git a/.gitea/workflows/deploy_new_config.yaml b/.gitea/workflows/deploy_new_config.yaml new file mode 100644 index 0000000..75f9e4e --- /dev/null +++ b/.gitea/workflows/deploy_new_config.yaml @@ -0,0 +1,21 @@ +name: Deploy new config to the Ansible server +run-name: Config is being deployed + +on: + pull_request: + types: [closed] + branches: [ main ] + +env: + REGISTRY: git.vmn.su + OWNER: max + REPO: vmn-ansible + +jobs: + trigger-webhook: + if: github.event.pull_request.merged == true + runs-on: ubuntu-latest + steps: + - name: Trigger the webhook to start pulling new Ansible configs + # LAN IP is used because those hosts are in the same network + run: curl "http://192.168.0.38:9000/hooks/run-maintain-playbook" diff --git a/inventory/group_vars/all/main.yaml b/inventory/group_vars/all/main.yaml index 8e4ba15..2fdf97c 100644 --- a/inventory/group_vars/all/main.yaml +++ b/inventory/group_vars/all/main.yaml @@ -1,3 +1,4 @@ --- ansible_become_passwd: "{{ ansible_password }}" +human_admin_user: max diff --git a/inventory/hosts.yaml b/inventory/hosts.yaml index 3fd09b0..b38a87b 100644 --- a/inventory/hosts.yaml +++ b/inventory/hosts.yaml @@ -1,5 +1,13 @@ --- physical: hosts: - 192.168.0.45: + localhost: + ansible_become_password: "{{ ansible_become_passwd }}" + ansible_connection: local + ansible_python_interpreter: "{{ ansible_playbook_python }}" + 192.168.0.98: + ansible_become_password: "{{ ansible_become_passwd }}" + 192.168.0.6: + ansible_become_password: "{{ ansible_become_passwd }}" + 192.168.0.8: ansible_become_password: "{{ ansible_become_passwd }}" diff --git a/inventory/localhost.yaml b/inventory/localhost.yaml new file mode 100644 index 0000000..b71186d --- /dev/null +++ b/inventory/localhost.yaml @@ -0,0 +1,7 @@ +--- +physical: + hosts: + localhost: + ansible_become_password: "{{ ansible_become_passwd }}" + ansible_connection: local + ansible_python_interpreter: "{{ ansible_playbook_python }}" diff --git a/playbooks/deploy_and_set_up_lxc_on_proxmox.yaml b/playbooks/deploy_and_set_up_lxc_on_proxmox.yaml new file mode 100644 index 0000000..285afd2 --- /dev/null +++ b/playbooks/deploy_and_set_up_lxc_on_proxmox.yaml @@ -0,0 +1,75 @@ +--- +- name: Deploy LXC + hosts: all + remote_user: ansible + gather_facts: false + + vars_files: + ../inventory/group_vars/all/secrets.yaml + vars: + ansible_user_passwd_hash: "{{ ansible_password | password_hash('sha512', 's3edscrj45e6r') }}" + user_passwd_hash: "{{ user_password | password_hash('sha512', 's3ed6123jhgcr') }}" + + vars_prompt: + - name: lxc_hostname + prompt: "Hostname for the container (may only contain letters (a-z, A-Z), numbers (0-9), and hyphens)" + private: false + + - name: lxc_root_password + prompt: "Root password" + private: true + confirm: true + encrypt: sha512_crypt + + - name: lxc_ip_address + prompt: "IP address for the container (in x.x.x.x/x formant)" + private: false + + pre_tasks: + - name: Validate hostname + ansible.builtin.fail: + msg: | + Invalid hostname: "{{ lxc_hostname }}" + Hostname may only contain letters (a-z, A-Z), numbers (0-9), and hyphens (-). + when: not lxc_hostname is regex('^[a-zA-Z0-9-]+$') + run_once: true + + roles: + - ../roles/deploy_lxc_on_proxmox + + tasks: + - name: Make the prompted hostname available to the whole playbook + ansible.builtin.set_fact: + fact_lxc_hostname: "{{ lxc_hostname }}" + + - name: Make the prompted IP available to the whole playbook + ansible.builtin.set_fact: + #fact_lxc_ip_address: "{{ lxc_ip_address | ansible.utils.ipaddr('address') }}" + fact_lxc_ip_address: "{{ lxc_ip_address.split('/') | first }}" + + - name: Add the target host to the inventory + ansible.builtin.add_host: + name: "{{ fact_lxc_ip_address }}" + groups: new_host + ansible_user: ansible + ansible_become_password: "{{ ansible_become_passwd }}" + + +- name: Configure LXC + hosts: new_host + remote_user: ansible + + vars_files: + ../inventory/group_vars/all/secrets.yaml + vars: + ansible_user_passwd_hash: "{{ ansible_password | password_hash('sha512', 's3edscrj45e6r') }}" + user_passwd_hash: "{{ user_password | password_hash('sha512', 's3ed6123jhgcr') }}" + + roles: + - ../roles/configure_ansible_user + - ../roles/harden_ssh + - ../roles/base_system + - ../roles/human_admin_user + # Update configs - omz, nvim, ranger and so on. Distribute the last version of those configs + - ../roles/update_configs + diff --git a/playbooks/deploy_lxc.yaml b/playbooks/deploy_lxc.yaml deleted file mode 100644 index b492713..0000000 --- a/playbooks/deploy_lxc.yaml +++ /dev/null @@ -1,17 +0,0 @@ ---- -- name: Deplot simple test LXC on Proxmox VE - hosts: localhost - gather_facts: false - roles: - - ../roles/basic_proxmox_lxc - -- name: Basic Proxmox guest deployment - hosts: all - remote_user: root - roles: - - ../roles/basic_postinstall - vars_files: - ../inventory/group_vars/all/secrets.yaml - vars: - ansible_user_passwd_hash: "{{ ansible_password | password_hash('sha512', 's3edscrj45e6r') }}" - user_passwd_hash: "{{ user_password | password_hash('sha512', 's3ed6123jhgcr') }}" \ No newline at end of file diff --git a/playbooks/deploy_vm_from_cloud_init.yaml b/playbooks/deploy_vm_from_cloud_init.yaml index 96c045c..61b3b8b 100644 --- a/playbooks/deploy_vm_from_cloud_init.yaml +++ b/playbooks/deploy_vm_from_cloud_init.yaml @@ -1,28 +1,68 @@ --- -- name: Deploy a virtual machine from a cloud init image - hosts: localhost - gather_facts: false - roles: - - ../roles/basic_proxmox_vm - -- name: Basic Proxmox guest deployment +- name: Deploy VM hosts: all remote_user: ansible - roles: - - ../roles/basic_postinstall + gather_facts: false + vars_files: ../inventory/group_vars/all/secrets.yaml vars: ansible_user_passwd_hash: "{{ ansible_password | password_hash('sha512', 's3edscrj45e6r') }}" user_passwd_hash: "{{ user_password | password_hash('sha512', 's3ed6123jhgcr') }}" - handlers: - - name: restart ssh-server - service: - name: ssh - state: restarted + vars_prompt: + - name: vm_hostname + prompt: "Hostname for the VM (may only contain letters (a-z, A-Z), numbers (0-9), and hyphens)" + private: false + + - name: vm_ip_address + prompt: "IP address for the VM (in x.x.x.x/x formant)" + private: false + + pre_tasks: + - name: Validate hostname + ansible.builtin.fail: + msg: | + Invalid hostname: "{{ vm_hostname }}" + Hostname may only contain letters (a-z, A-Z), numbers (0-9), and hyphens (-). + when: not vm_hostname is regex('^[a-zA-Z0-9-]+$') + run_once: true + + roles: + - ../roles/deploy_vm_on_proxmox + + tasks: + - name: Make the prompted hostname available to the whole playbook + ansible.builtin.set_fact: + fact_vm_hostname: "{{ vm_hostname }}" - - name: restart sshd-server - service: - name: sshd - state: restarted \ No newline at end of file + - name: Make the prompted IP available to the whole playbook + ansible.builtin.set_fact: + fact_vm_ip_address: "{{ vm_ip_address.split('/') | first }}" + + - name: Add the target host to the inventory + ansible.builtin.add_host: + name: "{{ fact_vm_ip_address }}" + groups: new_host + ansible_user: ansible + ansible_become_password: "{{ ansible_become_passwd }}" + + +- name: Configure VM + hosts: new_host + remote_user: ansible + + vars_files: + ../inventory/group_vars/all/secrets.yaml + vars: + ansible_user_passwd_hash: "{{ ansible_password | password_hash('sha512', 's3edscrj45e6r') }}" + user_passwd_hash: "{{ user_password | password_hash('sha512', 's3ed6123jhgcr') }}" + + roles: + - ../roles/configure_ansible_user + - ../roles/harden_ssh + - ../roles/base_system + - ../roles/human_admin_user + # Update configs - omz, nvim, ranger and so on. Distribute the last version of those configs + - ../roles/update_configs + diff --git a/playbooks/maintain.yaml b/playbooks/maintain.yaml index 368befe..45a9e45 100644 --- a/playbooks/maintain.yaml +++ b/playbooks/maintain.yaml @@ -1,12 +1,23 @@ --- -- name: Physical machines maintanance play +- name: Deploy and set up an LXC container in Proxmox hosts: all remote_user: ansible - roles: - - ../roles/common_healthcheck + vars_files: ../inventory/group_vars/all/secrets.yaml vars: ansible_user_passwd_hash: "{{ ansible_password | password_hash('sha512', 's3edscrj45e6r') }}" user_passwd_hash: "{{ user_password | password_hash('sha512', 's3ed6123jhgcr') }}" - ha_addr: https://ha.lan + + roles: + # Check the Internet connection + # Check free disk space + - ../roles/common_healthcheck + # Ensure that all the required packages are installed + - ../roles/base_system + # Update the system + - ../roles/update_system + # Harden SSH - we must be sure that the last version of ssh configs are distributed + - ../roles/harden_ssh + # Update configs - omz, nvim, ranger and so on. Distribute the last version of those configs + - ../roles/update_configs diff --git a/requirements.txt b/requirements.txt index 1d11f18..bb5d472 100644 --- a/requirements.txt +++ b/requirements.txt @@ -17,10 +17,12 @@ mypy_extensions==1.1.0 packaging==26.2 pathspec==1.1.1 platformdirs==4.10.0 +proxmoxer>=2.3 pycparser==3.0 pytokens==0.4.1 PyYAML==6.0.3 referencing==0.37.0 +requests>=2.34.2 resolvelib==1.2.1 rpds-py==2026.6.3 ruamel.yaml==0.19.1 diff --git a/roles/basic_postinstall/tasks/install_basic_utils.yaml b/roles/base_system/tasks/install_packages.yaml similarity index 69% rename from roles/basic_postinstall/tasks/install_basic_utils.yaml rename to roles/base_system/tasks/install_packages.yaml index 5a6ed89..fda6ee4 100644 --- a/roles/basic_postinstall/tasks/install_basic_utils.yaml +++ b/roles/base_system/tasks/install_packages.yaml @@ -1,19 +1,8 @@ --- - name: Installing basic utils for comfort work (apt-based system) - when: (ansible_facts['distribution'] == "Debian") or - (ansible_facts['distribution'] == "Ubuntu") + when: (ansible_facts['os_family'] == "Debian") ansible.builtin.apt: - name: - - vim - - ranger - - zsh - - rsync - - git - - curl - - kitty - - unattended-upgrades - - ssh - - openssh-server + name: "{{ debian_13_packages }}" update-cache: true # Run apt update before installation become: true remote_user: ansible @@ -37,6 +26,6 @@ - name: Update and install packages on Alpine when: (ansible_facts['distribution'] == "Alpine") community.general.apk: - name: vim ranger zsh rsync git curl kitty openssh + name: "{{ alpine_packages }}" update_cache: true remote_user: ansible diff --git a/roles/base_system/tasks/main.yaml b/roles/base_system/tasks/main.yaml new file mode 100644 index 0000000..3aff217 --- /dev/null +++ b/roles/base_system/tasks/main.yaml @@ -0,0 +1,9 @@ +--- +- name: Install basic utils + ansible.builtin.include_tasks: install_packages.yaml + +- name: Remove unnecessary packages + ansible.builtin.include_tasks: remove_packages.yaml + +- name: Set locale and time + ansible.builtin.include_tasks: set_locale_and_time.yaml diff --git a/roles/basic_postinstall/tasks/remove_packages.yaml b/roles/base_system/tasks/remove_packages.yaml similarity index 100% rename from roles/basic_postinstall/tasks/remove_packages.yaml rename to roles/base_system/tasks/remove_packages.yaml diff --git a/roles/basic_postinstall/tasks/set_locale_and_time.yaml b/roles/base_system/tasks/set_locale_and_time.yaml similarity index 100% rename from roles/basic_postinstall/tasks/set_locale_and_time.yaml rename to roles/base_system/tasks/set_locale_and_time.yaml diff --git a/roles/base_system/vars/main/alpine_packages.yaml b/roles/base_system/vars/main/alpine_packages.yaml new file mode 100644 index 0000000..038bac7 --- /dev/null +++ b/roles/base_system/vars/main/alpine_packages.yaml @@ -0,0 +1,13 @@ +--- + +alpine_packages: + - curl + - gcc + - git + - kitty + - neovim + - openssh-server + - ranger + - rsync + - ssh + - zsh diff --git a/roles/base_system/vars/main/debian_13_packages.yaml b/roles/base_system/vars/main/debian_13_packages.yaml new file mode 100644 index 0000000..b741437 --- /dev/null +++ b/roles/base_system/vars/main/debian_13_packages.yaml @@ -0,0 +1,13 @@ +--- + +debian_13_packages: + - curl + - gcc + - git + - kitty + - neovim + - openssh-server + - ranger + - rsync + - ssh + - zsh diff --git a/roles/basic_postinstall/files/.zshrc b/roles/basic_postinstall/files/.zshrc deleted file mode 100644 index 4423d1f..0000000 --- a/roles/basic_postinstall/files/.zshrc +++ /dev/null @@ -1,105 +0,0 @@ -export PATH=$HOME/bin:$HOME/.local/bin:/usr/local/bin:/home/max/soft/gnu_linux:$PATH - -# Path to your Oh My Zsh installation. -export ZSH="$HOME/.oh-my-zsh" - -export GTK_THEME=Adwaita-dark - -# Set name of the theme to load --- if set to "random", it will -# load a random theme each time Oh My Zsh is loaded, in which case, -# to know which specific one was loaded, run: echo $RANDOM_THEME -# See https://github.com/ohmyzsh/ohmyzsh/wiki/Themes -ZSH_THEME="gnzh" - -# Set list of themes to pick from when loading at random -# Setting this variable when ZSH_THEME=random will cause zsh to load -# a theme from this variable instead of looking in $ZSH/themes/ -# If set to an empty array, this variable will have no effect. -# ZSH_THEME_RANDOM_CANDIDATES=( "robbyrussell" "agnoster" ) - -# Uncomment the following line to use case-sensitive completion. -# CASE_SENSITIVE="true" - -# Uncomment the following line to use hyphen-insensitive completion. -# Case-sensitive completion must be off. _ and - will be interchangeable. -# HYPHEN_INSENSITIVE="true" - -# Uncomment one of the following lines to change the auto-update behavior -# zstyle ':omz:update' mode disabled # disable automatic updates -# zstyle ':omz:update' mode auto # update automatically without asking -# zstyle ':omz:update' mode reminder # just remind me to update when it's time - -# Uncomment the following line to change how often to auto-update (in days). -# zstyle ':omz:update' frequency 13 - -# Uncomment the following line if pasting URLs and other text is messed up. -# DISABLE_MAGIC_FUNCTIONS="true" - -# Uncomment the following line to disable colors in ls. -# DISABLE_LS_COLORS="true" - -# Uncomment the following line to disable auto-setting terminal title. -# DISABLE_AUTO_TITLE="true" - -# Uncomment the following line to enable command auto-correction. -# ENABLE_CORRECTION="true" - -# Uncomment the following line to display red dots whilst waiting for completion. -# You can also set it to another string to have that shown instead of the default red dots. -# e.g. COMPLETION_WAITING_DOTS="%F{yellow}waiting...%f" -# Caution: this setting can cause issues with multiline prompts in zsh < 5.7.1 (see #5765) -# COMPLETION_WAITING_DOTS="true" - -# Uncomment the following line if you want to disable marking untracked files -# under VCS as dirty. This makes repository status check for large repositories -# much, much faster. -# DISABLE_UNTRACKED_FILES_DIRTY="true" - -# Uncomment the following line if you want to change the command execution time -# stamp shown in the history command output. -# You can set one of the optional three formats: -# "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd" -# or set a custom format using the strftime function format specifications, -# see 'man strftime' for details. -# HIST_STAMPS="mm/dd/yyyy" - -# Would you like to use another custom folder than $ZSH/custom? -# ZSH_CUSTOM=/path/to/new-custom-folder - -# Which plugins would you like to load? -# Standard plugins can be found in $ZSH/plugins/ -# Custom plugins may be added to $ZSH_CUSTOM/plugins/ -# Example format: plugins=(rails git textmate ruby lighthouse) -# Add wisely, as too many plugins slow down shell startup. -#plugins=(git) - -source $ZSH/oh-my-zsh.sh - -# User configuration - -# export MANPATH="/usr/local/man:$MANPATH" - -# You may need to manually set your language environment -# export LANG=en_US.UTF-8 - -# Preferred editor for local and remote sessions -# if [[ -n $SSH_CONNECTION ]]; then -# export EDITOR='vim' -# else -# export EDITOR='nvim' -# fi - -# Compilation flags -# export ARCHFLAGS="-arch $(uname -m)" - -# Set personal aliases, overriding those provided by Oh My Zsh libs, -# plugins, and themes. Aliases can be placed here, though Oh My Zsh -# users are encouraged to define aliases within a top-level file in -# the $ZSH_CUSTOM folder, with .zsh extension. Examples: -# - $ZSH_CUSTOM/aliases.zsh -# - $ZSH_CUSTOM/macos.zsh -# For a full list of active aliases, run `alias`. -# -# Example aliases -# alias zshconfig="mate ~/.zshrc" -# alias ohmyzsh="mate ~/.oh-my-zsh" diff --git a/roles/basic_postinstall/tasks/main.yaml b/roles/basic_postinstall/tasks/main.yaml deleted file mode 100644 index b886049..0000000 --- a/roles/basic_postinstall/tasks/main.yaml +++ /dev/null @@ -1,18 +0,0 @@ ---- -- name: Create and set up Ansible user and environment - ansible.builtin.include_tasks: prepare_ansible_user.yaml - -- name: Improve SSH configuration - ansible.builtin.include_tasks: harden_ssh.yaml - -- name: Install basic utils - ansible.builtin.include_tasks: install_basic_utils.yaml - -- name: Remove unnecessary packages - ansible.builtin.include_tasks: remove_packages.yaml - -- name: Create and set up a new user - ansible.builtin.include_tasks: create_new_user.yaml - -- name: Set locale and time - ansible.builtin.include_tasks: set_locale_and_time.yaml diff --git a/roles/common_healthcheck/tasks/main.yaml b/roles/common_healthcheck/tasks/main.yaml index 6a08e66..c024da8 100644 --- a/roles/common_healthcheck/tasks/main.yaml +++ b/roles/common_healthcheck/tasks/main.yaml @@ -2,7 +2,7 @@ - name: Internet connection test block block: - name: Test reachability to ya.ru - become: true # Usually it's not necessary, but sometimes there are some wierd issues with ping, especially on Alpine + become: true # Usually it's not necessary, but sometimes ping is disabled for non-root by default ansible.builtin.shell: ping -c 5 ya.ru > /dev/null changed_when: false # This task does not change the system @@ -21,9 +21,10 @@ block: - name: Test free disk space in root become: false + # We have to use this complicated pipeline because of Alpine and its wierd df implementation ansible.builtin.shell: set -o pipefail && df -h / | tail -1 | awk '{gsub(/%/, "", $5); print $5}' - register: common_healthcheck_result - failed_when: common_healthcheck_result.stdout | int > 85 + register: free_disk_space_result + failed_when: free_disk_space_result.stdout | int > 85 changed_when: false # This task does not change the system rescue: diff --git a/roles/basic_postinstall/tasks/prepare_ansible_user.yaml b/roles/configure_ansible_user/tasks/main.yaml similarity index 100% rename from roles/basic_postinstall/tasks/prepare_ansible_user.yaml rename to roles/configure_ansible_user/tasks/main.yaml diff --git a/roles/basic_proxmox_lxc/tasks/main.yaml b/roles/deploy_lxc_on_proxmox/tasks/main.yaml similarity index 65% rename from roles/basic_proxmox_lxc/tasks/main.yaml rename to roles/deploy_lxc_on_proxmox/tasks/main.yaml index f5a96d6..6a74105 100644 --- a/roles/basic_proxmox_lxc/tasks/main.yaml +++ b/roles/deploy_lxc_on_proxmox/tasks/main.yaml @@ -1,6 +1,6 @@ --- -- name: Create new container with minimal options defining network interface with static ip +- name: Create a new container with minimal options defining network interface with static ip become: false community.proxmox.proxmox: validate_certs: false @@ -11,20 +11,21 @@ api_token_secret: "{{ proxmox_token_secret }}" cmode: "shell" - vmid: 1040 - password: ansible-test - hostname: "ansible-test" - # ostemplate: 'main:vztmpl/debian-13-standard_13.1-2_amd64.tar.zst' + password: "{{ lxc_root_password }}" + hostname: "{{ lxc_hostname }}" ostemplate: 'main:vztmpl/debian-13-golden-image.tar.gz' memory: 2048 - cores: 5 + cores: 2 state: present disk_volume: - size: 2 # 2GB rootfs + # This is minimal requirement for rootfs + # It might be resized later + size: 4 # 4GB rootfs + # We put rootfs on fast local storage (NVMe SSD) storage: local pubkey: "{{ lookup('file', lookup('env', 'HOME') + '/.ssh/ansible_key.pub') }}" netif: - net0: "name=eth0,gw=192.168.0.1,ip=192.168.0.40/24,bridge=vmbr0" + net0: "name=eth0,gw=192.168.0.1,ip={{ lxc_ip_address }},bridge=vmbr0" - name: Make sure the container has started become: false @@ -36,12 +37,13 @@ api_token_id: ansible api_token_secret: "{{ proxmox_token_secret }}" - vmid: 1040 + hostname: "{{ lxc_hostname }}" state: started + retries: 3 + delay: 15 - name: Sleep for a minute to ensure that ssh is ready become: false ansible.builtin.wait_for: timeout: 60 - delegate_to: localhost changed_when: false diff --git a/roles/basic_proxmox_vm/tasks/main.yaml b/roles/deploy_vm_on_proxmox/tasks/create_vm.yaml similarity index 57% rename from roles/basic_proxmox_vm/tasks/main.yaml rename to roles/deploy_vm_on_proxmox/tasks/create_vm.yaml index 990fec3..52bbc27 100644 --- a/roles/basic_proxmox_vm/tasks/main.yaml +++ b/roles/deploy_vm_on_proxmox/tasks/create_vm.yaml @@ -1,5 +1,6 @@ --- -- name: Create a new VM with minimal options + +- name: Create a new VM with minimal options only if it doesn't exist become: false community.proxmox.proxmox_kvm: validate_certs: false @@ -10,13 +11,38 @@ api_token_secret: "{{ proxmox_token_secret }}" clone: debian-13-cloud-init-template - newid: 1041 - name: ansible-ci-test + name: "{{ vm_hostname }}" storage: main format: qcow2 full: true timeout: 500 +- name: Sleep for 20 seconds to ensure that Proxmox has cloned the VM + become: false + ansible.builtin.wait_for: + timeout: 20 + delegate_to: localhost + changed_when: false + +- name: Update the cloned VM with cloud-init configuration + community.proxmox.proxmox_kvm: + validate_certs: false + node: proxmox-server + api_user: root@pam + api_host: 192.168.0.2 + api_token_id: ansible + api_token_secret: "{{ proxmox_token_secret }}" + + name: "{{ vm_hostname }}" + # Cloud-init parameters + update: true + ide: + ide2: "local:cloudinit,format=qcow2" + ciuser: "ansible" + cipassword: "{{ ansible_become_passwd }}" + ipconfig: + ipconfig0: "ip={{ vm_ip_address }},gw=192.168.0.1" + - name: Tweak the hardware settings become: false community.proxmox.proxmox_kvm: @@ -27,7 +53,7 @@ api_token_id: ansible api_token_secret: "{{ proxmox_token_secret }}" - vmid: 1041 + name: "{{ vm_hostname }}" cores: 4 memory: 4096 # Minimal value for debian based OS for smooth workflow update: true @@ -42,12 +68,6 @@ api_token_id: ansible api_token_secret: "{{ proxmox_token_secret }}" - vmid: 1041 + name: "{{ vm_hostname }}" state: started -- name: Sleep for 3 minutes to ensure that cloud-init's done its thing - become: false - ansible.builtin.wait_for: - timeout: 180 - delegate_to: localhost - changed_when: false diff --git a/roles/deploy_vm_on_proxmox/tasks/main.yaml b/roles/deploy_vm_on_proxmox/tasks/main.yaml new file mode 100644 index 0000000..07f5a53 --- /dev/null +++ b/roles/deploy_vm_on_proxmox/tasks/main.yaml @@ -0,0 +1,25 @@ +--- + +- name: Check if VM already exists + community.proxmox.proxmox_kvm: + validate_certs: false + node: proxmox-server + api_user: root@pam + api_host: 192.168.0.2 + api_token_id: ansible + api_token_secret: "{{ proxmox_token_secret }}" + + name: "{{ vm_hostname }}" + state: current + ignore_errors: true + register: vm_status + + +- name: Create a new VM with minimal options only if it doesn't exist + when: vm_status is failed or 'does not exist in cluster' in vm_status.msg + ansible.builtin.include_tasks: create_vm.yaml + +- name: Start the VM only if needed + when: '"does not exist in cluster" in vm_status.msg or vm_status.status != "running"' + ansible.builtin.include_tasks: start_vm.yaml + diff --git a/roles/deploy_vm_on_proxmox/tasks/start_vm.yaml b/roles/deploy_vm_on_proxmox/tasks/start_vm.yaml new file mode 100644 index 0000000..455bf6f --- /dev/null +++ b/roles/deploy_vm_on_proxmox/tasks/start_vm.yaml @@ -0,0 +1,22 @@ +--- + +- name: Make sure the VM has started + become: false + community.proxmox.proxmox_kvm: + validate_certs: false + node: proxmox-server + api_user: root@pam + api_host: 192.168.0.2 + api_token_id: ansible + api_token_secret: "{{ proxmox_token_secret }}" + + name: "{{ vm_hostname }}" + state: started + +- name: Sleep for 120 seconds to ensure that Proxmox has cloned the VM + become: false + ansible.builtin.wait_for: + timeout: 120 + delegate_to: localhost + changed_when: false + diff --git a/roles/basic_postinstall/files/hardened_ssh.conf b/roles/harden_ssh/files/hardened_ssh.conf similarity index 100% rename from roles/basic_postinstall/files/hardened_ssh.conf rename to roles/harden_ssh/files/hardened_ssh.conf diff --git a/roles/basic_postinstall/files/hardened_sshd.conf b/roles/harden_ssh/files/hardened_sshd.conf similarity index 98% rename from roles/basic_postinstall/files/hardened_sshd.conf rename to roles/harden_ssh/files/hardened_sshd.conf index 21f4436..498fad4 100644 --- a/roles/basic_postinstall/files/hardened_sshd.conf +++ b/roles/harden_ssh/files/hardened_sshd.conf @@ -2,7 +2,7 @@ PubkeyAuthentication yes AuthorizedKeysFile .ssh/authorized_keys PasswordAuthentication no KbdInteractiveAuthentication no -UsePAM no +UsePAM yes # Disable password authentication — keys only PasswordAuthentication no ChallengeResponseAuthentication no @@ -26,4 +26,4 @@ MaxSessions 3 # Use modern key exchange and ciphers, prioritize post-quantum algorithms (mlkem and sntrup) KexAlgorithms mlkem768x25519-sha256,sntrup761x25519-sha512,sntrup761x25519-sha512@openssh.com,curve25519-sha256,curve25519-sha256@libssh.org Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com -MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com \ No newline at end of file +MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com diff --git a/roles/harden_ssh/handlers/main.yaml b/roles/harden_ssh/handlers/main.yaml new file mode 100644 index 0000000..11f7fa4 --- /dev/null +++ b/roles/harden_ssh/handlers/main.yaml @@ -0,0 +1,13 @@ +--- + +- name: Restart ssh-server Debian + ansible.builtin.service: + name: sshd + state: restarted + changed_when: false # It's just a handler, no need to increase 'changed' counter + +- name: Restart ssh-server Ubuntu + ansible.builtin.service: + name: ssh + state: restarted + changed_when: false diff --git a/roles/basic_postinstall/tasks/harden_ssh.yaml b/roles/harden_ssh/tasks/main.yaml similarity index 58% rename from roles/basic_postinstall/tasks/harden_ssh.yaml rename to roles/harden_ssh/tasks/main.yaml index a1486dd..76d5ef0 100644 --- a/roles/basic_postinstall/tasks/harden_ssh.yaml +++ b/roles/harden_ssh/tasks/main.yaml @@ -6,6 +6,7 @@ dest: /etc/ssh/sshd_config.d/hardened_sshd.conf mode: u=rw,g=r,o=r when: ansible_facts['distribution'] == 'Ubuntu' + notify: Restart ssh-server Ubuntu - name: Configure ssh-server daemon ansible.builtin.copy: @@ -13,6 +14,7 @@ dest: /etc/ssh/sshd_config.d/hardened_sshd.conf mode: u=rw,g=r,o=r when: ansible_facts['distribution'] == 'Debian' + notify: Restart ssh-server Debian - name: Configure ssh client remote_user: ansible @@ -21,16 +23,16 @@ dest: /etc/ssh/ssh_config.d/hardened_ssh.conf mode: u=rw,g=r,o=r -- name: Restart ssh-server Debian - remote_user: ansible - ansible.builtin.service: - name: sshd - state: restarted - when: ansible_facts['distribution'] == 'Debian' - -- name: Restart ssh-server Ubuntu - remote_user: ansible - ansible.builtin.service: - name: ssh - state: restarted - when: ansible_facts['distribution'] == 'Ubuntu' + #- name: Restart ssh-server Debian + # remote_user: ansible + # ansible.builtin.service: + # name: sshd + # state: restarted + # when: ansible_facts['distribution'] == 'Debian' + # + #- name: Restart ssh-server Ubuntu + # remote_user: ansible + # ansible.builtin.service: + # name: ssh + # state: restarted + # when: ansible_facts['distribution'] == 'Ubuntu' diff --git a/roles/basic_postinstall/files/.vimrc b/roles/human_admin_user/files/.vimrc similarity index 100% rename from roles/basic_postinstall/files/.vimrc rename to roles/human_admin_user/files/.vimrc diff --git a/roles/human_admin_user/files/.zshrc b/roles/human_admin_user/files/.zshrc new file mode 100644 index 0000000..8b5db1a --- /dev/null +++ b/roles/human_admin_user/files/.zshrc @@ -0,0 +1,13 @@ +export PATH=$HOME/bin:$HOME/.local/bin:/usr/local/bin:/home/max/soft/gnu_linux:$PATH +# Path to your Oh My Zsh installation. +export ZSH="$HOME/.oh-my-zsh" +# GTK theme +export GTK_THEME=Adwaita-dark +# ZSH theme +ZSH_THEME="gnzh" +# OMZ updates +zstyle ':omz:update' mode auto # update automatically without asking +zstyle ':omz:update' frequency 7 + + +source $ZSH/oh-my-zsh.sh diff --git a/roles/basic_postinstall/files/install_omz.sh b/roles/human_admin_user/files/install_omz.sh similarity index 100% rename from roles/basic_postinstall/files/install_omz.sh rename to roles/human_admin_user/files/install_omz.sh diff --git a/roles/basic_postinstall/tasks/create_new_user.yaml b/roles/human_admin_user/tasks/main.yaml similarity index 70% rename from roles/basic_postinstall/tasks/create_new_user.yaml rename to roles/human_admin_user/tasks/main.yaml index 8ba891b..3391a6f 100644 --- a/roles/basic_postinstall/tasks/create_new_user.yaml +++ b/roles/human_admin_user/tasks/main.yaml @@ -2,7 +2,7 @@ - name: Create a new user with a password, set shell remote_user: ansible ansible.builtin.user: - name: max + name: "{{ human_admin_user }}" groups: sshusers,sudo password: "{{ user_passwd_hash }}" shell: /bin/zsh @@ -10,7 +10,7 @@ - name: Set authorized key taken from file remote_user: ansible ansible.posix.authorized_key: - user: max + user: "{{ human_admin_user }}" state: present key: "{{ lookup('file', lookup('env', 'HOME') + '/.ssh/ansible_key.pub') }}" @@ -18,34 +18,34 @@ remote_user: ansible ansible.builtin.copy: src: "{{ role_path }}/files/install_omz.sh" - dest: /home/max/install_omz.sh - owner: max - group: max + dest: "/home/{{ human_admin_user }}/install_omz.sh" + owner: "{{ human_admin_user }}" + group: "{{ human_admin_user }}" mode: u=rwx,g=r,o-rwx # WARNING: UNPRIVILEGED USER (not ansible) COMMANDS - name: Install oh my zsh - remote_user: max - become: false - ansible.builtin.command: /home/max/install_omz.sh + remote_user: "{{ human_admin_user }}" + ansible.builtin.command: "/home/{{ human_admin_user }}/install_omz.sh" changed_when: true + vars: - name: Configure oh my zsh, by pushing the config file remote_user: ansible ansible.builtin.copy: src: "{{ role_path }}/files/.zshrc" - dest: /home/max/.zshrc - owner: max - group: max + dest: "/home/{{ human_admin_user }}/.zshrc" + owner: "{{ human_admin_user }}" + group: "{{ human_admin_user }}" mode: u=rw,g=r,o-rwx - name: Configure vim, by pushing the config remote_user: ansible ansible.builtin.copy: src: "{{ role_path }}/files/.vimrc" - dest: /home/max/.vimrc - owner: max - group: max + dest: "/home/{{ human_admin_user }}/.vimrc" + owner: "{{ human_admin_user }}" + group: "{{ human_admin_user }}" mode: u=rw,g=r,o-rwx @@ -54,13 +54,13 @@ - name: Set authorized key taken from file remote_user: ansible ansible.posix.authorized_key: - user: max + user: "{{ human_admin_user }}" state: absent key: "{{ lookup('file', lookup('env', 'HOME') + '/.ssh/ansible_key.pub') }}" - name: Set authorized key taken from file remote_user: ansible ansible.posix.authorized_key: - user: max + user: "{{ human_admin_user }}" state: present key: "{{ lookup('file', lookup('env', 'HOME') + '/.ssh/max_regular_key.pub') }}" diff --git a/roles/update_configs/files/.vimrc b/roles/update_configs/files/.vimrc new file mode 100644 index 0000000..70d5a79 --- /dev/null +++ b/roles/update_configs/files/.vimrc @@ -0,0 +1,16 @@ +set number +set tabstop=2 +" Disable compatibility with vi which can cause unexpected issues. +set nocompatible + +" Enable type file detection. Vim will be able to try to detect the type of file in use. +filetype on + +" Enable plugins and load plugin for the detected file type. +filetype plugin on + +" Load an indent file for the detected file type. +filetype indent on + +" Turn syntax highlighting on. +syntax on diff --git a/roles/update_configs/files/.zshrc b/roles/update_configs/files/.zshrc new file mode 100644 index 0000000..8b5db1a --- /dev/null +++ b/roles/update_configs/files/.zshrc @@ -0,0 +1,13 @@ +export PATH=$HOME/bin:$HOME/.local/bin:/usr/local/bin:/home/max/soft/gnu_linux:$PATH +# Path to your Oh My Zsh installation. +export ZSH="$HOME/.oh-my-zsh" +# GTK theme +export GTK_THEME=Adwaita-dark +# ZSH theme +ZSH_THEME="gnzh" +# OMZ updates +zstyle ':omz:update' mode auto # update automatically without asking +zstyle ':omz:update' frequency 7 + + +source $ZSH/oh-my-zsh.sh diff --git a/roles/update_configs/files/nvim_config/init.lua b/roles/update_configs/files/nvim_config/init.lua new file mode 100644 index 0000000..77c10eb --- /dev/null +++ b/roles/update_configs/files/nvim_config/init.lua @@ -0,0 +1,2 @@ +require("config.lazy") +require("options") diff --git a/roles/update_configs/files/nvim_config/lua/config/lazy.lua b/roles/update_configs/files/nvim_config/lua/config/lazy.lua new file mode 100644 index 0000000..f5ee74c --- /dev/null +++ b/roles/update_configs/files/nvim_config/lua/config/lazy.lua @@ -0,0 +1,35 @@ +-- Bootstrap lazy.nvim +local lazypath = vim.fn.stdpath("data") .. "/lazy/lazy.nvim" +if not (vim.uv or vim.loop).fs_stat(lazypath) then + local lazyrepo = "https://github.com/folke/lazy.nvim.git" + local out = vim.fn.system({ "git", "clone", "--filter=blob:none", "--branch=stable", lazyrepo, lazypath }) + if vim.v.shell_error ~= 0 then + vim.api.nvim_echo({ + { "Failed to clone lazy.nvim:\n", "ErrorMsg" }, + { out, "WarningMsg" }, + { "\nPress any key to exit..." }, + }, true, {}) + vim.fn.getchar() + os.exit(1) + end +end +vim.opt.rtp:prepend(lazypath) + +-- Make sure to setup `mapleader` and `maplocalleader` before +-- loading lazy.nvim so that mappings are correct. +-- This is also a good place to setup other settings (vim.opt) +vim.g.mapleader = " " +vim.g.maplocalleader = "\\" + +-- Setup lazy.nvim +require("lazy").setup({ + spec = { + -- import your plugins + { import = "plugins" }, + }, + -- Configure any other settings here. See the documentation for more details. + -- colorscheme that will be used when installing plugins. + install = { colorscheme = { "habamax" } }, + -- automatically check for plugin updates + checker = { enabled = true }, +}) diff --git a/roles/update_configs/files/nvim_config/lua/options.lua b/roles/update_configs/files/nvim_config/lua/options.lua new file mode 100644 index 0000000..ea06b72 --- /dev/null +++ b/roles/update_configs/files/nvim_config/lua/options.lua @@ -0,0 +1,44 @@ +-- Use OSC52 only when we are in an SSH session +-- Without this part clipboard via SSH doesn't work properly +-- But if don't use SSH (X11 or Wayland session) then this part would only mess things up +if vim.env.SSH_CLIENT or vim.env.SSH_TTY then + vim.g.clipboard = { + name = "OSC52", + copy = { + ["+"] = require("vim.ui.clipboard.osc52").copy("+"), + ["*"] = require("vim.ui.clipboard.osc52").copy("*"), + }, + paste = { + ["+"] = require("vim.ui.clipboard.osc52").paste("+"), + ["*"] = require("vim.ui.clipboard.osc52").paste("*"), + }, + } +end + +vim.opt.clipboard = "unnamedplus" + + +vim.opt.completeopt = {'menu', 'menuone', 'noselect'} + +-- Tab +vim.opt.tabstop = 2 -- number of visual spaces per TAB +vim.opt.softtabstop = 2 -- number of spacesin tab when editing +vim.opt.shiftwidth = 2 -- insert 2 spaces on a tab +vim.opt.expandtab = true -- tabs are spaces, mainly because of python + +-- UI config +vim.opt.number = true -- show absolute number +vim.opt.cursorline = true -- highlight cursor line underneath the cursor horizontally +vim.opt.splitbelow = true -- open new vertical split bottom +vim.opt.splitright = true -- open new horizontal splits right +vim.opt.termguicolors = true -- enable 24-bit RGB color in the TUI + +-- Searching +vim.opt.incsearch = true -- search as characters are entered +vim.opt.hlsearch = true -- do (not) highlight matches +vim.opt.ignorecase = true -- ignore case in searches by default +vim.opt.smartcase = true -- but make it case sensitive if an uppercase is entered + +-- Code folding +vim.opt.foldmethod = "indent" + diff --git a/roles/update_configs/files/nvim_config/lua/plugins/autosave.lua b/roles/update_configs/files/nvim_config/lua/plugins/autosave.lua new file mode 100644 index 0000000..cc8172d --- /dev/null +++ b/roles/update_configs/files/nvim_config/lua/plugins/autosave.lua @@ -0,0 +1,15 @@ +return { + "okuuva/auto-save.nvim", + cmd = "ASToggle", -- optional for lazy loading on command + event = { "InsertLeave", "TextChanged" }, -- optional for lazy loading on trigger events + opts = { + -- your config goes here + -- or just leave it empty :) + }, + keys = { + { "sa", ":ASToggle", desc = "Toggle auto-save" }, + }, + config = function() + require("auto-save").setup { enabled = true } + end, +} diff --git a/roles/update_configs/files/nvim_config/lua/plugins/colorscheme.lua b/roles/update_configs/files/nvim_config/lua/plugins/colorscheme.lua new file mode 100644 index 0000000..b549fc7 --- /dev/null +++ b/roles/update_configs/files/nvim_config/lua/plugins/colorscheme.lua @@ -0,0 +1,66 @@ +return { + -- the colorscheme should be available when starting Neovim + { + 'ribru17/bamboo.nvim', + lazy = false, + priority = 1000, + config = function() + require('bamboo').setup { + -- optional configuration here + } + require('bamboo').load() + end, + }, + + -- I have a separate config.mappings file where I require which-key. + -- With lazy the plugin will be automatically loaded when it is required somewhere + { "folke/which-key.nvim", lazy = true }, + + { + "dstein64/vim-startuptime", + -- lazy-load on a command + cmd = "StartupTime", + -- init is called during startup. Configuration for vim plugins typically should be set in an init function + init = function() + vim.g.startuptime_tries = 10 + end, + }, + + { + "hrsh7th/nvim-cmp", + -- load cmp on InsertEnter + event = "InsertEnter", + -- these dependencies will only be loaded when cmp loads + -- dependencies are always lazy-loaded unless specified otherwise + dependencies = { + "hrsh7th/cmp-nvim-lsp", + "hrsh7th/cmp-buffer", + }, + config = function() + -- ... + end, + }, + + -- if some code requires a module from an unloaded plugin, it will be automatically loaded. + -- So for api plugins like devicons, we can always set lazy=true + { "nvim-tree/nvim-web-devicons", lazy = true }, + + -- you can use the VeryLazy event for things that can + -- load later and are not important for the initial UI + { "stevearc/dressing.nvim", event = "VeryLazy" }, + + { + "Wansmer/treesj", + keys = { + { "J", "TSJToggle", desc = "Join Toggle" }, + }, + opts = { use_default_keymaps = false, max_join_length = 150 }, + }, + + { + "monaqa/dial.nvim", + -- lazy-load on keys + -- mode is `n` by default. For more advanced options, check the section on key mappings + keys = { "", { "", mode = "n" } }, + }, +} diff --git a/roles/update_configs/files/ranger_config/commands.py b/roles/update_configs/files/ranger_config/commands.py new file mode 100644 index 0000000..97b7909 --- /dev/null +++ b/roles/update_configs/files/ranger_config/commands.py @@ -0,0 +1,62 @@ +# This is a sample commands.py. You can add your own commands here. +# +# Please refer to commands_full.py for all the default commands and a complete +# documentation. Do NOT add them all here, or you may end up with defunct +# commands when upgrading ranger. + +# A simple command for demonstration purposes follows. +# ----------------------------------------------------------------------------- + +from __future__ import (absolute_import, division, print_function) + +# You can import any python module as needed. +import os + +# You always need to import ranger.api.commands here to get the Command class: +from ranger.api.commands import Command + + +# Any class that is a subclass of "Command" will be integrated into ranger as a +# command. Try typing ":my_edit" in ranger! +class my_edit(Command): + # The so-called doc-string of the class will be visible in the built-in + # help that is accessible by typing "?c" inside ranger. + """:my_edit + + A sample command for demonstration purposes that opens a file in an editor. + """ + + # The execute method is called when you run this command in ranger. + def execute(self): + # self.arg(1) is the first (space-separated) argument to the function. + # This way you can write ":my_edit somefilename". + if self.arg(1): + # self.rest(1) contains self.arg(1) and everything that follows + target_filename = self.rest(1) + else: + # self.fm is a ranger.core.filemanager.FileManager object and gives + # you access to internals of ranger. + # self.fm.thisfile is a ranger.container.file.File object and is a + # reference to the currently selected file. + target_filename = self.fm.thisfile.path + + # This is a generic function to print text in ranger. + self.fm.notify("Let's edit the file " + target_filename + "!") + + # Using bad=True in fm.notify allows you to print error messages: + if not os.path.exists(target_filename): + self.fm.notify("The given file does not exist!", bad=True) + return + + # This executes a function from ranger.core.acitons, a module with a + # variety of subroutines that can help you construct commands. + # Check out the source, or run "pydoc ranger.core.actions" for a list. + self.fm.edit_file(target_filename) + + # The tab method is called when you press tab, and should return a list of + # suggestions that the user will tab through. + # tabnum is 1 for and -1 for by default + def tab(self, tabnum): + # This is a generic tab-completion function that iterates through the + # content of the current directory. + return self._tab_directory_content() diff --git a/roles/update_configs/files/ranger_config/commands_full.py b/roles/update_configs/files/ranger_config/commands_full.py new file mode 100644 index 0000000..5defa67 --- /dev/null +++ b/roles/update_configs/files/ranger_config/commands_full.py @@ -0,0 +1,1993 @@ +# -*- coding: utf-8 -*- +# This file is part of ranger, the console file manager. +# This configuration file is licensed under the same terms as ranger. +# =================================================================== +# +# NOTE: If you copied this file to /etc/ranger/commands_full.py or +# ~/.config/ranger/commands_full.py, then it will NOT be loaded by ranger, +# and only serve as a reference. +# +# =================================================================== +# This file contains ranger's commands. +# It's all in python; lines beginning with # are comments. +# +# Note that additional commands are automatically generated from the methods +# of the class ranger.core.actions.Actions. +# +# You can customize commands in the files /etc/ranger/commands.py (system-wide) +# and ~/.config/ranger/commands.py (per user). +# They have the same syntax as this file. In fact, you can just copy this +# file to ~/.config/ranger/commands_full.py with +# `ranger --copy-config=commands_full' and make your modifications, don't +# forget to rename it to commands.py. You can also use +# `ranger --copy-config=commands' to copy a short sample commands.py that +# has everything you need to get started. +# But make sure you update your configs when you update ranger. +# +# =================================================================== +# Every class defined here which is a subclass of `Command' will be used as a +# command in ranger. Several methods are defined to interface with ranger: +# execute(): called when the command is executed. +# cancel(): called when closing the console. +# tab(tabnum): called when is pressed. +# quick(): called after each keypress. +# +# tab() argument tabnum is 1 for and -1 for by default +# +# The return values for tab() can be either: +# None: There is no tab completion +# A string: Change the console to this string +# A list/tuple/generator: cycle through every item in it +# +# The return value for quick() can be: +# False: Nothing happens +# True: Execute the command afterwards +# +# The return value for execute() and cancel() doesn't matter. +# +# =================================================================== +# Commands have certain attributes and methods that facilitate parsing of +# the arguments: +# +# self.line: The whole line that was written in the console. +# self.args: A list of all (space-separated) arguments to the command. +# self.quantifier: If this command was mapped to the key "X" and +# the user pressed 6X, self.quantifier will be 6. +# self.arg(n): The n-th argument, or an empty string if it doesn't exist. +# self.rest(n): The n-th argument plus everything that followed. For example, +# if the command was "search foo bar a b c", rest(2) will be "bar a b c" +# self.start(n): Anything before the n-th argument. For example, if the +# command was "search foo bar a b c", start(2) will be "search foo" +# +# =================================================================== +# And this is a little reference for common ranger functions and objects: +# +# self.fm: A reference to the "fm" object which contains most information +# about ranger. +# self.fm.notify(string): Print the given string on the screen. +# self.fm.notify(string, bad=True): Print the given string in RED. +# self.fm.reload_cwd(): Reload the current working directory. +# self.fm.thisdir: The current working directory. (A File object.) +# self.fm.thisfile: The current file. (A File object too.) +# self.fm.thistab.get_selection(): A list of all selected files. +# self.fm.execute_console(string): Execute the string as a ranger command. +# self.fm.open_console(string): Open the console with the given string +# already typed in for you. +# self.fm.move(direction): Moves the cursor in the given direction, which +# can be something like down=3, up=5, right=1, left=1, to=6, ... +# +# File objects (for example self.fm.thisfile) have these useful attributes and +# methods: +# +# tfile.path: The path to the file. +# tfile.basename: The base name only. +# tfile.load_content(): Force a loading of the directories content (which +# obviously works with directories only) +# tfile.is_directory: True/False depending on whether it's a directory. +# +# For advanced commands it is unavoidable to dive a bit into the source code +# of ranger. +# =================================================================== + +from __future__ import (absolute_import, division, print_function) + +from collections import deque +import os +import re + +from ranger.api.commands import Command + + +class alias(Command): + """:alias + + Copies the oldcommand as newcommand. + """ + + context = 'browser' + resolve_macros = False + + def execute(self): + if not self.arg(1) or not self.arg(2): + self.fm.notify('Syntax: alias ', bad=True) + return + + self.fm.commands.alias(self.arg(1), self.rest(2)) + + +class echo(Command): + """:echo + + Display the text in the statusbar. + """ + + def execute(self): + self.fm.notify(self.rest(1)) + + +class cd(Command): + """:cd [-r] + + The cd command changes the directory. + If the path is a file, selects that file. + The command 'cd -' is equivalent to typing ``. + Using the option "-r" will get you to the real path. + """ + + def execute(self): + if self.arg(1) == '-r': + self.shift() + destination = os.path.realpath(self.rest(1)) + if os.path.isfile(destination): + self.fm.select_file(destination) + return + else: + destination = self.rest(1) + + if not destination: + destination = '~' + + if destination == '-': + self.fm.enter_bookmark('`') + else: + self.fm.cd(destination) + + def _tab_args(self): + # dest must be rest because path could contain spaces + if self.arg(1) == '-r': + start = self.start(2) + dest = self.rest(2) + else: + start = self.start(1) + dest = self.rest(1) + + if dest: + head, tail = os.path.split(os.path.expanduser(dest)) + if head: + dest_exp = os.path.join(os.path.normpath(head), tail) + else: + dest_exp = tail + else: + dest_exp = '' + return (start, dest_exp, os.path.join(self.fm.thisdir.path, dest_exp), + dest.endswith(os.path.sep)) + + @staticmethod + def _tab_paths(dest, dest_abs, ends_with_sep): + if not dest: + try: + return next(os.walk(dest_abs))[1], dest_abs + except (OSError, StopIteration): + return [], '' + + if ends_with_sep: + try: + return [os.path.join(dest, path) for path in next(os.walk(dest_abs))[1]], '' + except (OSError, StopIteration): + return [], '' + + return None, None + + def _tab_match(self, path_user, path_file): + if self.fm.settings.cd_tab_case == 'insensitive': + path_user = path_user.lower() + path_file = path_file.lower() + elif self.fm.settings.cd_tab_case == 'smart' and path_user.islower(): + path_file = path_file.lower() + return path_file.startswith(path_user) + + def _tab_normal(self, dest, dest_abs): + dest_dir = os.path.dirname(dest) + dest_base = os.path.basename(dest) + + try: + dirnames = next(os.walk(os.path.dirname(dest_abs)))[1] + except (OSError, StopIteration): + return [], '' + + return [os.path.join(dest_dir, d) for d in dirnames if self._tab_match(dest_base, d)], '' + + def _tab_fuzzy_match(self, basepath, tokens): + """ Find directories matching tokens recursively """ + if not tokens: + tokens = [''] + paths = [basepath] + while True: + token = tokens.pop() + matches = [] + for path in paths: + try: + directories = next(os.walk(path))[1] + except (OSError, StopIteration): + continue + matches += [os.path.join(path, d) for d in directories + if self._tab_match(token, d)] + if not tokens or not matches: + return matches + paths = matches + + return None + + def _tab_fuzzy(self, dest, dest_abs): + tokens = [] + basepath = dest_abs + while True: + basepath_old = basepath + basepath, token = os.path.split(basepath) + if basepath == basepath_old: + break + if os.path.isdir(basepath_old) and not token.startswith('.'): + basepath = basepath_old + break + tokens.append(token) + + paths = self._tab_fuzzy_match(basepath, tokens) + if not os.path.isabs(dest): + paths_rel = self.fm.thisdir.path + paths = [os.path.relpath(os.path.join(basepath, path), paths_rel) + for path in paths] + else: + paths_rel = '' + return paths, paths_rel + + def tab(self, tabnum): + from os.path import sep + + start, dest, dest_abs, ends_with_sep = self._tab_args() + + paths, paths_rel = self._tab_paths(dest, dest_abs, ends_with_sep) + if paths is None: + if self.fm.settings.cd_tab_fuzzy: + paths, paths_rel = self._tab_fuzzy(dest, dest_abs) + else: + paths, paths_rel = self._tab_normal(dest, dest_abs) + + paths.sort() + + if self.fm.settings.cd_bookmarks: + paths[0:0] = [ + os.path.relpath(v.path, paths_rel) if paths_rel else v.path + for v in self.fm.bookmarks.dct.values() for path in paths + if v.path.startswith(os.path.join(paths_rel, path) + sep) + ] + + if not paths: + return None + if len(paths) == 1: + return start + paths[0] + sep + return [start + dirname + sep for dirname in paths] + + +class chain(Command): + """:chain ; ; ... + + Calls multiple commands at once, separated by semicolons. + """ + resolve_macros = False + + def execute(self): + if not self.rest(1).strip(): + self.fm.notify('Syntax: chain ; ; ...', bad=True) + return + for command in [s.strip() for s in self.rest(1).split(";")]: + self.fm.execute_console(command) + + +class shell(Command): + escape_macros_for_shell = True + + def execute(self): + if self.arg(1) and self.arg(1)[0] == '-': + flags = self.arg(1)[1:] + command = self.rest(2) + else: + flags = '' + command = self.rest(1) + + if command: + self.fm.execute_command(command, flags=flags) + + def tab(self, tabnum): + from ranger.ext.get_executables import get_executables + if self.arg(1) and self.arg(1)[0] == '-': + command = self.rest(2) + else: + command = self.rest(1) + start = self.line[0:len(self.line) - len(command)] + + try: + position_of_last_space = command.rindex(" ") + except ValueError: + return (start + program + ' ' for program + in get_executables() if program.startswith(command)) + if position_of_last_space == len(command) - 1: + selection = self.fm.thistab.get_selection() + if len(selection) == 1: + return self.line + selection[0].shell_escaped_basename + ' ' + return self.line + '%s ' + + before_word, start_of_word = self.line.rsplit(' ', 1) + return (before_word + ' ' + file.shell_escaped_basename + for file in self.fm.thisdir.files or [] + if file.shell_escaped_basename.startswith(start_of_word)) + + +class open_with(Command): + + def execute(self): + app, flags, mode = self._get_app_flags_mode(self.rest(1)) + self.fm.execute_file( + files=[f for f in self.fm.thistab.get_selection()], + app=app, + flags=flags, + mode=mode) + + def tab(self, tabnum): + return self._tab_through_executables() + + def _get_app_flags_mode(self, string): # pylint: disable=too-many-branches,too-many-statements + """Extracts the application, flags and mode from a string. + + examples: + "mplayer f 1" => ("mplayer", "f", 1) + "atool 4" => ("atool", "", 4) + "p" => ("", "p", 0) + "" => None + """ + + app = '' + flags = '' + mode = 0 + split = string.split() + + if len(split) == 1: + part = split[0] + if self._is_app(part): + app = part + elif self._is_flags(part): + flags = part + elif self._is_mode(part): + mode = part + + elif len(split) == 2: + part0 = split[0] + part1 = split[1] + + if self._is_app(part0): + app = part0 + if self._is_flags(part1): + flags = part1 + elif self._is_mode(part1): + mode = part1 + elif self._is_flags(part0): + flags = part0 + if self._is_mode(part1): + mode = part1 + elif self._is_mode(part0): + mode = part0 + if self._is_flags(part1): + flags = part1 + + elif len(split) >= 3: + part0 = split[0] + part1 = split[1] + part2 = split[2] + + if self._is_app(part0): + app = part0 + if self._is_flags(part1): + flags = part1 + if self._is_mode(part2): + mode = part2 + elif self._is_mode(part1): + mode = part1 + if self._is_flags(part2): + flags = part2 + elif self._is_flags(part0): + flags = part0 + if self._is_mode(part1): + mode = part1 + elif self._is_mode(part0): + mode = part0 + if self._is_flags(part1): + flags = part1 + + return app, flags, int(mode) + + def _is_app(self, arg): + return not self._is_flags(arg) and not arg.isdigit() + + @staticmethod + def _is_flags(arg): + from ranger.core.runner import ALLOWED_FLAGS + return all(x in ALLOWED_FLAGS for x in arg) + + @staticmethod + def _is_mode(arg): + return all(x in '0123456789' for x in arg) + + +class set_(Command): + """:set