{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Running `brew update --auto-update`...\n", "\u001b[34m==>\u001b[0m \u001b[1mAuto-updated Homebrew!\u001b[0m\n", "Updated 1 tap (homebrew/core).\n", "\n", "You have \u001b[1m19\u001b[0m outdated formulae installed.\n", "You can upgrade them with \u001b[1mbrew upgrade\u001b[0m\n", "or list them with \u001b[1mbrew outdated\u001b[0m.\n", "\n", "\u001b[33mWarning:\u001b[0m fetch 0.4.5 is already installed and up-to-date.\n", "To reinstall 0.4.5, run:\n", " brew reinstall fetch\n", "Defaulting to user installation because normal site-packages is not writeable\n", "Requirement already satisfied: requests-html in /home/donaldrich/.local/lib/python3.10/site-packages (0.10.0)\n", "Requirement already satisfied: fake-useragent in /home/donaldrich/.local/lib/python3.10/site-packages (from requests-html) (0.1.11)\n", "Requirement already satisfied: pyquery in /home/donaldrich/.local/lib/python3.10/site-packages (from requests-html) (1.4.3)\n", "Requirement already satisfied: pyppeteer>=0.0.14 in /home/donaldrich/.local/lib/python3.10/site-packages (from requests-html) (1.0.2)\n", "Requirement already satisfied: bs4 in /home/donaldrich/.local/lib/python3.10/site-packages (from requests-html) (0.0.1)\n", "Requirement already satisfied: w3lib in /home/donaldrich/.local/lib/python3.10/site-packages (from requests-html) (1.22.0)\n", "Requirement already satisfied: requests in /usr/lib/python3/dist-packages (from requests-html) (2.25.1)\n", "Requirement already satisfied: parse in /home/donaldrich/.local/lib/python3.10/site-packages (from requests-html) (1.19.0)\n", "Requirement already satisfied: urllib3<2.0.0,>=1.25.8 in /usr/lib/python3/dist-packages (from pyppeteer>=0.0.14->requests-html) (1.26.5)\n", "Requirement already satisfied: tqdm<5.0.0,>=4.42.1 in /home/donaldrich/.local/lib/python3.10/site-packages (from pyppeteer>=0.0.14->requests-html) (4.64.0)\n", "Requirement already satisfied: pyee<9.0.0,>=8.1.0 in /home/donaldrich/.local/lib/python3.10/site-packages (from pyppeteer>=0.0.14->requests-html) (8.2.2)\n", "Requirement already satisfied: websockets<11.0,>=10.0 in /home/donaldrich/.local/lib/python3.10/site-packages (from pyppeteer>=0.0.14->requests-html) (10.3)\n", "Requirement already satisfied: appdirs<2.0.0,>=1.4.3 in /home/donaldrich/.local/lib/python3.10/site-packages (from pyppeteer>=0.0.14->requests-html) (1.4.3)\n", "Requirement already satisfied: certifi>=2021 in /home/donaldrich/.local/lib/python3.10/site-packages (from pyppeteer>=0.0.14->requests-html) (2022.6.15)\n", "Requirement already satisfied: importlib-metadata>=1.4 in /home/donaldrich/.local/lib/python3.10/site-packages (from pyppeteer>=0.0.14->requests-html) (4.12.0)\n", "Requirement already satisfied: beautifulsoup4 in /home/donaldrich/.local/lib/python3.10/site-packages (from bs4->requests-html) (4.11.1)\n", "Requirement already satisfied: cssselect>0.7.9 in /home/donaldrich/.local/lib/python3.10/site-packages (from pyquery->requests-html) (1.1.0)\n", "Requirement already satisfied: lxml>=2.1 in /usr/lib/python3/dist-packages (from pyquery->requests-html) (4.8.0)\n", "Requirement already satisfied: six>=1.4.1 in /usr/lib/python3/dist-packages (from w3lib->requests-html) (1.16.0)\n", "Requirement already satisfied: zipp>=0.5 in /usr/lib/python3/dist-packages (from importlib-metadata>=1.4->pyppeteer>=0.0.14->requests-html) (1.0.0)\n", "Requirement already satisfied: soupsieve>1.2 in /home/donaldrich/.local/lib/python3.10/site-packages (from beautifulsoup4->bs4->requests-html) (2.3.2.post1)\n", "Note: you may need to restart the kernel to use updated packages.\n", "Defaulting to user installation because normal site-packages is not writeable\n", "Requirement already satisfied: html2text in /home/donaldrich/.local/lib/python3.10/site-packages (2020.1.16)\n", "Note: you may need to restart the kernel to use updated packages.\n", "Defaulting to user installation because normal site-packages is not writeable\n", "Requirement already satisfied: markdown in /home/donaldrich/.local/lib/python3.10/site-packages (3.4.1)\n", "Note: you may need to restart the kernel to use updated packages.\n", "Defaulting to user installation because normal site-packages is not writeable\n", "Requirement already satisfied: python-frontmatter in /home/donaldrich/.local/lib/python3.10/site-packages (1.0.0)\n", "Requirement already satisfied: PyYAML in /home/donaldrich/.local/lib/python3.10/site-packages (from python-frontmatter) (5.1)\n", "Note: you may need to restart the kernel to use updated packages.\n", "Defaulting to user installation because normal site-packages is not writeable\n", "Requirement already satisfied: readability-lxml in /home/donaldrich/.local/lib/python3.10/site-packages (0.8.1)\n", "Requirement already satisfied: lxml in /usr/lib/python3/dist-packages (from readability-lxml) (4.8.0)\n", "Requirement already satisfied: cssselect in /home/donaldrich/.local/lib/python3.10/site-packages (from readability-lxml) (1.1.0)\n", "Requirement already satisfied: chardet in /usr/lib/python3/dist-packages (from readability-lxml) (4.0.0)\n", "Note: you may need to restart the kernel to use updated packages.\n" ] } ], "source": [ "!brew install fetch\n", "!mkdir temp\n", "\n", "%pip install requests-html\n", "%pip install html2text\n", "%pip install markdown\n", "%pip install python-frontmatter\n", "%pip install readability-lxml" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "url = \"https://spacelift.io/blog/terraform-commands-cheat-sheet\"\n", "https://spacelift.io/blog/terraform\n", "https://res.cloudinary.com/acloud-guru/image/fetch/c_thumb,f_auto,q_auto/https://acg-wordpress-content-production.s3.us-west-2.amazonaws.com/app/uploads/2020/11/terraform-cheatsheet-from-ACG.pdf\n", "https://www.techbeatly.com/terraform-cheat-sheet\n", "https://jayendrapatil.com/terraform-cheat-sheet/\n", "https://github.com/antonbabenko/terraform-best-practices.git\n" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " % Total % Received % Xferd Average Speed Time Time Time Current\n", " Dload Upload Total Spent Left Speed\n", " 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Trying 151.101.129.137:443...\n", "* Connected to res.cloudinary.com (151.101.129.137) port 443 (#0)\n", "* ALPN, offering h2\n", "* ALPN, offering http/1.1\n", "* CAfile: /etc/ssl/certs/ca-certificates.crt\n", "* CApath: /etc/ssl/certs\n", "* TLSv1.0 (OUT), TLS header, Certificate Status (22):\n", "} [5 bytes data]\n", "* TLSv1.3 (OUT), TLS handshake, Client hello (1):\n", "} [512 bytes data]\n", "* TLSv1.2 (IN), TLS header, Certificate Status (22):\n", "{ [5 bytes data]\n", "* TLSv1.3 (IN), TLS handshake, Server hello (2):\n", "{ [122 bytes data]\n", "* TLSv1.2 (IN), TLS header, Finished (20):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.3 (IN), TLS handshake, Encrypted Extensions (8):\n", "{ [19 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.3 (IN), TLS handshake, Certificate (11):\n", "{ [2999 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.3 (IN), TLS handshake, CERT verify (15):\n", "{ [264 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.3 (IN), TLS handshake, Finished (20):\n", "{ [52 bytes data]\n", "* TLSv1.2 (OUT), TLS header, Finished (20):\n", "} [5 bytes data]\n", "* TLSv1.3 (OUT), TLS change cipher, Change cipher spec (1):\n", "} [1 bytes data]\n", "* TLSv1.2 (OUT), TLS header, Supplemental data (23):\n", "} [5 bytes data]\n", "* TLSv1.3 (OUT), TLS handshake, Finished (20):\n", "} [52 bytes data]\n", "* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384\n", "* ALPN, server accepted to use h2\n", "* Server certificate:\n", "* subject: C=IL; L=Petah Tikva; O=Cloudinary Ltd; CN=*.cloudinary.com\n", "* start date: May 30 06:40:39 2022 GMT\n", "* expire date: Jul 1 06:40:39 2023 GMT\n", "* subjectAltName: host \"res.cloudinary.com\" matched cert's \"*.cloudinary.com\"\n", "* issuer: C=US; ST=Arizona; L=Scottsdale; O=GoDaddy.com, Inc.; OU=http://certs.godaddy.com/repository/; CN=Go Daddy Secure Certificate Authority - G2\n", "* SSL certificate verify ok.\n", "* Using HTTP2, server supports multiplexing\n", "* Connection state changed (HTTP/2 confirmed)\n", "* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0\n", "* TLSv1.2 (OUT), TLS header, Supplemental data (23):\n", "} [5 bytes data]\n", "* TLSv1.2 (OUT), TLS header, Supplemental data (23):\n", "} [5 bytes data]\n", "* TLSv1.2 (OUT), TLS header, Supplemental data (23):\n", "} [5 bytes data]\n", "* Using Stream ID: 1 (easy handle 0x55cc70ee6e80)\n", "* TLSv1.2 (OUT), TLS header, Supplemental data (23):\n", "} [5 bytes data]\n", "> GET /acloud-guru/image/fetch/c_thumb,f_auto,q_auto/https://acg-wordpress-content-production.s3.us-west-2.amazonaws.com/app/uploads/2020/11/terraform-cheatsheet-from-ACG.pdf HTTP/2\n", "> Host: res.cloudinary.com\n", "> user-agent: curl/7.81.0\n", "> accept: */*\n", "> \n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):\n", "{ [193 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (OUT), TLS header, Supplemental data (23):\n", "} [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "< HTTP/2 200 \n", "< content-type: image/png\n", "< etag: \"4c05202557d1f3a51bac32d0ca142fe8\"\n", "< last-modified: Mon, 23 Nov 2020 21:34:47 GMT\n", "< date: Wed, 10 Aug 2022 09:16:25 GMT\n", "< vary: Save-Data\n", "< strict-transport-security: max-age=604800\n", "< cache-control: private, no-transform, immutable, max-age=604800\n", "< server-timing: fastly;dur=2;cpu=1;start=2022-08-10T09:16:25.962Z;desc=hit,rtt;dur=92\n", "< server: Cloudinary\n", "< timing-allow-origin: *\n", "< access-control-allow-origin: *\n", "< accept-ranges: bytes\n", "< x-content-type-options: nosniff\n", "< access-control-expose-headers: Content-Length,ETag,Server-Timing,Vary,X-Content-Type-Options\n", "< content-length: 432177\n", "< \n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "* TLSv1.2 (IN), TLS header, Supplemental data (23):\n", "{ [5 bytes data]\n", "100 422k 100 422k 0 0 1685k 0 --:--:-- --:--:-- --:--:-- 1688k\n", "* Connection #0 to host res.cloudinary.com left intact\n" ] } ], "source": [ "!curl -fLvo tf.pdf https://res.cloudinary.com/acloud-guru/image/fetch/c_thumb,f_auto,q_auto/https://acg-wordpress-content-production.s3.us-west-2.amazonaws.com/app/uploads/2020/11/terraform-cheatsheet-from-ACG.pdf" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n", "\n", "\n", "\n", "Terraform Cheat Sheet – techbeatly\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", " \n", "\n", "\n", "\n", "\n", "
\n", "Skip to content\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\"\"
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "

Terraform Cheat Sheet

\n", "
\n", "
\n", "
\n", "
\n", "
\n", "

\n", "
\n", "
\n", "
\n", "
\n", "

Gineesh Mada Pparambath
\n", "

\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "

\n", "

\"\"

What is Terraform

\n", "

Terraform is an open-source software tool to manage end to end lifecycle of your IT infrastructure. Terraform provides a consistent CLI workflow to manage hundreds of cloud services.

\n", "

Latest Terraform Articles

\n", "

Installing Terraform

\n", "

You can download the Terraform software from HashiCorp’s download page and use native installation methods for your operating system. Also you can install Terraform using the package managers like yum, apt, homebrew, Chocolatey (choco) etc. Refer install Terraform page for the appropriate method for your operating system.

\n", "
\"\"

Terraform CLI Cheat Sheet

\n", "

Please note, this cheat sheet is a living document and I will make changes whenever there is an update or changes in the Terraform CLI options or versions. This cheat sheet does not written in an alphabetical order or based on workflow.

\n", "

Planning HashiCorp Certified Terraform Associate Certification ? Watch the video for details.

\n", "
\n", "
\n", "

terraform version

\n", "
$ terraform version\n",
      "Terraform v1.0.1\n",
      "on darwin_amd64
\n", "

terraform init

\n", "
$ terraform init
\n", "

Ask for input if necessary. If false, will error if input was required.

\n", "
$ terraform init -input=false
\n", "

You can also change the backend details using -backend-config option. -reconfigure will reconfigure the backend, ignoring any saved configuration.

\n", "
$ terraform init -backend-config=PATH/TO/CONFIGURATION_FILE -reconfigure
\n", "

terraform plan

\n", "

The plan will check the configuration files (basically all the *.tf files in the directory) and will show you the items or changes going to made on target infrastructure or resources. Please note, this command will not actually perform the planned actions.

\n", "
$ terraform plan
\n", "

You can optionally save the plan to a file, which you can then pass to the apply command to perform exactly the actions described in the plan.

\n", "
$ terraform plan -out plan.out
\n", "

terraform get

\n", "

Downloads and installs modules needed for the configuration given by PATH. get recursively downloads all modules needed, such as modules imported by modules imported by the root and so on. Module installation also happens automatically by default as part of
the “terraform init” command, so you should rarely need to run this command separately.

\n", "
$ terraform get
\n", "

You can update the already downloaded modules using -update=true option.

\n", "
$ terraform get -update=true
\n", "

terraform apply

\n", "

apply will do the actual operation on the infrastructure resources. apply will show the plan and actions in detail.

\n", "
$ terraform apply
\n", "

apply will ask for your confirmation to proceed with changes. You can use -auto-approve for auto-confirmation.

\n", "
$ terraform apply -auto-approve
\n", "

You can pass different variables or variable files.

\n", "
$ terraform plan -var=\"instancetype=t2.small\"\n",
      "$ terraform plan -var-file=\"custom.tfvars
\n", "

You can use -target option to target specific resources, modules, or collections of resources.

\n", "
$ terraform apply -target=\"aws_s3_bucket_object.objects\"
\n", "

terraform destroy

\n", "

Warning: destroy will delete all resource but with confirmation.

\n", "
$ terraform destroy
\n", "

You can create a deletion plan as below.

\n", "
$ terraform plan –destroy
\n", "

Use the -target to destroy a specific resource.

\n", "
$ terraform destroy -target=\"aws_s3_bucket_object.objects\"
\n", "

Also note, you can comment out the resource, then terraform will detect it as not part of config and will remove when you do plan or apply.

\n", "

terraform refresh

\n", "

You can update the terraform state file with metadata that matches the physical resources they are tracking.

\n", "
$ terraform refresh
\n", "

terraform show

\n", "

Show the terraform state information in a human readable format. You can also use it for displaying information from plan file.

\n", "
$ terraform show
\n", "

terraform validate

\n", "

You can check the syntax and validate the configuration using validate subcommand.

\n", "
$ terraform validate\n",
      "Success! The configuration is valid.
\n", "

terraform providers

\n", "

You can see the providers in use by the modules and configurations in your Terraform files.

\n", "
$ terraform providers\n",
      "\n",
      "Providers required by configuration:\n",
      ".\n",
      "└── provider[registry.terraform.io/hashicorp/aws]
\n", "

terraform state

\n", "

terraform state has multiple subcommands to manage the terraform state. You can move, rm (delete), list or show the resource state.

\n", "
Subcommands:\n",
      "    list                List resources in the state\n",
      "    mv                  Move an item in the state\n",
      "    pull                Pull current state and output to stdout\n",
      "    push                Update remote state from a local state file\n",
      "    replace-provider    Replace provider in the state\n",
      "    rm                  Remove instances from the state\n",
      "    show                Show a resource in the state
\n", "

Example usages

\n", "
# List state\n",
      "$ terraform state list\n",
      "aws_iam_user.lb\n",
      "aws_instance.myec2\n",
      "\n",
      "# Show resource\n",
      "$ terraform state show aws_instance.myec2\n",
      "\n",
      "# Push terraform state to remote backend\n",
      "$ tarraform state push\n",
      "\n",
      "# Pull the remote terraform state to a local copy\n",
      "$ terraform state pull > terraform.tfstate\n",
      "\n",
      "# Update and tell terraform that packet_device.worker has been renamed to packet_device.helper\n",
      "$ terraform state mv packet_device.worker packet_device.helper\n",
      "\n",
      "# Move the resource block into the child module configuration\n",
      "$ terraform state mv packet_device.worker module.worker.packet_device.worker\n",
      "\n",
      "# Remove the resource from state but it will not remove the resource from cloud/provider.\n",
      "$ terraform state rm aws_instance.myec2
\n", "

Remove the resource from state but it will not remove the resource from cloud/provider. But next time when you run terraform plan or apply, Terraform will recreate the instance as again as the resource definition is still there.

\n", "
$ terraform state rm aws_instance.myec2\n",
      "Removed aws_instance.myec2\n",
      "Successfully removed 1 resource instance(s).
\n", "

terraform graph

\n", "

graph will generate the visual graph of your infrastructure based on Terraform configuration files.

\n", "

Outputs the visual execution graph of Terraform resources according to
either the current configuration or an execution plan.

\n", "
$ terraform graph
\n", "

The output of terraform graph will be in DOT format and you can use tools like dot to generate image files from dot files.

\n", "
sudo apt-get install graphviz\n",
      "# or \n",
      "sudo yum install graphviz\n",
      "\n",
      "$ terraform graph | dot –Tpng > graph.png
\n", "

terraform fmt

\n", "

Rewrites all Terraform configuration files to a canonical format with appropriate indentation and styling. (JSON files (.tf.json or .tfvars.json) are not modified.)

\n", "
$ terraform fmt
\n", "

terraform taint

\n", "

You can manually mark a terraform managed resource as tainted and forcing it to be destroyed and recreated on the next apply. terraform taint command will make modification in the tfstate file and recreate action will happen in next apply. Please note, terraform taint command will not modify the .tf file or the infrastructure.

\n", "
$ terraform taint aws_instance.myec2
\n", "

terraform import

\n", "

You can import your existing infrastructure into Terraform and manage using Terraform.

\n", "
# Importing VMWare VM to terraform\n",
      "$ terraform import vsphere_virtual_machine.vm /DC1/vm/DEV/DEV2
\n", "

Read our detailed guide: How to Import Existing VMWare VM’s into Terraform

\n", "

terraform workspaces

\n", "

Terraform Workspaces will help to manage same terraform configurations for different environments (eg: dev, staging, production) in the same project directory.

\n", "
# Check the workspace\n",
      "$ terraform workspace show\n",
      "default\n",
      "\n",
      "# Create new workspace\n",
      "$ terraform workspace new dev\n",
      "Created and switched to workspace \"dev\"!\n",
      "\n",
      "# List all workspaces\n",
      "$ terraform workspace list\n",
      "  default\n",
      "* dev\n",
      "\n",
      "# Switch to a specific workspace\n",
      "$ terraform workspace select dev\n",
      "Switched to workspace \"dev\".
\n", "

Terraform will create separate terraform.tfstate files in terraform.tfstate.d/WORKSPACE_NAME/ directories in the project directory.

\n", "
$ tree terraform.tfstate.d/\n",
      "terraform.tfstate.d/\n",
      "├── dev\n",
      "│   └── terraform.tfstate\n",
      "├── prod\n",
      "└── stage\n",
      "    └── terraform.tfstate\n",
      "\n",
      "3 directories, 2 files
\n", "

You can use ${terraform.workspace} interpolation to dynamically use the workspace name inside your terraform configuration (*.tf). Eg: you can use it for selecting instance type from an array based on workspace.

\n", "
resource \"aws_instance\" \"myec2\" {\n",
      "  ami           = \"ami-0cd31be676780afa7\"\n",
      "  instance_type = lookup(var.instance_type,terraform.workspace)\n",
      "\n",
      "}\n",
      "variable \"instance_type\" {\n",
      " type = map\n",
      "\n",
      " default = {\n",
      "   default = \"t2.nano\"\n",
      "   stage = \"t2.nano\"\n",
      "   dev = \"t2.micro\"\n",
      "   prod = \"t2.large\"\n",
      " }\n",
      "}
\n", "

Or you can use this ${terraform.workspace} for tagging the instance.

\n", "
resource \"aws_instance\" \"example\" {\n",
      "  # ... other arguments\n",
      "  tags = {\n",
      "    Name = \"web-${terraform.workspace}\"\n",
      "  }\n",
      "}
\n", "

Refer Terraform Workspaces documentation for more details.

\n", "

\n", "

Terraform Default Plugin Directories

\n", "
  • Windows: %APPDATA%\\terraform.d\\plugins
  • All other systems: ~/.terraform.d/plugins

Terraform Variable Assignment

\n", "

You can pass variables to Terraform in different methods.

\n", "

1. Environment variables – with a prefix TF_VAR_

\n", "
$ export TF_VAR_instance_type=t2.micro
\n", "

2. Command Line Flags

\n", "
$ terraform plan -var=\"instancetype=t2.small\"
\n", "

3. From a variable file – use terraform.tfvars – terraform will load all variables from this file. If different var files to be used then,

\n", "
$ terraform plan -var-file=\"custom.tfvars
\n", "

4. Variable Defaults – can keep variable default in another .tf file.

\n", "
$ cat variables.tf\n",
      "variable \"my_ip\" {\n",
      "default = \"10.1.10.10/32\"\n",
      "}
\n", "
  • if no value mentioned, then default value will be used.
  • if default value not defined, then terraform will ask for variable when you do apply or plan operation.

Resources

\n", "\n", "
\n", "\n", "

\n", "
\n", "
\n", "

Disclaimer: The views expressed and the content shared are those of the author and do not reflect the views of the author's employer or techbeatly platform.

\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "

Latest posts

\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "
\n", "
\n", "
\n", "\n", "\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "\n", "\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "

\n", "
\n", "
\n", "
\n", "
\n", "

Gineesh Mada Pparambath
\n", "
Gineesh has worked as a Systems Engineer, Automation Specialist, and content author. His primary focus is on Ansible Automation, Containerisation (OpenShift & Kubernetes), and Infrastructure as Code (Terraform).\n", "(aka Gini Gangadharan - iamgini.com)

\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "\n", "
\n", "
\n", "
\n", "
\n", "\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "\n", "\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "
\n", "

Comments

\n", "
\n", "

\n", "

\n", "

7 Responses

\n", "
\n", "
    \n", "
  1. \n", "
    \n", "\n", "\n", "

    […] https://www.techbeatly.com/terraform-cheat-sheet/ […]

    \n", "
    \n", "\n", "
    \n", "
    \n", "\n", "
    \n", "
  2. \n", "
  3. \n", "
    \n", "
    \n", " alexis says:
    \n", "\n", "\n", "
    \n", "\n", "
  4. \n", "
  5. \n", "
    \n", "
    \n", " Vergnaud Damien says:
    \n", "\n", "

    Hey, Thank you dude for this usefull piece of information 🙂

    \n", "

    Would you consider adding :
    \n", "${terraform.workspace} variable inside your “terraform workspace” section ?

    \n", "

    This variable is SOOO usefull, because you have multiples .tfstate … right … but you only have 1 .tf plan.

    \n", "

    So you need sometimes to changes small things according to the workspace you’re in, right ? (I said small things, not the whole stack)
    \n", "At least the name of the instances or the VPC you are connected to or others things like that.

    \n", "

    I recommand you to make a small mention of it if you share my though 🙂
    \n", "https://www.terraform.io/docs/language/state/workspaces.html

    \n", "

    Have a great day 🙂

    \n", "
    \n", "\n", "
    \n", "
    \n", "\n", "
    \n", "
      \n", "
    • \n", "
      \n", "\n", "\n", "

      Thank you so much Damien,
      \n", "Appreciate your suggestion and feedback. I have added the same under Workspace section.

      \n", "
      \n", "\n", "
      \n", "
      \n", "\n", "
      \n", "
    • \n", "
    \n", "
  6. \n", "
  7. \n", "
    \n", "
    \n", " Vaishnavi says:
    \n", "\n", "

    thanks for the great article!!

    \n", "
    \n", "\n", "
    \n", "
    \n", "\n", "
    \n", "
  8. \n", "
  9. \n", "
    \n", "\n", "\n", "

    […] Terraform? Check this Terraform cheat sheet for quick […]

    \n", "
    \n", "\n", "
    \n", "
    \n", "\n", "
    \n", "
  10. \n", "
\n", "
\n", "
\n", "

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

\n", "

\n", "

\n", "

\n", "\n", "

\n", "

This site uses Akismet to reduce spam. Learn how your comment data is processed.

\n", "

\n", "
\n", "
\n", "
\n", "
\n", "
\n", "\n", "
\n", "
\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
%d bloggers like this:
\n", "\n", "\n", "\n", "\n" ] } ], "source": [ "from requests_html import HTMLSession\n", "\n", "session = HTMLSession()\n", "r = session.get(\"https://www.techbeatly.com/terraform-cheat-sheet\")\n", "\n", "print(r.text)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Terraform Cheat Sheet - techbeatly\n", "
\n", "

\n", "

\"\"

What is Terraform

\n", "

Terraform is an open-source software tool to manage end to end lifecycle of your IT infrastructure. Terraform provides a consistent CLI workflow to manage hundreds of cloud services.

\n", "

Latest Terraform Articles

\n", "

Installing Terraform

\n", "

You can download the Terraform software from HashiCorp’s download page and use native installation methods for your operating system. Also you can install Terraform using the package managers like yum, apt, homebrew, Chocolatey (choco) etc. Refer install Terraform page for the appropriate method for your operating system.

\n", "
\"\"

Terraform CLI Cheat Sheet

\n", "

Please note, this cheat sheet is a living document and I will make changes whenever there is an update or changes in the Terraform CLI options or versions. This cheat sheet does not written in an alphabetical order or based on workflow.

\n", "

Planning HashiCorp Certified Terraform Associate Certification ? Watch the video for details.

\n", "

terraform version

\n", "
$ terraform version\n",
      "Terraform v1.0.1\n",
      "on darwin_amd64
\n", "

terraform init

\n", "
$ terraform init
\n", "

Ask for input if necessary. If false, will error if input was required.

\n", "
$ terraform init -input=false
\n", "

You can also change the backend details using -backend-config option. -reconfigure will reconfigure the backend, ignoring any saved configuration.

\n", "
$ terraform init -backend-config=PATH/TO/CONFIGURATION_FILE -reconfigure
\n", "

terraform plan

\n", "

The plan will check the configuration files (basically all the *.tf files in the directory) and will show you the items or changes going to made on target infrastructure or resources. Please note, this command will not actually perform the planned actions.

\n", "
$ terraform plan
\n", "

You can optionally save the plan to a file, which you can then pass to the apply command to perform exactly the actions described in the plan.

\n", "
$ terraform plan -out plan.out
\n", "

terraform get

\n", "

Downloads and installs modules needed for the configuration given by PATH. get recursively downloads all modules needed, such as modules imported by modules imported by the root and so on. Module installation also happens automatically by default as part of
the “terraform init” command, so you should rarely need to run this command separately.

\n", "
$ terraform get
\n", "

You can update the already downloaded modules using -update=true option.

\n", "
$ terraform get -update=true
\n", "

terraform apply

\n", "

apply will do the actual operation on the infrastructure resources. apply will show the plan and actions in detail.

\n", "
$ terraform apply
\n", "

apply will ask for your confirmation to proceed with changes. You can use -auto-approve for auto-confirmation.

\n", "
$ terraform apply -auto-approve
\n", "

You can pass different variables or variable files.

\n", "
$ terraform plan -var=\"instancetype=t2.small\"\n",
      "$ terraform plan -var-file=\"custom.tfvars
\n", "

You can use -target option to target specific resources, modules, or collections of resources.

\n", "
$ terraform apply -target=\"aws_s3_bucket_object.objects\"
\n", "

terraform destroy

\n", "

Warning: destroy will delete all resource but with confirmation.

\n", "
$ terraform destroy
\n", "

You can create a deletion plan as below.

\n", "
$ terraform plan –destroy
\n", "

Use the -target to destroy a specific resource.

\n", "
$ terraform destroy -target=\"aws_s3_bucket_object.objects\"
\n", "

Also note, you can comment out the resource, then terraform will detect it as not part of config and will remove when you do plan or apply.

\n", "

terraform refresh

\n", "

You can update the terraform state file with metadata that matches the physical resources they are tracking.

\n", "
$ terraform refresh
\n", "

terraform show

\n", "

Show the terraform state information in a human readable format. You can also use it for displaying information from plan file.

\n", "
$ terraform show
\n", "

terraform validate

\n", "

You can check the syntax and validate the configuration using validate subcommand.

\n", "
$ terraform validate\n",
      "Success! The configuration is valid.
\n", "

terraform providers

\n", "

You can see the providers in use by the modules and configurations in your Terraform files.

\n", "
$ terraform providers\n",
      "\n",
      "Providers required by configuration:\n",
      ".\n",
      "└── provider[registry.terraform.io/hashicorp/aws]
\n", "

terraform state

\n", "

terraform state has multiple subcommands to manage the terraform state. You can move, rm (delete), list or show the resource state.

\n", "
Subcommands:\n",
      "    list                List resources in the state\n",
      "    mv                  Move an item in the state\n",
      "    pull                Pull current state and output to stdout\n",
      "    push                Update remote state from a local state file\n",
      "    replace-provider    Replace provider in the state\n",
      "    rm                  Remove instances from the state\n",
      "    show                Show a resource in the state
\n", "

Example usages

\n", "
# List state\n",
      "$ terraform state list\n",
      "aws_iam_user.lb\n",
      "aws_instance.myec2\n",
      "\n",
      "# Show resource\n",
      "$ terraform state show aws_instance.myec2\n",
      "\n",
      "# Push terraform state to remote backend\n",
      "$ tarraform state push\n",
      "\n",
      "# Pull the remote terraform state to a local copy\n",
      "$ terraform state pull > terraform.tfstate\n",
      "\n",
      "# Update and tell terraform that packet_device.worker has been renamed to packet_device.helper\n",
      "$ terraform state mv packet_device.worker packet_device.helper\n",
      "\n",
      "# Move the resource block into the child module configuration\n",
      "$ terraform state mv packet_device.worker module.worker.packet_device.worker\n",
      "\n",
      "# Remove the resource from state but it will not remove the resource from cloud/provider.\n",
      "$ terraform state rm aws_instance.myec2
\n", "

Remove the resource from state but it will not remove the resource from cloud/provider. But next time when you run terraform plan or apply, Terraform will recreate the instance as again as the resource definition is still there.

\n", "
$ terraform state rm aws_instance.myec2\n",
      "Removed aws_instance.myec2\n",
      "Successfully removed 1 resource instance(s).
\n", "

terraform graph

\n", "

graph will generate the visual graph of your infrastructure based on Terraform configuration files.

\n", "

Outputs the visual execution graph of Terraform resources according to
either the current configuration or an execution plan.

\n", "
$ terraform graph
\n", "

The output of terraform graph will be in DOT format and you can use tools like dot to generate image files from dot files.

\n", "
sudo apt-get install graphviz\n",
      "# or \n",
      "sudo yum install graphviz\n",
      "\n",
      "$ terraform graph | dot –Tpng > graph.png
\n", "

terraform fmt

\n", "

Rewrites all Terraform configuration files to a canonical format with appropriate indentation and styling. (JSON files (.tf.json or .tfvars.json) are not modified.)

\n", "
$ terraform fmt
\n", "

terraform taint

\n", "

You can manually mark a terraform managed resource as tainted and forcing it to be destroyed and recreated on the next apply. terraform taint command will make modification in the tfstate file and recreate action will happen in next apply. Please note, terraform taint command will not modify the .tf file or the infrastructure.

\n", "
$ terraform taint aws_instance.myec2
\n", "

terraform import

\n", "

You can import your existing infrastructure into Terraform and manage using Terraform.

\n", "
# Importing VMWare VM to terraform\n",
      "$ terraform import vsphere_virtual_machine.vm /DC1/vm/DEV/DEV2
\n", "

Read our detailed guide: How to Import Existing VMWare VM’s into Terraform

\n", "

terraform workspaces

\n", "

Terraform Workspaces will help to manage same terraform configurations for different environments (eg: dev, staging, production) in the same project directory.

\n", "
# Check the workspace\n",
      "$ terraform workspace show\n",
      "default\n",
      "\n",
      "# Create new workspace\n",
      "$ terraform workspace new dev\n",
      "Created and switched to workspace \"dev\"!\n",
      "\n",
      "# List all workspaces\n",
      "$ terraform workspace list\n",
      "  default\n",
      "* dev\n",
      "\n",
      "# Switch to a specific workspace\n",
      "$ terraform workspace select dev\n",
      "Switched to workspace \"dev\".
\n", "

Terraform will create separate terraform.tfstate files in terraform.tfstate.d/WORKSPACE_NAME/ directories in the project directory.

\n", "
$ tree terraform.tfstate.d/\n",
      "terraform.tfstate.d/\n",
      "├── dev\n",
      "│   └── terraform.tfstate\n",
      "├── prod\n",
      "└── stage\n",
      "    └── terraform.tfstate\n",
      "\n",
      "3 directories, 2 files
\n", "

You can use ${terraform.workspace} interpolation to dynamically use the workspace name inside your terraform configuration (*.tf). Eg: you can use it for selecting instance type from an array based on workspace.

\n", "
resource \"aws_instance\" \"myec2\" {\n",
      "  ami           = \"ami-0cd31be676780afa7\"\n",
      "  instance_type = lookup(var.instance_type,terraform.workspace)\n",
      "\n",
      "}\n",
      "variable \"instance_type\" {\n",
      " type = map\n",
      "\n",
      " default = {\n",
      "   default = \"t2.nano\"\n",
      "   stage = \"t2.nano\"\n",
      "   dev = \"t2.micro\"\n",
      "   prod = \"t2.large\"\n",
      " }\n",
      "}
\n", "

Or you can use this ${terraform.workspace} for tagging the instance.

\n", "
resource \"aws_instance\" \"example\" {\n",
      "  # ... other arguments\n",
      "  tags = {\n",
      "    Name = \"web-${terraform.workspace}\"\n",
      "  }\n",
      "}
\n", "

Refer Terraform Workspaces documentation for more details.

\n", "

\n", "

Terraform Default Plugin Directories

\n", "

Terraform Variable Assignment

\n", "

You can pass variables to Terraform in different methods.

\n", "

1. Environment variables – with a prefix TF_VAR_

\n", "
$ export TF_VAR_instance_type=t2.micro
\n", "

2. Command Line Flags

\n", "
$ terraform plan -var=\"instancetype=t2.small\"
\n", "

3. From a variable file – use terraform.tfvars – terraform will load all variables from this file. If different var files to be used then,

\n", "
$ terraform plan -var-file=\"custom.tfvars
\n", "

4. Variable Defaults – can keep variable default in another .tf file.

\n", "
$ cat variables.tf\n",
      "variable \"my_ip\" {\n",
      "default = \"10.1.10.10/32\"\n",
      "}
\n", "

Resources

\n", "

Share this to your network:

\n", "

\n", "

\n", "

\n", "
\n", "
\n" ] } ], "source": [ "import requests\n", "from readability import Document\n", "\n", "response = requests.get(\"https://www.techbeatly.com/terraform-cheat-sheet\")\n", "doc = Document(response.text)\n", "print(doc.title())\n", "\n", "print(doc.summary())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create Book if it doesn't exist\n" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\"name\":\"python-cheatsheet\",\"description\":\"python-cheatsheet\",\"created_by\":1,\"updated_by\":1,\"owned_by\":1,\"slug\":\"python-cheatsheet\",\"updated_at\":\"2022-08-10T00:14:32.000000Z\",\"created_at\":\"2022-08-10T00:14:32.000000Z\",\"id\":3}\n" ] } ], "source": [ "import requests\n", "\n", "import os\n", "\n", "payload = {\n", " \"name\": \"terraform-cheatsheet\",\n", " \"description\": \"terraform-cheatsheet\",\n", " \"tags\": [\n", " {\"name\": \"Platform\", \"value\": \"terraform\"},\n", " {\"name\": \"Category\", \"value\": \"Code\"},\n", " {\"name\": \"Type\", \"value\": \"Cheatsheet\"},\n", " ],\n", "}\n", "headers = {\n", " \"X-API-KEY\": os.getenv(X_API_KEY),\n", " \"Authorization\": os.getenv(BOOKSTACK_API_TOKEN),\n", "}\n", "\n", "response = requests.request(\"POST\", url, json=payload, headers=headers)\n", "\n", "print(response.text)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create Chapters\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### List folders to map to chapters\n" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "18\n", "19\n", "20\n" ] } ], "source": [ "import requests\n", "\n", "chapters = [\"cheatsheet\", \"modules\", \"builtin\"]\n", "\n", "url = \"https://donavanaldrich.com/api/bookstack/chapters\"\n", "\n", "for chapter_name in chapters:\n", "\n", " payload = {\n", " \"book_id\": 2,\n", " \"name\": chapter_name,\n", " \"description\": chapter_name,\n", " \"tags\": [{\"name\": \"chapter\", \"value\": chapter_name}],\n", " }\n", " headers = {\n", " \"X-API-KEY\": os.getenv(X_API_KEY),\n", " \"Authorization\": os.getenv(BOOKSTACK_API_TOKEN),\n", " }\n", "\n", " response = requests.request(\"POST\", url, json=payload, headers=headers)\n", " response_json = response.json()\n", " chapter_id = response_json[\"id\"]\n", " print(chapter_id)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Add Pages\n" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "26\n", "27\n", "28\n" ] } ], "source": [ "from pathlib import Path\n", "import requests\n", "import frontmatter\n", "\n", "chapters = [\"cheatsheet\", \"modules\", \"builtin\"]\n", "# The Python interpreter has a number of functions and types built into it that are always available.\n", "# Standard Library\n", "headers = {\n", " \"X-API-KEY\": os.getenv(X_API_KEY),\n", " \"Authorization\": os.getenv(BOOKSTACK_API_TOKEN),\n", "}\n", "\n", "url = \"https://donavanaldrich.com/api/bookstack/books\"\n", "\n", "payload = {\n", " \"name\": \"python-cheatsheet\",\n", " \"description\": \"python-cheatsheet\",\n", " \"tags\": [\n", " {\"name\": \"Platform\", \"value\": \"Python\"},\n", " {\"name\": \"Category\", \"value\": \"Code\"},\n", " {\"name\": \"Type\", \"value\": \"Cheatsheet\"},\n", " ],\n", "}\n", "\n", "response = requests.request(\"POST\", url, json=payload, headers=headers)\n", "response_json = response.json()\n", "book_id = response_json[\"id\"]\n", "\n", "# book_id = xs\n", "#\n", "for chapter in chapters:\n", " payload = {\n", " \"book_id\": book_id,\n", " \"name\": chapter,\n", " \"description\": chapter,\n", " \"tags\": [{\"name\": \"chapter\", \"value\": chapter}],\n", " }\n", " url = \"https://donavanaldrich.com/api/bookstack/chapters\"\n", " response = requests.request(\"POST\", url, json=payload, headers=headers)\n", " response_json = response.json()\n", " chapter_id = response_json[\"id\"]\n", " print(chapter_id)\n", "\n", " for page in Path(\"../temp/python-cheatsheets/\" + chapter).iterdir():\n", " url = \"https://donavanaldrich.com/api/bookstack/pages\"\n", " with open(page, \"r\") as f:\n", " # text = f.read()\n", " # post = frontmatter.load(page)\n", " metadata, content = frontmatter.parse(f.read())\n", " try:\n", " page_name = metadata[\"title\"]\n", " except:\n", " page_name = str(page)\n", " payload = {\n", " \"book_id\": book_id,\n", " \"chapter_id\": chapter_id,\n", " \"name\": page_name,\n", " \"markdown\": content,\n", " \"tags\": [{\"name\": \"chapter\", \"value\": chapter}],\n", " }\n", " response = requests.request(\"POST\", url, json=payload, headers=headers)\n", "\n", " # print(response.text)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Development/Sandboxing\n" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "# Python Debugging\n", "\n", "\n", " \n", " Finding and resolving bugs\n", " \n", " \n", " In computer programming and software development, debugging is the process of finding and resolving bugs (defects or problems that prevent correct operation) within computer programs, software, or systems.\n", " \n", "\n", "\n", "## Raising Exceptions\n", "\n", "Exceptions are raised with a raise statement. In code, a raise statement consists of the following:\n", "\n", "- The `raise` keyword\n", "- A call to the `Exception()` function\n", "- A string with a helpful error message passed to the `Exception()` function\n", "\n", "```python\n", ">>> raise Exception('This is the error message.')\n", "# Traceback (most recent call last):\n", "# File \"\", line 1, in \n", "# raise Exception('This is the error message.')\n", "# Exception: This is the error message.\n", "```\n", "\n", "Typically, it’s the code that calls the function, not the function itself, that knows how to handle an exception. So, you will commonly see a raise statement inside a function and the `try` and `except` statements in the code calling the function.\n", "\n", "```python\n", ">>> def box_print(symbol, width, height):\n", "... if len(symbol) != 1:\n", "... raise Exception('Symbol must be a single character string.')\n", "... if width <= 2:\n", "... raise Exception('Width must be greater than 2.')\n", "... if height <= 2:\n", "... raise Exception('Height must be greater than 2.')\n", "... print(symbol * width)\n", "... for i in range(height - 2):\n", "... print(symbol + (' ' * (width - 2)) + symbol)\n", "... print(symbol * width)\n", "...\n", ">>> for sym, w, h in (('*', 4, 4), ('O', 20, 5), ('x', 1, 3), ('ZZ', 3, 3)):\n", "... try:\n", "... box_print(sym, w, h)\n", "... except Exception as err:\n", "... print('An exception happened: ' + str(err))\n", "...\n", "# ****\n", "# * *\n", "# * *\n", "# ****\n", "# OOOOOOOOOOOOOOOOOOOO\n", "# O O\n", "# O O\n", "# O O\n", "# OOOOOOOOOOOOOOOOOOOO\n", "# An exception happened: Width must be greater than 2.\n", "# An exception happened: Symbol must be a single character string.\n", "```\n", "\n", "Read more about [Exception Handling](/cheatsheet/exception-handling).\n", "\n", "## Getting the Traceback as a string\n", "\n", "The `traceback` is displayed by Python whenever a raised exception goes unhandled. But can also obtain it as a string by calling traceback.format_exc(). This function is useful if you want the information from an exception’s traceback but also want an except statement to gracefully handle the exception. You will need to import Python’s traceback module before calling this function.\n", "\n", "```python\n", ">>> import traceback\n", "\n", ">>> try:\n", "... raise Exception('This is the error message.')\n", ">>> except:\n", "... with open('errorInfo.txt', 'w') as error_file:\n", "... error_file.write(traceback.format_exc())\n", "... print('The traceback info was written to errorInfo.txt.')\n", "...\n", "# 116\n", "# The traceback info was written to errorInfo.txt.\n", "```\n", "\n", "The 116 is the return value from the `write()` method, since 116 characters were written to the file. The `traceback` text was written to errorInfo.txt.\n", "\n", " Traceback (most recent call last):\n", " File \"\", line 2, in \n", " Exception: This is the error message.\n", "\n", "## Assertions\n", "\n", "An assertion is a sanity check to make sure your code isn’t doing something obviously wrong. These sanity checks are performed by `assert` statements. If the sanity check fails, then an `AssertionError` exception is raised. In code, an `assert` statement consists of the following:\n", "\n", "- The `assert` keyword\n", "- A condition (that is, an expression that evaluates to `True` or `False`)\n", "- A comma\n", "- A `string` to display when the condition is `False`\n", "\n", "```python\n", ">>> pod_bay_door_status = 'open'\n", ">>> assert pod_bay_door_status == 'open', 'The pod bay doors need to be \"open\".'\n", "\n", ">>> pod_bay_door_status = 'I\\'m sorry, Dave. I\\'m afraid I can\\'t do that.'\n", ">>> assert pod_bay_door_status == 'open', 'The pod bay doors need to be \"open\".'\n", "# Traceback (most recent call last):\n", "# File \"\", line 1, in \n", "# assert pod_bay_door_status == 'open', 'The pod bay doors need to be \"open\".'\n", "# AssertionError: The pod bay doors need to be \"open\".\n", "```\n", "\n", "In plain English, an assert statement says, “I assert that this condition holds true, and if not, there is a bug somewhere in the program.” Unlike exceptions, your code should not handle assert statements with try and except; if an assert fails, your program should crash. By failing fast like this, you shorten the time between the original cause of the bug and when you first notice the bug. This will reduce the amount of code you will have to check before finding the code that’s causing the bug.\n", "\n", "### Disabling Assertions\n", "\n", "Assertions can be disabled by passing the `-O` option when running Python.\n", "\n", "## Logging\n", "\n", "To enable the `logging` module to display log messages on your screen as your program runs, copy the following to the top of your program:\n", "\n", "```python\n", ">>> import logging\n", ">>> logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s- %(message)s')\n", "```\n", "\n", "Say you wrote a function to calculate the factorial of a number. In mathematics, factorial 4 is 1 × 2 × 3 × 4, or 24. Factorial 7 is 1 × 2 × 3 × 4 × 5 × 6 × 7, or 5,040. Open a new file editor window and enter the following code. It has a bug in it, but you will also enter several log messages to help yourself figure out what is going wrong. Save the program as factorialLog.py.\n", "\n", "```python\n", ">>> import logging\n", ">>> logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s- %(message)s')\n", ">>> logging.debug('Start of program')\n", "\n", ">>> def factorial(n):\n", "... logging.debug('Start of factorial(%s)' % (n))\n", "... total = 1\n", "... for i in range(1, n + 1):\n", "... total *= i\n", "... logging.debug('i is ' + str(i) + ', total is ' + str(total))\n", "... logging.debug('End of factorial(%s)' % (n))\n", "... return total\n", "...\n", ">>> print(factorial(5))\n", ">>> logging.debug('End of program')\n", "# 2015-05-23 16:20:12,664 - DEBUG - Start of program\n", "# 2015-05-23 16:20:12,664 - DEBUG - Start of factorial(5)\n", "# 2015-05-23 16:20:12,665 - DEBUG - i is 0, total is 0\n", "# 2015-05-23 16:20:12,668 - DEBUG - i is 1, total is 0\n", "# 2015-05-23 16:20:12,670 - DEBUG - i is 2, total is 0\n", "# 2015-05-23 16:20:12,673 - DEBUG - i is 3, total is 0\n", "# 2015-05-23 16:20:12,675 - DEBUG - i is 4, total is 0\n", "# 2015-05-23 16:20:12,678 - DEBUG - i is 5, total is 0\n", "# 2015-05-23 16:20:12,680 - DEBUG - End of factorial(5)\n", "# 0\n", "# 2015-05-23 16:20:12,684 - DEBUG - End of program\n", "```\n", "\n", "## Logging Levels\n", "\n", "Logging levels provide a way to categorize your log messages by importance. There are five logging levels, described in Table 10-1 from least to most important. Messages can be logged at each level using a different logging function.\n", "\n", "| Level | Logging Function | Description |\n", "| ---------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------ |\n", "| `DEBUG` | `logging.debug()` | The lowest level. Used for small details. Usually you care about these messages only when diagnosing problems. |\n", "| `INFO` | `logging.info()` | Used to record information on general events in your program or confirm that things are working at their point in the program. |\n", "| `WARNING` | `logging.warning()` | Used to indicate a potential problem that doesn’t prevent the program from working but might do so in the future. |\n", "| `ERROR` | `logging.error()` | Used to record an error that caused the program to fail to do something. |\n", "| `CRITICAL` | `logging.critical()` | The highest level. Used to indicate a fatal error that has caused or is about to cause the program to stop running entirely. |\n", "\n", "## Disabling Logging\n", "\n", "After you’ve debugged your program, you probably don’t want all these log messages cluttering the screen. The logging.disable() function disables these so that you don’t have to go into your program and remove all the logging calls by hand.\n", "\n", "```python\n", ">>> import logging\n", "\n", ">>> logging.basicConfig(level=logging.INFO, format=' %(asctime)s -%(levelname)s - %(message)s')\n", ">>> logging.critical('Critical error! Critical error!')\n", "# 2015-05-22 11:10:48,054 - CRITICAL - Critical error! Critical error!\n", "\n", ">>> logging.disable(logging.CRITICAL)\n", ">>> logging.critical('Critical error! Critical error!')\n", ">>> logging.error('Error! Error!')\n", "```\n", "\n", "## Logging to a File\n", "\n", "Instead of displaying the log messages to the screen, you can write them to a text file. The `logging.basicConfig()` function takes a filename keyword argument, like so:\n", "\n", "```python\n", ">>> import logging\n", ">>> logging.basicConfig(filename='myProgramLog.txt', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')\n", "```\n" ] } ], "source": [ "# for page in Path('../temp/python-cheatsheets/' + chapter).iterdir():\n", "page = \"../temp/python-cheatsheets/cheatsheet/debugging.md\"\n", "url = \"https://donavanaldrich.com/api/bookstack/pages\"\n", "# print(page)\n", "with open(page, \"r\") as f:\n", " # text = f.read()\n", " # post = frontmatter.load(page)\n", " metadata, content = frontmatter.parse(f.read())\n", "print(content)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Reference\n", "\n", "### Payloads\n", "\n", "#### book\n", "\n", "```json\n", "{\n", " \"name\": \"python-cheatsheet\",\n", " \"description\": \"python-cheatsheet\",\n", " \"tags\": [\n", " { \"name\": \"Platform\", \"value\": \"Python\" },\n", " { \"name\": \"Category\", \"value\": \"Code\" },\n", " { \"name\": \"Type\", \"value\": \"Cheatsheet\" }\n", " ]\n", "}\n", "```\n", "\n", "#### Chapter\n", "\n", "```json\n", "{\n", " \"book_id\": 1,\n", " \"name\": \"My fantastic new chapter\",\n", " \"description\": \"This is a great new chapter that I've created via the API\",\n", " \"tags\": [\n", " { \"name\": \"Category\", \"value\": \"Top Content\" },\n", " { \"name\": \"Rating\", \"value\": \"Highest\" }\n", " ]\n", "}\n", "```\n", "\n", "#### Page\n", "\n", "```json\n", "{\n", " \"book_id\": 1,\n", " \"name\": \"My API Page\",\n", " \"markdown\": \"

my new API page

\",\n", " \"tags\": [\n", " { \"name\": \"Category\", \"value\": \"Not Bad Content\" },\n", " { \"name\": \"Rating\", \"value\": \"Average\" }\n", " ]\n", "}\n", "```\n" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "ename": "AttributeError", "evalue": "module 'frontmatter' has no attribute 'load'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m/home/donaldrich/projects/secrets/jupyter-notebooks/documentation/python-cheatsheet.ipynb Cell 19\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 6\u001b[0m file_parts \u001b[39m=\u001b[39m frontmatter\u001b[39m.\u001b[39mload(filepath)\n\u001b[1;32m 8\u001b[0m \u001b[39mreturn\u001b[39;00m {\n\u001b[1;32m 9\u001b[0m \u001b[39m# 'html': markdown_parser.convert(file_parts.content),\u001b[39;00m\n\u001b[1;32m 10\u001b[0m \u001b[39m'\u001b[39m\u001b[39mmetadata\u001b[39m\u001b[39m'\u001b[39m: file_parts\u001b[39m.\u001b[39mmetadata\n\u001b[1;32m 11\u001b[0m }\n\u001b[0;32m---> 13\u001b[0m parse_markdown(\u001b[39m'\u001b[39;49m\u001b[39m../temp/python-cheatsheets/cheatsheet/debugging.md\u001b[39;49m\u001b[39m'\u001b[39;49m)\n", "\u001b[1;32m/home/donaldrich/projects/secrets/jupyter-notebooks/documentation/python-cheatsheet.ipynb Cell 19\u001b[0m in \u001b[0;36mparse_markdown\u001b[0;34m(filepath)\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[39mdef\u001b[39;00m \u001b[39mparse_markdown\u001b[39m(filepath):\n\u001b[1;32m 5\u001b[0m \u001b[39m# markdown_parser = markdown.Markdown(extensions=markdown_extensions)\u001b[39;00m\n\u001b[0;32m----> 6\u001b[0m file_parts \u001b[39m=\u001b[39m frontmatter\u001b[39m.\u001b[39;49mload(filepath)\n\u001b[1;32m 8\u001b[0m \u001b[39mreturn\u001b[39;00m {\n\u001b[1;32m 9\u001b[0m \u001b[39m# 'html': markdown_parser.convert(file_parts.content),\u001b[39;00m\n\u001b[1;32m 10\u001b[0m \u001b[39m'\u001b[39m\u001b[39mmetadata\u001b[39m\u001b[39m'\u001b[39m: file_parts\u001b[39m.\u001b[39mmetadata\n\u001b[1;32m 11\u001b[0m }\n", "\u001b[0;31mAttributeError\u001b[0m: module 'frontmatter' has no attribute 'load'" ] } ], "source": [ "import frontmatter # https://pypi.org/project/python-frontmatter/\n", "import markdown\n", "\n", "\n", "def parse_markdown(filepath):\n", " # markdown_parser = markdown.Markdown(extensions=markdown_extensions)\n", " file_parts = frontmatter.load(filepath)\n", "\n", " return {\n", " # 'html': markdown_parser.convert(file_parts.content),\n", " \"metadata\": file_parts.metadata\n", " }\n", "\n", "\n", "parse_markdown(\"../temp/python-cheatsheets/cheatsheet/debugging.md\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3.8.9 64-bit", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.4" }, "orig_nbformat": 4, "vscode": { "interpreter": { "hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6" } } }, "nbformat": 4, "nbformat_minor": 2 }