mirror of
https://github.com/Fechin/reference.git
synced 2026-11-22 14:01:45 +03:00
Merge branch 'main' into main
This commit is contained in:
17 files changed
+5899
-61
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -1006,8 +1006,64 @@ func main() {
|
||||
var r Shape = Rectangle{Length: 3, Width: 4}
|
||||
fmt.Printf("Type of r: %T, Area: %v, Perimeter: %v.", r, r.Area(), r.Perimeter())
|
||||
}
|
||||
|
||||
```
|
||||
Go generics {.cols-2}
|
||||
-------------
|
||||
|
||||
|
||||
### example 1
|
||||
```go
|
||||
// comparable represents types that can be compared.
|
||||
type comparable interface {
|
||||
int | float64 | string
|
||||
}
|
||||
|
||||
// Max returns the maximum of two comparable values.
|
||||
func Max[T comparable](a, b T) T {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func main() {
|
||||
// Find the maximum of two integers.
|
||||
maxInt := Max(10, 20)
|
||||
fmt.Println("Max integer:", maxInt)
|
||||
|
||||
// Find the maximum of two floats.
|
||||
maxFloat := Max(3.14, 2.71)
|
||||
fmt.Println("Max float:", maxFloat)
|
||||
|
||||
// Find the maximum of two strings.
|
||||
maxString := Max("apple", "banana")
|
||||
fmt.Println("Max string:", maxString)
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### example 2
|
||||
```go
|
||||
|
||||
// Pair[T, U] represents a generic pair of values.
|
||||
type Pair[T, U any] struct {
|
||||
First T
|
||||
Second U
|
||||
}
|
||||
|
||||
func main() {
|
||||
pair := Pair[int, string]{First: 42, Second: "hello"}
|
||||
|
||||
fmt.Println("First:", pair.First)
|
||||
fmt.Println("Second:", pair.Second)
|
||||
|
||||
// Print the types of the values in the pair.
|
||||
fmt.Println("Type of First:", reflect.TypeOf(pair.First))
|
||||
fmt.Println("Type of Second:", reflect.TypeOf(pair.Second))
|
||||
}
|
||||
|
||||
```
|
||||
Miscellaneous
|
||||
-------------
|
||||
|
||||
@@ -1037,6 +1093,8 @@ Miscellaneous
|
||||
- import
|
||||
- return
|
||||
- var
|
||||
- iota
|
||||
|
||||
{.cols-3 .marker-none}
|
||||
|
||||
### Operators and punctuation
|
||||
|
||||
@@ -3,21 +3,21 @@ title: HTTP Status Code
|
||||
background: bg-[#3b7dc0]
|
||||
date: 2020-12-26 16:09:09
|
||||
tags:
|
||||
- response
|
||||
- server
|
||||
- response
|
||||
- server
|
||||
categories:
|
||||
- Other
|
||||
- Other
|
||||
intro: |
|
||||
The http status codes cheat sheet. a quick reference to every HTTP status code.
|
||||
The HTTP status codes cheat sheet. A quick reference to every HTTP status code.
|
||||
plugins:
|
||||
- tooltip
|
||||
- tooltip
|
||||
---
|
||||
|
||||
HTTP Status code
|
||||
-----------
|
||||
|
||||
|
||||
### Means
|
||||
### Means
|
||||
|
||||
- [1xx: Informational](#1xx-information){data-tooltip="It means the request has been received and the process is continuing."}
|
||||
- [2xx: Success](#2xx-successful){data-tooltip="It means the action was successfully received, understood, and accepted."}
|
||||
@@ -26,20 +26,20 @@ HTTP Status code
|
||||
- [5xx: Server Error](#5xx-server-error){data-tooltip="It means the server failed to fulfill an apparently valid request."}
|
||||
|
||||
|
||||
|
||||
### 2xx. Successful {.row-span-2}
|
||||
* [200: OK](https://tools.ietf.org/html/rfc7231#section-6.3.1){data-tooltip="The request is OK."}
|
||||
* [201: Created](https://tools.ietf.org/html/rfc7231#section-6.3.2){data-tooltip="The request is complete, and a new resource is created ."}
|
||||
* [201: Created](https://tools.ietf.org/html/rfc7231#section-6.3.2){data-tooltip="The request is complete, and a new resource is created."}
|
||||
* [202: Accepted](https://tools.ietf.org/html/rfc7231#section-6.3.3){data-tooltip="The request is accepted for processing, but the processing is not complete."}
|
||||
* [203: Non-Authoritative Information](https://tools.ietf.org/html/rfc7231#section-6.3.4){data-tooltip="The information in the entity header is from a local or third-party copy, not from the original server."}
|
||||
* [204: No Content](https://tools.ietf.org/html/rfc7231#section-6.3.5){data-tooltip="A status code and a header are given in the response, but there is no entity-body in the reply."}
|
||||
* [205: Reset Content](https://tools.ietf.org/html/rfc7231#section-6.3.6){data-tooltip="The browser should clear the form used for this transaction for additional input."}
|
||||
* [206: Partial Content](https://tools.ietf.org/html/rfc7233#section-4.1){data-tooltip="The server is returning partial data of the size requested. Used in response to a request specifying a Range header. The server must specify the range included in the response with the Content-Range header."}
|
||||
* [207: Multi-Status](https://tools.ietf.org/html/rfc4918#section-11.1){data-tooltip="Provides status for multiple independent operations."}
|
||||
* [208: Already Reported](https://tools.ietf.org/html/rfc5842#section-7.1){data-tooltip="Used inside a DAV: propstat response element to avoid enumerating the internal members of multiple bindings to the same collection repeatedly."}
|
||||
* [226: IM Used](https://tools.ietf.org/html/rfc3229#section-10.4.1){data-tooltip="The server has fulfilled a request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance."}
|
||||
|
||||
|
||||
|
||||
|
||||
### 4xx. Client Error {.row-span-3}
|
||||
### 4xx. Client Error {.row-span-3}
|
||||
* [400: Bad Request](https://tools.ietf.org/html/rfc7231#section-6.5.1){data-tooltip="The server did not understand the request."}
|
||||
* [401: Unauthorized](https://tools.ietf.org/html/rfc7235#section-3.1){data-tooltip="The requested page needs a username and a password."}
|
||||
* [402: Payment Required](https://tools.ietf.org/html/rfc7231#section-6.5.2){data-tooltip="You can not use this code yet."}
|
||||
@@ -50,38 +50,39 @@ HTTP Status code
|
||||
* [407: Proxy Authentication Required](https://tools.ietf.org/html/rfc7235#section-3.2){data-tooltip="You must authenticate with a proxy server before this request can be served."}
|
||||
* [408: Request Timeout](https://tools.ietf.org/html/rfc7231#section-6.5.7){data-tooltip="The request took longer than the server was prepared to wait."}
|
||||
* [409: Conflict](https://tools.ietf.org/html/rfc7231#section-6.5.8){data-tooltip="The request could not be completed because of a conflict."}
|
||||
* [410: Gone](https://tools.ietf.org/html/rfc7231#section-6.5.9){data-tooltip="The requested page is no longer available ."}
|
||||
* [411: Length Required](https://tools.ietf.org/html/rfc7231#section-6.5.10){data-tooltip="The "Content-Length" is not defined. The server will not accept the request without it ."}
|
||||
* [410: Gone](https://tools.ietf.org/html/rfc7231#section-6.5.9){data-tooltip="The requested page is no longer available."}
|
||||
* [411: Length Required](https://tools.ietf.org/html/rfc7231#section-6.5.10){data-tooltip="The "Content-Length" is not defined. The server will not accept the request without it."}
|
||||
* [412: Precondition Failed](https://tools.ietf.org/html/rfc7232#section-4.2){data-tooltip="The pre condition given in the request evaluated to false by the server."}
|
||||
* [413: Payload Too Large](https://tools.ietf.org/html/rfc7231#section-6.5.11){data-tooltip="The server will not accept the request, because the request entity is too large."}
|
||||
* [414: URI Too Long](https://tools.ietf.org/html/rfc7231#section-6.5.12){data-tooltip="The server will not accept the request, because the url is too long. Occurs when you convert a "post" request to a "get" request with a long query information ."}
|
||||
* [415: Unsupported Media Type](https://tools.ietf.org/html/rfc7231#section-6.5.13){data-tooltip="The server will not accept the request, because the mediatype is not supported ."}
|
||||
* [414: URI Too Long](https://tools.ietf.org/html/rfc7231#section-6.5.12){data-tooltip="The server will not accept the request, because the URL is too long. Occurs when you convert a "post" request to a "get" request with a long query information."}
|
||||
* [415: Unsupported Media Type](https://tools.ietf.org/html/rfc7231#section-6.5.13){data-tooltip="The server will not accept the request, because the media type is not supported."}
|
||||
* [416: Range Not Satisfiable](https://tools.ietf.org/html/rfc7233#section-4.4){data-tooltip="The requested byte range is not available and is out of bounds."}
|
||||
* [417: Expectation Failed](https://tools.ietf.org/html/rfc7231#section-6.5.14){data-tooltip="The expectation given in an Expect request-header field could not be met by this server."}
|
||||
* [421: Misdirected Request](https://tools.ietf.org/html/rfc7540#section-9.1.2){data-tooltip="The request was directed at a server that is not able to produce a response."}
|
||||
* [426: Upgrade Required](https://tools.ietf.org/html/rfc7231#section-6.5.15){data-tooltip="The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol."}
|
||||
* [428: Precondition Required](https://tools.ietf.org/html/rfc6585#section-3){data-tooltip="The origin server requires the request to be conditional."}
|
||||
* [429: Too Many Requests](https://tools.ietf.org/html/rfc6585#section-4){data-tooltip="The user has sent too many requests in a given amount of time."}
|
||||
* [431: Request Header Fields Too Large](https://tools.ietf.org/html/rfc6585#section-5){data-tooltip="The server is unwilling to process the request because its header fields are too large."}
|
||||
* [451: Unavailable For Legal Reasons](https://datatracker.ietf.org/doc/html/rfc7725#section-3){data-tooltip="This status code indicates that the server is denying access to the resource as a consequence of a legal demand."}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
### 1xx. Information
|
||||
* [100: Continue](https://tools.ietf.org/html/rfc7231#section-6.2.1){data-tooltip="Only a part of the request has been received by the server, but as long as it has not been rejected, the client should continue with the request."}
|
||||
* [101: Switching Protocols](https://tools.ietf.org/html/rfc7231#section-6.2.2){data-tooltip="The server switches protocol."}
|
||||
* [102: Processing](https://tools.ietf.org/html/rfc2518#section-10.1){data-tooltip="An interim response used to inform the client that the server has accepted the complete request, but has not yet completed it."}
|
||||
|
||||
|
||||
* [103: Early Hints](https://tools.ietf.org/html/rfc8297){data-tooltip="Indicates to the client that the server is likely to send a final response with the header fields included in the informational response."}
|
||||
|
||||
|
||||
### 3xx. Redirection
|
||||
* [300: Multiple Choices](https://tools.ietf.org/html/rfc7231#section-6.4.1){data-tooltip="A link list. The user can select a link and go to that location. Maximum five addresses ."}
|
||||
* [301: Moved Permanently](https://tools.ietf.org/html/rfc7231#section-6.4.2){data-tooltip="The requested page has moved to a new url ."}
|
||||
* [302: Found](https://tools.ietf.org/html/rfc7231#section-6.4.3){data-tooltip="The requested page has moved temporarily to a new url ."}
|
||||
* [303: See Other](https://tools.ietf.org/html/rfc7231#section-6.4.4){data-tooltip="The requested page can be found under a different url ."}
|
||||
* [300: Multiple Choices](https://tools.ietf.org/html/rfc7231#section-6.4.1){data-tooltip="A link list. The user can select a link and go to that location. Maximum five addresses."}
|
||||
* [301: Moved Permanently](https://tools.ietf.org/html/rfc7231#section-6.4.2){data-tooltip="The requested page has moved to a new URL."}
|
||||
* [302: Found](https://tools.ietf.org/html/rfc7231#section-6.4.3){data-tooltip="The requested page has moved temporarily to a new URL."}
|
||||
* [303: See Other](https://tools.ietf.org/html/rfc7231#section-6.4.4){data-tooltip="The requested page can be found under a different URL."}
|
||||
* [304: Not Modified](https://tools.ietf.org/html/rfc7232#section-4.1){data-tooltip="This is the response code to an If-Modified-Since or If-None-Match header, where the URL has not been modified since the specified date."}
|
||||
* [305: Use Proxy](https://tools.ietf.org/html/rfc7231#section-6.4.5){data-tooltip="The requested URL must be accessed through the proxy mentioned in the Location header."}
|
||||
* [306: Unused](https://tools.ietf.org/html/rfc7231#section-6.4.6){data-tooltip="This code was used in a previous version. It is no longer used, but the code is reserved."}
|
||||
* [307: Temporary Redirect](https://tools.ietf.org/html/rfc7231#section-6.4.7){data-tooltip="The requested page has moved temporarily to a new url."}
|
||||
* [307: Temporary Redirect](https://tools.ietf.org/html/rfc7231#section-6.4.7){data-tooltip="The requested page has moved temporarily to a new URL."}
|
||||
* [308: Permanent Redirect](https://tools.ietf.org/html/rfc7538#section-3){data-tooltip="The request and all future requests should be repeated using another URI."}
|
||||
|
||||
|
||||
### 5xx. Server Error
|
||||
@@ -91,4 +92,8 @@ HTTP Status code
|
||||
* [503: Service Unavailable](https://tools.ietf.org/html/rfc7231#section-6.6.4){data-tooltip="The request was not completed. The server is temporarily overloading or down."}
|
||||
* [504: Gateway Timeout](https://tools.ietf.org/html/rfc7231#section-6.6.5){data-tooltip="The gateway has timed out."}
|
||||
* [505: HTTP Version Not Supported](https://tools.ietf.org/html/rfc7231#section-6.6.6){data-tooltip="The server does not support the "http protocol" version."}
|
||||
|
||||
* [506: Variant Also Negotiates](https://tools.ietf.org/html/rfc2295#section-8.1){data-tooltip="Transparent content negotiation for the request results in a circular reference."}
|
||||
* [507: Insufficient Storage](https://tools.ietf.org/html/rfc4918#section-11.5){data-tooltip="The server is unable to store the representation needed to complete the request."}
|
||||
* [508: Loop Detected](https://tools.ietf.org/html/rfc5842#section-7.2){data-tooltip="The server detected an infinite loop while processing the request."}
|
||||
* [510: Not Extended](https://tools.ietf.org/html/rfc2774#section-7){data-tooltip="Further extensions to the request are required for the server to fulfill it."}
|
||||
* [511: Network Authentication Required](https://tools.ietf.org/html/rfc6585#section-6){data-tooltip="The client needs to authenticate to gain network access."}
|
||||
@@ -378,7 +378,7 @@ then, true || evaluates to false and eventually returns true
|
||||
|
||||
```kotlin
|
||||
var studied = true
|
||||
var well Rested = true
|
||||
var wellRested = true
|
||||
|
||||
if (wellRested) {
|
||||
println("Good luck today!")
|
||||
|
||||
@@ -248,7 +248,7 @@ preview | method | preview | method | preview | method | preview | method
|
||||
:- | :- | :- | :-
|
||||
:- | :- | :- | :-
|
||||
| Correct: | <pur>`\tan(at-n\pi)`</pur> | `KaTeX:\rightarrow` | `KaTeX:\tan(at-n\pi)`|
|
||||
| Incorrect: | <pur>`tan(at-n\pi)`</pur> | `katex:\rightarrow` | `KaTeX:tan(at-n\pi)` | {.left-align}
|
||||
| Incorrect: | <pur>`tan(at-n\pi)`</pur> | `KaTeX:\rightarrow` | `KaTeX:tan(at-n\pi)` | {.left-align}
|
||||
|
||||
### Logic and Set Theory{.col-span-3}
|
||||
|
||||
|
||||
@@ -558,7 +558,7 @@ ON t(c3,c4)
|
||||
Drop an index
|
||||
|
||||
```sql
|
||||
DROP INDEX idx_name;
|
||||
DROP INDEX idx_name ON t;
|
||||
```
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
---
|
||||
title: OpenSSL
|
||||
date: 2020-11-25 18:28:43
|
||||
icon: icon-style
|
||||
background: bg-emerald-600
|
||||
tags:
|
||||
categories:
|
||||
- Linux Command
|
||||
intro: |
|
||||
This is a reference of commands to use to interact with electronic certificates
|
||||
plugins:
|
||||
- copyCode
|
||||
---
|
||||
|
||||
## Private Key {.cols-2}
|
||||
|
||||
### Print out the private key details
|
||||
|
||||
```bash
|
||||
openssl rsa -check -text -in privateKey.key
|
||||
```
|
||||
|
||||
### Print out the hashes of the private key
|
||||
|
||||
```bash
|
||||
openssl rsa -noout -modulus -in privateKey.key | openssl md5
|
||||
openssl rsa -noout -modulus -in privateKey.key | openssl sha1
|
||||
openssl rsa -noout -modulus -in privateKey.key | openssl sha256
|
||||
openssl rsa -noout -modulus -in privateKey.key | openssl sha512
|
||||
```
|
||||
|
||||
### Change password
|
||||
|
||||
```bash
|
||||
openssl rsa -aes256 -in privateKey.key -out newPrivateKey.key
|
||||
```
|
||||
|
||||
### List available elliptic curves
|
||||
|
||||
```bash
|
||||
openssl ecparam -list_curves
|
||||
```
|
||||
|
||||
### Create elliptic curve private key with a specific curve
|
||||
|
||||
```bash
|
||||
openssl ecparam -name secp521r1 -genkey -noout -out privateKey.key
|
||||
```
|
||||
|
||||
## Certificate {.cols-2}
|
||||
|
||||
### Print out the hashes of the certificate
|
||||
|
||||
```bash
|
||||
openssl x509 -noout -modulus -in certificate.crt | openssl md5
|
||||
openssl x509 -noout -modulus -in certificate.crt | openssl sha1
|
||||
openssl x509 -noout -modulus -in certificate.crt | openssl sha256
|
||||
openssl x509 -noout -modulus -in certificate.crt | openssl sha512
|
||||
```
|
||||
|
||||
Or, alternatively:
|
||||
|
||||
```bash
|
||||
openssl x509 -noout -fingerprint -in certificate.crt
|
||||
openssl x509 -noout -fingerprint -sha256 -in certificate.crt
|
||||
```
|
||||
|
||||
### Print out the content of the certificates
|
||||
|
||||
```bash
|
||||
openssl x509 -in certificate.crt -noout -text|more
|
||||
```
|
||||
|
||||
### Print out specific fields of the certificates
|
||||
|
||||
```bash
|
||||
openssl x509 -noout -subject certificate.crt
|
||||
openssl x509 -noout -issuer certificate.crt
|
||||
openssl x509 -noout -dates certificate.crt
|
||||
```
|
||||
|
||||
### Inspect server certificates
|
||||
|
||||
```bash
|
||||
echo | openssl s_client -servername www.openssl.org -connect \
|
||||
www.openssl.org:443 2>/dev/null | openssl x509 -noout -text|more
|
||||
echo | openssl s_client -servername imap.arcor.de -connect \
|
||||
imap.arcor.de:993 2>/dev/null | openssl x509 -noout -text|more
|
||||
```
|
||||
|
||||
### Verify certificates
|
||||
|
||||
**OK**
|
||||
|
||||
```bash
|
||||
openssl verify -verbose -x509_strict -CAfile \
|
||||
issuer.crt Test\ Haeschen\ 1.crt
|
||||
```
|
||||
Result:
|
||||
```bash
|
||||
Test Haeschen 1.crt: OK
|
||||
```
|
||||
|
||||
**Corrupted** ([for example](https://security.stackexchange.com/questions/60804/creating-an-x-509-certificate-with-an-invalid-signature))
|
||||
|
||||
```bash
|
||||
openssl verify -verbose -x509_strict -CAfile \
|
||||
issuer.crt Test\ Haeschen\ 1_corrupted.crt
|
||||
```
|
||||
Result:
|
||||
```bash
|
||||
C = DE, ST = Thueringen, L = Rudolstadt, O = Damaschkestr. 11, OU = Arbeitszimmer, CN = Test Haeschen 1
|
||||
error 7 at 0 depth lookup: certificate signature failure
|
||||
error Test Haeschen 1_corrupted.crt: verification failed
|
||||
40270500477F0000:error:0200008A:rsa routines:RSA_padding_check_PKCS1_type_1:invalid padding:../crypto/rsa/rsa_pk1.c:75:
|
||||
40270500477F0000:error:02000072:rsa routines:rsa_ossl_public_decrypt:padding check failed:../crypto/rsa/rsa_ossl.c:598:
|
||||
40270500477F0000:error:1C880004:Provider routines:rsa_verify:RSA lib:../providers/implementations/signature/rsa_sig.c:774:
|
||||
40270500477F0000:error:06880006:asn1 encoding routines:ASN1_item_verify_ctx:EVP lib:../crypto/asn1/a_verify.c:217:
|
||||
```
|
||||
|
||||
## S/Mime {.cols-2}
|
||||
|
||||
### create signature
|
||||
|
||||
```bash
|
||||
openssl smime -sign -in msg.txt -text -out msg.p7s \
|
||||
-signer certificate.crt -inkey privateKey.key
|
||||
```
|
||||
|
||||
|
||||
### Verify signature
|
||||
|
||||
```bash
|
||||
openssl smime -verify -in msg.p7s -CAfile chain.pem
|
||||
```
|
||||
|
||||
|
||||
## CRL {.cols-2}
|
||||
|
||||
### Print out the contents of the CRL
|
||||
|
||||
```bash
|
||||
openssl crl -inform DER -noout -text -in crl/cacrl.der
|
||||
openssl crl -inform PEM -noout -text -in crl/cacrl.pem
|
||||
```
|
||||
|
||||
## PKCS#12 {.cols-2}
|
||||
|
||||
### Display contents
|
||||
|
||||
```bash
|
||||
openssl pkcs12 -info -in digitalIdentity.p12
|
||||
```
|
||||
|
||||
### Create from certificate and private key
|
||||
|
||||
```bash
|
||||
openssl pkcs12 -export -in certificate.cert \
|
||||
-inkey privateKey.key -out digitalIdentity.p12
|
||||
```
|
||||
|
||||
### Extract private key
|
||||
|
||||
```bash
|
||||
openssl pkcs12 -in digitalIdentity.p12 -out privateKey.key
|
||||
```
|
||||
|
||||
### Convert to PEM
|
||||
|
||||
```bash
|
||||
openssl pkcs12 -in digitalIdentity.p12 -out digitalIdentity.pem
|
||||
```
|
||||
|
||||
## TSA {.cols-2}
|
||||
|
||||
### Display query
|
||||
|
||||
```bash
|
||||
openssl ts -query -in query.tsq -text
|
||||
```
|
||||
|
||||
### Display reply
|
||||
|
||||
```bash
|
||||
openssl ts -reply -in reply.tsr -text
|
||||
```
|
||||
|
||||
### Verify reply
|
||||
|
||||
```bash
|
||||
openssl ts -verify -in reply.tsr -data data.dat -CAfile chain.pem
|
||||
```
|
||||
|
||||
### Extract token from reply
|
||||
|
||||
```bash
|
||||
openssl ts -reply -in reply.tsr -token_out -out token.tk
|
||||
```
|
||||
|
||||
### Extract certificates from token
|
||||
|
||||
```bash
|
||||
openssl pkcs7 -inform DER -in token.tk -print_certs -noout -text
|
||||
```
|
||||
|
||||
## CSR {.cols-2}
|
||||
|
||||
### Create from existing key
|
||||
|
||||
```bash
|
||||
openssl req -new -key privateKey.key -out my.csr
|
||||
```
|
||||
|
||||
This can of course be a RSA key or one based on an elliptic curve. Available curves can be listed using
|
||||
|
||||
```bash
|
||||
openssl ecparam -list_curves
|
||||
```
|
||||
|
||||
Afterwards you chose one of the curves and create a private key like so:
|
||||
|
||||
```bash
|
||||
openssl ecparam -name secp521r1 -genkey -noout \
|
||||
-out privateKey.key
|
||||
```
|
||||
|
||||
### Display
|
||||
|
||||
```bash
|
||||
openssl req -in my.csr -noout -text
|
||||
```
|
||||
|
||||
## HTTPS {.cols-2}
|
||||
|
||||
### Dump Certificates PEM encoded
|
||||
```bash
|
||||
openssl s_client -showcerts -connect www.example.com:443
|
||||
```
|
||||
|
||||
## STARTTLS {.cols-2}
|
||||
|
||||
### Dump Certificates PEM encoded
|
||||
```bash
|
||||
openssl s_client -showcerts -starttls imap \
|
||||
-connect mail.domain.com:139
|
||||
```
|
||||
|
||||
## S/MIME verification {.cols-2}
|
||||
|
||||
### Possible outcomes
|
||||
|
||||
Message was tampered with (return code 4):
|
||||
|
||||
```bash
|
||||
Verification failure
|
||||
140485684135232:error:2E09A09E:CMS routines:CMS_SignerInfo_verify_content:verification failure:../crypto/cms/cms_sd.c:847:
|
||||
140485684135232:error:2E09D06D:CMS routines:CMS_verify:content verify error:../crypto/cms/cms_smime.c:393:
|
||||
```
|
||||
|
||||
Message signature not trusted (return code 4):
|
||||
|
||||
```bash
|
||||
Verification failure
|
||||
140146111432000:error:2E099064:CMS routines:cms_signerinfo_verify_cert:certificate verify error:../crypto/cms/cms_smime.c:252:Verify error:unable to get local issuer certificate
|
||||
```
|
||||
|
||||
Message not signed (return code 2):
|
||||
|
||||
```bash
|
||||
Error reading S/MIME message
|
||||
140701208487232:error:0D0D40CD:asn1 encoding routines:SMIME_read_ASN1:invalid mime type:../crypto/asn1/asn_mime.c:469:type: multipart/alternative
|
||||
```
|
||||
|
||||
Validation successful (return code 0):
|
||||
|
||||
```bash
|
||||
Verification successful
|
||||
```
|
||||
|
||||
### Verify the validity of an email message
|
||||
|
||||
```bash
|
||||
openssl cms -verify -in some_email_message.eml
|
||||
```
|
||||
|
||||
### Verify the validity of an email message explicitly specifying trust
|
||||
|
||||
```bash
|
||||
openssl cms -verify -in some_email_message \
|
||||
-CAfile trust_anchor-crt
|
||||
```
|
||||
|
||||
### Signed and encrypted messages need to be decrypted first:
|
||||
|
||||
Note: the P12 file holding the digital identity must be pem-encoded! (see above)
|
||||
|
||||
```bash
|
||||
openssl cms -decrypt -out decrypted_email_message \
|
||||
-inkey p12.pem -in some_encrypted_email_message
|
||||
```
|
||||
|
||||
## Raw {.cols-2}
|
||||
|
||||
### See the raw structure of an ASN.1 file (only for DER encoded files)
|
||||
|
||||
```bash
|
||||
openssl asn1parse -in mysterious_file.pem
|
||||
```
|
||||
|
||||
### With a bit more detail
|
||||
|
||||
```bash
|
||||
openssl asn1parse -dump -strictpem -in mysterious_file.pem
|
||||
```
|
||||
|
||||
## Some resources with useful OpenSSL commands
|
||||
|
||||
* [OpenSSL command cheatsheet](https://www.freecodecamp.org/news/openssl-command-cheatsheet-b441be1e8c4a/)
|
||||
* [21 OpenSSL Examples to Help You in Real-World](https://geekflare.com/openssl-commands-certificates/)
|
||||
* [The Most Common OpenSSL Commands](https://www.sslshopper.com/article-most-common-openssl-commands.html)
|
||||
* [OpenSSL Quick Reference Guide](https://www.digicert.com/ssl-support/openssl-quick-reference-guide.htm)
|
||||
* [openssl_commands.md](https://gist.github.com/webtobesocial/5313b0d7abc25e06c2d78f8b767d4bc3)
|
||||
* [OpenSSL Essentials: Working with SSL Certificates, Private Keys and CSRs](https://www.digitalocean.com/community/tutorials/openssl-essentials-working-with-ssl-certificates-private-keys-and-csrs)
|
||||
* [OpenSSL tips and tricks](https://commandlinefanatic.com/cgi-bin/showarticle.cgi?article=art030)
|
||||
* [Checking A Remote Certificate Chain With OpenSSL ](https://langui.sh/2009/03/14/checking-a-remote-certificate-chain-with-openssl/)
|
||||
* [OpenSSL: how to extract certificates and token status from RFC3161 timestamping reply?](https://stackoverflow.com/questions/66044640/openssl-how-to-extract-certificates-and-token-status-from-rfc3161-timestamping)
|
||||
* [Steps to generate CSR for SAN certificate with openssl](https://www.golinuxcloud.com/openssl-subject-alternative-name/)
|
||||
* [Howto add a Subject Alternative Name extension into a Certificate Signing Request](https://support.microfocus.com/kb/doc.php?id=3522065)
|
||||
+186
-1
@@ -382,4 +382,189 @@ export default function Weather(props) {
|
||||
}
|
||||
}
|
||||
```
|
||||
Note: Make sure to import Axios first to your project.
|
||||
Note: Make sure to import Axios first to your project.
|
||||
|
||||
|
||||
HOOKS
|
||||
------------
|
||||
|
||||
### useState Hook
|
||||
|
||||
```javascript
|
||||
import React, { useState } from "react";
|
||||
|
||||
function Counter() {
|
||||
const [count, setCount] = useState(0);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<p>Count: {count}</p>
|
||||
<button onClick={() => setCount(count + 1)}>Increment</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default Counter;
|
||||
```
|
||||
Note: The useState Hook is a built-in React Hook that allows functional components to manage local state. It provides a way to declare state variables and update them within a functional component.
|
||||
Example code illustrating how to use it
|
||||
|
||||
|
||||
### Multiple State Variable Declaration
|
||||
|
||||
```javascript
|
||||
import React, { useState } from "react";
|
||||
|
||||
function Counter() {
|
||||
const [count, setCount] = useState(0);
|
||||
const [name, setName] = useState("");
|
||||
const [isCompleted, setIsCompleted] = useState(false);
|
||||
|
||||
const handleIncrement = () => {
|
||||
setCount(count + 1);
|
||||
};
|
||||
|
||||
const handleNameChange = (event) => {
|
||||
setName(event.target.value);
|
||||
};
|
||||
|
||||
const toggleCompletion = () => {
|
||||
setIsCompleted(!isCompleted);
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<p>Count: {count}</p>
|
||||
<button onClick={handleIncrement}>Increment</button>
|
||||
|
||||
<input type="text" value={name} onChange={handleNameChange} placeholder="Enter your name" />
|
||||
|
||||
<label>
|
||||
<input type="checkbox" checked={isCompleted} onChange={toggleCompletion} />
|
||||
Completed
|
||||
</label>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default Counter;
|
||||
```
|
||||
Note: You can declare multiple state variables using the useState Hook by calling it multiple times in a functional component. Each call to useState manages a separate piece of state.
|
||||
|
||||
### Input State Management
|
||||
|
||||
```javascript
|
||||
import { useState } from "react";
|
||||
|
||||
function FormExample() {
|
||||
const [formData, setFormData] = useState({name: "",email: "",message: ""});
|
||||
|
||||
const handleChange = (event) => {
|
||||
const { name, value } = event.target;
|
||||
setFormData((prevFormData) => ({ ...prevFormData, [name]: value }));
|
||||
};
|
||||
|
||||
const handleSubmit = (event) => {
|
||||
event.preventDefault();
|
||||
alert(`Name: ${formData.name}, Email: ${formData.email}, Message: ${formData.message}`
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit}>
|
||||
<label htmlFor="name">Name:</label>
|
||||
<input type="text" id="name" name="name" value={formData.name} onChange={handleChange}/>
|
||||
|
||||
<label htmlFor="email">Email:</label>
|
||||
<input type="email" id="email" name="email" value={formData.email} onChange={handleChange}/>
|
||||
|
||||
<label htmlFor="message">Message:</label>
|
||||
<textarea id="message" name="message" value={formData.message} onChange={handleChange}/>
|
||||
|
||||
<button type="submit">Submit</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
export default FormExample;
|
||||
```
|
||||
|
||||
### useEffect Hook
|
||||
|
||||
```javascript
|
||||
import React, { useState, useEffect } from "react";
|
||||
|
||||
function Timer() {
|
||||
const [seconds, setSeconds] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
setSeconds((prevSeconds) => prevSeconds + 1);
|
||||
}, 1000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
return <div>Seconds: {seconds}</div>;
|
||||
}
|
||||
|
||||
export default Timer;
|
||||
```
|
||||
Note: The useEffect Hook in React is used for performing side effects in functional components. It allows you to execute code based on component lifecycle events like mounting, updating, and unmounting.
|
||||
|
||||
### Fetch API using useEffect
|
||||
|
||||
```javascript
|
||||
import React, { useState, useEffect } from "react";
|
||||
import axios from "axios";
|
||||
|
||||
function UserList() {
|
||||
const [users, setUsers] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
axios.get("https://jsonplaceholder.typicode.com/users")
|
||||
.then(response => {
|
||||
setUsers(response.data);
|
||||
})
|
||||
.catch(error => {
|
||||
console.error("Error fetching users:", error);
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h2>User List</h2>
|
||||
<ul>
|
||||
{users.map(user => (
|
||||
<li key={user.id}>{user.name}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default UserList;
|
||||
```
|
||||
Note: Make sure to import Axios first to your project.
|
||||
|
||||
### Custom Hook creation useLocalStorage
|
||||
|
||||
```javascript
|
||||
import { useState, useEffect } from "react";
|
||||
|
||||
function useLocalStorage(key, initialValue) {
|
||||
const [value, setValue] = useState(() => {
|
||||
const storedValue = localStorage.getItem(key);
|
||||
return storedValue !== null ? JSON.parse(storedValue) : initialValue;
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
localStorage.setItem(key, JSON.stringify(value));
|
||||
}, [key, value]);
|
||||
|
||||
return [value, setValue];
|
||||
}
|
||||
|
||||
export default useLocalStorage;
|
||||
```
|
||||
Note: Custom Hooks are reusable functions in React that contain logic shared across multiple components. They allow you to extract stateful logic from components into standalone functions.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -277,7 +277,7 @@ println!("Share {cs} for developers");
|
||||
|
||||
```rust
|
||||
// Creating an empty string object
|
||||
let my_string = String::new;
|
||||
let my_string = String::new();
|
||||
|
||||
// Converting to a string object
|
||||
let S_string = a_string.to_string()
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
---
|
||||
title: Selenium
|
||||
date: 2024-05-04 19:50:01
|
||||
background: bg-[#d33731]
|
||||
tags:
|
||||
- automation
|
||||
- testing
|
||||
categories:
|
||||
- Programming
|
||||
intro: |
|
||||
This cheat sheet is a crash course for Selenium beginners and help to get the idea about the basic concepts of Selenium.
|
||||
---
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Initialize Browser Drivers {.row-span-2}
|
||||
|
||||
| Browser | Syntax |
|
||||
| --------- | --------------------------------------- |
|
||||
| `Chrome` | WebDriver driver = new ChromeDriver(); |
|
||||
| `Edge` | WebDriver driver = new EdgeDriver(); |
|
||||
| `Firefox` | WebDriver driver = new FirefoxDriver(); |
|
||||
| `Safari` | WebDriver driver = new SafariDriver(); |
|
||||
|
||||
{.show-header .left-text}
|
||||
|
||||
### Selenium Locators {.col-span-2}
|
||||
|
||||
| Locator | Syntax |
|
||||
| ----------------- | --------------------------------------------- |
|
||||
| `className` | driver.findElement(By.className (“key”)) |
|
||||
| `cssSelector` | driver.findElement(By.cssSelector(key")) |
|
||||
| `id ` | driver.findElement(By.id(key")) |
|
||||
| `linkText` | driver.findElement(By.linkText(key")) |
|
||||
| `name` | driver.findElement(By.name(“key")) |
|
||||
| `partialLinkText` | driver.findElement(By.partialLinkText(“key")) |
|
||||
| `tagName ` | driver.findElement(By.tagName (“key”)) |
|
||||
| `xpath` | driver.findElement(By.xpath(“key")) |
|
||||
|
||||
{.show-header .left-text}
|
||||
|
||||
### Navigate to URL
|
||||
|
||||
```shell script
|
||||
driver.get("https://www.example.com");
|
||||
```
|
||||
|
||||
### Close all browser windows
|
||||
|
||||
```shell script
|
||||
driver.quit();
|
||||
```
|
||||
|
||||
### Close the current browser window
|
||||
|
||||
```shell script
|
||||
driver.close();
|
||||
```
|
||||
|
||||
### Navigation {.col-span-2}
|
||||
|
||||
| Description | Syntax |
|
||||
| ------------------------------- | ------------------------------------------------ |
|
||||
| `Navigate to a new URL` | driver.navigate().to("https://www.newsite.com"); |
|
||||
| `Go forward to the next page` | driver.navigate().forward(); |
|
||||
| `Go back to the previous page ` | driver.navigate().back(); |
|
||||
| `Refresh the current page` | driver.navigate().refresh(); |
|
||||
|
||||
{.show-header .left-text}
|
||||
|
||||
### Frame Handling {.col-span-2}
|
||||
|
||||
| Description | Syntax |
|
||||
| --------------------------------- | ----------------------------------- |
|
||||
| `Switch to a frame` | driver.switchTo().frame("frameId"); |
|
||||
| `Switch back to the main content` | driver.switchTo().defaultContent(); |
|
||||
|
||||
{.show-header .left-text}
|
||||
|
||||
### Alerts/Pop-Ups
|
||||
|
||||
```shell script
|
||||
Alert alert = driver.switchTo().alert();
|
||||
|
||||
// Used to click on the ‘OK’ button of the alert.
|
||||
alert.accept();
|
||||
|
||||
// Used when the ‘Cancel’ button is clicked in the alert box.
|
||||
alert.dismiss();
|
||||
|
||||
// Used to send text to an alert
|
||||
alert.sendKeys("text");
|
||||
|
||||
// Used to capture the alert message.
|
||||
alert().getText();
|
||||
|
||||
```
|
||||
|
||||
### Mouse and Keyboard Actions {.col-span-2}
|
||||
|
||||
```shell script
|
||||
Actions actions = new Actions(driver);
|
||||
|
||||
// Shifts the mouse pointer to the center of the element and click on it
|
||||
actions.moveToElement(element).click().build().perform();
|
||||
|
||||
// Performs double click on the element
|
||||
actions.doubleClick(element).perform();
|
||||
|
||||
// Drags the element from one point and drops to another
|
||||
actions.dragAndDrop(source, target).perform();
|
||||
|
||||
// Sends a series of keys to the element
|
||||
actions.sendKeys(element, "text").perform();
|
||||
|
||||
```
|
||||
|
||||
### Page Information {.col-span-1}
|
||||
|
||||
```shell script
|
||||
// Get the page title
|
||||
driver.getTitle();
|
||||
|
||||
// Get the current page URL
|
||||
driver.getCurrentUrl();
|
||||
|
||||
// Get the entire page source code
|
||||
driver.getPageSource();
|
||||
|
||||
```
|
||||
|
||||
### Waits {.col-span-3}
|
||||
|
||||
```shell script
|
||||
// Explicit Wait :- These are conditional waits can be applied to satisfy a particular condition
|
||||
WebDriverWait wait = new WebDriverWait(driver, 10);
|
||||
wait.until(ExpectedConditions.elementToBeClickable(element));
|
||||
```
|
||||
|
||||
```shell script
|
||||
// Implicit Wait :- Once the command is run, Implicit Wait remains for the entire duration for which the browser is open.
|
||||
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
|
||||
```
|
||||
|
||||
```shell script
|
||||
// Fluent Wait :- Fluent Wait in Selenium marks the maximum amount of time for Selenium WebDriver to wait for a certain condition (web element) becomes visible. It also defines how frequently WebDriver will check if the condition appears before throwing the “ElementNotVisibleException”.
|
||||
FluentWait wait = new FluentWait(driver);
|
||||
//Specify the timeout of the wait
|
||||
wait.withTimeout(5000, TimeUnit.MILLISECONDS);
|
||||
//Specify polling time
|
||||
wait.pollingEvery(250, TimeUnit.MILLISECONDS);
|
||||
//Specify what exceptions to ignore
|
||||
wait.ignoring(NoSuchElementException.class)
|
||||
//This is how we specify the condition to wait on.
|
||||
wait.until(ExpectedConditions.alertIsPresent());
|
||||
```
|
||||
@@ -0,0 +1,434 @@
|
||||
---
|
||||
title: Terraform
|
||||
date: 2024-4-18
|
||||
background: bg-[#7f48be]
|
||||
tags:
|
||||
- container
|
||||
- virtual
|
||||
categories:
|
||||
- Programming
|
||||
intro: |
|
||||
This is a quick reference cheat sheet for [Terraform](https://docs.docker.com/get-started/).
|
||||
plugins:
|
||||
- copyCode
|
||||
---
|
||||
|
||||
## HCL Syntax:
|
||||
|
||||
```
|
||||
(Block Name) (Resource Type) (Resource Name)
|
||||
| | |
|
||||
▽ ▽ ▽
|
||||
resource "aws_instance" "my_aws_server" {
|
||||
--
|
||||
ami = "ami-1251351351513" |<--(Arguments)
|
||||
instance_type = "t2.micro" |
|
||||
--
|
||||
|
||||
}
|
||||
|
||||
```
|
||||
### Variable Types
|
||||
|
||||
1. Simple types: number, string, bool, null.
|
||||
|
||||
2. Complex types:
|
||||
Collection types: list, map, set
|
||||
Structural types: `object({<KEY> = <TYPE>, ...})`, `tuple([<TYPE>, ...])`
|
||||
|
||||
Order of Precedence:
|
||||
defaults < env vars < terraform.tfvars file < terraform.tfvars.json file < .auto.tfvars < command line (-var & -var-file)
|
||||
|
||||
```
|
||||
variable "<VAR NAME>" {
|
||||
description = "<DESCRIPTION OF THE VAR>"
|
||||
type = <VAR TYPE>
|
||||
default = <DEFAULT VALUE>
|
||||
}
|
||||
|
||||
# type string
|
||||
variable "aws_region" {
|
||||
description = "AWS Region"
|
||||
type = string
|
||||
default = "us-east-1"
|
||||
}
|
||||
|
||||
# type list(string)
|
||||
variable "azs" {
|
||||
description = "AZs in the Region"
|
||||
type = list(string)
|
||||
default = [ "us-east-1a", "us-east-1b", "us-east-1c"]
|
||||
}
|
||||
|
||||
# type map
|
||||
variable "amis" {
|
||||
type = map(string)
|
||||
default = {
|
||||
"eu-west-1" = "ami-0fdke15151513145",
|
||||
"us-east-1" = "ami-0d17359173587519"
|
||||
}
|
||||
}
|
||||
|
||||
# type object
|
||||
variable "egress_dsg" {
|
||||
type = object({
|
||||
from_port = number
|
||||
to_port = number
|
||||
protocol = string
|
||||
cidr_blocks = list(string)
|
||||
})
|
||||
default = {
|
||||
from_port = 0,
|
||||
to_port = 65365,
|
||||
protocol = "tcp",
|
||||
cidr_blocks = ["100.0.0.0/16", "200.0.0.0/16", "0.0.0.0/0"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Meta-Arguments
|
||||
|
||||
### Loops
|
||||
count, for_each, [for( o in var.list: o.id])
|
||||
|
||||
```
|
||||
# creating multiple EC2 instances using count
|
||||
resource "aws_instance" "server" {
|
||||
ami = "ami-06ec8443c2a35b0ba"
|
||||
instance_type = "t2.micro"
|
||||
count = 3 # creating 3 resources
|
||||
}
|
||||
|
||||
# declaring a variable
|
||||
variable "users" {
|
||||
type = list(string)
|
||||
default = ["demo-user", "admin1", "john"]
|
||||
}
|
||||
|
||||
# creating IAM users using for_each
|
||||
resource "aws_iam_user" "test" {
|
||||
for_each = toset(var.users) # converts a list to a set
|
||||
name = each.key
|
||||
}
|
||||
|
||||
# A for expression creates a complex type value by transforming another complex type value.
|
||||
variable "names" {
|
||||
type = list
|
||||
default = ["som", "john", "mary"]
|
||||
}
|
||||
|
||||
output "show_names" {
|
||||
# similar to Python's list comprehension
|
||||
value = [for n in var.names : upper(n)]
|
||||
}
|
||||
|
||||
output "short_upper_names" {
|
||||
# filter the resulting list by specifying a condition:
|
||||
value = [for name in var.names : upper(name) if length(name) > 7]
|
||||
}
|
||||
```
|
||||
|
||||
### Splat
|
||||
|
||||
`Splat(var.list[*].id)`
|
||||
|
||||
```
|
||||
# Launch an EC2 instance
|
||||
resource "aws_instance" "server" {
|
||||
ami = "ami-05cafdf7c9f772ad2"
|
||||
instance_type = "t2.micro"
|
||||
count = 3
|
||||
}
|
||||
|
||||
output "private_addresses"{
|
||||
value = aws_instance.server[*].private_ip # splat expression
|
||||
}
|
||||
```
|
||||
|
||||
### depends_on
|
||||
|
||||
if two resources depends on each other, depends_on specifies that dependency to enforce ordering
|
||||
```
|
||||
resource "aws_iam_role_policy" "example" {
|
||||
name = "example"
|
||||
role = "s3 access"
|
||||
policy = jsonencode({
|
||||
"Statement" = [{
|
||||
"Action" = "s3:*",
|
||||
"Effect" = "Allow",
|
||||
}],
|
||||
})
|
||||
}
|
||||
|
||||
resource "aws_instance" "my_server" {
|
||||
ami = "ami-a255235"
|
||||
instance_type = "t2.micro"
|
||||
|
||||
iam_instance_profile = aws_iam_instance_profile.my_server
|
||||
|
||||
depends_on = [
|
||||
aws_iam_role_policy.example,
|
||||
]
|
||||
```
|
||||
|
||||
### lifecycle
|
||||
|
||||
A set of meta arguments to control behavior specific resources
|
||||
```
|
||||
resources "aws_instance" "server" {
|
||||
ami = "ami-a1b3414"
|
||||
instance_type = "t2.micro"
|
||||
|
||||
lifecycle {
|
||||
create_before_destroy = true
|
||||
ignore_changes = [
|
||||
# Some resources have metadata
|
||||
# modified automatically outside of TF
|
||||
|
||||
tags
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Conditionals
|
||||
|
||||
`condition ? true_val : false_val`
|
||||
|
||||
### Built-In functions
|
||||
|
||||
| Function | Result |
|
||||
| ------------------------------------------------|-------------------------|
|
||||
| `max(5, 10, 9)` | 12 |
|
||||
| `min(5, 10, 9)` | 5 |
|
||||
| `format("There are %d servers", 4)` | There are 4 lights |
|
||||
| `join("," ["foo", "bar", "baz"])` | foo,bar,baz |
|
||||
| `split(",", "foo,bar,baz")` | `["foo", "bar", "baz"]` |
|
||||
| `replace("hi world", "/w.*d/", "mom"` | hi mom |
|
||||
| `substr("hello world", 1, 4)` | ello |
|
||||
| `lookup({a="lol", b="sad"}, "a", "what?")` | lol |
|
||||
| `lookup({a="lol", b="sad"}, "c", "what?")` | what? |
|
||||
| `slice(["a", "b", "c", "d"], 1, 3)` | `["b", "c"]` |
|
||||
| `timestamp()` | "2022-04-02T05:52:48Z" |
|
||||
| `cidr("10.1.2.240/28", 1)` | 10.1.2.241 |
|
||||
| `cidr("10.1.2.240/28", 14)` | 10.1.2.254 |
|
||||
|
||||
|
||||
### Provider block
|
||||
|
||||
Details of the provider(s) being used. Includes information like access mechanisms, regional options, profile touse etc.
|
||||
|
||||
```
|
||||
provider "aws" {
|
||||
region = "us-east-1"
|
||||
}
|
||||
|
||||
# Additional provider config reference as `aws.west`.
|
||||
provider "aws" {
|
||||
alias = "west"
|
||||
region = "us-west-2"
|
||||
}
|
||||
```
|
||||
|
||||
### Requiring Providers
|
||||
```
|
||||
terraform {
|
||||
|
||||
# required_providers block specifies source and version
|
||||
required_providers {
|
||||
aws = {
|
||||
source = "hashicorp/aws" # where to find the provider
|
||||
version = "5.8.0" # which version of the provider is needed for this config
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
### Locals block
|
||||
|
||||
A local value assigns a name to an expression, so you can use the name multiple times within a module instead of repeating the expression
|
||||
```
|
||||
locals {
|
||||
service_name = "forum"
|
||||
owner = "Community Team"
|
||||
}
|
||||
|
||||
# once local declared you can reference it
|
||||
locals {
|
||||
common_tags = {
|
||||
Service = local.service_name
|
||||
Owner = local.owner
|
||||
```
|
||||
|
||||
### Output block
|
||||
|
||||
```
|
||||
output "api_base_url" {
|
||||
value = "https://${aws_instance.example.private_dns}:8433/"
|
||||
|
||||
# The EC2 instance must have an encrypted root volume.
|
||||
precondition {
|
||||
condition = data.aws_ebs_volume.example.encrypted
|
||||
error_message = "The server's root volume is not encrypted."
|
||||
}
|
||||
|
||||
# output can be marked as containing sensitive
|
||||
sensitive = true # output can be marked as containing sensitive
|
||||
}
|
||||
```
|
||||
|
||||
### Data block
|
||||
|
||||
Data sources that can be queried (cloud provider, local list, etc.)
|
||||
|
||||
```
|
||||
data "aws_ami" "example" {
|
||||
most_recent = true
|
||||
|
||||
owners = ["self"]
|
||||
tags = {
|
||||
Name = "app-server"
|
||||
Tested = "true"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Modules
|
||||
|
||||
```
|
||||
module "myec2" {
|
||||
source = "../modules/ec2"
|
||||
|
||||
# module inputs
|
||||
ami_id = var.ami_id
|
||||
instance_type = var.instance_type
|
||||
servers = var.servers
|
||||
}
|
||||
```
|
||||
|
||||
### Backends
|
||||
|
||||
A backend defines where Terraform stores its state data files.
|
||||
|
||||
Available backends: local(default), remote, azurerm, consul, cos, gcs, http, Kubernetes, oss, pg, s3
|
||||
```
|
||||
terraform {
|
||||
backend "remote" {
|
||||
organization = "example_corp"
|
||||
|
||||
workspaces {
|
||||
name = "my-app-prod"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Resource Addressing
|
||||
|
||||
| Example | Description |
|
||||
| ------------------------------------------------- | ----------------------- |
|
||||
| `[module path][resource info` | Resource path syntax |
|
||||
| `module.<MODULE_PATH>[optional] module index` | Module path syntax |
|
||||
| `resource_type.user_defined_name[optional index]` | Resource spec syntax |
|
||||
| `<RESOURCE_TYPE>.<NAME>` | List all images |
|
||||
| `var.<NAME>` | Input Variable |
|
||||
| `local.<NAME>` | Locals |
|
||||
| `module.<MODULE_NAME>` | Child module outputs |
|
||||
| `data.<DATA TYPE>.<NAME>` | Data blocks |
|
||||
| `path.module` | Location of expresssion |
|
||||
| `path.root` | Root Module location |
|
||||
| `terraform.workspace` | Current workspace |
|
||||
---
|
||||
## Terraform CLI
|
||||
|
||||
Create/Edit TF config file -> init -> plan -> validate -> apply -> destroy
|
||||
|
||||
### Initialization
|
||||
```sh
|
||||
terraform init [options]
|
||||
|
||||
-upgrade # Install latest module & provider versions
|
||||
-reconfigure # reconfigure backend, ignoring any saved config
|
||||
-backend=false # Disable backend & use previous Initialization
|
||||
-migrate-state # reconfigure backend & attempt to migrate any existing state
|
||||
```
|
||||
### Planning
|
||||
|
||||
Generates & review an execution plan
|
||||
```sh
|
||||
terraform plan [options]
|
||||
|
||||
-var 'user=john' # set value for input vars in the root module of config
|
||||
-var-file=filename # load var values from the given file
|
||||
-input=true # ask for input for vars if not directly set
|
||||
-out=path # write a plan file to given path. can be used as input for "apply"
|
||||
-refresh-only # verifies remote object consistency without proposing actions to undo changes done outside TF
|
||||
-destroy # create plan to destroy all objects currenly managed
|
||||
-target=resource # target planning to given resouce & its dependencies only.
|
||||
|
||||
terraform plan -refresh-only # updates state to match changes made outside of TF. Good for drift detection
|
||||
|
||||
```
|
||||
### Validation
|
||||
```sh
|
||||
terraform validate # Validates the config files for errors
|
||||
|
||||
```
|
||||
|
||||
### Apply
|
||||
|
||||
Executes changes to infra
|
||||
```sh
|
||||
terraform apply [options]
|
||||
|
||||
-auto-approve # skip interactive approval of plan before applying
|
||||
-replace # force replacement of a particular resource instance
|
||||
-var 'foo=bar' # set a value for input vars in the root module of config
|
||||
-var-file=filename # load var values from the given file
|
||||
-parallelism=n # limit the no of concurrent operations. Default=10
|
||||
|
||||
terraform apply -auto-approve var-file=web-dev.tfvars
|
||||
terraform apply -replace="aws_instance.server"
|
||||
terraform plan -refresh-only # Updates statefile to accept changes made manually.
|
||||
```
|
||||
|
||||
### Destroy
|
||||
|
||||
Destroy (deletes) Terraform managed infra. Same as `terraform apply -destroy `
|
||||
|
||||
```sh
|
||||
terraform destroy [options]
|
||||
|
||||
-auto-approve # skip interactive approval before destroying
|
||||
-target # limits destroy to only given resource & its dependencies
|
||||
|
||||
|
||||
terraform destroy -target aws_vpc.my_vpc -auto-approve
|
||||
```
|
||||
|
||||
# Miscellaneous
|
||||
|
||||
```sh
|
||||
terraform state show aws_instance.my_vm
|
||||
terraform state pull > my_terraform.tfstate
|
||||
terraform state mv aws_iam_role.my_ssm_role
|
||||
terraform state list
|
||||
terraform state rm aws_instance.my_server
|
||||
|
||||
terraform import aws_instance.new_server i-243abc
|
||||
sudo apt install graphviz
|
||||
terraform graph | dot -Tpng > graph.png
|
||||
```
|
||||
|
||||
# Logging
|
||||
log levels = TRACE > DEBUG > INFO > WARN > ERROR
|
||||
|
||||
```sh
|
||||
export TF_LOG_CORE=TRACE # enable core logging
|
||||
export TF_LOG_PROVIDER=TRACE # enable provider logging
|
||||
export TF_LOG_PATH=logs.txt # to persist logs
|
||||
```
|
||||
|
||||
# Also See
|
||||
|
||||
- [Docs](https://developer.hashicorp.com/terraform/language)
|
||||
- [Good FCC Article](https://www.freecodecamp.org/news/terraform-certified-associate-003-study-notes/)
|
||||
Reference in new issue
Block a user