[{"content":"Files Ansible Config Ansible config file: ansible.cgf\n[defaults] # Define default path to inventory file inventory = /path/to/hosts [ssh_connections] # Speed up ansible commands (don’t know whyn to check) pipelining = true Hosts The Ansible hosts file is where targets and some parameters are specified.\n[myhosts] 10.0.0.12 [myhosts:vars] # Connect with SSH and Password ansible_connection=ssh ansible_port=1212 ansible_user=myUser ansible_password=myPassword # Connect with SSH and Private Key ansible_connection=ssh ansible_port=1212 ansible_user=myUser ansible_ssh_private_key_file=/path/to/private/key # Connect to Cisco Device (probably more config is needed) ansible_connection=network_cli\t# Cisco ansible_network_os=ios #Cisco ansible_port=1212 Variables A file to specify variables: myVars.yml\n--- myVar: myValue username: myUser packages: - neofetch - htop Task File used to define little units of tasks (myTask.yml), that can be imported in playbooks. The goal here is modularity.\n- name: Update Debian Packages apt: update_cache: yes upgrade: yes - name: Install Package package: name: neofetch state: latest Playbook File that specify tasks to run on hosts: myPlaybook.yml\n--- - hosts: all become: yes - import_playbook: playbooks/base_clock.yml roles: - myRole tasks: - import_tasks: myTask.yml - name: Install Package package: name: neofetch state: latest Playbook Structures Debug - name: Print a simple statement debug: msg: \u0026#34;This is the value: {{ my_var }}\u0026#34; Condition - name: Run the command if \u0026#34;epic\u0026#34; or \u0026#34;monumental\u0026#34; is true ansible.builtin.shell: echo \u0026#34;This certainly is epic!\u0026#34; when: epic or monumental | bool - name: Run the command if \u0026#34;epic\u0026#34; is false ansible.builtin.shell: echo \u0026#34;This certainly isn\u0026#39;t epic!\u0026#34; when: not epic Loops - name: Loop package: name: \u0026#34;{{ item }}\u0026#34; state: latest with_items: - neofetch - htop - name: Loop (same as above but different syntax) package: name: \u0026#34;{{ item }}\u0026#34; state: latest loop: - neofetch - htop - name: Loop with Kev Value Variables ansible.builtin.user: name: \u0026#34;{{ item.name }}\u0026#34; state: present groups: \u0026#34;{{ item.groups }}\u0026#34; loop: - { name: \u0026#39;user1\u0026#39;, groups: \u0026#39;wheel\u0026#39; } - { name: \u0026#39;user2\u0026#39;, groups: \u0026#39;root\u0026#39; } Register Save task output in a variable.\n- name: Register example shell: \u0026#34;find /somedir/*.txt\u0026#34; register: find_output Notify \u0026amp; Handlers tasks: -name: Task that notify (\u0026#34;call\u0026#34;) the handler lineinfile: dest: /etc/ssh/sshd_config regexp: \u0026#34;^#PasswordAuthentication yes\u0026#34; line: \u0026#34;PasswordAuthentication no\u0026#34; notify: Restart SSH daemon handlers: - name: Restart SSH daemon service: name: sshd state: restarted Ansible Facts Ansible Facts are information about the target that can be used in conditions. https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html#commonly-used-facts\nOS and Distribution ansible_facts['os_family']\nOS Family (ex: RedHat, Debian, ...).\nansible_facts['distribution']\nOS Distribution (ex: RedHat can be RedHat, CentOS, Fedora, ..., and Debian can be Debian, Ubuntu, Kali, ...).\nansible_facts['distribution_major_version']\nOS major version.\n","permalink":"https://devops.kaldei.com/iac/ansible-basics/","summary":"A note about the basics of Ansible (Files and Structures).","title":"Ansible Basics"},{"content":"Commands Ansible ansible all -a \u0026quot;whoami\u0026quot;\nExecute command on all hosts specified in inventory file.\nansible all -m ping\nExecute a module on all hosts.\nansible all -m ansible.builtin.setup -a \u0026quot;filter=ansible_os_family\u0026quot;\nReturn the ansible_os_family Ansible fact.\nPlaybook ansible-playbook myPlaybook.yml\nExecute a playbook.\nInventory ansible-inventory -i myHostsFile --list\nList hosts in the inventory.\nansible-inventory -i myHostsFile --list --yaml --output myHostsFile.yml\nConvert inventory file format form INI to YAML.\nVault ansible-vault create secret.yml\nCreate a secure file (secured by password) to store secrets.\nansible-vault edit secret.yml\nEdit the secure file.\nFlags Variables -e ansible_python_interpreter=/usr/bin/python3\nSet additional variable.\nInventory -i myHostsFile\nSpecify inventory file to use.\n-i \u0026quot;192.168.1.1,\u0026quot;\nSpecify a host inline.\n-i \u0026quot;localhost,\u0026quot; --connection=local\nRun on localhost.\nUser -u myUser\nSpecify the user to use for remote connection.\n--become\nUse sudo when executing commands.\nPasswords -k\nPrompt user to enter SSH password (--ask-pass).\n-K\nPrompt user to enter Become password (--ask-become-pass).\n-J\nPrompt user to enter Secure Variables's Vault password (--ask-vault-pass).\nMisc -C\nDry run, show expected output of playbook (--check).\n-D\nShow details of the changes (--diff).\n","permalink":"https://devops.kaldei.com/iac/ansible-cli/","summary":"A note about the Ansible CLI.","title":"Ansible CLI"},{"content":"System Update - name: Update packages (Fedora) dnf: name: \u0026#34;*\u0026#34; state: latest - name: Update packages (Debian) apt: update_cache: yes upgrade: yes Install Packages -name: Install packages package: name: - neofetch - htop state: latest Restart Service -name: Restart SSH daemon service: name: sshd state: restarted Files Replace Line in a File -name: Disable SSH password auth lineinfile: dest: /etc/ssh/sshd_config regexp: \u0026#34;^#PasswordAuthentication yes\u0026#34; line: \u0026#34;PasswordAuthentication no\u0026#34; Copy File - name: Install Vault service file ansible.builtin.copy: src: ../config_files/vault/vault.service dest: /etc/systemd/system/vault.service owner: vault group: vault mode: \u0026#39;0660\u0026#39;\t- name: Install GitLab config file ansible.builtin.copy: dest: /etc/gitlab/gitlab.rb owner: root group: root mode: \u0026#39;0600\u0026#39; content : | external_url \u0026#39;https://{{ inventory_hostname }}\u0026#39; letsencrypt[\u0026#39;enable\u0026#39;] = true Services Disable SSH -name: Diable SSH password auth lineinfile: dest: /etc/ssh/sshd_config regexp: \u0026#34;^#PasswordAuthentication yes\u0026#34; line: \u0026#34;PasswordAuthentication no\u0026#34; notify: Restart SSH daemon handlers: - name: Restart SSH daemon service: name: sshd state: restarted Docker - name: Pull Docker Image docker_image: name: ubuntu - name: Build Docker Image (Deprecated?) docker_image: path: /path/to/Dockerfile name: myImageName - name: Create/Start Docker Container docker_container: name: myContainerName image: myImage container_default_behavior: no_defaults state: started ports: - \u0026#34;80:80\u0026#34; tty: true detach: true","permalink":"https://devops.kaldei.com/iac/ansible-modules/","summary":"A note about the Ansible Modules.","title":"Ansible Modules"},{"content":"S3 Basis import boto3 s3_client = boto3.client(\u0026#39;s3\u0026#39;) Object Get Object (JSON) response = s3_client.get_object(Bucket = \u0026#39;myBucketName\u0026#39;, Key = \u0026#39;myFile.txt\u0026#39;) fileContent = json.loads(response[\u0026#39;Body\u0026#39;].read()) Put Object (JSON) s3_client.put_object(Bucket = \u0026#39;myBucketName\u0026#39;, Key = \u0026#39;myFile.txt\u0026#39;, Body = json.dumps(\u0026#39;{...}\u0026#39;), ContentType = \u0026#39;application/json\u0026#39;) DynamoDB Basis import boto3 dynamodb_client = boto3.client(\u0026#39;dynamodb\u0026#39;) Query response = dynamodb_client.query( TableName = \u0026#34;tableName\u0026#34;, # Use when atribute is a reserved word, contains dot or begins with number ExpressionAttributeName = { \u0026#39;#myAttribute\u0026#39;: \u0026#39;myAttributeName\u0026#39; }, # Attribute to recieve when reading (kind of SELECT column) ProjectionExpression = \u0026#34;#myAttribute\u0026#34; # Same as ExpressionAttributeName but for values in used in comparaison ExpressionAttributeValues = { \u0026#39;:myNumberMax\u0026#39;: 12 }, # Condition for the query (kind of WHERE condition) KeyConditionExpression = Key(\u0026#39;#myAttribute\u0026#39;).gt(\u0026#39;:myNumberMax\u0026#39;) ) # All Items items = response[\u0026#39;Items\u0026#39;] # Specific Item items = response[\u0026#39;Items\u0026#39;][0][\u0026#39;myCategory\u0026#39;][\u0026#39;S\u0026#39;] SSM Basis import boto3 ssm_client = boto3.client(\u0026#34;ssm\u0026#34;) Parameter Get Parameter response = ssm_client.get_parameter(Name=\u0026#39;myParameterName\u0026#39;) parameterValue = response[\u0026#39;Parameter\u0026#39;][\u0026#39;Value\u0026#39;] Put Parameter ssm_client.put_parameter(Name=\u0026#34;myParameterName\u0026#34;, Value=\u0026#34;myValue\u0026#34;, Type=\u0026#39;String\u0026#39;, Overwrite=True) Security Hub Basis import boto3 ssm_securityhub = boto3.client(\u0026#39;securityhub\u0026#39;) Controls List Security Control IDs paginator = securityhub.get_paginator(\u0026#39;list_security_control_definitions\u0026#39;) controlsIds = paginator.paginate().search(\u0026#34;SecurityControlDefinitions[].SecurityControlId\u0026#34;) Alternative to boto3 (aws-requests-auth) Example import requests from aws_requests_auth.aws_auth import AWSRequestsAuth auth = AWSRequestsAuth(aws_access_key=\u0026#39;MY_ACCESS_KEY\u0026#39;, aws_secret_access_key=\u0026#39;MY_SECRET_KEY\u0026#39;, aws_host=\u0026#39;MY_AWS_API_HOST\u0026#39;, aws_region=\u0026#39;us-east-1\u0026#39;, aws_service=\u0026#39;execute-api\u0026#39;) response = requests.get(\u0026#39;https://dqf7ti8g66.execute-api.us-east-1.amazonaws.com/api/\u0026#39;, auth=auth) print(response.content)","permalink":"https://devops.kaldei.com/cloud/aws-boto3/","summary":"A note about the AWS Boto3 (Python SDK).","title":"AWS Boto3"},{"content":"DVA Specific Deployment (Publishing Strategies) Requirement Service Least impact on user accessing prod Blue-Green Deployment Least impact on user accessing prod and lower cost Canary Release (small percentage test) Deployment that test on a small percentage and then deploy for all users Canary (e.g. Canary10Percent5Minutes -\u0026gt; 5 min) Deployment that deploy the same amount of users periodically Linear (e.g. Linear10PercentEvery10Minutes -\u0026gt; 50 min) ECS Rolling Update and keep same capacity during rolling Min 100%, Max 150% Deploy a configuration change with the ability to roll-back AWS AppConfig Instantly effortlessly switch traffic to a new tested Lambda Set AutoPublishAlias property Deploy new version of a Lambda but keep the ability to return to older version Use function alias with different versions Use AWS Fault Injection Simulator only on a specified region Use resource filter of a target component in the template Troubleshooting and Optimization Requirement Service ThrottlingExeption Use exponential back off (retry 1s \u0026gt; 2s \u0026gt; 4s \u0026gt; 8s \u0026gt; 16s \u0026gt; ...) 5xx errors and throttling Implement retries 4xx errors Do not implement retries Troubleshoot when getting HTTP 503 slow down response on S3 PUT or DELETE Probably due to objects having millions of versions, so S3 automatically throttles. Use Amazon S3 Inventory to create a report Signed AWS HTTP API request SigV4 (header Authorization or X-Amz-...) Application Integration SQS Requirement Service SQS need to manage message that are \u0026gt; 256KB SQS extended Library for Java Configure messages to be processed only after 5 minutes of being published in the queue Use DelaySeconds parameter Messages are processed more than once Increase Visibility Timeout (default: 30s, min: 0s, max: 12h) Consumers are polling the SQS Queue too often and are getting empty result Enable Long Polling Some messages are not processed correctly Add SQS Dead Letter Queue Multiple consumers need to receive same message form SQS SNS with SQS Fan Out Pattern SNS Requirement Service Send SNS message to certain subscribers and not others SNS Message Filtering Compute Beanstalk Requirement Service Ignoring application HTTP errors in Beanstalk Enhanced health monitoring Beanstalk deployment mode for development and test purpose Single Instance (no ASG) Beanstalk deployment mode for production purpose High Availability (ASG) Beanstalk update deployment all at the same time (fast but downtime) All at once Beanstalk update deployment by batches called buckets (no additional cost but run at below capacity) Rolling Beanstalk update deployment by batches but not running below capacity (small additional cost) Rolling with additional batches Beanstalk update deployment using a temporary ASG to confirm new version works (higher cost) Immutable Specify how the application will be deployed to the underlying instances File appspec.yml Beanstalk is free, but we pay for the infrastructure deployed by Beanstalk. We can choose between 2 Tier: Web Server Tier: Architecture with an ELB in front of an Auto Scaling Group of EC2 web servers. Worker Tier: Architecture with an SQS Queue in front of an Auto Scaling Group of EC2 workers. Beanstalk can store at most 1000 application versions. They can be removed with a Lifecycle Policy (based on time or space). Beanstalk source bundle (extension) have to respect the following rules: Folder named .ebextension (\u0026lt;500MB). Files in YAML or JSON with .config extension. Lambda Requirement Service Stop a Lambda function that recursively call itself Set function concurrent execution to 0 Improve performance of a Lambda that is CPU, network or memory bound Increase memory Lambda@Edge functions can only be created in us-east-1. SAM Requirement Service Define serverless resources in a YAML template AWS Serverless Application Model (SAM) Test a Lambda in a SAM locally Run cdk synth and sam local start-lambda commands Containers ECS Requirement Service Place tasks on the EC2 with the least available CPU or Memory (cost-effective) Binpack Placement Strategy Place task randomly on available EC2s Random Placement Strategy Spread tasks based on a specified parameter (instance ID, AZ, ...) Spread Placement Strategy Constraint to place tasks on different EC2 Constraint distinctInstance Allow tasks to access AWS resources Create an IAM role at the task level and enable ECS_ENABLE_TASK_IAM_ROLE in /etc/ecs/ecs.config The Load Balancer can only be added during the creation of a service (it can't be modified or removed). Database DynamoDB Requirement Service Use one Partition Key in a query Query Use the Partition Key and the Sort Key in a query GetItem Use multiple Partition Keys in a single query BatchGetItem Capture and store (for 24h) time ordered item modifications on a DynamoDB table DynamoDB Streams Developer Tools Code Suite Requirement Service Fully managed VCS, can contain file \u0026gt; 5GB AWS CodeCommit Service that can compile and test code AWS CodeBuild Help to troubleshoot issue in code Amazon CloudGuru X-Ray Requirement Service Trace Lambda invoked by non-instrumented service Enable Active Tracing in AWS Lambda config Filter X-Ray traces (logs) on a specific value (e.g. a user) Use Annotations (key-value pair that can be used with filters) Enable X-Ray logs on BeanStalk Add the .ebextensions/xray-daemon.config Enable X-Ray on EC2 Run X-Ray Daemon Change X-Ray Daemon listening port Use --bind flag X-Ray Default Sampling Rule 1 request/second \u0026amp; 5% of any additional request per host Security and Compliance IAM Requirement Service Tool to analyze access control policies to resources like S3 IAM Access Analyzer Report on IAM users and the status of their credentials IAM Credentials Manager \u0026amp; Governance AWS CLI Requirement Service AWS CLI credential precedence usage CLI options \u0026gt; Environment variables \u0026gt; Files in ~/.aws \u0026gt; Resource Instance profile (EC2, ECS, Lambda) CloudFormation Requirement Service Create a CloudFormation stack in multiple AWS accounts in multiple Regions CloudFormation StackSets Detect changes made to a stack resource outside of CloudFormation CloudFormation Drift Analyze upcoming changes on a stack update without executing it ChangeSets CloudWatch Requirement Service Not all data is delivered IteratorAge (age of the last records processed by functions) Monitor EC2 memory usage (RAM is not included in EC2 metrics) Use Unified CloudWatch Agent (custom metric) Collect metrics for EC2 every 5 minutes Basic Monitoring Collect metrics for EC2 every 1 minute Detailed Monitoring High Resolution Custom Metrics can be collected at minimum Every 1 second Regular alarms can be triggered Any multiple of 60 seconds High Resolution alarms can be triggered Every 10 or 30 seconds Detect unusual activity on all AWS Regions CloudTrail Insights Test a CloudWatch Alarm Use the set-alarm-state CLI command CloudWatch Metric Filters do not retroactively filter data. CloudWatch only publish metrics after the Filter has been created. ","permalink":"https://devops.kaldei.com/cloud/aws-cheat-sheet-dva-c02/","summary":"A cheat sheet to study the Developer Associate certification.","title":"AWS Cheat Sheet DVA-C02"},{"content":"SAA Specific Design Cost-Optimized Architectures Requirement Service Predictable capacity and uptime requirements Reserved Instance Sockets and cores capacity Dedicated Host Design Resilient Architectures (Disaster Recovery) Requirements Service RPO/RTO happens in real time Multi Site (Active/Active) RPO/RTO happens in minutes Warm Standby RPO/RTO happens in minutes, lower cost (RPO in seconds and RTO 5-20 min) Pilot Light RPO/RTO happens in hours Backup and Restore RPO means Recovery Point Objective, it represents the data loss. RTO means Recovery Time Objective, it represents the downtime. Analytics Service / Requirement Requirement Service SQL-based analytical queries on S3 Amazon Athena Complex queries on S3 (without copying to Redshift) Redshift Spectrum Creating data visualizations Amazon QuickSight Data intensive workload, managed cluster platform for running big data framework (Hadoop, Spark) Amazon EMR (Elastic MapReduce) Extract, Transform and Load data AWS Glue Convert files to Apache Parquet AWS Glue Capture, transform and load data from various sources in Near Real Time Kinesis Data Firehose Capture Real Time Data of GBs every second Kinesis Data Streams Capture Real Time Data for use cases like video playback Kinesis Video Stream Gather streaming data and run analysis by performing queries (SQL) Kinesis Data Analytics Kinesis Kinesis Data Streams has a data retention of up to 365 days. Kinesis Data Streams can be used as the source to Kinesis Data Firehose. Application Integration Service / Requirement Requirement Service Managing services events Amazon EventBridge SaaS integration Amazon AppFlow GraphQL serverless AWS AppSync RESTful web services (not GraphQL) API Gateway Send marketing emails SES (Simple Email Service) Migration from RabbitMQ Amazon MQ SQS SQS and SNS messages are limited to 256KB. SQS can retain messages from 1 minute to 14 days. The type of queue (Standard or FIFO) must be chosen when the queue is created. Compute EC2 Requirement Service Get Instance AMI ID from Metadata http://169.254.169.254/latest/meta-data/ami-id Get Instance Public IP from Metadata http://169.254.169.254/latest/meta-data/public-ip Instance launch type for short workloads, reliable On Demand Instances Instance launch type for short workloads that can be stopped at any time, cheaper Spot Instances Instance launch type for long workloads (minimum 1 year) Reserved Instances Instance launch type for long workloads (minimum 1 year) with flexible instances types Convertible reserved Instances Instance launch type for use cases that require no other customers use the same hardware Dedicated Instances Instance launch type for use cases that require an entire physical server (host affinity, licenses that operate at core, CPU socket level) Dedicated Hosts AMI IDs are Region specific. Containers Service / Requirement Requirement Service Running K8s on premise but use AWS-managed service for managing multiple clusters of nodes EKS Anywhere Installer Connect an EKS Anywhere Cluster to AWS EKS Connector ECS ECS Anywhere requires the installation of two agents (these agents register themselves): ECS Agent, SSM Agent. EKS Amazon EKS distribution includes open-source K8S components and few more tools on top of it. Database Service / Requirement Requirement Service Graph database, highly connected datasets Amazon Neptune Time series database for IoT Amazon Timestream HA and scalable database supporting Cassandra Amazon Keyspaces Petabyte scale database Amazon Redshift MongoDB compatible database Amazon DocumentDB Key-value NoSQL for web apps Amazon DynamoDB Database connection issues (timeout, rejection) RDS Proxy Handle write intensive traffic peak RDS Proxy Read performance issues Amazon ElastiCache Cache that support replication, HA, multi AZ failover, archival Amazon ElastiCache for Redis Cache for multi node partitioning (sharding) Amazon ElastiCache for Memcached RDS RDS only support IO1, it does not support IO2 or IO2express Storage autoscaling can be enabled on a running RDS. Enable RDS encryption: Create snapshot Copy the snapshot with encryption enabled Restore DB using encrypted snapshot Aurora Aurora is Highly Available: 2 copies of data are kept in each AZ with a minimum of 3 AZ. Aurora Serverless v2 scales compute capacity automatically based on actual usage, down to zero when not in use. DynamoDB DynamoDB is highly scalable.\nThere are 2 read types:\nQuery (using Index): I know what I'm looking for. Scan: Scan all the database to find what I'm looking for. An Index is composed of 2 keys:\nThe Partition Key is used to group the data. Data with the same Partition Key is stored together (this allows to query a \u0026quot;partition\u0026quot; in 1 query). The Sort Key is optional, it determines the way data with the same Partition Key is stored. For better performance, the keys have to be well architected in order to use Queries instead of Scanning the database.\nAWS offers the ability to add a secondary Index (warning, paid by hour).\nManagement \u0026amp; Governance Service / Requirement Requirements Service Automated deployment in multi-Account environments Control Tower Share resource with other Accounts within an Organization AWS Resource Access Manager Input custom values to the template CloudFormation Parameter Declare output value that can be imported into other stack CloudFormation Outputs Roll out package installation AWS System Manager Run Command Performance Metrics CloudWatch Capture which resource accessed an API CloudWatch Access Logging Capture user request and response, error traces CloudWatch Execution Logging Capture info about IP traffic VPC Flow Log Microservice and Serverless analyze AWS X-Ray Auditing solution to check API calls (for compliance, governance, ...) AWS CloudTrail Compliance reports for AWS resources AWS Artifact AWS Organizations SCP does not affect users or roles in the management account. Service Control Policies (SCP) are similar to IAM permissions policies, but are a feature of AWS Organizations. They can be attached to Roots, OU, or Accounts in an Organization. Migration and Transfer Service / Requirement Requirement Service Migrate Database AWS DMS (Database Migration Service) Migrate data (specify data source and an AWS managed service as a destination) AWS DataSync SFTP, FTPS or FTP and no changes to the customer’s application AWS Transfer Family Data transfer device and data processing, storage up to 8TB AWS Snowcone HDD Data transfer device and data processing, storage up to 14TB AWS Snowcone SSD Data transfer device and data processing, storage up to 80TB AWS Snowball Edge Data transfer device and data processing, storage up to 100PB AWS Snowmobile DataSync is the only option that can transfer metadata and file permissions of files. Networking Service / Requirement Requirement Service Non-full manage Access to internet NAT Instance Fully managed access to internet from private VPC for IPv4 NAT gateway Fully managed access to internet from private VPC for IPv6 Egress-only Internet Gateway Connect API Gateway to a VPC securely VPC Link VPC traffic to S3 or DynamoDB VPC Gateway Endpoint Link API endpoint in the same VPC VPC Interface Gateway AWS side of the VPN Virtual Private Gateway Customer side of the VPN Customer Gateway Add new IPs when all IPs in a VPC are used Add a secondary CIDR range to the VPC (it automatically create a route) Low latency and high throughput for high-performance computing Elastic Fabric Adapter Web content distribution Amazon CloudFront Accelerate IP traffic distribution Global Accelerator DynamoDB Table distribution for multiple region DynamoDB Global Tables Implement some logic at CDN level (e. g. resize images) Lambda@Edge VPC The default NACL in the default VPC allow all traffic in and out. Security Groups deny all in and allow all out by default. Each subnet has a single Route Table. The VPC and all its subnets are always reachable via the default localroute (it cannot be modified or removed). VPC Peering is not transitive: a VPC cannot use the NAT Gateway of a peered VPC. A VPC cannot reference the security group of a peer VPC that's in a different Region. VPC Endpoint work with Kinesis. VPC Endpoint always takes precedence (priority) over NAT Gateway or Internet Gateway. ELB ELB can only balance traffic in one region CloudFront To be able to use an ACM Certificate with CloudFront, the certificate must be requested or imported (third party) in us-eaast-1 Region. Security Identity, and Compliance Service / Requirement Requirement Service Store secrets (passwords, AMI IDs, ...), no rotation, low-cost AWS System Manager Parameter Store Store secret that require automatic rotation, specifically designed for RDS creds or API keys AWS Secrets Manager Ensure that all objects uploaded to an S3 bucket are encrypted Update policy to deny if PutObject doesn't have the x-amz-server-side-encryption header set Find and protect sensitive data from unauthorized access in S3 Amazon Macie URL filtering AWS Network Firewall Protect against DDoS attack, layer 3, 4 and 7 AWS Shield Protect against injections (SQL, XSS, ...) AWS WAF Automated vulnerability assessment service (vulnerabilities, and network exposure) AWS Inspector Intelligent threat detection service (form CloudTrail, VPC Flow Logs, DNS Query Logs) Amazon GuardDuty Investigate to identify root cause of security issue (from GuardDuty, Macie and Security Hub) Amazon Detective Serverless Service / Requirement Requirement Service Least operational overhead means Serverless Lambda function needs to be invoked by a third party via a webhook Lambda URL Lambda Lambda execution max duration is 15 min. Lambda SnapStart for Java (only Java 11 and Java 17) can improve startup performance for latency-sensitive applications by up to 10x at no extra cost with no changes to your function code. Storage Service / Requirement Requirement Service Physical drive attached to an instance Local Instance Store Network drive that can be attached to only one instance Amazon EBS (Elastic Block Storage) POSIX file system Amazon EFS (Elastic File System) High Performance Computing (HPC) Linux file system Amazon FSx for Lustre High Performance Windows file system (compatible with SMB, NTFS, AD, ...) Amazon FSx for Windows File Server High Performance ONTAP file system (compatible NFS, SMB, iSCSI) Amazon FSx for NEtApp ONTAP On premise VM that serve as a bridge to seamlessly access data stored on AWS (act kind like a NAS) AWS Storage Gateway Access data stored on S3 form on premise like an NFS or SMB compatible file share S3 File Gateway Access data stored on FSx form on premise like a Windows compatible file share (SMB, NTFS, AD) FSx File Gateway Access data stored on S3 backed by EBS snapshots from on premise a block storage (iSCI) Volume Gateway Volume Gateway where a subset of data (frequently accessed) is stored on premise Volume Gateway Cached Volume Volume Gateway where the entire data is stored on premise with a scheduled backup to S3 Volume Gateway Stored Volume Storage Gateway also exists as a hardware appliance EBS Requirement Service General purpose SSD volume that go up to 16000 IOPS EBS GP2 or GP3 (GP3 is more cost-effective) High performance SSD volume EBS IO1 or IO2 Low Cost HDD volume for throughput intensive workloads EBS ST1 Low Cost HDD volume for less frequently accessed workloads EBS SC1 EBS volumes types that can be used as boot volumes GP2, GP3, IO1, IO2 Create a fully initialized at creation volume from snapshot (eliminates latency of I/O when accessing a block for the first time) EBS Fast Snapshot Restore (FSR) Attach an EBS volume to multiple instance in the same AZ EBS Multi Attach (only IO1 and IO2) S3 Requirement Service Read the first 250 bytes of each objects in S3 Use Byte Range Fetch Increase transfer speed of S3 by transferring files through AWS Edge Location S3 Transfer Acceleration Upload object in a single operation: max 5 GB. BUT it is recommended use multipart upload when the object size is \u0026gt; 100MB.\nUpload object in parts: max 5 TB.\nA DELETE API call on an object does not delete the actual object, but places a marker on it.\nOnly the standard Amazon SQS queue is allowed as an Amazon S3 event notification destination.\nS3 website URL:\nhttp://bucket-name.s3-website.Region.amazonaws.com http://bucket-name.s3-website-Region.amazonaws.com Amazon S3 Standard stores data in a minimum of three Availability Zones.\nSSE-S3 encryption is automatically enabled on new objects stored in S3 (keys are managed by AWS).\nGlacier Flexible Retrieval:\nExpedited (1-5 min) \u0026gt; Standard (3-5 min) \u0026gt; Bulk (5 - 12 hours). If you delete, overwrite, or transition the object to a different storage class before the 90-day minimum, you are charged for 90 days. Glacier Deep Archive:\nStandard (12 hours) \u0026gt; Bulk Retrieval (within 48 hours). - If you delete, overwrite, or transition the object to a different storage class before the 180-day minimum, you are charged for 180 days. ","permalink":"https://devops.kaldei.com/cloud/aws-cheat-sheet-saa-c03/","summary":"A cheat sheet to study the Solution Architect Associate certification.","title":"AWS Cheat Sheet SAA-C03"},{"content":"SOA Specific Monitoring, Logging, and Remediation Requirement Service Create a CloudWatch alarm but without knowing expected usage CloudWatch alarm based on Anomaly Detection HTTP 502 errors from CloudFront Error in the validation of the SSL/TLS certificate on the origin server Monitor network between ECS tasks Choose awsvpc network mode and enable CloudWatch Logs on the ENI of each task A VPC Flow Log cannot be modified. Reliability and Business Continuity Requirement Service Find out if resources in an Account experienced an outage AWS Personal Health Dashboard Find out if a service in a Region had an outage AWS Service Health Dashboard Cost and Performance Optimization Requirement Service Separate costs into categories Use Cost Allocation Tags Analyze resources (EC2, EBS, ECS on Fargate, Lambda) to provide insights on how to improve performance and reduce costs AWS Compute Optimizer Compute EC2 Requirement Service Migrate an EC2 instance in another AZ Create an AMI from the instance and create a new instance from the AMI Linearly increase traffic to EC2 instance that needs time before being able to receive all the requests Configure Slow Start Mode for the Target Group Getting InsufficientInstanceCapacity error when trying to launch an EC2 instance AWS does not have enough on-demand capacity in the AZ Getting InstanceLimitExceeded error when trying to launch an EC2 instance Ask for a Quota increase Log Processes running on an EC2 instance Install Unified Cloud Agent with procstat plugin Pack instances close together in an AZ to achieve the low-latency network for HPC Cluster Placement Group Spread instances across logical partitions (using different underlying) for large distributed and replicated workloads (Hadoop, Cassandra, Kafka). Partition Placement Group Strictly places instances across distinct underlying hardware to reduce correlated failures. Spread Placement Group Move an EC2 instance in or out of a Placement Group: Stop the instance, Use CLI with modify-instance-placement, Start the instace. Lambda The maximum size of /tmp in a Lambda is 10240 MB. Databases Aurora Requirement Service Restore the DB Cluster in the same DB Cluster Aurora Backtracking (Rewind the Cluster) Restore the DB Cluster creating a new DB Cluster Point in Time Recovery Highly available database for multi-tenant workloads Aurora multi-master DB cluster The maximum number of Read Replicas for in a single Aurora Cluster is 15. Aurora Cluster Automatic Backups cannot be disabled. RDS Requirement Service Get notifications when there is a change in a database instance RDS Event \u0026amp; Event Subscription Troubleshoot performance issues on databases instances with dashboards RDS Performance Insights Auto Scaling for RDS instance can only scale up once every 6 hours. The maximum number of Read Replicas for an RDS instance is 15. It is required for the RDS database to be encrypted in order to create encrypted Read Replicas. Memcached Requirement Service Connect a fleet of EC2 to ElasticCache Memcached Memcached Auto Discovery Memcached Evictions are high Need to scale up (increase memory) or scale out (add additional node) Management and Governance CloudFormation Requirement Service Delete a CloudFormation Stack without deleting the resources Add a Retain Deletion Policy on the resources to keep AWS CloudTrail Requirement Service Ensure CloudTrail logs store in S3 haven't been modified or deleted CloudTrail Log File Integrity Validation (verify file integrity with AWS CLI) Detect unusual activity in the Account with CloudTrail enabled CloudTrail Insights AWS Config Requirement Service Evaluate compliance over time AWS Config Automatically reconfigure to match compliance AWS Config Remediation AWS Organization Requirement Service Standardize Tags in all AWS Account in an AWS Organizations AWS Organizations Tag Policies AWS System Manager Requirement Service One time patch a fleet of EC2 instances SSM Run Command Automatically patch a fleet of EC2 instances SSM Patch Manager Policy that needs to be assigned to an EC2 instance to connect via SSM AmazonSSMManagedInstanceCore Instance is not able to get SSM Parameters even with the right IAM permissions Install the SSM agent on the instance Networking and Content Delivery VPC The maximum size of CIDR in AWS VPC is /16. When creating a VPC, AWS \u0026quot;reserve\u0026quot; 5 IPs addresses (the four firsts IPs and the last one). 10.0.0.0: Network address. 10.0.0.1: Reserved by AWS for the VPC router. 10.0.0.2: Reserved by AWS for VPCs with multiple CIDR blocks, the IP address of the DNS server. 10.0.0.3: Reserved by AWS for future use. 10.0.255: Network broadcast address (broadcast is not supported in a VPC, therefore AWS reserve this address). Route 53 In order to use a Route 53 domain name with S3 Website Hosting, the bucket has to be the same as the record set in Route 53. To set an automated failover, you need to create two Routing Policy: Create a Primary Failover Routing Policy record with a Health Check Create a Secondary Failover Routing Policy Security Identity, and Compliance Cognito Requirement Service Authenticate to get tokens Cognito User Pool Use Web Identity Providers Cognito User Pool Exchange Tokens for AWS credentials (access to services) Cognitoy Identity Pools Provide guest access to a web application Cognito Identity Pools KMS Requirement Service Control Access to KMS CMK Use KMS Key Periodically rotate CMK that is in KMS Create a new Key and use Key Aliases in KMS (keep old Key to decrypt old data) Dedicated hardware module to manage encryption keys (full control over them) AWS CloudHSM CMK stands for Customer Managed Key. When Automatic Rotation is enabled on KMS CMK, the backing key is rotated every 1 year. Storage S3 Requirement Service Get insights on the optimal numbers of days to move S3 objects to different storage tiers S3 Analytics (Storage Class Analysis) Create reports on the replication and encryption status on objects in S3 S3 Inventory When multiple applications are using a bucket so it became complex to manage the bucket policy S3 Access Points It is required to enable S3 Versioning on buckets before enabling S3 Replication. It is required to enable S3 Versioning on a bucket before enabling MFA Delete. ","permalink":"https://devops.kaldei.com/cloud/aws-cheat-sheet-soa-c02/","summary":"A cheat sheet to study the SysOps Administrator Associate certification.","title":"AWS Cheat Sheet SOA-C02"},{"content":"Basis Command Structure aws serviceName commands\nGeneral structure of a command.\n--region us-east-1\nSet the region for this command (change from default).\n--no-sign-request\nAccess to public objects (no signing in).\n--profile myProfile\nSet profile ot use for this command (change from default).\nProfile Configuration https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html\nProfile configuration are stored in two files:\n~/.aws/config [default] region=eu-west-1 output=json ~/.aws/credentials [default] aws_access_key_id=[ACCESS_KEY_ID] aws_secret_access_key=[SECRET_ACCESS_KEY] aws configure list-profiles\nList created profiles.\naws configure list --profile myProfileName\nShow details for the specified profile.\naws configure --profile myProfileName\nCreate or modify a profile.\naws configure set aws_session_token MY_AWS_SESSION_TOKEN --profile myProfileName\nSet a AWS_SESSION_TOKEN (after aws configure).\naws configure sso --profile myProfileName\nCreate or modify an SSO profile.\nQuery --query 'Jobs[? WorkerType==`Standard`]'\nFilter results based on a condition.\n--query 'Jobs[].[Name,WorkerType]'\nOnly returning selected properties.\n--query 'Jobs[].{JobName:Name,WorkerType:WorkerType}' --out table\nOnly return selected properties as a table and with custom names for columns.\nIAM Basis aws sts get-access-key-info --access-key-id [MY_ACCESS_KEY_ID]\nReturn Account ID of the access key.\naws sts get-caller-identity\nReturn User ID, Account ID, and ARN of the selected profile.\n{ \u0026#34;UserId\u0026#34;: \u0026#34;AIDATAAH6Q3WAYKDXJV5B\u0026#34;, \u0026#34;Account\u0026#34;: \u0026#34;206175110892\u0026#34;, \u0026#34;Arn\u0026#34;: \u0026#34;arn:aws:iam::206175110892:user/myUserName\u0026#34; } Roles aws sts assume-role --role-arn [MY_ROLE_ARN] --role-session-name mySessionName\nReturn temporary credentials for the role.\nexport AWS_ACCESS_KEY_ID=\u0026quot;[OUTPUT_FROM_ASSUME_ROLE_COMMAND]\u0026quot; export AWS_SECRET_ACCESS_KEY=\u0026quot;[OUTPUT_FROM_ASSUME_ROLE_COMMAND]\u0026quot; export AWS_SESSION_TOKEN=\u0026quot;[OUTPUT_FROM_ASSUME_ROLE_COMMAND]\u0026quot;\nUse credentials of the assumed role.\nCognito Basis aws cognito-identity get-id --identity-pool-id [MY_IDENTOTY_POOL_ID]\nReturn the Cognito ID for the specified identity pool ID.\n{ \u0026#34;IdentityId\u0026#34;: \u0026#34;us-east-1:1b0bcc16-b32f-44c1-8f1e-14e8d4c5f7af\u0026#34; } Secret Manager List aws secretsmanager list-secrets --query \u0026quot;SecretList[].{Name:Name}\u0026quot; --out table\nList Secrets Names\nGet aws secretsmanager get-secret-value --secret-id \u0026quot;myNewValue\u0026quot;\nGet a secret value (--secret-id can be the secret name or the arn).\nUpdate aws secretsmanager update-secret --secret-id \u0026quot;my/secret/name\u0026quot; --secret-string \u0026quot;myNewValue\u0026quot;\nUpdate secret value.\naws secretsmanager update-secret --secret-id \u0026quot;my/secret/name\u0026quot; --secret-string file://myFile\nUpdate a secret value using a file.\nEC2 Basis aws ec2 describe-instances --output text --profile myProfileName\nListing all EC2 instances running within a profile.\nEKS Kubeconfig aws eks update-kubeconfig --name my-cluster\nUpdate ~/.kube/config file to be able to connect to the cluster.\nAddons aws eks describe-addon-versions --addon-name aws-ebs-csi-driver --region myRegion\nShow latest version of the addon (region is mandatory).\nECR Retag Image MANIFEST=$(aws ecr batch-get-image --repository-name myRepo --image-ids imageTag=oldTag --query 'images[].imageManifest' --output text)\nFetch the manifest of an existing image.\naws ecr put-image --repository-name myRepo --image-tag newTag --image-manifest \u0026quot;$MANIFEST\u0026quot;\nRetag an existing image without pulling/pushing it.\nLambda Basis aws lambda invoke --function-name my-lambda\nExecute a Lambda.\nS3 Create Bucket aws s3 mb s3://myBucketURL\nCreate a bucket (mb = make bucket).\nCopy aws s3 cp s3://myBucketURL/myFile ./\nCopies a bucket file to my current local directory.\naws s3 sync myFile s3://myBucketURL\nSynchronize a local file or directory to the buckets.\naws s3 sync s3://myBucketURL/myFolder /myLocalFolder\nSynchronize bucket folder to local directory.\nDelete aws s3 rm s3://myBucketURL/myPrefix/myFile\nRemove a file.\naws s3 rm --recursive s3://myBucketURL/myPrefix/\nRemove all file from the given profile.\nS3API aws s3api put-bucket-policy s3://myBucketURL myPolicyFile\nAdd policy config file to the bucket.\naws s3api put-bucket-website s3://myBucketURL myIndexFile\nSets the default file to be served when using the bucket as a static web server.\nDynamoDB Basis aws dynamodb list-tables\nList tables.\naws dynamodb describe-table --table-name my-table\nReturn information about selected table.\naws dynamodb scan --table-name my-table\nReturn items (and their attributes) stored in the selected table.\nCloudWatch Basis aws logs describe-log-streams --log-group-name my-log-group\nRetrieve information about log streams in a specific log group.\naws logs get-log-events --log-group-name my-log-group --log-stream-name some-log-stream\nRetrieve log events from a log stream in a specific log group.\nSecurity Hub Basis aws securityhub enable-security-hub --no-enable-default-standards --control-finding-generator SECURITY_CONTROL\nEnable Security Hub with no Standards enabled by default, and findings are generated based on Controls (only one finding if the controls exist in multiple Standards).\nStandards aws securityhub describe-standards\nList available Standards (packs of controls like CIS or NSIT) and whether they're enabled or not.\naws securityhub get-enabled-standards\nList enabled Standards.\naws securityhub batch-enable-standards --standards-subscription-requests '{\u0026quot;arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0\u0026quot;}'\nEnable a Standard using it's ARN.\naws securityhub describe-standards-controls --standards-subscription-arn arn:aws:securityhub:eu-west-1:123456789123:subscription/cis-aws-foundations-benchmark/v/1.2.0\nList control in a standard, and show whether they are enabled or not.\nControls aws securityhub list-security-control-definitions\nList Security Controls IDs (and description ...).\naws securityhub list-security-control-definitions --standards-arn \u0026quot;arn:aws:securityhub:us-east-1::standards/cis-aws-foundations-benchmark/v/1.4.0\u0026quot;\nList Security Controls IDs (and description ...) of the specified Standards.\naws securityhub list-standards-control-associations --security-control-id CloudTrail.1\nList Standards that cover the given Control (ControlId). This will only return Controls that belong in an enabled Standard.\naws securityhub batch-get-standards-control-associations --standards-control-association-ids [{\u0026quot;SecurityControlId\u0026quot;: \u0026quot;ACM.1\u0026quot;, \u0026quot;StandardsArn\u0026quot;: \u0026quot;arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0\u0026quot;}, ...]\nFor a given Control return associated Standards Controls (with ARNs) for the specified standard.\n","permalink":"https://devops.kaldei.com/cloud/aws-cli/","summary":"A note about the AWS CLI.","title":"AWS CLI"},{"content":"AWS Shared Responsibility Model Credit: AWS Skill Builder\nRegion, Availability Zones, Local Zones, Edge Locations Regions are independent groups of datacenters physically distant from one another. This allows fault tolerance against failures caused by natural disasters.\nAvailability Zones are datacenters physically separated but linked with a high-performance network within a Region. Each Region is composed of at least 2 Availability Zones. This allows fault tolerance against outages caused failures that may be caused by power or network failures.\nLocal Zones are \u0026quot;extensions of region\u0026quot;, they are datacenter closer to you, to reduce the latency. They are like an additional Availability Zone. It is useful when very low latency is required.\nEdge Locations are local places for the user to access data. They are datacenters specifically built for content delivery (websites). They store data temporarily (cache).\nARN An Amazon ARN is the way AWS generate a unique identifier for all resources in the AWS Cloud. It consists of multiple strings separated by colons.\nThe format is:\narn:aws:\u0026lt;service\u0026gt;:\u0026lt;region\u0026gt;:\u0026lt;account_id\u0026gt;:\u0026lt;resource_type\u0026gt;/\u0026lt;resource_name\u0026gt; Security, Identity, \u0026amp; Compliance IAM \u0026amp; STS (Security Token Service) IAM is the service used for controlling how users and programs in an AWS account can interact with the AWS API.\nCognito Amazon Cognito provides authentication, authorization, and user management for web and mobile apps. It can be configured to work with a regular user/password or with a third party identity providers that support SAML or OpenID Connect (e. g. Facebook or Google).\nThere are two services in Cognito:\nUser Pools (Authentication Service): User directories that provide sign-up and sign-in options for your app users. Returns OIDC Tokens. Free under 50000 active users per month. External Provider for federated user pool. Identity Pools (Authorization Service): Used to grant access to other AWS services. Return an STS Session (assumed IAM Role) in exchange for a token. Free to use. Secret Manager Secret Manager can store secrets and automatically rotate them.\nMacie Amazon Macie is a data security service that uses machine learning (ML) and pattern matching to discover and help protect your sensitive data.\nAWS Certificate Manager (ACM) AWS Certificate Manager\nWAF \u0026amp; Shields To create a WAF protection, it is required to first create a condition (like Geo match for example), and then create a rule using this condition. After that, create an ACL (Access Control List) with the rule previously created and associate it to the resource to protect (a Load Balancer for example).\nSummary: ACL based on a Rule using a Condition.\nNetworking and Content Delivery Route 53 Credit: Stephane Maarek\nVPC (Virtual Private Cloud) VPC stands for Virtual Private Cloud. It's Virtual Network in which to place Virtual Machines. A VPC reside in a Region (this means it is available to all Availability Zones within the Region).\nIn order to build a highly available network, it is recommended to deploy it in at least two Availability Zones.\nCloudFront (CDN) CloudFront improves performance for both cacheable content (such as images and videos) and dynamic content (such as API acceleration and dynamic site delivery).\nCDN with over 160 points of presence. Creating a distribution takes around 10-15 min.\nOnly outgoing bandwidth is charged (and CloudFront's costs around 10-15% less than S3's).\nGlobal Accelerator Global Accelerator improves performance for a wide range of applications over TCP or UDP by proxying packets at the edge to applications running in one or more AWS Regions.\nUse cases:\nGood fit for non-HTTP use cases, such as gaming (UDP), IoT (MQTT), or Voice over IP. Good for HTTP use cases that require static IP addresses. Good for HTTP use cases that required deterministic, fast regional failover. ELB (Elastic Load Balancer) ELB is a managed load balancer (by AWS). It costs more than a self-managed load balancer, but it is effortless to manage.\nELB allows \u0026quot;Sitckiness\u0026quot; (Session Affinity): a user will end up using the same instance.\nNetwork ACL vs Security Group Network ACL A NACL is bound to a Subnet. It only applies (evaluate a packet) when crossing a subnet.\nA Security group is Stateless (check very packets that cross border).\nStateless firewall Access Control In Access Control Out The Defaut Network ACL of an AWS allows all inbound and outbound traffic\nSecurity Group A Security Group is bound to an ENI (Elastic Network Interface). It applies to check if packets can reach specific instances or not:\nProtocol (UDP or TCP), Port Range, Source. The source can be another Security Group!\nA Security group is Stateful.\nStateful firewall, Deny all Inbound traffic by default, Allow all Outbound traffic by default, Can only create \u0026quot;Allow\u0026quot; rules. Compute Lightsail Little virtual servers stacks for simple websites, or development/tests environments.\nOS available : Amazon Linux, Ubuntu, Debian, FreeBSD, Windows Server Stacks available : Node.js, GitLab, LAMP, Nginx, Django, ...\nEC2 (Elastic Compute Cloud) EC2 stands for Elastic Compute Cloud. It's the same as Lightsail, but with more options and features.\nLambda (Serverless Function) AWS Lambda is a serverless function.\nBeanstalk With given code and configuration settings, Elastic Beanstalk deploys the resources necessary (EC@, QSG,ELB, RDS, ...) to perform the following tasks:\nAdjust capacity Load balancing Automatic scaling Application health monitoring Containers ECS (Elastic Container Service) Container orchestrator made by Amazon. Containers can be run on AWS Fargate (serverless), EC2 instances or ECS Anywhere (External Instance)\nTerminology:\nService: containers designed to run continuously (equivalent to a Pod in Kubernetes?). Task: a container that will execute a task and then stop. EKS (Elastic Kubernetes Service) Container orchestrator Kubernetes.\nFargate (Serverless Compute Engine) Fargate is a serverless compute engine for containers (uses ECS and EKS).\nStorage S3 (Simple Storage Service) S3 (Simple Storage Service) is a file storage service accessible via HTTP and HTTPS requests.\nIt's an object storage: when there is a change to the object, the entire file must be re-uploaded.\nEBS (Elastic Bock Store) Amazon Elastic Block Store is a service that provides block-level storage volumes that you can use with Amazon EC2 instances. If you stop or terminate an Amazon EC2 instance, all the data on the attached EBS volume remains available.\nBlock storage breaks files in small blocks: when a change is made to the file, only modified blocks are re-uploaded.\nMulti Attach EBS max to 16 instances.\nEFS (Elastic File System) EFS (Elastic File System) allows you to have multiple EC2 instances accessing data at the same time.\nAWS Backup AWS Backup is a simple and cost-effective way to protect your data by backing up your Amazon EFS file systems. Amazon EFS is natively integrated with AWS Backup.\nS3 vs EBS vs EFS S3 vs EBS S3:\nWhen using complete objects or occasional changes. EBS:\nWhen using complex read, write change functions. EBS vs EFS EBS:\nIt's a volume attached to EC2 instances. Availability Zone level resource (requires to be in the same AZ as the EC2 instances to be attached to it). EFS:\nMultiple instances can read and write at the same time. Linus file system (like NFS). It's a regional resource. Automatically scales? Database RDS (Relational Database Service) RDS stands for Relational Database Service. Available databases are: AWS Aurora (MySQL Compatible), AWS Aurora (PostgreSQL Compatible), MySQL, MariaDB, PostgreSQL, Oracle and Microsoft SQL Server.\nAmazon Aurora (Relational Database) Aurora is a cloud optimized database service from AWS (proprietary tech). Available databases are: MySQL and PostgreSQL.\nCost 20% more than RDS, but it is more efficient and comes with functionalities like:\nstorage automatically grows (10Gb to 64 TB), data replication (up to 15 replicas), backup to S3, high availability (with failover instantaneous), point-in-time recovery (Backtrack), can't ssh. Credit: Stephane Maarek\nDynamoDB (NoSQL Database) Amazon DynamoDB(opens in a new tab) is a key-value database service. It delivers single-digit millisecond performance at any scale. DynamoDB is serverless, which means that you do not have to provision, patch, or manage servers.\nAmazon Redshift (Data Warehouse) Amazon Redshift is a data warehousing service that you can use for big data analytics. It offers the ability to collect data from many sources and helps you to understand relationships and trends across your data.\nDMS (Database Migration Service) AWS DMS, allows moving data between a source database and a target database. The source and target databases can be of the same type or different types.\nThe source can be a database on premise, an EC2 or an RDS. The target can be an EC2 or an RDS.\nDuring the migration, your source database remains operational, reducing downtime for any applications that rely on the database.\nAWS Migration Hub can be used to track the progress of migrations.\nUses cases:\nDatabase migration (to the cloud). Development and test database migration (copy production database to test database). Database consolidation (migrate multiple databases into one). Continuous database replication (disaster recovery or geographic separation). Other Databases Amazon DocumentDB: a document database service that supports MongoDB workloads.\nAmazon Neptune: a graph database service. For building and running applications that work with highly connected datasets, such as recommendation engines, fraud detection, and knowledge graphs.\nAmazon QLDB (Amazon Quantum Ledger Database): a ledger database service. For reviewing a complete history of all the changes that have been made to your application data.\nAmazon Managed Blockchain: a service that can be used to create and manage blockchain networks with open-source frameworks. Blockchain is a distributed ledger system that lets multiple parties run transactions and share data without a central authority.\nAmazon ElastiCache: a service that adds caching layers on top of databases to help improve the read times of common requests. It supports two types of data stores: Redis and Memcached.\nAmazon DAX (DynamoDB Accelerator): an in-memory cache for DynamoDB. It helps improve response times from single-digit milliseconds to microseconds.\nApplication Integration SQS (Simple Queue Service) Send, store, receive messages at any volume. SQS queues are where messages are places until they are consumed.\nSQS (Simple Notification Service) Similar to SQS, but can send notification to end users (publish/subscribe mode). An SNS topic is a channel for messages to be deliverd.\nAnalytics Kinesis Collect, process, and analyze real-time data streams.\nKinesis vs SQS FIFO Kinesis Data Stream Ordering Data with Kinesis is done by distributing data in the multiple shards available resulting in a kind of FIFO.\nSQS FIFO In a SQS FIFO only one customer can be set if no Group IDs are configured.\nUsing a Group ID result in a similar approach to Kinesis. The key difference is that in order to add a customer it is necessary to add a Group ID (in Kinesis it is necessary to add shards, which cost more).\nManagement \u0026amp; Governance CloudWatch (Logs) Metrics and logs about resources. These metrics can be used to create Dashboards and Alarms.\nCloudTrail CloudTrail records API calls for your account (useful for auditing). The recorded information includes the identity of the API caller, the time of the API call, the source IP address of the API caller, ...\nTrusted Advisor Trusted Advisor gives recommendation on our AWS resources:\nCost optimization Performance Security Fault tolerance Service limits CloudFormation CloudFormation is a service to automate deployment of AWS resources. It is an IaC tool using JSON or YAML files.\nNote: In CloudFormation, all actions are resources (including actions to attach items to each other).\nService Catalog AWS Service Catalog allows you to create and manage catalogs of IT services that can be deployed within your organization.\nWith Service Catalog, you can define a standardized set of products (solutions and tools in this case) that customers can self-service provision. By creating Service Catalog products, you can control and enforce the deployment of approved and validated solutions and tools.\n","permalink":"https://devops.kaldei.com/cloud/aws-services/","summary":"A note to briefly introduce AWS services.","title":"AWS Services"},{"content":"Resources https://github.com/curl/curl HTTP Codes Mind Map - Ignitetechnologies Basis Basis curl http://my.url\nGet HTTP Content.\nFlags -s\nSilent (do not print curl info).\n-i\nShow response Headers.\n-L\nFollow redirections.\n-k\nIgnore HTTPS Errors.\n--tls-max 1.2\nSet the maximum TLS version.\n-u admin:admin\nBasic Auth (Authorization: Basic header).\n-H 'myHeader: myValue'\nSet Header.\n-X POST\nSpecifies method.\n-d\nPOST data.\n-o myFile\nSave response in a file.\nExamples GET current IPv4 curl -4 https://ifconfig.me\nReturn current public IPv4 (-4 force using IPv4 for hostname resolution).\nGET request with JWT curl 'http://[TARGET_HOST]/api/book/1' \\\n-H 'Authorization: Bearer [JWT_TOKEN]'\nExample GET request with JWT.\nPOST request with JSON content curl 'http://[TARGET_HOST]/api/auth/login' \\\n-X POST \\\n-H \u0026quot;Content-Type: application/json\u0026quot; \\\n-d '{\u0026quot;username\u0026quot;:\u0026quot;User\u0026quot;,\u0026quot;password\u0026quot;:\u0026quot;P@ssw0rd\u0026quot;}'\nExample POST request with JSON content.\n","permalink":"https://devops.kaldei.com/cli/curl/","summary":"A command line tool and library for transferring data with URL syntax.","title":"CURL"},{"content":"Administration Context docker context ls\nShow created contexts (list of Docker sockets).\ndocker context use myRemoteContext\nSwitch to a Docker context.\ndocker context create myRemoteContext --docker \u0026quot;host=ssh://my.remote.docker.ip\u0026quot;\nCreate a remote context (connect via ssh to execute Docker commands).\nMonitoring docker ps\nShow running containers.\ndocker ps -a\nShow all containers.\ndocker stats\nStats about running containers.\ndocker volume ls\nShow volumes.\nSystem docker system df\nShow used host disk space (images, containers, volumes and build cache).\ndocker system prune\nRemove stopped containers and unused volumes.\ndocker system prune -a\nRemove stopped containers, unused volumes and images.\nImages Basis docker images\nShow images locally available.\ndocker pull registryImage\nPull image from an image registry.\ndocker pull registryImage:imageTag\nPull specific tag of an image an image registry.\ndocker rmi myImage\nRemove the local image.\nCreate docker build path/to/Dockerfile -t myUser/myImageName:myVersion\nCreate an image from a Dockerfile.\ndocker diff myContainer\nShow differences between an image and a container created from this image.\ndocker commit myContainer myNewImage\nSave the current state of a container into a new image.\ndocker save myImage \u0026gt; /path/myImage.tar\nExport an image (archive).\ndocker load -i /path/myImage.tar\nImport an image (form archive).\nInspect docker image history myImage\nShow image layers.\ndocker image history myImage --no-trunc --format json | tac | jq -r '.CreatedBy'\nShow image layers commands.\nContainers Flags --name myContainer\nGive a name to the container.\n-d\nDetached Mode (run in background).\n-it\nKeep stdin open (to use it like a shell).\n--rm\nRemove the container when it is stopped.\n-p 1212:1212\nMap ports (host:container).\n-v /myHostFolder:/myContainerFolder\nMap a folder between the host and the container.\n--read-only\nMakes the container's root file system read-only.\n--security-opt=no-new-privileges\nPrevents processes inside the container from gaining new privileges during execution (security measure against privilege escalation).\n--cap-drop=ALL\nStart the container without capabilities.\n--cap-add=SYS_NICE\nCapability for scheduling (required for GPU scheduling?).\n--cpus=2\nSet CPU limit.\n--gpu all\nSet GPU limits (syntax allows for more detailed control than CPU).\n--memory=4g\nSet RAM limit.\n--memory-swap=4g\nSet Swap limit.\nCreate docker create myImage\nCreate a new container.\ndocker run myImage myCommand\nRun a command in new container.\nManage docker rename myContainer myContainerNewName\nRename container.\ndocker start myContainer\nStart the container.\ndocker pause myContainer\nPause the container.\ndocker stop myContainer\nStop the container.\ndocker rm myContainer\nRemove the container.\nInteract docker exec myCommand myContainer\nRun the command in a running container.\ndocker exec -it /bin/bash myContainer\nRun Bash in interactive mode in a running container.\ndocker cp myFile.txt myContainer:/path/to/destination\nCopy a file from host to the container.\ndocker cp myContainer:/path/to/source myFile.txt\nCopy a file form the container to the host.\nInspect docker inspect myContainer | jq .[].State\nGet container state.\ndocker inspect myContainer | jq .[].Config\nGet container config (Entreypoint, WorkingDir, Env, ...).\ndocker inspect myContainer | jq .[].Mounts\nGet container mounts.\ndocker inspect myContainer | jq .[].NetworkSettings\nGet container networks (Networks and Ports).\nTips Exec in Containers Without Shell CONTAINER_PID=$(docker inspect -f '{{.State.Pid}}' myContainer)\nGet container's PID.\nnsenter --target $CONTAINER_PID --user --pid --network --ipc /bin/sh\nRun a command entering user, pid, network and ipc namespaces.\nAccess Container File System CONTAINER_PID=$(docker inspect -f '{{.State.Pid}}' myContainer)\nGet container's PID.\nnsenter --target $CONTAINER_PID --mount ls /\nRun ls in the container's file system.\nMERGED_LAYER_PATH=$(docker inspect -f '{{.GraphDriver.Data.MergedDir}}' myContainer)\nGet Merge Layer path (unified filesystem of the containers).\nls $MERGED_LAYER_PATH\nRun ls in the container's file system.\n","permalink":"https://devops.kaldei.com/containers/docker-cli/","summary":"A note about the Docker CLI.","title":"Docker CLI"},{"content":"Resources https://github.com/docker/awesome-compose CLI Basis docker-compose up -f /pathToComposeFiles\nCreate a network and run containers in it.\ndocker-compose stop -f /pathToComposeFiles\nStop containers.\ndocker-compose down -f /pathToComposeFiles\nRemove network and containers.\nCompose File Examples Network version: \u0026#34;3\u0026#34; services: myContainer1: image: nginx ports: - \u0026#34;8081:80\u0026#34; restart: always\t# Restart at machine startup. myContainer2: image: nginx ports: - \u0026#34;8082:80\u0026#34; restart: always\t# Restart at machine startup. networks:\t# Put the container in the network ipv4_address: 192.168.168.0.100 networks: myNetwork: ipam:\t# IP Address Managment driver: default # Bridge config: - subnet: \u0026#34;192.168.168.0.0/24\u0026#34;","permalink":"https://devops.kaldei.com/containers/docker-compose/","summary":"A tool for defining and running multi-container applications.","title":"Docker Compose"},{"content":"Resources Learn Git Branching Oh Shit Git Workflows Git - Stéphane Robert The difference between the working directory and the repository - Anna Skoulikari How Git Actually Works - LeanThatStack Concepts HEAD HEAD is the location in the commit tree. It's a \u0026quot;pointer\u0026quot; to a commit. HEAD can be moved using git checkout. If HEAD points to a raw commit (not a branch), the branch is in detachedstate. If new commits are created from a detached points, those commits will be orphaned (and they will be deleted by garbage collector). Areas Working Directory: Actual files on the disk. Staging Area (also called Index): Area to prepare which file will be included in next commit. Local Repository: The database of commits. Remote Repository: Remote save of the Repository. Stash: Space to temporary save changes without having to commit. Simplified Workflows:\nWorking Directory \u0026gt; git add \u0026gt; Staging Area \u0026gt; git commit \u0026gt; Local Repository \u0026gt; git push \u0026gt; Remote Repository Working Directory \u0026gt; git stash \u0026gt; Stash Basis Workflow git init\nCreate git repository (local).\ngit status\nShow status files (modified, added, removed, staged, ...).\ngit add myFile\nStage myFile (prepare for commit).\ngit add -A\nStage all files (including untracked/new ones).\ngit commit -S -m \u0026quot;Commit Message\u0026quot;\nCreate a commit (-S to sign the commit and -m to set the commit's message).\ngit commit --amend\nModify last commit.\nWarning: will create a conflict if the commit was previously pushed to remote.\nStash git stash list\nList stashes.\ngit stash save myStashName\nPut changes in a side working directory for later use.\ngit stash apply stashIndex\nAdd stashed code back into the code.\ngit stash drop stashIndex\nDelete stash.\nCommit History git show myCommit\nDisplay commit information.\ngit log\nShow commit history.\ngit log --pretty=fuller\nCommit history with more info (Committer name, commit date,...).\ngit log --show-signature\nShow signature information on commit history.\ngit log --oneline --graph --decorate\nShow commit history with graph.\ngit log -p\nShows difference between commits.\ngit reflog\nShow recent local history with commit IDs.\nNote: reflog entries expires (90d for reachable commits, 30d for orphaned commits).\nBranching Branch git branch\nShow local branches.\ngit branch -r\nShow remote branches.\ngit branch myBranch\nCreate new branch.\ngit merge myBranch\nMerge myBranch to current branch.\nCheckout git checkout HEAD^\nMoves HEAD to 1 commit back from current HEAD.\ngit checkout HEAD^^^\nMoves HEAD to 3 commits back from current HEAD.\ngit checkout HEAD~12\nMoves HEAD to 12 commits back from current HEAD.\ngit checkout HEAD^\nMoves HEAD to 1 commit back from current HEAD in the 1st parent of a merge.\ngit checkout HEAD^2\nMoves HEAD to 1 commit back from current HEAD in the 2nd parent of a merge.\ngit checkout myBranch\nMove HEAD to last commit of myBranch.\ngit checkout myBranch^\nMove HEAD to penultimate commit of myBranch.\nTag git tag myTag\nCreate a tag.\ngit tag -d myTag\ngit push --delete origin myTag\nDelete a tag.\nRemote Remote Workflow git clone [REPO_URL]\nClone remote repo to local machine.\ngit push\nPush commits to remote repo.\ngit fetch\nGet last changes from the remote repo.\ngit pull\nGet last changes from the remote repo and merge them with local.\nRemote Branch git remote -v\nDisplay Remote Branches and their URL.\ngit remote add origin git@github.com:myUser/myRepo.git\nAdd Remote Branch (origin is the name of the branch, it can be anything).\ngit remote set-url origin git@github.com:myUser/myOtherRepo.git\nUpdate URL for the Remote Branch.\ngit remote remove origin\nRemove Remote Branch.\ngit branch myBranch --set-upstream-to=origin/myBranch\nSet Upstream for a Branch.\nGit Config Basis git config --list\nParameters list.\ngit config user.name\nDisplay a parameter (user.name here).\ngit config --global user.name myName\nChange parameter value.\nCredentials Helpers git config --global credential.helper cache\nSave credentials in memory.\ngit config --global credential.helper store\nSave credentials in plaintext in ~/.git-credentials (less secure).\ngit config --global credential.helper osxkeychain\nSave credentials in MacOS Keychain (more secure).\ngit config --global credential.helper manager\nSave credentials in Windows Keychain (more secure).\nCommit Signing git config --global gpg.format ssh\nSet SSH key format to sign commits.\ngit config --global user.signingkey /path/to/my/public/key\nSpecify the public key to used for signing commits (the private key has to be configured in GitHub settings.\nSSL git config --global http.sslBackend schannel\nSwitch SSL Backend from OpenSSL (default) to Schannel (Windows built-in). This is useful in an organization with enterprise-managed certificates.\nGit Tools Submodule git submodule status\nShow if any submodules are configured in the current repo. A submodule is a repo in a repo.\ngit add submodule [SUBMODULE_REPO_URL]\nAdd a submodule . Use --recurse-submodule to include submodule when using git commands.\ngit submodule update --init --remote --rebase\nUpdate submodule version (use the last commit of the submodule).\ngit clone --recurse-submodule\nClone repo and it's submodules.\nLFS git count-objects -vH\nShow size of the repo. Not directly related to LFS but cans be usefull.\ngit lfs ls-files -s\nShow LFS files and their size on current branch.\ngit lfs ls-files -a\nShow LFS files on the full history (after a file is uploaded on LFS it will still exist on the remote storage even if its reference is removed in the HEAD.\ngit lfs install\ngit lfs track \u0026quot;*.png\u0026quot;\ngit add .gitattributes\nAdd LFS to the repo (will track all new PNG files added to the repo).\ngit lfs status\nShow staged files.\ngit lfs untrack \u0026quot;*.png\u0026quot;\ngit add --renormalize .\ngit commit -m 'Restore file that were previously in LFS'\ngit push\nRevert files from being on LFS. Do not remove .gitattributes, it is required to run git add --renormalize.\nRewrite History Reset / Revert git reset --soft HEAD^\nMoves current branch to one commit back and puts changes in Staging.\nWarning: will create a conflict if the commit was previously pushed to remote.\ngit reset --mixed HEAD^\nMoves current branch to one commit back and puts changes from the commit in Working Directory.\nWarning: will create a conflict if the commit was previously pushed to remote.\ngit reset --hard HEAD^\nMoves current branch to one commit back and discard all changes (this also removes any unstaged files that were not part of the commit).\nWarning: will create a conflict if the commit was previously pushed to remote.\ngit revert HEAD^\nCreate new commit that undo last commit changes.\nCherry Pick git cherry-pick commit1 commit12 ccommit7\nAdd commits from other branches after HEAD.\nRebase git rebase myBranch\nReplays current branch commits on myBranch (from their last common parent).\ngit rebase --root\nReplays all commits from the root of the repository.\ngit rebase --root --committer-date-is-author-date\nReplays all commits from the root and keep original commit date.\ngit rebase -i myBranch\nUse rebase in interactive mode. Select commits to keep (pick), to modify (edit), squash commits (squash), reorder commits, ...\ngit rebase --continue\nContinue to the next commit marked for edition.\ngit commit --amend --no-edit\nMake your modification to the code and then issue this command to modify the commit (--no-edit to keep the name of the old commit).\ngit rebase --abort\nAbort the rebase (useful in case of issues).\ngit rebase -i $(git merge-base myBranch HEAD)\nRebase from the point it diverged from myBranch (first commit on current branch). Useful for squashing commit before a merge.\n","permalink":"https://devops.kaldei.com/cli/git/","summary":"A free and open source distributed version control system.","title":"GIT"},{"content":"Basis Flags --commit-filter\nSpecify a custom filter that processes each commit individually.\n--env-filter\nSpecify a custom filter that to modify environment variables for each commit (e.g. GIT_AUTHOR_NAME or GIT_AUTHOR_EMAIL.).\n--tag-name-filter cat\nPreserve existing tag name.\n-- --all\nApply the filter to all branches and tags in the repository.\n--force\nRequire when the repo has already been pushed to a remote server.\nApply Filter on all Branches # Checkout all branches locally git branch -r | grep -v \u0026#39;\\-\u0026gt;\u0026#39; | while read remote; do git branch --track \u0026#34;${remote#origin/}\u0026#34; \u0026#34;$remote\u0026#34;; done # Apply filter git filter-branch ... # Push all branches to origin git push --all origin --force Examples Sets Committer info to Author info This is useful because Committer and Author info can be different when modifying history (e.g. Committer date).\ngit filter-branch --force --tag-name-filter cat --commit-filter \u0026#39; GIT_COMMITTER_NAME=$GIT_AUTHOR_NAME; GIT_COMMITTER_EMAIL=$GIT_AUTHOR_EMAIL; GIT_COMMITTER_DATE=$GIT_AUTHOR_DATE; git commit-tree \u0026#34;$@\u0026#34;;\u0026#39; -- --all Change Commits Author git filter-branch --force --tag-name-filter cat --commit-filter \u0026#39; if [ \u0026#34;$GIT_AUTHOR_NAME\u0026#34; = \u0026#34;myOldName\u0026#34; ]; then GIT_AUTHOR_NAME=\u0026#34;myNewName\u0026#34;; GIT_AUTHOR_EMAIL=\u0026#34;myEmail@email.com\u0026#34;; GIT_COMMITTER_NAME=\u0026#34;myNewName\u0026#34;; GIT_COMMITTER_EMAIL=\u0026#34;myEmail@email.com\u0026#34;; GIT_COMMITTER_DATE=$GIT_AUTHOR_DATE; git commit-tree \u0026#34;$@\u0026#34;; else git commit-tree \u0026#34;$@\u0026#34;; fi\u0026#39; -- --all Sign old Commits of a specific Author git filter-branch --force --tag-name-filter cat --commit-filter \u0026#39; if [ \u0026#34;$GIT_AUTHOR_NAME\u0026#34; = \u0026#34;myName\u0026#34; ]; then git commit-tree -S \u0026#34;$@\u0026#34;; else git commit-tree \u0026#34;$@\u0026#34;; fi\u0026#39; -- --all Remove Commits older than 90 days git filter-branch --force --commit-filter \u0026#39; if [ \u0026#34;$(date -d \u0026#34;$(git show -s --format=%ci $GIT_COMMIT)\u0026#34; +%s)\u0026#34; -gt \u0026#34;$(date -d\u0026#34;90 days ago\u0026#34; +%s)\u0026#34; ]; then git commit-tree \u0026#34;$@\u0026#34;; else skip_commit \u0026#34;$@\u0026#34;; fi\u0026#39; -- --all","permalink":"https://devops.kaldei.com/cli/git-filter-branch/","summary":"A Git command for advanced history rewriting.","title":"GIT FILTER-BRANCH"},{"content":"Workflow Syntax On on: # Triggered manually (run button) workflow_dispatch: # Triggered on pull request pull_request: # Triggered on push on specified branch push: branchs: - my-branch # Triggered by another workflow workflow_run: workflows: - myWorkflow Checkout - name: Checkout code uses: actions/checkout@v3 with: submodules: recursive # Fetch repo submodules lfs: true # Fetch LFS data Variables github User github.actor: name of the use the triggered the workflow. Ref github.ref_name: branch name (warning: don't work in PR triggered workflow see github.head_ref). github.head_ref: PR source branch name. github.head_ref: PR target branch name. GitHub CLI Workflow gh workflow run my-test-workflow.yml \\\n--ref my-test-branch \\\n--field my_input_1=12 \\\n--field my_input_2=bla\nRun a workflow that doesn't exist on the default branch yes (needs to have on: push: branchs set).\n","permalink":"https://devops.kaldei.com/scripting/github-actions/","summary":"A note about GitHub's automation tool.","title":"GitHub Actions"},{"content":"Repositories Explore helm repo list\nShow registered Charts repos.\nhelm repo update\nGrab latest Charts available in registered repos.\nhelm search repo my-keyword\nLook for Charts in registered repositories based on a keyword.\nAdd helm repo add stable https://charts.helm.sh/stable\nAdd the standard stable repo to local Helm config.\nhelm repo add my-repo-name https://my-repo-address/\nAdd a repo to the local Helm config.\nCharts Pull helm pull my-chart\nDownload the chart locally.\nValues helm show values my-chart\nDisplay values for a chart added locally.\nhelm show values oci://my-registry/my-chart\nDisplay values for a remote chart.\nValidate helm lint /path/to/folder\nVerify chart syntax and best practices.\nhelm template --debug /path/to/folder\nTest chart template rendering locally.\nhelm install --dry-run --debug /path/to/folder --values /path/to/valuesFiles.yml\nTest chart template rendering locally and check potentials conflitcs on the cluster.\nReleases List helm list -A\nList installed releases on the kube cluster.\nhelm list --pending\nList pending releases.\nhelm list --uninstalling\nList releases being uninstalled.\nInstall helm install my-release-name my-chart -n my-namespace\nInstall helm release.\n--version 1.2.3\nInstall specific version.\n--debug\nInstall helm release with debug logs.\n--wait\nWait that resources to be in ready state to mark the relesase as successful.\n--create-namespace\nCreate namespace if do not exist.\n--generate-name\nGenerate a name for the deployment (don't specify my-release-name).\nUpgrade helm upgrade my-release-name my-chart -n my-namespace\nUpgrade helm release.\nUninstall helm uninstall my-release-name -n my-namespace\nUninstall helm release.\n","permalink":"https://devops.kaldei.com/containers/helm-cli/","summary":"A tool for managing Charts (packages of pre-configured Kubernetes resources).","title":"Helm CLI"},{"content":"Resources Try jq online: https://jqplay.org/# Interactive JSON filter : https://github.com/ynqa/jnv Basis Usage cat myFile.json | jq\njq myFile.json\njq \u0026lt;\u0026lt;\u0026lt; { \u0026quot;player\u0026quot;: { \u0026quot;name\u0026quot;: \u0026quot;apple\u0026quot;, \u0026quot;color\u0026quot;: \u0026quot;blue\u0026quot; } }\nFlags -r\nOutput raw strings (without the quotes).\nFilter Filter JSON Array [\u0026#34;myPlayer1\u0026#34;, \u0026#34;myPlayer2\u0026#34;, \u0026#34;myPlayer3\u0026#34;] jq '.[]' myFile.json\nReturn elements line by line (without [ ]).\njq '.[2]' myFile.json\nReturn an element by its ID.\njq '.[2:12]' myFile.json\nReturn a subset of elements.\nFilter JSON Object { \u0026#34;player\u0026#34;: { \u0026#34;name\u0026#34;: \u0026#34;myPlayer\u0026#34;, \u0026#34;color\u0026#34;: \u0026#34;blue\u0026#34; } } jq '.player.name' myFile.json\nReturn the a property.\njq '.player | {name,color}' myFile.json\nReturn the multiple properties.\njq '.player | select(.player_class == \u0026quot;knight\u0026quot;)' myFile.json\nReturn player that have the property player_class set to knight.\njq '.player | keys' myFile.json\nReturn the keys of player (name and color).\njq '.player | length' myFile.json\nReturn the length of player (here the number of properties is 2).\n","permalink":"https://devops.kaldei.com/cli/jq/","summary":"A lightweight and flexible JSON processor.","title":"JQ"},{"content":"Config CLI Setup alias k=kubectl\nCreate alias for kubectl.\nsource \u0026lt;(kubectl completion bash)\nEnable kubectl completion.\nKubeconfig kubectl cluster-info --kubeconfig /path/to/kubeconfig.yml\nShow info about the specifed Kubeconfig file.\nexport KUBECONFIG=/path/to/kubeconfig.yml\nSet the Kubeconfig file to use.\nkubectl config view\nShow configured clusters in the current Kubeconfig file.\nAWS EKS Kubeconfig aws eks update-kubeconfig --name my-cluster\nUpdate ~/.kube/config file to be able to connect to the cluster.\nContext kubectl -context my-context-name get pods\nSpecify context in a command.\nkubectl -n my-namespace get pods\nSpecify namespace in a command.\nkubectl config use-context myContext\nSwitch to the specify context.\nkubectl config current-context\nShow current context.\nkubectl config view --minify | grep namespace:\nShow current namespace (other method).\nkubectl config set-context --current --namespace myNameSpace\nSet namespace for current context.\nkubectl config unset current-context\nUnset current context.\nBasis Apply kubectl apply -f myResoyrce.yml\nCreate or update a resource from a YAML file.\nkubectl apply -f /myResourcesFolder\nCreate or update multiple resources from YAML files in a folder (requires --- at the beginning of files).\nGet kubectl get nodes\nList nodes.\nkubectl get services\nReturn active services.\nkubectl get ingress\nShow ingress.\nkubectl get deployments\nShow deployments.\nkubectl get pods\nShow Pods.\nDescribe kubectl describes nodes myNode\nReturn information about the resource.\nDelete kubectl delete pod my-pod Delete Pod.\nkubectl delete pod my-pod --now\nDelete Pod now.\nkubectl delete pod my-pod --force\nForce delete the Pod.\nkubectl delete pods --all\nDelete all Pods.\nkubectl delete -f myDeployment.yml\nDelete deployment from file.\nOuput kubectl get pods -o wide\nOuput more info (e.g. for Pods, outputs Node and IP).\nkubectl get deployment -o custom-columns=DEPLOYMENT:.metadata.name,CONTAINER_IMAGE:.spec.template.spec.containers[].image,READY_REPLICAS:.status.readyReplicas --sort-by=.metadata.name\nCustom column output.\nkubectl get pods my-pod -o yaml\nOuput yaml configuration.\nkubectl get nodes -o jsonpath='{.items[*].status.nodeInfo.osImage}'\nJsonpath output.\nFlags --no-headers\nDo not output headers.\n--as myUser\nExecute command as another user.\nMonitoring Metrics Server Note: For the Metrics API to be available, metrics-server has to be installed on the cluster.\nkubectl top nodes\nShow nodes metrics.\nkubectl top pods\nShow pods metrics.\nMetadata Labels kubectl label node myNode myLabel=myValue\nAdd a Label to a Node.\nkubectl label node myNode myLabel-\nRemove a Label from a Node.\nLabel Selector kubectl get pod --selector myLablel=myValue\nGet pods based on label value.\nkubectl get pod --selector myLablel=myValue,myLablel2=myValue2\nGet pods based on multiple labels values.\nNodes Unschedule kubectl cordon myNode\nMark the node as unschedulable (node status will be Ready,SchedulingDisabled).\nkubectl uncordon myNode\nMark the node as schedulable (node status will be Ready).\nkubectl drain myNode\nMark the node as unschedulable and empty it from its pods.\nkubectl drain myNode --ignore-daemonsets\nAllows to drain node even if there are DaemonSets (DaemonSets can create Pods that ignore unschedulable taints).\nkubectl drain myNode --force\nAllows to drain node even if there are Pods that are not declared in the controller (Pods not in Job, DaemonSet, ReplicationSet, ...). Warning: pods that are not in the controller will be lost.\nTaint kubectl taint node myNode myKey=myValue:myEffect\nAdd a Taint to a Node (effect can be NoExecute, NoSchedule, PreferNoSchedule...)\nkubectl taint node myNode myKey=myValue:myEffect-\nRemove Taint from a Node.\nPods Static Pods To create a static pod, look at the path configured for staticPodPath in /var/lib/kubelet/config.yaml. Then create a manifest and move it in the specified path.\nkubectl describe pods -A | grep \u0026quot;Controlled By\u0026quot;\nFind Static Pods (they are the ones controlled by Node/controlplane).\nRun (imperative) kubectl run webserver --image=httpd\nStart a Pod (Appache in this case).\nkubectl run webserver --image=httpd --port=80\nStart a Pod and set the containerPort spec.\nLike EXPOSE it is for information purpose only: it does not actually publish the port.\nkubectl run my-pod --image=myImage -- /bin/bash\nRun a Pod that overrides the CMD of the container.\nkubectl run my-pod --image=myImage --command -- /bin/bash --myArg\nRun a Pod that overrides the ENTRYPOINT and the CMD of the container.\nkubectl run my-pod --image=myImage -rm -it --command -- /bin/bash --myArg\nRun a Pod that is interactive (-it) and gets deleted when exited (--rm)\nExec kubectl exec my-pod -c my-container -it -- /bin/bash\nExec a command in a container (when there is only one container -c is not required).\nLogs kubectl logs my-pod -c my-container\nShow logs of the specified container (when there is only one container -c is not required).\nkubectl logs -f my-pod\nShow and follows logs.\nEdit kubectl edit pod myPod\nEdit pod configuration\nThe only specifications that can be edited without --force are the following:\nspec.containers[*].image spec.initContainers[*].image spec.activeDeadlineSeconds spec.tolerations Deployments Create kubectl create my-deployment --image=httpd:alpine --replicas=4\nCreate a deployment with 4 replicas.\nUpdate (imperative) kubectl scale deployment my-deployment --replicas 4\nChange the number of replicas for the Deployment.\nkubectl set image deployment/my-deployment my-container=my-new-image\nChange the image used in a Deployment.\nkubectl rollout status deployment/my-deployment\nShow rollout status.\nService Exposure Port Forward (imperative) kubectl port-forward my-pod \u0026lt;HOST_PORT\u0026gt;:\u0026lt;POD_PORT\u0026gt;\nCreate a port forward to the specified pod.\nAccess via localhost:\u0026lt;POD_PORT\u0026gt;\nExpose Services (imperative) kubectl expose pod my-pod --type=ClusterIP --port=\u0026lt;POD_PORT\u0026gt; --name my-app-service\nCreate a service of type ClusterIP.\nAccess via \u0026lt;CLUSTER_IP\u0026gt;:\u0026lt;POD_PORT\u0026gt; (only accessible inside the cluster).\nkubectl expose pod my-pod --type=NodePort --port=\u0026lt;POD_PORT\u0026gt; --name my-app-service\nCreate a service of type NodePort.\nAccess via \u0026lt;ANY_NODE_IP\u0026gt;:\u0026lt;NODE_PORT\u0026gt;\nkubectl expose pod my-pod --type=LoadBalancer --port=\u0026lt;POD_PORT\u0026gt; --name my-app-service\nCreate a service of type LoadBalancer (requires that cluster is able to ask for a load balancer).\nAccess via \u0026lt;EXTERNAL_IP\u0026gt;:\u0026lt;POD_PORT\u0026gt; (EXTERNAL_IP is the IP of the Load Balancer).\nIngress kubectl create ingress my-ingress --rule=\u0026quot;/mypath=my-app-cluster-ip-service:8080\u0026quot;\nCreate an Ingress that route traffic address to /mypath path.\nkubectl create ingress my-ingress --rule=\u0026quot;myapp.local/*=my-app-cluster-ip-service:8080\u0026quot;\nCreate an Ingress that route traffic addressed to myapp.local host.\nHere are some annotations that could be usefull when using an Ingress of type Nginx.\nmetadata: annotations: # Allow to do /myapp -\u0026gt; / nginx.ingress.kubernetes.io/rewrite-target: / # Redirect HTTP traffic to HTTPS nginx.ingress.kubernetes.io/ssl-redirect: \u0026#34;true\u0026#34; Secrets Create kubectl create secret generic mySecret --from-literal my_key_1=my_value_1 --from-literal my_key_2=my_value_2\nCreate a generic Secret.\nkubectl create secret docker-registry my-private-reg-creds --docker-server=myprivateregistry.com:5000 --docker-username=dock_user --docker-password=dock_password --docker-email=dock_user@myprivateregistry.com\nCreate a docker-registry Secret.\nExample of the usage of a docker-registry Secret:\ndeployment spec: imagePullSecrets: - name: private-reg-cred containers: - image: myprivateregistry.com:5000/nginx:alpine imagePullPolicy: IfNotPresent Certificates Signing Requests kubect get certificatesigningrequests.certificates.k8s.io\nReturn Signing Requests.\ncat my-signing-request.csr | base64 -w 0\nOuput base64 as only one line\napiVersion: certificates.k8s.io/v1 kind: CertificateSigningRequest metadata: name: my-singing-request spec: request: LS0tLS1CRUdJTiBDRV... signerName: kubernetes.io/kube-apiserver-client usages: - client auth Create a Singing Request.\nkubectl certificate approve my-singing-request\nApprove Singning Request.\nOpenSSL openssl x509 -in /etc/kubernetes/pki/apiserver.crt -text -noout\nOutput certificate content.\nRBAC Service Accounts kubectl create serviceaccount my-service-account\nCreate a Serivce Account.\n# Specify Service Account for a resource spec: spec: serviceAccountName: dashboard-sa kubectl create token my-service-account\nCreate a Service Account token (JWT).\nRoles kubectl create role developer --verb=list,create,delete --resource=pods\nCreate a Role (can list, create, delete Pods).\nkubectl create rolebinding dev-user-binding --role=developer --serviceaccount=default:dev-user\nCreate a Binding between a Role and a Service Account.\nCluster Roles kubectl create clusterrole storage-admin --verb=* --resource=storageclasses --resource=persistentvolumes\nCreate a Cluster Role (can do anything on Persistant Volumes).\nkubectl create clusterrolebinding myUser-storage-admin --clusterrole=storage-admin --user=myUser\nCreate a Binding between a Role and a User.\nAuthorization Checks kubectl auth whoami\nReturns username and groups.\nkubectl auth can-i create pods\nChecks an action is allowed (returns yes or no).\nkubectl auth can-i --list\nReturns all allowed actions.\nTroubleshooting Broken Scheduler If the scheduler isn't working, check the configuration of /etc/kubernetes/manifests/kube-scheduler.yaml.\nBroken Worker Node If a Worker Node isn't working, try systemctl status kubelet.service\nIf the service don't start check:\njournalctl -u kubelet.service /var/lib/kubelet/config.yaml If Connection refused to control node check the Kubeconfig file:\nIs the port right? server: https://controlplane:6443 Troubleshoot Containers crictl ps -a\nSee Containers that are CRI-compatible.\ncrictl logs containerID\nSee Logs for a container.\nMisc Get all Objects kubectl get all\nGet info about all objects.\nGet all Images kubectl get pods --all-namespaces -o jsonpath=\u0026quot;{.items[].spec.containers[].image}\u0026quot; | \\ tr -s '[[:space:]]' '\\n' | \\ sort | \\ uniq -c Retrieve all images used by pods in the cluster.\nFind Resouces API Name kubectl api-resources | grep storage\nFind the API name of a resource using keyword.\nGet Cluster IP Ranges Config kubectl logs -n kube-system weave-net | grep ipalloc-range\nFind Pods IP range configuration.\ncat /etc/kubernetes/manifests/kube-apiserver.yaml | grep \u0026quot;--service-cluster-ip-range=\u0026quot;\nFind Services IP range configuration.\nExpose Kube-apiserver kubectl proxy\nExpose Kube-apiserver to localhost.\n","permalink":"https://devops.kaldei.com/containers/kubectl/","summary":"A CLI tool for communicating with a Kubernetes cluster's control plane.","title":"Kubectl"},{"content":"Metadata Labels Basis ... metadata: name: myObjectName labels: myLabel1: myValue1 myLabel2: myValue2 Lalbels on ReplicasSets ... metadata: name: myObjectName # Labels of the ReplicaSet labels: myLabel1: myValue1 myLabel2: myValue2 ... spec: replicas:3 selector # Lables used by the ReplicasSet to discover its pods matchLabels: myLabel1: myValue1 template: metadata: # Labels of the pods labels: myLabel1: myValue1 myLabel2: myValue2 Annotations Annotations are used to add information (e.g. tools name or version).\n... metadata: name: myObjectName annotations: myAnnotation1: myValue1 myAnnotation2: myValue2 Node and Scheduling Nodes Nodes are where the Pods run. A Node can be a physical or a virtual machine.\nNodes carrying the Kubernetes API are called Control Plane Nodes. Nodes obeying the API and owning Kubelets are called Workers Nodes.\nManual Scheduling New Pod If the pod is not created yet, simply add the nodeName property.\nspec: nodeName: myNode Already Created Pod - Method 1 (kubectl --force) Add the nodeName property to the pod definition file and apply it with --force\nkubectl apply --force -f myPodDefinition.yml Already Created Pod - Method 2 (Binding Object) Create a Binding Object and send a POST request to the pods binding api (/binding/).\napiVersion: v1 kind: Binding metadata: name: myPod target: apiVersion:v1 kind: noode name: myNode # Convert the binding object to JSON and use it as the data curl http://\u0026lt;myHost\u0026gt;/api/v1/namespaces/\u0026lt;myNamespace\u0026gt;/pods/\u0026lt;myPod\u0026gt;/binding/ \\ -X POST \\ -H \u0026#34;Content-Type:application/json\u0026#34; \\ --data {...} Scheduler The role of the Scheduler is to find a Node to deploy pending Pods. To do that it uses a series of plugins:\nQueue PrioritySort: Prioritises pods scheduling based on the priorityClassName pod spec value (high number means higher priority). Filtering NodeResourcesFit: Filters nodes that can recieve pods based on the pod requests spec. NodeName: Filters nodes that doesn't match the value of nodeName pod spec. NodeUnschedulable: Filters nodes that have the Unschedaleble flag set to true. TaintToleration NodePorts NodeAffinity Scoring NodeResourcesFit: Scores nodes that can recieve pods based on the pod requests spec. ImageLocality: Associates higher score to nodes that alerady have the image. TaintToleration `NodeAffinity Binding DefaultBinder: Provides binding mechanism. Custom Scheduler Specify a custom Schduler for a pod.\nspec: schedulerName: my-scheduler Taints and Toleration # Pod toleration spec: tolerations: - key: \u0026#34;spray\u0026#34; operator: \u0026#34;Equal\u0026#34; value: \u0026#34;mortein\u0026#34; effect: \u0026#34;NoSchedule Node Affinity spec: affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: disktype operator: In values: - ssd spec: affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: disktype operator: Exists Requests and Limits spec: containers: - name: app image: images.my-company.example/app:v4 resources: requests: memory: \u0026#34;64Mi\u0026#34; cpu: \u0026#34;250m\u0026#34; limits: memory: \u0026#34;128Mi\u0026#34; cpu: \u0026#34;500m\u0026#34; Basic Resources Namespaces Namespaces are folders used to isolate projects from one another (can be seen as \u0026quot;virtual clusters\u0026quot;).\nPods A Pod is a coherent set of one or more containers. Container in the same pods can communicate with each other directly.\nCommand and Args Note: command overrides the ENTRYPOINT of a container and args overrides the CMD.\nspec: container: -name: myContainer image: ubuntu command: [\u0026#39;sleep\u0026#39;,\u0026#39;5000\u0026#39;] args: [\u0026#34;--myArg\u0026#34;] spec: containers: - name: ubuntu image: ubuntu command: - \u0026#34;sleep\u0026#34; - \u0026#34;1200\u0026#34; args: - \u0026#34;--myArg\u0026#34; Environment Variable spec: containers: - name: ubuntu image: ubuntu env: spec: containers: - name: ubuntu image: ubuntu env: # Classic variable - name: myVar value: myValue # One value from Config Map - name: myVar valueFrom: configMapKeyRef: name: myConfigMap key: myVar # One value from Secret - name: myVar valueFrom: secretKeyRef: name: mySecret key: myVar # All values from Config Map envFrom: - configMapRef: name: myConfigMap # All values from Secret envFrom: - secretRef: name: mySecret Sidecar Additional helper container that run in a Pod to complement functionalities of the main container.\nSecurity Contexts # Secruity Context for a Pod spec: securityContext: runAsUser: 1000 runAsGroup: 3000 supplementalGroups: [4000] # Secruity Context for a Container containers: - name: sec-ctx-4 image: gcr.io/google-samples/hello-app:2.0 securityContext: capabilities: add: [\u0026#34;NET_ADMIN\u0026#34;, \u0026#34;SYS_TIME\u0026#34;] Jobs A Pod to run a task. When the task is completed, the pod is destroyed. However, if the task failed, the job will try to create a new pod.\nDeployments Deployments are objects that run and scale containers. A Deployment define the number of replicas of pods desired. If a pod fail, the Deployment will recreate it.\nTo avoid creation failure of a pod using a Persistent Volumes Claim, configure the Strategy to type:Recreate. This will unmount the volume, destroy the pod, and then mount the volume to the new pod.\nRolling Update Strategy: spec: strategy: rollingUpdate: maxSurge: 25% maxUnavailable: 25% type: RollingUpdate Recreate Strategy spec: strategy: type: Recreate Stateful Sets Similar to Deployments with some additional the features:\nDefine Volume Claim Templates that can dynamically create Persistent Volume Claims. Each pod will have a DNS name with this format: statefulsetName-ordinal.serviceName.namespaceName.svc.cluster.local. There will be A record and SRV records. By default, Stateful Set will deploy pods in sequential order. To deploy all pods simultaneously, use the spec podManagmentPolicy: Parrallel. Environment Variables ConfigMap ConfigMaps are used to store environment variables.\napiVersion: v1 kind: ConfigMap metadata: name: myConfigMap data: myVariable: \u0026#34;myValue\u0026#34; Secret Secrets are used to store sensitive information.\nNetworking DNS Here are some examples of working DNS names to access Pods in a Cluster:\nmy-pod.my-namespace my-pod.my-namespace.svc my-pod.my-namespace.cluster.local my-service.my-namespace CNI By default, Kubernetes does not provide any networking functionality. It is required to install a CNI (Container Network Interface) plugin.\nSome plugins like kindnet and flannel don't support network policies. Others like Cilium and Calico support network policies.\nNetwork Policies apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: internal-policy namespace: default spec: podSelector: matchLabels: name: internal policyTypes: - Egress egress: - to: - podSelector: matchLabels: name: my-webapp ports: - protocol: TCP port: 8080 - to: - podSelector: matchLabels: name: my-db ports: - protocol: TCP port: 3306 Service Basis A Service is an object that manage internal access to pods in a cluster (sort of Load Balancer with Port Forwarding). Create an abstraction layer to communicate between containers inside a cluster.\nServices use label selectors to pods IPs.\nThere are 3 types of Services: ClusterIP, NodePort and LoadBalancer.\nClusterIP Service of type ClusterIP allows for communication between services in the same cluster only.\nNodePort Service to expose Pods outside the cluster.\nAll traffic send to the specified port on the Node will be sent to the pods (this requires that the client is able to directly reach nodes).\nNotes\nIf the request is sent to a different Node than the Pod is running on, the request will be forwarded to the right Node. Ports supported for this method are from 30000 to 32767. A NodePort Service sends the traffic to a ClusterIP which then sends it to the Pods. Use case:\nWhen using a Load Balancer Service is too expensive or not possible (no Load Balancer Class). Not recommended for production Requires exposing nodes to clients. If using a DNS record, it needs to be updated frequently to match Nodes IPs. LoadBalancer Default method to expose a service. Depends on the Cloud Controller Manager. This type of service can be used for any kind of protocols.\nAWS NLB Creates an NLB (Layer 4 Load Balancer). This Load Balancer can be configured with specific annotations.\nConfiguration # New configuration (eks \u0026gt;= v1.22) kind: Service spec: type: LoadBalancer loadBalancerClass: nlb # Old configuration kind: Service spec: type: LoadBalancer annotations: service.beta.kubernetes.io/aws-load-balancer-type: external Annotations Here are some annotations that could be usefull:\nmetadata: annotations: # Use Instance mode service.beta.kubernetes.io/aws-load-balancer-nlb-target-type: instance # Use IP mode service.beta.kubernetes.io/aws-load-balancer-nlb-target-type: ip # Configure a Load Balancer with public IP address service.beta.kubernetes.io/aws-load-balancer-scheme: internet-facing # Configure a Load Balancer with only a private IP address (accessible only in the VPC). service.beta.kubernetes.io/aws-load-balancer-scheme: internal AWS Classic LB (Legacy) If the AWS Load Balancer Controller is not installed or the aws-load-balancer-type annotation is not set to nlb-ip or external, AWS will use the Legacy Load Balancer and deploy an AWS Classic Load Balancer.\nConfiguration kind: Service spec: type: LoadBalancer Ingress Basis An Ingress is an object that manage external access to services in a cluster (sort of Reverse Proxy / API Gateway). When using an Ingress Controller, all services will share one Load Balancer.\nThere are many types of Ingress Controllers: Nginx, Kong, Istio, AWS Load Balancer Controler, ...\nNotes:\nIngress only allows the use of HTTP and HTTPS. Ingress can be useful for monitoring: all metrics (latency, throughput, ...) in one place without needed to instrument each app. Nginx Ingress Controller Nginx Ingress Controller is a pod that will act as a Reverse Proxy in the cluster. When installing Nginx controller in Cloud Managed clusters, it will create a layer 4 Load Balancer. Layer 4 Load Balancer does not understand TLS, so it will not terminate TLS.\nhttps://kubernetes.github.io/ingress-nginx/deploy/\nAnton Putra - Nginx Ingress Controller Tutorial\nAnton Putra - NGINX Ingress Controller for Kubernetes Tutorial\nHelm Installation Configuration https://kubernetes.github.io/ingress-nginx/deploy/\n# Values files for Helm Chart --- controller: ingressClassResource: name: external-nginx service: annotations: # Configuration when using with AWS Load Balancer Controller service.beta.kubernetes.io/aws-load-balancer-type: external service.beta.kubernetes.io/aws-load-balancer-nlb-target-type: ClusterIP service.beta.kubernetes.io/aws-load-balancer-scheme: internet-facinge Resource Configuration king: Ingress spec: ingressClassName: nginx Architecture Example Source: Anton Putra\nHere are some annotations that could be usefull when using an Ingress of type Nginx.\nmetadata: annotations: # Allow to do /myapp -\u0026gt; / nginx.ingress.kubernetes.io/rewrite-target: / # Redirect HTTP traffic to HTTPS nginx.ingress.kubernetes.io/ssl-redirect: \u0026#34;true\u0026#34; AWS ALB Ingress (AWS Load Balancer Controller) AWS Ingress, creates an ALB (Layer 7 Load Balancer). This Load Balancer understand TLS and will terminate it when passing traffic to the cluster.\nAnton Putra - Expose Kubernetes Services Running on Amazon EKS (9 Ways) Anton Putra - Native EKS Ingress: AWS Load Balancer Controller Configuration kind: Ingress spec: ingressClassName: alb Annotations Here are some annotations that could be usefull:\nmetadata: annotations: # Listen on ports 80 and 443 alb.ingress.kubernetes.io/listen-ports: \u0026#39;[{\u0026#34;HTTP:80}, {\u0026#34;HTTPS\u0026#34;:443}]\u0026#39; # Redirect HTTP traffic to HTTPS alb.ingress.kubernetes.io/ssl-redirect: 443 alb.ingress.kubernetes.io/scheme: internet-facing alb.ingress.kubernetes.io/target-type: ip # Set a custom healthcheck path alb.ingress.kubernetes.io/healthcheck-path: /health Volumes Persistent Volume Persistent volumes provide a file system that can be mounted to the cluster and accessible to any node.\napiVersion: v1 kind: PersistentVolume metadata: name: pv-log spec: capacity: storage: 100Mi hostPath: path: /pv/log accessModes: - ReadWriteMany persistentVolumeReclaimPolicy: Retain Reclaim Policies (persistentVolumeReclaimPolicy):\nRetain: Volume is not destroyed but is not available. Persistent Volume Claim Volume attached to a Pod. It's a subsection of a Persistent Volume.\napiVersion: v1 kind: PersistentVolumeClaim metadata: name: claim-log-1 spec: accessModes: - ReadWriteOnce resources: requests: storage: 50Mi Volume Binding Modes (VolumeBindingMode) WaitForFirstConsumer: this will delay the binding and provisioning of a PersistentVolume until a Pod using the PersistentVolumeClaim is created. Pod Volume Mount Inline volume declaration spec: containers: volumeMounts: - name: log-volume mountPath: /log # Path in the container volumes: - name: log-volume hostPath: path: /var/log/webapp # Path on the host Persitant Volume Claim spec: containers: volumeMounts: - name: log-volume mountPath: /log # Path in the container volumes: - name: log-volume persistentVolumeClaim: claimName: claim-log-1 Autoscaling Cluster Autoscaler Node autoscaling.\nKarpenter Karpenter is a Cluster Autoscaler that create nodes spcificly sized for the pending pods.\nPod Autosclaer Horizontal Pod Autoscaler Use metrics from the Metric Server to adjust the number of replicas.\nThe HPA relies on the requets part of a deployment to compute the usage:\nresources: requets: memory: 256Mi cpu: 100m limits: memory: 256Mi cpu: 100m If the resource block on a Deployment is not defined, the HPA target will show Unkown.\nWarning: Do not use replica on Deployments or Stateful Sets when using GitOps tools because they will be in concurrence to set the number of replicas. Instead, use minReplicas and maxReplicas.\nEvent Driven Horizontal Pod Autoscaler (Kada) Autocaler for Event Driven platforms (Kafka, RabbitMQ, ...). It scales the app based on the number of message in a queue. Can scale down to 0 when there are no messages int the queue.\nVertical Pod Autoscaler Autoscaler for scaling applications vertically (e.g. a standalone database). Do not use it on application that can scale horizontally. The controller for Vertical Pod Autoscaler do not come with Kubernetes by default.\nThere are 3 modes:\nRecreate: Recreate a new pod with updated needed resources. Initial: Only when deploying the application Off: Only provide recommendations without doing anything. Monitoring Metrics Server Metrics Server get the metrics (CPU and RAM) by scrapping the Kubelet of each node. It then serves those metrics via the Metrics API: metrics.k8s.io\nPrometheus Prometheus: service that can get advanced metrics (Latency, Traffic, Errors, Saturation, ...).\nPrometheus Operator: manage lifecycle of Prometheus instances and convert Service and Pod Monitors to Prometheus configuration.\nService Monitor: Service that will scrap the app and store metrics in the Prometheus instance.\nPrometheus Adapter: Convert Prometheus metrics to usable metrics for Horizontal Pod Autoscaler. It serves thoses metrics to custom.metrics.k8s.io.\nNote: It is possible to replace the Metrics Server by Prometheus by adding cAdvisor and a Node Exporter on each nodes.\n","permalink":"https://devops.kaldei.com/containers/kubernetes-basics/","summary":"A note about the basics of Kubernetes (Scheduling, Resources and Networking).","title":"Kubernetes Basics"},{"content":"Comparison AWS vs GCP vs Azure Metrics Server Azure AKS and Google GKE comes with Metrics Server by default. AWS EKS does not come with Metrics Server by default. Node Autoscaler In AWS it is required to configure permissions and deploy the autoscaler (Auto Scaling Group) In Azure and GCP, the cluster autoscaler is managed (it just needs to be enabled). Node Types EKS Self-managed Managed node groups Fargate AWS EKS IAM Cluster Assume Role { ... \u0026#34;Principal\u0026#34;: { \u0026#34;Service\u0026#34;: \u0026#34;eks.amawonaws.com\u0026#34; } } Policy For cluster using legacy Cloud Controller : arn:aws:iam::aws:policy/AmazonEKSClusterPolicy. Grant required permissions + ELB permission for legacy Ingress (half of the policy).\nWorker Nodes Policies arn:aws:iam::aws:policy/AmazonEKSWoekerNodePolicy: core EC2 permissions + required permission for Pod Identity Agent. arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy: permission to modify IP address config of pods. arn:aws:iam::aws:policy/AmawonEC2ContainerRegistryReadOnly: allows to pull container images from ECR. Pod Identity Assume Role { ... \u0026#34;Principal\u0026#34;: { \u0026#34;Service\u0026#34;: \u0026#34;pods.eks.amawonaws.com\u0026#34; } } Admin Access Policy Add AmazonEKSClusterAdmin to IAM Access entries in order to create and get any resources in the cluster.\nAWS Load Balancer Controller Prerequisites The AWS LBC is not installed by default on EKS, it needs to be installed (https://aws.github.io/eks-charts/aws-load-balancer-controller).\nAWS NLB Creates an NLB (Layer 4 Load Balancer). This Load Balancer can be configured with specific annotations.\nConfiguration # New configuration (eks \u0026gt;= v1.22) kind: Service spec: type: LoadBalancer loadBalancerClass: nlb # Old configuration kind: Service spec: type: LoadBalancer annotations: service.beta.kubernetes.io/aws-load-balancer-type: external Annotations Here are some annotations that could be usefull:\nmetadata: annotations: # Use Instance mode service.beta.kubernetes.io/aws-load-balancer-nlb-target-type: instance # Use IP mode service.beta.kubernetes.io/aws-load-balancer-nlb-target-type: ip # Configure a Load Balancer with public IP address service.beta.kubernetes.io/aws-load-balancer-scheme: internet-facing # Configure a Load Balancer with only a private IP address (accessible only in the VPC). service.beta.kubernetes.io/aws-load-balancer-scheme: internal Legacy Classic LB If the AWS Load Balancer Controller is not installed or the aws-load-balancer-type annotation is not set to nlb-ip or external, AWS will use the Legacy Load Balancer and deploy an AWS Classic Load Balancer.\nConfiguration kind: Service spec: type: LoadBalancer Ingress (ALB) AWS Ingress, creates an ALB (Layer 7 Load Balancer). This Load Balancer understand TLS and will terminate it when passing traffic to the cluster.\nAnton Putra - Expose Kubernetes Services Running on Amazon EKS (9 Ways) Anton Putra - Native EKS Ingress: AWS Load Balancer Controller Configuration kind: Ingress spec: ingressClassName: alb Annotations Here are some annotations that could be usefull:\nmetadata: annotations: # Listen on ports 80 and 443 alb.ingress.kubernetes.io/listen-ports: \u0026#39;[{\u0026#34;HTTP:80}, {\u0026#34;HTTPS\u0026#34;:443}]\u0026#39; # Redirect HTTP traffic to HTTPS alb.ingress.kubernetes.io/ssl-redirect: 443 alb.ingress.kubernetes.io/scheme: internet-facing alb.ingress.kubernetes.io/target-type: ip # Set a custom healthcheck path alb.ingress.kubernetes.io/healthcheck-path: /health AWS EBS CSI Driver Driver to enable the cluster to create EBS storage on AWS.\nEBS Default Storage Class is GP2. The access mode is ReadWriteOnce, which allows the EBS volume to be mounted only to one pod (one node).\napiVersion: v1 kind: PersistantVolume spec: volumeMode: Filesystem accessModes: [ReadWrtieOnce] storageCapacity: 5Gi EFS This can be mounted to multiple pods.\napiVersion: v1 kind: PersistantVolumeClaim spec: storageClassName: efs accessModes: [ReadWrtieMany] resources: requests storage: 5Gi","permalink":"https://devops.kaldei.com/containers/kubernetes-cloud-managed/","summary":"A note about the spceifics of Kubernetes managed by Cloud Providers.","title":"Kubernetes Cloud Managed"},{"content":"Debian Based Distros APT (Advanced Package Tool) - High Level Source repos config files: /etc/apt/sources.list\n# versionCodeName examples: jammy jammy-security (for security updates only) # packageGroup example: main deb http://source/ versionCodeName packageGroup apt update\nGo to sources list and update packages version cache file (/var/cache/pkgcache).\napt upgrade\nUpgrade Packages with new versions from the cache.\napt dist-upgrade\nStronger upgrade (some packages are told by the maintainer to not upgrade just with upgrade).\napt-mark hold myPackage\nDo not update this package when doing upgrade.\napt search myString\nSearch package with myString in the name.\napt info myPackage\nGive infos about a package (Version, Origin, Maintainer).\napt remove myPackage\nRemove myPackage (only the package).\napt install myPackage\nInstall myPackage (check in the cache file).\napt install -s myPackage\nSimulate installation.\napt install -f myPackage\nFix Broken (install missing dependencies).\napt download myPackage\nDownload the deb file myPackage without installing.\napt remove myPackage\nRemove myPackage (only the package).\napt autoremove myPackage\nRemove myPackage and dependencies.\napt autoremove --purge myPackage\nRemove myPackage, dependencies and config files with purge.\nDPKG – Low Level dpkg -l\nShow installed packages.\ndpkg -i myPackage.deb\nInstall package.\ndpkg-reconfigure myPackage\nRe-run installation configuration scripts.\nRedHat Based Distros DNF (Dandified YUM) - High Level DNF is the modern replacement for YUM (faster and memory efficient). Sub-commands are the same as YUM.\nYUM (Yellowdog Updater Modified) – High Level Main config file: /etc/yum.conf Source repos config file: /etc/yum.repos.d/\nyum update\nUpdate repositories and packages.\nyum upgrade\nUpgrade packages and remove obsolete ones.\nyum search myString\nSearch package with myString in the name.\nyum install myPackage\nInstall a package.\nRPM (Red Hat PackMan) – Low Level rpm query myString\nSearch package with myString in the name.\nrpm -U myFile.rpm\nInstall or Upgrade a package.\nrpm -i myFile.rpm\nInstall a package.\nrpm -i -v -h myFile.rpm\nInstall a package with verbose and loadfing bar.\n","permalink":"https://devops.kaldei.com/cli/linux-package-managers/","summary":"A note about Linux packages managers.","title":"LINUX PACKAGE MANAGERS"},{"content":"Basis Shortcuts Ctrl + A\nGo to the beginning of the line.\nCtrl + E\nGo to the end of the line.\nCtrl + Alt + F2\nOpen TTY 2 (there are 6 TTYs on Linux that can be opened in parallel, from F1 to F6).\nLS ls -lS\nSort by size.\nls -lX\nSort by extension.\nFiles FIND find /search/path/ -name myFile\nFind a file by name.\nfind /search/path/ -type f\nFind by type (f (file), d (directory), l (symbolic link)).\nfind /search/path/ -size 50M\nFind a file by size (c (octets / bytes), k (kilo octets), M (mega octets), G (giga octets), b (blocs of 512 octets).\nfind /search/path/ -user myUser\nFind a file by user.\nfind /search/path/ -group myGroup\nFind a file by group.\nfind /search/path/ -perm 000\nFind a file by permission.\nfind /search/path/ -name .txt -exec rm {};\nFind files and execute a command for each of them ({} is replaced by what is found by find).\nUNIQ uniq\nDeletes duplicate lines in a file (the comparison is done with the previous line, so use sort -d before).\nuniq -u\nReturn lines that appear only once.\nuniq -d\nReturn lines that appear more than once.\nDIFF diff myFile1 myFile2\nReturn differences between the two files.\ndiff \u0026lt;(ls my_directory_1) \u0026lt;(ls my_directory_2)\nReturn differences between two directory contents (using process substitution).\nPS2PDF ps2pdf -d PDFSETTINGS=/ebook myFile.pdf myFile-Compressed.pdf\nCompress a PDF.\n/screen\n72 dpi, lowest quality, smallest file size.\n/ebook\n150 dpi, better quality, slightly larger size.\n/prepress\n300 dpi, high quality, larger size.\n/printer\n300 dpi, printer-quality output.\n/default\nUseful for multiple purposes, may result in large files.\nString Manipulation GREP grep myString myFile\nReturn lines containing myString.\ngrep -e myString1 -e myString2\nMatch multiple patterns.\ngrep -f myFileA myFileB\nRead the search patterns from a file (myFileA).\ngrep -vxF -f myFileA myFileB\nPrints all lines in fileA that are not found in fileB.\ngrep -E\nUse a Regex.\ngrep -F\nInterpret patterns as fixed strings.\ngrep -i\nReturn lines that correspond to the string but is not case-sensitive.\ngrep -x\nReturn lines that correspond exactly to the string.\ngrep -v\nReturn lines that do not contain the string.\ngrep -A 12\nReturn 12 lines after the match.\ngrep -B 12\nReturn 12 lines before the match.\ngrep -C 12\nReturn 12 lines before and after the match.\ngrep -c\nCounts the number of lines containing the string.\ngrep -n\nEach line containing the string is numbered.\ngrep -l\nReturn the names of files containing the string.\ngrep -h\nDo not return the folder prefix.\nCUT cut -c 1-12\nReturn characters from 1 to 12 of the input string.\ncut -c -12\nReturn the first 12 characters of the input string.\ncut -c 12-\nReturn the last 12 characters of the input string.\ncut -c 1,12\nReturn characters 1 and 12 of the input string.\ncut -d : -f 2\nReturn the second field (-f 2). Field separator is defined with -d.\nSED sed -d\nRemove a line (\u0026quot;/.../d\u0026quot;).\nsed -s\nReplace a string (\u0026quot;s/old/new/\u0026quot;).\nsed -g\nApply on all lines (\u0026quot;/old/new/g\u0026quot;).\nTR tr 'a-z' 'A-Z'\nReplace lower case letters with upper case letters.\ntr 'abcd' 'jkmn'\nReplace a by j, b by k, c by m and d by n.\nSORT sort myFile.txt\nSort the contents of a file.\nsort -d myFile.txt\nSort using only blanks and alphanumeric chars (dictionary order).\nsort -k 2 myFile.txt\nSort on the second column in the file (separated by space).\nMonitoring WATCH watch my-command\nRun a command every 2 seconds (default).\n-n 0.5\nSpecify the interval in seconds.\n-d\nHighlight changes.\nJOURNALCTL journalctl -u my-service.service\nReturns logs for the specified service.\njournalctl -fu my-service.service\nFollow logs for the specified service.\njournatl --since \u0026quot;1 hour ago\u0026quot;\nReturns logs since one hour ago.\njournalctl --since \u0026quot;2025-01-01 12:00:00\u0026quot; --until \u0026quot;2025-01-01 13:00:00\u0026quot;\nReturns logs between given dates.\nNetworking DNS dig my.domain\nReturn records for the given domain.\ndig @my.dns.provider my.domain\nSpecify the server to use for the query.\n(e.g query the authoritative server to check if record have been correctly updated).\ndig -x 12.12.12.12\nReverse DNS.\ndig +short my.domain\nShort form answer (only record value).\ndig +noall +answer my.domain\nShort form answer (ttl, type, record).\ndig +nostats +nocomments +nocmd my.domain\nShort form answer (ttl, type, record).\ndig +trace my.domain\nShows steps in the lookup chain.\ndig -t NS my.domain\nReturn NS Records (authoritative servers for the domain).\ndig -t TXT my.domain\nReturn TXT Records.\ndig -t CNAME my.domain\nReturn CNAME Record.\ndig -t MX my.domain\nReturn MX Records.\ndig +udp my.domain\nQuery using UDP.\ndig +tcp my.domain\nQuery using TCP.\nSSL/TLS openssl s_client -connect [MY_HOST]:[MY_PORT]\nMake an SSL/TLS client request.\nSS ss -tunp\nReturns established connections (TCP and UDP).\nss -tulnp\nReturns listening sockets (TCP and UDP).\nss -tuanp\nReturns established connection and listening sockets (TCP and UDP).\nNMCLI nmcli device\nList network devices (ethernet, wifi, ...)\nnmcli device wifi connect MY_SSID\nConnect to specified SSID.\nnmcli connection down MY_SSID\nDisconnect from specified SSID.\nnmcli connection up MY_SSID\nConnect back to a known SSID.\nDisk Management Disk usage alias dutop='sh -c '''du -h --all --max-depth=1 \u0026quot;$1\u0026quot; | sort -hr | head -n 20 ''' _'\nAlias for searching large files (vanilla alternative to ncdu).\nWIPEFS (Erase partitions) sudo wipefs -a /dev/sda\nErase filesystem and partition signatures (without deleting data).\nFDISK (Edit partitions) sudo fdisk /dev/sda\ng (create GPT table) or o (create legacy DOS/MBR table).\nn (new partition, use all default to use whole disk).\nw (write changes and exit).\nMKFS (Format partitions) mkfs -t ext4 /dev/sda\nCreate an ext4 filesystem in a disk partition (old command).\nsudo mkfs.ext4 /dev/sda\nCreate an ext4 filesystem in a disk partition (new command).\nsudo mkfs.ext4 -L MY_LABEL /dev/sda\nCreate an ext4 filesystem in a disk partition and set the volume label.\n","permalink":"https://devops.kaldei.com/cli/linux-tools/","summary":"CLI tools and tricks for Linux.","title":"LINUX TOOLS"},{"content":"Resources Memory Explained - LearnThatStack Stack Properties Small. Fast. Automatic. Data is ordered: LIFO (Last In First Out). Fixed size (1-8 MB). Data is popped (removed) from the stack when function returns. Allocation sizes must be known in advance. Stack Overflow Stack Overflow happens when:\nDepth Problem when creating too many frames in the Stack until the stack limit. e.g. recursion with no stop condition. fix: always have a base case. Size Problem when creating a frame too large. e.g. try to create a huge variable. fix: put large data in the Heap. Heap Properties Large pool of memory (can grow to use most of available RAM). Flexible. Managed. Data is not ordered: you program request space, the system finds a free block and returns the address. Access data using its address which is tiny and lives on the stack. Use cases: when don't know how much space is need until runtime. when data needs to survive after the function. when data is too large for the Stack. Memory Leak How does the Garbage Collector work:\nCollector starts from the Stack and traces every reference chain. Anything reachable in the Heap is kept. Anything unreachable is deleted. Problem: if the program keeps references to object it no longer needs, the Heap memory is no cleared because still reachable\nFix: Explicit cleanup. The garbage collector claim unreachable memory, making memory unreachable is the developer job.\nProgramming Language Variables Types Primitive Primitives / Pass by Values (numbers, booleans, ...)\nWhen a primitive variable values is passed to another variable, the value is copied. Now there are two separates variables with the same value in the Stack, modify one variable value will not impact the other one. Objects Objects / Pass by Reference (lists, dicts, classes, ...)\nWhen an object variable value is passed to another variables, the reference is copied. Now the two variables old the same reference (address) pointing to the same data in the Heap, modify one variable value and the other variable will be impacted. Example in Python Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other.\nSource: Shallow and deep copy operations - Python\n# List of dicts my_list = [ { \u0026#34;player\u0026#34;: 1, \u0026#34;class\u0026#34;: \u0026#34;knight\u0026#34; }, { \u0026#34;player\u0026#34;: 2, \u0026#34;class\u0026#34;: \u0026#34;pirate\u0026#34; } ] # Normal Copy # Assign reference of the list that contains references to the dicts my_list_2 = my_list # Swallow Copy # Create a new list that contains the same references to the dicts my_list_3 = copy.copy(my_list) # Deep Copy # Create a new list and new dicts my_list_4 = copy.deepcopy(my_list)","permalink":"https://devops.kaldei.com/scripting/memory/","summary":"A note about Memory architecure and mangment.","title":"Memory Management"},{"content":"Remote Operations SSH ssh myUser@myTargetHost\nOpen a secure interactive session to the targeted host.\nssh myUser@myTargetHost myCommand\nRun a command in the targeted host.\nssh myUser@myTargetHost -N -L localhost:1212:myUnreachableHost:1212\nCreate a local port forward.\nAllows local machine to access a port on a machine that is in another network.\nScenario where local machine doesn't have access to myUnreachableHostp while myTargetHost does.\nssh myUser@myTargetHost -N -R 0.0.0.0:8080:localhost:80\nCreate a remote port forward.\nAllows target machine to access a local machine port.\nScenario where remote machine is not allowed to open connections to local machine, but the contrary is allowed.\nSSH Flags -p\nSpecify the port to connect to on the target.\n-i myPrivateKeyFile\nConnect using private key (need that target trust public key beforehand).\n-t\nForce pseudo-terminal allocation (e.g. allows connecting to a user that do not have a default shell).\n-L myLocalBindAddr:myLocalPort:myUnreachableHost:myUnreachableHostPort\nLocal port forward.\n-R myTargetHostAddr:myTargetHostPort:localhost:myLocalPort\nRemote port forward.\n-D myBindAddr:myLocalPort\nDynamic port forward via specified port (ssh will act as a SOCKS proxy server).\n-N\nDo not execute a remote command (useful for just forwarding ports).\n-f\nRun in background (useful for just forwarding ports).\nSCP scp /path/to/myLocalFile.txt myUser@myTargetHost:/destination/path/\nCopy a local file to a remote host.\nscp -r /path/to/myFolder myUser@myTargetHost:/destination/path/\nCopy a folder and its content to a remote host.\n*scp -r /path/to/myFolder/ myUser@myTargetHost:/destination/path/myFolder/**\nCopy the content of a folder to a remote host.\nSFTP sftp myUser@myTargetHost\nCreate an SFTP session.\nhelp\nDisplay help.\npwd\nReturns remote current folder.\nlpwd\nReturns local current folder.\nls\nLists folders and files in remote current folder.\nlls\nLists folders and files in local current folder.\ncd\nChanges remote directory.\nlcd\nChanges local directory\nget\nDownloads a file from server to client (-r for a directory).\nput\nUploads a file from client to server (-r for a directory).\nmkdir\nCreates a folder in remote.\nlmkdir\nCreates a folder in local.\nrmdir\nDeletes a folder.\nrm\nDeletes a file.\nexit\nExit SFTP session.\nKey Management Generate ssh-keygen -t rsa\nGenerate a OpenSSH key pair (public and private keys).\nTrust Keys ssh-copy-id myUser@myHost\nCopy public key to target host (allows connecting with private key -i).\n","permalink":"https://devops.kaldei.com/cli/openssh/","summary":"Suite of secure tunneling capabilities.","title":"OPENSSH"},{"content":"Resources ChristianLempa/cheat-sheets SSL Client Diag an SSL/TLS connection openssl s_client -connect [MY_HOST]:[MY_PORT]\nMake an SSL/TLS client request.\nGenerate Keys Generate RSA Key openssl genrsa -out my-key.key 4096\nGenerate an RSA key (4096 bits for more robust than default 2048 bits).\n-aes256\nGen a AES256 key. Encrypt key with passphrase.\nRead Certificates Read Local Certificates openssl req -in cert.csr -text\nOutput CSR content as text.\nopenssl x509 -in cert.pem -text\nOutput certificate content as text.\nopenssl x509 -in cert.pem -text -noout\nDo not output raw certificate at the end.\nopenssl x509 -in cert.pem -text -noout | grep -i valid -A2\nReturn validity dates.\nRead Remote Certificates openssl s_client -showcerts -connect [MY_HOST]:[MY_PORT]\nReturn detail about SSL/TLS connection and certificate chain.\nGenerate Certificates Generate CA Certificate openssl genrsa -aes256 -out ca.key 4096\nGenerate an RSA key.\nopenssl req -new -x509 -sha256 -days 3650 -key ca.key -out ca.pem\nGenerate CA certificate with the given key (use -x509 to self sign the CSR).\nGenerate Server Certificate openssl genrsa -out cert.key 4096\nGenerate an RSA key.\nopenssl req -new -sha256 -key cert.key -out cert.csr\nGenerate a certificate singing request with the given key.\necho \u0026quot;subjectAltName=DNS:my-domain.tld,IP:10.0.0.1\u0026quot; \u0026gt; sans.txt\nCreate a config file for SANs.\nopenssl x509 -req -sha256 -days 365 -in cert.csr -CA ca.pem -CAkey ca.key -out cert.pem -extfile sans.txt\nCreate a certificate signed by CA and with a SAN config.\nFlags -subj \u0026quot;/C=FR/ST=Ile-de-France/L=Paris/O=MyOrg/OU=MyUnit/CN=my.domain\u0026quot;\nSpecify information for the certificate in the command.\n-addext \u0026quot;subjectAltName=DNS:my.alt.domain\u0026quot;\nAdding this with req new command does add the SAN to the request, but it does seem to be added to the final cert.\nThe workaround of adding \u0026lt;(printf \u0026quot;subjectAltName=DNS:my.alt.domain\u0026quot;) at the end of the command seem to work.\n-CAcreateserial\nNo longer needed with OpenSSL 3 as it now generates a random serial numbers by default.\n","permalink":"https://devops.kaldei.com/cli/openssl/","summary":"TLS/SSL and crypto library.","title":"OPENSSL"},{"content":"Workflow Initialize packer init -var-file variables.pkrvars.hcl .\nInitialize the directory (download plugins, ...).\nValidate and Format (optional) packer validate -var-file variables.pkrvars.hcl .\nValidate config file.\npacker fmt -var-file variables.pkrvars.hcl .\nFormat config file.\nBuild packer build -var-file variables.pkrvars.hcl .\nBuild config file.\nMisc Convert from JSON to HCL packer hcl2_upgrade myUbuntu.json\nConvert JSON file to HCL.\n","permalink":"https://devops.kaldei.com/iac/packer-cli/","summary":"A note about the Packer CLI.","title":"Packer CLI"},{"content":"Virtual Env Create Venv python -m venv myVenv/\nCreate Venv.\nWindows myVenv/scripts/activate\nActivate Venv.\ndeactivate\nDeactivate Venv.\nLinux source myVenv/bin/activate\nActivate Venv.\ndeactivate\nDeactivate Venv.\nData Types Set Sets are like lists but with no duplicates.\n# Create a set players = {\u0026#34;player1\u0026#34;, \u0026#34;player2\u0026#34;} Hence, they can be used to remove duplicates from a list:\nset(\u0026#39;abracadabra\u0026#39;) # Return {\u0026#39;b\u0026#39;, \u0026#39;d\u0026#39;, \u0026#39;r\u0026#39;, \u0026#39;a\u0026#39;, \u0026#39;c\u0026#39;} Tuples Tuples are like lists, but can’t be changed (immutable).\n# Create an empty typle empty_tuple = () # Create a tuple players = \u0026#34;player1\u0026#34;, \u0026#34;player2\u0026#34; Note: A tuple is not defined by parenthesis, it is defined by commas (except for declaring an empty tuple).\nDict Dictionaries work like JSON.\n# Create a dict myDictionary = { \u0026#34;key1\u0026#34; : value1, \u0026#34;key2\u0026#34; : value2 } # Add a new key/value pair myDictionary[newKey] = newValue # Add a new key/value pair (alternative method) myDictionary.update({newKey: newValue}) # Return the keys of the dictionary. myDictionary.keys() # Return the values of the dictionary. myDictionary.values() # Return all key/value pairs as tuples myDictionary.items() Object Copy Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other.\nSource: Shallow and deep copy operations - Python\n# List of dicts my_list = [ { \u0026#34;player\u0026#34;: 1, \u0026#34;class\u0026#34;: \u0026#34;knight\u0026#34; }, { \u0026#34;player\u0026#34;: 2, \u0026#34;class\u0026#34;: \u0026#34;pirate\u0026#34; } ] # Normal Copy # Assign reference of the list that contains references to the dicts my_list_2 = my_list # Swallow Copy # Create a new list that contains the same references to the dicts my_list_3 = copy.copy(my_list) # Deep Copy # Create a new list and new dicts my_list_4 = copy.deepcopy(my_list) String Manipulation Input / Output input(\u0026quot;Message\u0026quot;)\nKeyboard input.\nprint(\u0026quot;Message\u0026quot;)\nWrite a message to the output.\nprint(\u0026quot;Message {}\u0026quot;.format(myVar))\nReplace {} with myVar.\nprint(\u0026quot;Message\u0026quot;, myVar)\nVariable concatenation.\nprint(f \u0026quot;Message {myVar}\u0026quot;)\nReplace {myVar} with myVar.\nprint(r \u0026quot;c:\\path\\name\u0026quot;)\nDo not interpret special characters (e.g. \\', \\n).\nprint(\u0026quot;Message\u0026quot; + myString)\nString concatenation.\nprint(\u0026quot;Message\u0026quot;.join(myString))\nString concatenation.\nprint('bla', 'bla', 'bla', sep=',')\nPrint all the elements separated by a comma.\nprint('bla', 'bla', 'bla', end='\\n')\nPrint all the elements and a new line at the end.\nStrip \u0026amp; Split split(\u0026quot;,\u0026quot;)\nSplit a string based on a delimiter.\nmyString.strip([chars])\nRemove all \u0026quot;chars\u0026quot; at the beginning and the end of the string.\nmyString.rstrip([chars])\nRemove all \u0026quot;chars\u0026quot; at the end of the string.\nEncoding ord('A')\nConvert character to Decimal ASCII code.\nchr(65)\nConvert Decimal ASCII code to character.\n\u0026quot;\\x41\u0026quot;\nConvert Hexadecimal ASCII code to character.\nbytes(\u0026quot;myString\u0026quot;, \u0026quot;UTF-8\u0026quot;)\nConvert a string into an array of bytes.\nMisc str(intVar)\nConvert int variable to string.\nlen(myVar)\nCount the number of characters in the variable.\nmyString.title()\nConvert to title (e.g. This Is A Title).\nmyString.upper()\nConvert to uppercase.\nmyString.lower()\nConvert to lowercase.\nFiles Read File with open(\u0026#34;myFile.txt\u0026#34;, \u0026#34;r\u0026#34;) as file: # Get entire file content file_data = file.read() # Get all lines at once lines = file.read().splitlines() # Get lines one by one line1 = file.readline() line2 = file.readline() This syntax handles automatically closing the file if anything goes wrong inside the with block.\nWrite File with open(\u0026#39;myFile.txt\u0026#39;, \u0026#39;w\u0026#39;, encoding=\u0026#34;utf-8\u0026#34;) as file: file.write(\u0026#39;This is a line\\n\u0026#39;) This syntax handles automatically closing the file if anything goes wrong inside the with block.\nRead File (Old Way) from typing import TextIO file: textIO = open(\u0026#39;myFile.txt\u0026#39;) try: content: str = file.read() print(content) finally: file.close() OOP Main This condition will be evaluated to True if this file is the one that was run. This is not the case is the file is imported thus the condition is will be evaluated to False.\nif __name__ == \u0026#39;__main__\u0026#39;: print(\u0026#34;Hello\u0026#34;) Class class Player: # Constructor def __init__(self, name:str) -\u0026gt; None: self.name: str = name self.health: int = 100 self.max_health: int = 100 # Method def increase_max_health(self) -\u0026gt; None: self.max_health += 10 # Init new instance of the class (a new object) myPlayer: Player = Player(name: \u0026#39;myPlayerName\u0026#39;) # Use a method myPlayer.increase_max_health() # Access an attribute print(myPlayer.max_health) # Will print 110 Class Attributes vs Instance Attributes class Player: # Class Attribute max_mana: int = 100 # Constructor def __init__(self) -\u0026gt; None: # Instance Attribute self.health: int = 100 myPlayer1: Player = Player() myPlayer2: Player = Player() # Implicitly create an Instance Attribute myPlayer1.max_mana = 200 print(myPlayer1.max_mana) # Will print 200 print(myPlayer2.max_mana) # Will print 100 # Change the Class Attribute value Player.max_mana = 300 print(myPlayer1.max_mana) # Will print 300 print(myPlayer2.max_mana) # Will print 300 Name Mangling Name mangling is a mechanism that alters attribute’s name by prefixing it with _ClassName, it concerns attributes that starts with __. This has two purposes :\npreventing from overwriting attributes that are named the same. indicates that the attribute is intended for internal use. class Player: # Constructor def __init__(self) -\u0026gt; None: self.__private_attribute: str = \u0026#34;private_str\u0026#34; myPlayer: Player = Player() print(myPlayer.__private_attribute) # Will not work print(myPlayer._Player__private_attribute) # Will work @staticmethod Adding the @staticmethod annotation allows creating a method that don't require anything from the object (self). This method could be defined outside the class but if its only relevant to this class, it can be nice to keep the code inside this class.\nclass Player: # Constructor def __init__(self) -\u0026gt; None: self.health: int = 100 self.max_health: int = 100 # Non static method def increase_max_health(self) -\u0026gt; None: self.max_health += 10 # Static method @staticmethod def say_hello() -\u0026gt; None: print(\u0026#34;Hello\u0026#34;) Also, @staticmethod allows calling the method even if no object were instantiated.\nPlayer.say_hello() Dunder Methods class Player: # Constructor def __init__(self) -\u0026gt; None: self.health: int = 100 self.max_health: int = 100 # Dunder Methods __add__(self, other): ... __mul__(self, other): ... # __str__ should return something user friendly # If __str__ is not defined is will fallback to __repr__ __str__(self) -\u0026gt; str: ... # __repr__ should return something usefull for developpers # Default is memory address __repr__(self) -\u0026gt; str: ... myPlayer1: Player = Player() myPlayer2: Player = Player() print(myPlayer1 + myPlayer2) # Will use dunder method __add__ print(myPlayer1 * myPlayer2) # Will use dunder method __mul__ print(myPlayer1) # Will use dunder method __str__ print(repr(myPlayer1)) # Will use dunder method __str__","permalink":"https://devops.kaldei.com/scripting/python/","summary":"A note about Python.","title":"Python"},{"content":"Typing Iterable The Iterable type represent every type that can be iterated (that can be looped through_): list, tuple, set, ...\nfrom typing import Iterable players_iterable: Iterator[str] = [\u0026#39;Player1, Player2, Player3\u0026#39;] players_iterable: Iterator[str] = (\u0026#39;Player1, Player2, Player3\u0026#39;) players_iterable: Iterator[str] = {\u0026#39;Player1, Player2, Player3\u0026#39;} Iterator When we get an information form an iterator with next() or list() it is removed from the iterator.\nfrom typing import Iterator players: list[str] = [\u0026#39;Player1, Player2, Player3\u0026#39;] players_iter: Iterator[str] = iter(players) print(next(players_iter)) # Player1 print(next(players_iter)) # Player2 print(next(players_iter)) # Player3 print(list(players_iter)) # [] Generator Basis A generator as 3 parameters:\n1st is the type to yield 2nd is the type that can be sent to the generator 3rd is the type that is returned by the generator Note: a Generator is under the hood an Iterator\nYield Example from typing import Generator def fibonacci_generator() -\u0026gt; Generator[int, None, None] a, b = 0, 1 while True: yield a a, b = b, (a + b) fib_gen: Generator[int, None, None] = fibonacci_generator() n: int = 10 line_break: str = \u0026#39;-\u0026#39; * 20 while True: input(f\u0026#39;Press \u0026#34;enter\u0026#34; for the next {n} numbers of ficonnacci) for i in range(n): print(f\u0026#39;{next(fib_gen)}\u0026#39;) print(line_break) Source : Indently - 5 Useful Generator Functions In Python\nYield + Return Example from typing import Generator def read(path: string) -\u0026gt; Generator[str, None, str]: with open(path, \u0026#39;r\u0026#39;) as file: for line in file: yield line.strip() return \u0026#39;This is the end of the file.\u0026#39; reader: Generator[str, None, str] = read(\u0026#39;file.txt\u0026#39;) while True: input(f\u0026#39;Press \u0026#34;enter for the next line\u0026#34;) try: print(next(reader)) except StopIteration as e: # StopIteration the return of the Genenrator print(\u0026#39;StopIteration:\u0026#39;, e.value) sys.exit() Source : Indently - 5 Useful Generator Functions In Python\nYield + Send Example from typing import Generator def cumulative_sum() -\u0026gt; Generator[float, float, None]: total: flaot = 0 while True: total += yield total # yield act like retrive cumulative_generator: Generator[float, float, None] = cumulative_sum() next(cumulative_generator) # start the generator while True: value: float = float(input(\u0026#39;Enter a value: \u0026#39;)) current_sum: float = cumulative_generator.send(value) print(f\u0026#39;Cumulative sum: {current_sum}\u0026#39;) Source : Indently - 5 Useful Generator Functions In Python\nItertools Product from itertools import product my_list: list[str] = [\u0026#39;A\u0026#39;, \u0026#39;B\u0026#39;, \u0026#39;C\u0026#39;] # Return all the combinations of the list with specified lenght (repeat) products: product = product(my_list, repeat=2) for product in products: print(product) \u0026#34;\u0026#34;\u0026#34; This will output this: (\u0026#39;A\u0026#39;, \u0026#39;A\u0026#39;) (\u0026#39;A\u0026#39;, \u0026#39;B\u0026#39;) (\u0026#39;A\u0026#39;, \u0026#39;C\u0026#39;) (\u0026#39;B\u0026#39;, \u0026#39;A\u0026#39;) (\u0026#39;B\u0026#39;, \u0026#39;B\u0026#39;) (\u0026#39;B\u0026#39;, \u0026#39;C\u0026#39;) (\u0026#39;C\u0026#39;, \u0026#39;A\u0026#39;) (\u0026#39;C\u0026#39;, \u0026#39;B\u0026#39;) (\u0026#39;C\u0026#39;, \u0026#39;C\u0026#39;) \u0026#34;\u0026#34;\u0026#34; Source: 5 Useful Iterator Functions in Python - Indently\nPandas Import import pandas as pd Create a DataFrame # The data dictionary can be like this data = {\u0026#39;col_1\u0026#39;: [3, 2, 1, 0], \u0026#39;col_2\u0026#39;: [\u0026#39;a\u0026#39;, \u0026#39;b\u0026#39;, \u0026#39;c\u0026#39;, \u0026#39;d\u0026#39;]} # or a list of dicts data = [ {\u0026#39;col1\u0026#39;:\u0026#39;value1\u0026#39;,\u0026#39;col2\u0026#39;:\u0026#39;value1\u0026#39;}, {\u0026#39;col1\u0026#39;:\u0026#39;value2\u0026#39;,\u0026#39;col2\u0026#39;:\u0026#39;value2\u0026#39;} ] # Create DataFrame form dict df = pd.DataFrame.from_dict(data) Select Columns # This can be used to rearrange the columns order df = df[[\u0026#39;my_column_name_3\u0026#39;, \u0026#39;my_column_name_1\u0026#39;, \u0026#39;my_column_name_4\u0026#39;]] Rename Columns df = df.rename(columns={\u0026#39;column_name_1\u0026#39;: \u0026#39;my_column_name_1\u0026#39;}) Drop Columns df = df.drop(columns=[\u0026#39;my_column_name_3\u0026#39;, \u0026#39;my_column_name_4\u0026#39;]) Sort Values df = df.sort_values(by=\u0026#39;my_column_name_2\u0026#39;) Group By and Count df = df.groupby([\u0026#39;my_column_name_2\u0026#39;]).size().reset_index(name=\u0026#39;count\u0026#39;) Left Join merged_df = pd.merge( left_dataset, right_dataset, how=\u0026#39;left\u0026#39;, left_on=\u0026#39;left_column_name\u0026#39;, right_on=\u0026#39;right_column_name\u0026#39; ) Time Locale import locale print(locale.getlocale()) #(\u0026#39;en_US\u0026#39;, \u0026#39;UTF-8\u0026#39;) # Set local to get right format for the date locale.setlocale(locale.LC_TIME, locale.getlocale()) Datetime import datetime print(f\u0026#39;{datetime.datetime.now()}\u0026#39;) #2024-08-02 22:30:04.850285 print(f\u0026#39;{datetime.datetime.now():%c}\u0026#39;) #Fri 02 Aug 2024 10:30:01 PM print(f\u0026#39;{datetime.datetime.now():%x}\u0026#39;) #08/02/2024 Regex Match import re MY_REGEX = \u0026#34;.*\u0026#34; # Cache the regex (usefull if expression is reused multilple times) re_compiled = re.compile(MY_REGEX) # Check if a string matches the expression if re_compiled.match(myString) print(f\u0026#34;Expression matched for: {myString}\u0026#34;) Useful Regex IP_REGEX = r\u0026#34;^([0-9]{1,3}\\.){3}[0-9]{1,3}$\u0026#34; Scapy Send packets import scapy IP_DEST = \u0026#34;10.0.0.12\u0026#34; # Create a packet pkt = IP(dst=IP_DEST)/ICMP() # ICMP packet ptk = IP(dst=IP_DEST)/TCP(dport=53, flags=\u0026#34;S\u0026#34;) # TCP packet # Send packets send(pkt) # Send packet only sr1(pkt) # Send and receive one packet sr(pkt) # Send and receive packets (loop) # Display packets content pkt.show() # Show packet pkt.show2() # Show actual packet that will be transmitted pkt.hexdump() # Show packet hexdump Sniff import scapy MY_LISTEN_IFACE = \u0026#34;wlp1s0\u0026#34; FILTER_HOST = \u0026#34;host 10.0.0.12\u0026#34; FILTER_PORT = \u0026#34;port 80\u0026#34; FILTER_TCP = \u0026#34;tcp[tcpflags] \u0026amp; (tcp-push) != 0\u0026#34; # Filter ACKs and SYNs BPF_FILTER = FILTER_HOST + \u0026#34;and\u0026#34; + FILTER_PORT + \u0026#34;and\u0026#34; + FILTER_TCP pkts = sniff( iface=MY_LISTEN_IFACE, # Interface to sniff filter=BPF_FILTER, # Berkeley Packet Filter prn=lambda x:x.show() # Callback to display packet as they’re captured ) Pcap files import scapy # Sniff network for 10 packets pkts = sniff(count=10) # Write packets in a pcap file wrpcap(\u0026#34;myPcap.pcap\u0026#34;, pkts) import scapy # Import pcap file content pcap = rdpcap(\u0026#34;myPcap.pcap\u0026#34;) PwnTools Interact with a binary from pwn import * p = process(\u0026#34;./my-bin\u0026#34;) # Execute the binary p.recvuntil(\u0026#34;Enter your name:\u0026#34;) # Read until reach specified string p.interactive() # Interact with the binary via terminal Send a payload to a remote machine import pwn offset = 5*8 payload = b\u0026#39;A\u0026#39;*offset+pwn.p64(0x1122334455667788) c = pwn.remote(\u0026#34;TAGET_HOST\u0026#34;,TARGET_PORT) c.sendline(payload) c.interactive()","permalink":"https://devops.kaldei.com/scripting/python-libs/","summary":"A note about Python Libraries.","title":"Python Libs"},{"content":"Dict Sort Values in Reverse Order dict(sorted(myDict.items(), key=lambda x: x[1],reverse=True)) import operator dict(sorted(myDict.items(), key=operator.itemgetter(1),reverse=True)) Files Copy Files Source: How To Copy Files - Intently\nfrom tkinter import filedialog from pathlib import Path import shutil # Open a file explorer window to choose a file src_path: str = filedialog.askopenfilename(title=\u0026#39;Pick a file to copy\u0026#39;) # Open a file explorer window to choose a directory dst_directory: str = filedialog.askopendirectory(title=\u0026#39;Pick a destination\u0026#39;) # Path handle path regardless of the OS dst_path: Path = Path(directory) / f\u0026#39;copy.{src_path.split(\u0026#34;.\u0026#34;)[-1]}\u0026#39; # Copy a file without metadata shutil.copyfile(src=src_path, dst=dst_path) # Copy a file with metadata shutil.copy2(src=src_path, dst=dst_path)","permalink":"https://devops.kaldei.com/scripting/python-recipes/","summary":"A note about Python useful bits of code.","title":"Python Recipes"},{"content":"Basis Syntax /.../\nA regex is enclosed between two forward slashes.\n\\\nCancels the special effect of a special character.\n|\nAlternative (or).\n^\nStart of line.\n$\nEnd of line.\n[ ab ]\nMatch one of the characters inside the square brackets (a or b).\n[ a-z ]\nMatch on a range of characters.\n[^a]\nMatch if the character is not the one that is after the ^.\n(myWord)\nMatch the group inside the parenthesis.\n.\nMatch any character.\n?\nThe preceding element is present 0 or 1 times.\n{ 2 }\nThe preceding element is repeated a defined a number of times.\n{ 0,3 }\nThe preceding element is repeated between 0 and 3 times.\n*\nThe preceding element is repeated between 0 and infinite number of times.\n+\nThe preceding element is repeated between 1 and infinite number of times.\nPython import re MY_REGEX = \u0026#34;.*\u0026#34; # Cache the regex (usefull if expression is reused multilple times) re_compiled = re.compile(MY_REGEX) # Check if a string matches the expression if re_compiled.match(myString) print(f\u0026#34;Expression matched for: {myString}\u0026#34;) Useful Regex IP IP_REGEX = r\u0026#34;^([0-9]{1,3}\\.){3}[0-9]{1,3}$\u0026#34; ip a show eth0 | grep -oP '(?\u0026lt;=inet\\s)\\d+(.\\d+){3}' Extract IP from ip a.\n","permalink":"https://devops.kaldei.com/scripting/regex/","summary":"A sequence of characters to match pattern in text.","title":"Regex"},{"content":"Variables Basis myVar=myValue\nAssign a value to the variable (warning, no space!).\nmyVar=$(whoami)\nAssign command output to the variable.\n$myVar\nAccess variable content.\nArray myArray=()\nCreate an empty array.\nmyArray=( 12 12 )\nCreate an array with values (note the space between values).\nmyArray[0]=myValue\nAssign a value to the first value of the array.\nmyArray+=(myValue)\nAppend value at the end of the array (add a value).\n${myArray[0]}\nReturn the first value of the array.\n${myArray[@]}\nReturn the whole array.\n${myArray[3:@]}\nReturn the values form third to last.\n${#myArray[@]}\nReturn the array size.\nSpecial Variables $?\nOutput code of previously executed program.\n$0\nPath of the currently called script.\n$1, $2 ...\nArguments passed to the script.\n$#\nArguments numbers.\n$@\nReturn all the arguments.\ndate\nReturn date, time, and time difference.\ndate \u0026quot;+%H\u0026quot;\nReturn the current hour. (%H = hour, %M = minute, %S = second, …).\nseq 1 12\nReturn a number sequence.\nStructures Condition if [ boolean ] then ... elif then ... else ... fi\nFor Loop for i in `seq 0 100` do ... done for i in {1..100} do ... done directories=( myDir1 myDir2 myDir3) for directory in \u0026#34;${directories[@]}\u0026#34;; do mkdir -p $directory ... done While Loop # Read lines for file while read line do echo $line done \u0026lt; myFile while read line; do echo $line; done \u0026lt; myFile.txt\nOne liner version of while loop to read file.\nRedirections Chevrons \u0026gt;\nRedirects to a file (if it already exists, it will be overwritten).\n\u0026gt;\u0026gt;\nRedirects to the end of a file (if it doesn't exist, it will be created).\n2\u0026gt;\nRedirects errors to a file (if it already exists, it will be overwritten).\n2\u0026gt;\u0026gt;\nRedirects errors to the end of a file (if it doesn't exist, it will be created).\n2\u0026gt;\u0026amp;1 Redirects errors in the standard output.\n\u0026lt; myFile\nSends a file as a input command.\nKEYWORD \u0026lt;\u0026lt;\nSwitches the console to keyboard input mode, line by line. All the lines will be sent when the end keyword has been written.\n\u0026lt;\u0026lt;\u0026lt; myString\nSends a string as a input command.\nAmpersand cmd1 \u0026amp; cmd2\nFirst command will be executed in background.\ncmd1 \u0026amp;\u0026amp; cmd2\nSecond command is executed if the first command return code is 0 (ok).\nPipe cmd1 | cmd2\nChains commands (output from command 1 is sent to command 2).\ncmd1 || cmd2\nSecond command is executed if the first command return code is not 0 (error).\n","permalink":"https://devops.kaldei.com/scripting/shell-bash/","summary":"A note about Bash.","title":"Shell Bash"},{"content":"Output Log Function LOGFILE=\u0026#34;/var/log/log_file.log\u0026#34; function log { local level=\u0026#34;$1\u0026#34; local message=\u0026#34;$2\u0026#34; local timestamp=$(date +\u0026#34;%Y-%m-%d %H:%M:%S\u0026#34;) local log_entry=\u0026#34;$timestamp [$level] - $message\u0026#34; echo \u0026#34;$log_entry\u0026#34; | tee -a \u0026#34;$LOGFILE\u0026#34; } log \u0026#34;INFO\u0026#34; \u0026#34;Installing myPackage\u0026#34; ... log \u0026#34;ERROR\u0026#34; \u0026#34;Failed Installing myPackage\u0026#34;","permalink":"https://devops.kaldei.com/scripting/shell-bash-recipes/","summary":"A note about Bash useful bits of code.","title":"Shell Bash Recipes"},{"content":"Basis Fish Fish generally works like other shells, like Bash or Zsh. A few important differences can be found at https://fishshell.com/docs/current/tutorial.html by searching for the magic phrase \u0026quot;unlike other shells\u0026quot;.\nConfig fish_config\nOpen web interface to config fish.\nfish_add_path /my/path/to/add\nAdd new path to PATH.\nAlias alias --save k=\u0026quot;kubectl\u0026quot;\nCreate an alias (--save make permanent).\nVariables Set Variable set MY_VAR myValue\nSet variable.\n-x\nExport the variable (make it an environment variable, available to child processes).\n-g\nGlobal variable (available to all function in the same shell).\n-U\nSet \u0026quot;Universal\u0026quot; variable (available all fish instances and persist across restarts).\nStructures While while read line; echo $line; end \u0026lt; myFile.txt\nOne liner version of while loop to read file.\n","permalink":"https://devops.kaldei.com/scripting/shell-fish/","summary":"A note about the Fish shell.","title":"Shell Fish"},{"content":"Files Terraform Directory This directory is used to store the project's providers and modules. It contains two subdirectories: modules and providers. Manage Providers Version .terraform.lock.hcl :\nUsed to lock dependencies (providers and modules) versions. To be included in the VSC. By default, Terraform will attempt to download the provider version specified by the lock file. If the lock file does not exist, Terraform will use the required_providers block. If neither exists, Terraform will download the latest provider version. terraform.tf:\nContain the terraform block. State terraform.tfstate Stores the IDs and properties of the resources Can contain credentials Note: Descriptions (of variables outputs, ...) are not stored in the state file.\nCLI Config File Windows: %APPDATA%\\terraform.rc Others: ~/.terraformrc Resources Files main.tf: Deploy resources using providers. Variables Local Variables Local variables are only accessible within the module they are declared.\nlocals { my_varaible_1 = \u0026#34;my_value_1\u0026#34; my_varaible_2 = \u0026#34;my_value_2\u0026#34; my_varaible_3 = { my_sub_varaible_1 = \u0026#34;my_value_3\u0026#34; my_sub_varaible_2 = \u0026#34;my_value_4\u0026#34; } } Then in resources, use the following:\nressource \u0026#34;my_resource_type\u0026#34; \u0026#34;my_resource_name\u0026#34;{ ... my_parameter1 = local.my_varaible_1 my_parameter2 = local.my_varaible_1 my_parameter_list = local.my_varaible_3 } Variables All attributes in a variable block are optional.\nHere is an example of a String variable:\nvariable \u0026#34;my_map_variable\u0026#34; { type = string # Type of the variable defautl = \u0026#34;my_value\u0026#34; # Default value for the varaible descritption = \u0026#34;This a variable\u0026#34; # Descritpion # Warning: the value will still be in the state file sensitive = true # Do not show this value in output validation = ... # Constraint or condition on the varaible } Here is an example of a Map Variable:\nvariable \u0026#34;my_map_variable\u0026#34; { type = map my_map = {key1 = \u0026#34;value1\u0026#34;, key2 = \u0026#34;value2\u0026#34;, key3 = \u0026#34;value3\u0026#34;} } # Access a value ressource \u0026#34;my_resource_type\u0026#34; \u0026#34;my_resource_name\u0026#34;{ ... my_value = my_map_variable.my_map[key1] } Variable Provisioning There are 3 ways to provision variables\nVariables Files In my_file.tf:\nvariable \u0026#34;my_variable\u0026#34; { } In my_variables_file.tfvars:\nmy_variable = \u0026#34;my_value\u0026#34; Then use -var-file=\u0026quot;my_variables_file.tfvars\u0026quot; in the CLI.\nNotes:\nVariables in the variables.tf files are \u0026quot;required\u0026quot;. Terraform will not run if these variables do not have values.` Terraform load by automatically default variables files: that are named exactly terraform.tfvars or terraform.tfvars.json. any files with names ending in .auto.tfvars or .auto.tfvars.json. CLI Parameter If a variable is used, but no value is attributed to it, the CLI will ask to enter a value. The value can also directly be passed with the command with -var=\u0026quot;my_var=my_value\u0026quot; or by ).\nEnvironment Variables Create environment variables starting with TF_VAR_:\nexport TF_VAR_myVar=myValue Precedence Terraform loads variables in the following order, with later sources taking precedence over earlier ones:\nEnvironment variables The terraform.tfvars file, if present. The terraform.tfvars.json file, if present. Any *.auto.tfvars or *.auto.tfvars.json files, processed in lexical order of their filenames. Any -var and -var-file options on the command line, in the order they are provided. (This includes variables set by a Terraform Cloud workspace.) Blocks Terraform The terraform block contains the settings including:\nrequired_providers block: specifies the provider local name, the source address, and the version. Required Providers By default, Terraform will attempt to download the provider version specified by the lock file. If the lock file does not exist, Terraform will use the required_providers block. If neither exists, Terraform will download the latest provider version.\nterraform { required_providers { azurerm = { source = \u0026#34;hashicorp/azurerm\u0026#34; version = \u0026#34;=3.0.0\u0026#34; } } } Versions Constraints version = \u0026#34;= 3.0.0\u0026#34; # Fix the version version = \u0026#34;\u0026gt;= 3.0.0\u0026#34; # Set a minimum version versiom = \u0026#34;~\u0026gt; 3.0.0\u0026#34; # Allows for minor upgrades Provider This block contains providers configurations.\nprovider \u0026#34;my_provider\u0026#34; { ... } When you need to use the same provider but with different parameters, it is required to specify aliases (otherwise Terraform will not be able to know which provider to use). And then specify the alias in resource blocks.\nprovider \u0026#34;my_provider\u0026#34; { ... alias = \u0026#34;my_provider_alias\u0026#34; } ressource \u0026#34;my_resource_type\u0026#34; \u0026#34;my_resource_name\u0026#34;{ ... provider = my_provider.my_provider_alias } Backend Note: When a change is made to the backend configuration, it is required to re-run terraform init.\nLocal Backend When there is no cloud or backend Terraform defaults to the local backend. The local backend can be explicitly described like this (optional):\nterraform { backend \u0026#34;local\u0026#34; { path = \u0026#34;relative/path/to/terraform.tfstate\u0026#34; } } Remote Backends Available Remote Backends:\nazurerm consul cos gcs http Kubernetes oss pg s3 Backend that support State Storage with default locking:\nazurem gcs Terraform Cloud Backend https://developer.hashicorp.com/terraform/tutorials/cloud/cloud-migrate If the cloud block is present, Terraform will integrate with Terraform Cloud and create a Terraform Cloud workspace with the name specified in the block.\nWarning: For the Cloud backend to work, it is required to set the deployment environment credentials in the Variables section of the workspace on Terraform Cloud.\nterraform { backend { # Organization name can be found on Terraform Cloud organization = \u0026#34;my-organization-name\u0026#34; workspaces { name = \u0026#34;my-workspace\u0026#34; } } } terraform login\nLogin to Terraform Cloud.\nterraform init\nReinitialize configuration, create the my-workspace workspace in Terraform Cloud and migrate state to Terraform Cloud.\nrm terraform.tfstate\nDelete local Terraform State.\nOutputs Outputs are used for showing information to the admin and passing information between modules.\noutput \u0026#34;my_output\u0026#34; { value = my_ressource.my_attribute description = \u0026#34;This an output\u0026#34; # Warning: the value will still be in the state file sensitive = true # Do not show this value in output } For In Structure output \u0026#34;my_output\u0026#34; { value = { for subnet in aws_subnet.public : subnet.tags.Name =\u0026gt; subnet.id } } my_output = { subnet_public_0 = \u0026#34;subnet-0fb6244694b0541cc\u0026#34; subnet_public_1 = \u0026#34;subnet-01fee6936ba518b49\u0026#34; subnet_public_2 = \u0026#34;subnet-0399dad1114e521aa\u0026#34; } Resource Define the resource. The ID of the resource is my_ressource_type.my_ressource_name\nressource \u0026#34;my_ressource_type\u0026#34; \u0026#34;my_ressource_name\u0026#34; {} Module Define the module to use with its path in parent module.\nmodule \u0026#34;my_module\u0026#34; { source = \u0026#34;./network_module\u0026#34; # Set value for a variable inside the module module_variable = \u0026#34;My Value\u0026#34; } Use module output in parent module.\nvariable \u0026#34;my_child_value\u0026#34; { value = module.my_module.my_module_output } Functions String Functions upper(\u0026quot;myString\u0026quot;)\nReturn uppercased string.\nCollection Functions element(list, index)\nReturn an element in a list by its index.\nzipmap(keyslist, valueslist)\nCreate a map from a list of keys and a list of values\nMeta-Arguments Count The count meta-argument is used to create a defined number of instances of the resource or module.\n","permalink":"https://devops.kaldei.com/iac/terraform-basics/","summary":"A note about the basics of Terraform (Files and Blocks).","title":"Terraform Basics"},{"content":"Workflow Initialize terraform init\nInitialize working directory (configure the backend, install providers and modules, and create lock file).\nterraform init -backend-config=myBackendVars.tfvars\nInitialize with a backend var file.\nterraform init -upgrade\nInitialize and upgrade providers to the latest version that respects the constraint in the required_providers block. Update the version and signature in the lock file.\nterraform get\nUpgrade module version when you change a module's source or version (same as doing terraform init again).\nterraform providers\nShow providers used in the current configuration.\nterraform providers -schema\nPrint detailed schemas for the providers.\nValidate and Format (optional) terraform validate\nCheck for syntax errors in configuration files.\nterraform init -backend=false terraform validate\nValidate the configuration without accessing the backend.\nterraform fmt\nFormat configuration files in current directory (print out names of modified files).\nterraform fmt -recursive\nFormat configuration files in current directory and subdirectories.\nPlan terraform plan\nShow expected changes (Execution Plan).\nterraform plan -destroy\nShow expected deletions (Destruction Plan).\nterraform plan -out=my_tfplan.zip\nSave plan to a zip archive.\nPlan output signification:\n+: Create -: Destroy -/+: Destroy and Recreate ~: Update Apply terraform apply\nRun Plan, then Apply changes.\nterraform apply my_tfplan.zip\nApply changes form Plan file (will not ask for approbation).\nterraform apply -replace=my_resource\nForce the replacement of a resource even if there are no changes in its configuration.\nterraform apply -parallelism=12\nSet the maximum number of concurrent API calls made to the providers.\nDefault value is 10.\nBefore increasing the value consider reworking resource dependencies.\nDestroy terraform destroy\nDelete provisioned infrastructure.\nWorkspaces Explore terraform workspace list\nList current workspace.\nterraform workspace select myWorkspace\nChange workspace.\nCreate terraform workspace new myWorkspace\nCreate new workspace.\nDelete terraform workspace delete myWorkspace\nDelete a workspace. Note: The Default workspace can't be deleted.\nState Browse State Warning: State files can contain sensitive data. Never commit a State file to version control system.\nterraform state pull\nReturn the full state.\nterraform state list\nList resources in current state.\nterraform state show myResource.myProperty\nDisplay resource property.\nModify State terraform state mv my_old_resource my_new_resource\nRename a resource.\nterraform state remove myResourceType.myResourceName\nRemove resource from state (the resource will not be destroyed, just not managed by Terraform anymore).\nterraform state push my_state.json\nOverwrite remote state with a local state file (this should be avoided if possible).\nterraform import myResourceType.myResourceName cloudResourceID\nImport a resource (add it to the state). The resource has to be defines in a tf file.\nterraform refresh\nUpdate state to match actual remote resources. Deprecated because it is unsafe. It is an alias for terraform apply -refresh-only -auto-approve.\nLock terraform force-unlock my_lock_ID\nManually unlock state.\nEnvironment Variables Log export TF_LOG=trace\nEnable maximum verbosity (TRACE \u0026gt; DEBUG \u0026gt; INFO \u0026gt; WARN \u0026gt; ERROR).\nexport TF_LOG=off\nDisable detailed logs.\nInput export TF_INPUT=0\nDisable prompts for variables that haven't had their values specified (same as -input=false).\nConfig export TF_CLI_CONFIG_FILE=\u0026quot;$HOME/.terraformrc-custom\u0026quot;\nSet the location of the CLI config file.\n","permalink":"https://devops.kaldei.com/iac/terraform-cli/","summary":"A note about the Terraform CLI.","title":"Terraform CLI"},{"content":"Panes Split Ctrl + b then %\nSplit screen vertically.\nCtrl + b then \u0026quot;\nSplit screen horizontally.\nResize Ctrl + b + →\nResize current panel.\nFocus Ctrl + b then →\nChange focus to right panel.\nNavigate Ctrl + b then [\nMove your cursor up and down.\nWindows Create Ctrl + b then c\nCreate a new tab.\nSwitch Ctrl + b then 1\nSwitch to tab 1.\nSessions List tmux ls\nList current existing sessions (alias for list-sessions).\nManage Ctrl+b then $\nor\ntmux rename-session -t mySessionId myNewName\nRenamed a session.\nAttach Ctrl + b then d\nor\ntmux detach\nDetach form session.\ntmux attach -t mySessionId\nAttach to a session.\nNavigate Ctrl + b then s\nOpen Tmux session manager\nCtrl + b then )\nor Ctrl + b then (\nQuickly switch between sessions\nConfiguration # Set predix shortcut set -g prefix ^B # Start indexing windows at 1 instead of 0 set -g base-index 1 # Renumber windows when one is closed set -g renumber-windows on","permalink":"https://devops.kaldei.com/cli/tmux/","summary":"A terminal multiplexer for Unix-like OS","title":"TMUX"},{"content":"Basis Workflow vagrant init\nCreate default Vagrant file.\nvagrant up\nCreate VMs.\nvagrant reload\nRestart VMs.\nvagrant destroy\nDelete VMs.\nvagrant ssh\nConnect to VM with SSH.\nvagrant suspend\nPause VMs.\nvagrant resume\nUnpause VMs\nBoxes Boxes are ready to use Vagrant VMs. They can be find here: https://app.vagrantup.com/boxes/search\nvagrant box list\nShow locally available boxes.\nvagrant box add myBox\nDownload a box from Vagrant Cloud.\nvagrant box remove myBox\nRemove a local box.\nPlugins Basis vagrant plugin list\nShow locally available boxes.\nvagrant plugin install myPlugin\nInstall a plugin.\nVMware Workstation https://developer.hashicorp.com/vagrant/docs/providers/vmware/configuration\nvagrant plugin install vagrant-vmware-desktop\nInstall VMware Workstation Plugin\nFor it to work, it is required to install Vagrant VMware Utility: https://developer.hashicorp.com/vagrant/docs/providers/vmware/vagrant-vmware-utility\nVMware ESXi https://github.com/josenk/vagrant-vmware-esxi\nvagrant plugin install vagrant-vmware-esxi\nInstall VMware ESXi plugin\nvagrant up --provider=vmware_esxi\nTo use the plugin specify the provider when using Vagrant commands.\n","permalink":"https://devops.kaldei.com/iac/vagrant-cli/","summary":"A note about the Vagrant CLI.","title":"Vagrant CLI"},{"content":"Basis Env Variables export VAULT_TOKEN=hvs.xxxxxxxxxxxxxxxx\nSet Token for Token Authentication Method.\nexport VAULT_SKIP_VERIFY=true\nSkip TLS check.\nInitialization Check Status vault status\nCheck if server is running.\nInitialize and Unseal Vault vault operator init\nInitialize Vault (default values).\nvault operator init -recovery-shares=5 -recovery-threshold=3\nInitialize Vault with specified values.\nvault operator unseal\nAsk for an unseal keys to unlock the vault (it unlocks when the required number of unseal keys are given).\nLogin vault login\nLogin to Vault using a Token.\nvault login -method=userpass username=\u0026quot;my_user\u0026quot; password=\u0026quot;my_pass\u0026quot;\nLogin to Vault using UserPass.\nvault login -method=oidc role=\u0026quot;my_role\u0026quot;\nLogin to Vault with OIDC.\nvault write auth/approle/login role_id=\u0026quot;my_role_id\u0026quot; secret_id=\u0026quot;my_secret_id\u0026quot;\nLogin to Vault using AppRole.\nvault write auth/jwt/login role=my_role jwt=my_jwt\nLogin to Vault using a JWT.\nTokens Lookup vault list auth/my_auth_method/accessors\nList tokens created with specified Auth Method.\nvault token lookup -accessor \u0026lt;token_accessor\u0026gt;\nReturn info about the token (type, TTL, max TTL ...).\nCreate vault token create -policy=my_policy -ttl=30m\nCreate a token with a specified Policy and TTL.\nvault token renew myToken\nRenew a token.\nRevoke vault token revoke \u0026lt;token_id\u0026gt;\nRevoke token.\nvault token revoke -accessor \u0026lt;token_accessor\u0026gt;\nRevoke token using its accessor.\nvault token revoke -self\nRevoke current token.\nvault token revoke -mode-path auth/my_auth_method\nRevoke all tokens (and their children) created with specified auth method.\nTraceability Entity vault list identity/entity/id\nList entities.\nvault delete identity/entity/id/f53c4994-8458-6b6c-8cff-eaf869c9aefc\nDelete entity.\nAudit Device vault audit list\nList audit devices.\nvault audit enable file file_path=/var/log/vault_audit.log\nCreate an audit device (the user running Vault has to be able to write to the given path).\nvault audit disable file\nDisable specified audit device.\nvault write sys/audit-hash/file input=\u0026quot;P@ssword!\u0026quot;\nCompute the hash for a given input (can be used to check hashed values in audit file). Warning: only admin should be able to write in sys/audit-hash/file.\nAccess Control Lease vault lease revoke aws/creds/myRole/my_lease_id\nRevoke specified lease.\nvault lease revoke -prefix aws/\nRevoke all leases under the specified prefix.\nPolicy vault policy list\nList policies.\nvault policy read my-policy\nRead policy content.\nvault policy write my-policy my-policy.hcl\nCreate a policy from local file.\nvault token capabilities hvs.XXXXXXXXXXXX /transit/encrypt/my_key\nCheck capabilities of a token for the given path (output example: update).\nNamespaces (Enterprise) vault namespace list\nList namespaces.\nvault namespace create my-namespace\nCreate namespace.\nvault namespace delete my-namespace\nDelete namespace.\nvault secrets list -namespace=my_namespace\nUse a namespace in a command.\nAuthentication Methods List vault auth list\nList authentication backends enabled.\nEnable vault auth enable oidc\nEnable an authentication backend (e.g. OIDC).\nSecret Engines For more details on specific Secret Engines see: Vault CLI Secret Engines\nList vault secrets list\nReturn info about secret engines.\nvault secrets list -detailed\nReturn more info about secret engines (e.g. KV version).\nEnable vault secrets enable kv\nEnable a secret engine (e.g KV).\nModify vault secrets move my/old/path my/new/path\nChange the path of the Secret Engine.\nvault secrets tune -default-lease-ttl=12h\nChange the configuration of the Secret Engine.\nOperator Regenerate Root Token WARNING: Before revoking the current root token, remember that generate-root endpoints are now authenticated and need the following ACL.\n# Status (-init, -cancel) path \u0026#34;sys/generate-root/attempt\u0026#34; { capabilities = [\u0026#34;read\u0026#34;, \u0026#34;update\u0026#34;, \u0026#34;delete\u0026#34;] } # Submit a key share path \u0026#34;sys/generate-root/update\u0026#34; { capabilities = [\u0026#34;update\u0026#34;] } # Only needed if the CLI decodes the token server side path \u0026#34;sys/decode-token\u0026#34; { capabilities = [\u0026#34;update\u0026#34;] } vault operator generate-root -generate-otp\nGenerate an OTP for the generate-root command.\nvault operator generate-root -init -otp=\u0026lt;otp_token\u0026gt;\nInitialize Root Token Generation. Give the generated nonce to the Recovery Keys holders.\nvault operator generate-root -nonce=\u0026lt;request_nonce\u0026gt;\nValidate the request with every one that has a Recovery Keys until quorum is reached. This will return the encoded token.\nvault operator generate-root -decode=\u0026lt;encoded_token\u0026gt; -otp=\u0026lt;otp_token\u0026gt;\nDecode the newly generated Root Token.\nReKey (Regenerate Unseal Keys) vault operator rekey -init -key-shares=3 -key-threshold=2\nInitialize request for ReKey.\nvault operator rekey -nonce=\u0026lt;request_nonce\u0026gt;\nValidate the request with Useal Keys until quorum is reached. This will output new Unseal.\nvault operator rekey -target=recovery -init -key-shares=3 -key-threshold=2\nInitialize request for ReKey with Recovery Key mode (Auto Unseal enabled).\nvault operator rekey -target=recovery -nonce=\u0026lt;request_nonce\u0026gt;\nValidate the request with Recovery Keys until quorum is reached. This will output new Unseal.\nRotate Encryption Keys vault operator rotate\nVault automatically rotate the Encryption Key.\nRaft Cluster vault operator raft list-peers\nList Raft members.\nvault operator raft autopilot state\nShow current cluster autopilot state.\nvault operator raft autopilot get-config\nShow autopilot config.\nSnapshot vault operator raft snapshot save backup.snap\nCreate a Snapshot.\nvault operator raft snapshot restore -force backup.snap\nRestore Snapshot from local file (copy the Snapshot file on the machine to restore). -force option is required here since the Auto-Unseal or Shamir keys will not be consistent with the snapshot data (snapshot from a different cluster). https://developer.hashicorp.com/vault/tutorials/standard-procedures/sop-restore\nSnapshot Auto (Enterprise) vault list /sys/storage/raft/snapshot-auto/config\nList Auto Snapshot configs.\nvault read /sys/storage/raft/snapshot-auto/config/my-auto-snapshot-config\nCheck specified Auto Snapshot config.\nReplication Basis vault read sys/replication/status\nCheck replication status (DR and Performance).\nDisaster Recovery https://developer.hashicorp.com/vault/tutorials/enterprise/disaster-recovery\nvault read sys/replication/dr/status\nCheck DR replication status.\nvault write -f sys/replication/dr/primary/enable\nEnable DR replication as Primary.\nvault write sys/replication/dr/primary/secondary-token id=dr-secondary\nCreate a token for a Secondary cluster.\nvault write sys/replication/dr/secondary/enable token=DR_SECONDARY_TOKEN\nEnable DR replication as Secondary.\nPerformance https://developer.hashicorp.com/vault/tutorials/enterprise/performance-replication#configure-the-secondary-cluster\nvault read sys/replication/performance/status\nCheck Performance replication status.\nvault write -f sys/replication/performance/primary/enable\nEnable Performance replication as Primary.\nvault write sys/replication/performance/primary/secondary-token id=perf-secondary\nCreate a token for a Secondary cluster.\nvault write sys/replication/performance/secondary/enable token=PERF_SECONDARY_TOKEN\nEnable Performance replication as Secondary.\nAgent Basis vault agent generate-config -type=\u0026quot;env-template\u0026quot; -exec=\u0026quot;./my_script.sh\u0026quot; -path=\u0026quot;secret/my_secret\u0026quot; agent-config.hcl\nGenerate a configuration file for an agent.\nvault agent -config=agent-config.hcl\nRun an agent.\n","permalink":"https://devops.kaldei.com/iac/vault-cli/","summary":"A note about the Vault CLI.","title":"Vault CLI"},{"content":"KV Enable (KV v1) vault secrets enable kv\nEnable KV v1 secret engine (default is KV v1).\nvault secrets enable kv -version=1\nEnable KV v1 secret engine.\nvault kv enable-versioning my_kv_path\nEnable versioning for a KV v1 Secret Engine (convert to KV v2).\nEnable (KV v2) vault secrets enable kv-v2\nEnable KV v2 secret engine.\nvault secrets enable kv -version=2\nEnable KV v2 secret engine.\nList vault kv list my_kv_path\nList secrets in a kv secret engine.\nGet vault kv get my_secret\nRead a secret.\nvault kv get -format=json my_secret | jq -r .data\nRead a secret and output in JSON.\nvault kv get -field=password my_credentials\nRead one field.\nvault kv get -format=json my_credentials | jq -r .data.data.password\nRead one field and output in JSON.\nPut vault kv put my_secret key=value\nCreate or replace a secret with one key value.\nvault kv put my_credentials username=myUser password=myPass\nCreate or replace a new secret composed multiple key values.\nPatch (KV v2) vault kv patch my_credentials password=myNewPass\nCreate a new version by replacing only provided values (partial update) instead of replacing all values like kv put.\nRollback (KV v2) vault kv rollback -versions=12 my_secret\nRestore a non deleted version (create a new version with the values of the one to restore).\nDelete vault kv delete my_secret\nPermanently delete the secret.\nDelete (KV v2) vault kv delete -versions=12 my_secret\nMark the version as deleted (soft delete).\nIt can be restored with vault kv undelete.\nUndelete (KV v2) vault kv undelete -versions=12 my_secret\nRestore a version of a secret. Only works if secret was not destroyed (destroyed property set to false).\nDestroy (KV v2) vault kv destroy -versions=12 my_secret\nPermanently delete specified version(s) of a secret (cannot be recovered).\nMetadata (KV v2) vault kv metadata delete my_secret\nPermanently deletes the secret (thus all of it versions).\nTransit Enable vault secrets enable transit\nEnable Transit secret engine.\nKeys vault list transit/keys\nList Keys in Transit engine.\nvault write -f transit/keys/my-key\nCreate a new Key.\nvault write -f transit/keys/my_key/rotate\nRotate the Key (create a new version).\nOld versions of the key will still exist (they are managed by min_decryption_version).\nEncryption vault write transit/encrypt/my_key plaintext=$(echo \u0026quot;my secret data\u0026quot; | base64)\nEncrypt data.\nvault write -field=plaintext transit/decrypt/my_key ciphertext=vault:v1:qRuV... | base64 -d\nDecrypt data (-field=plaintext to only get the base64 decrypted data).\nvault write transit/rewrap/my-key ciphertext=vault:v1:8SDd...\nDecrypt then re-encrypt data with a newer version of the key.\n","permalink":"https://devops.kaldei.com/iac/vault-cli-secret-engines/","summary":"A note on how to configure and interact with some Vault Secret Engines.","title":"Vault CLI Secret Engines"}]