Merge branch 'MichaelCade:main' into main
This commit is contained in:
commit
4facd58520
16
.github/workflows/Auto_message_on_creatingissues.yml
vendored
Normal file
16
.github/workflows/Auto_message_on_creatingissues.yml
vendored
Normal file
@ -0,0 +1,16 @@
|
||||
name: Auto message on Creating a Issue.
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened]
|
||||
|
||||
jobs:
|
||||
greeting:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Create comment for issue
|
||||
if: github.event_name =='issues'
|
||||
uses: peter-evans/create-or-update-comment@v1
|
||||
with:
|
||||
issue-number: ${{tojson(github.event.issue.number)}}
|
||||
body: Hello there!👋, @${{ github.actor }} Welcome to the Solidity-Pathshala! 🚀⚡Thank you and Congratulations🎉 for opening a issue in this project. Please make sure not to start working on this issue, unless you are assigned to it.😄
|
19
.github/workflows/Auto_message_on_pr_merge.yml
vendored
Normal file
19
.github/workflows/Auto_message_on_pr_merge.yml
vendored
Normal file
@ -0,0 +1,19 @@
|
||||
name: Auto message on Pr merge
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [closed]
|
||||
|
||||
jobs:
|
||||
auto-response:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: derekprior/add-autoresponse@master
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
respondableId: ${{ github.event.pull_request.node_id }}
|
||||
response: "Thank you @${{ github.event.pull_request.user.login }} for taking out your valuable time in order to contribute to our project. Looking forward for more such amazing contributions :)"
|
||||
author: ${{ github.event.pull_request.user.login }}
|
||||
exemptedAuthors: "Vikash-8090-Yadav"
|
19
.github/workflows/Auto_message_on_pr_open.yml
vendored
Normal file
19
.github/workflows/Auto_message_on_pr_open.yml
vendored
Normal file
@ -0,0 +1,19 @@
|
||||
name: Auto message on PR opened
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened]
|
||||
|
||||
jobs:
|
||||
auto-response:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: derekprior/add-autoresponse@master
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
respondableId: ${{ github.event.pull_request.node_id }}
|
||||
response: "Our team will soon review your PR. Thanks @${{ github.event.pull_request.user.login }} :)"
|
||||
author: ${{ github.event.pull_request.user.login }}
|
||||
exemptedAuthors: "Vikash-8090-Yadav"
|
@ -71,10 +71,10 @@ I have taken these from [atlassian](https://www.atlassian.com/git/tutorials/atla
|
||||
| Command | Example | Description |
|
||||
| ------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git init | `git init <directory>` | Create an empty git repository in the specified directory. |
|
||||
| git clone | `git clone <repo>` | Clone repository located at <repo> onto local machine. |
|
||||
| git clone | `git clone <repo>` | Clone repository located at \<repo> onto local machine. |
|
||||
| git config | `git config user.name` | Define author name to be used for all commits in current repository `system`, `global`, `local` flag to set config options. |
|
||||
| git add | `git add <directory>` | Stage all changes in <directory> for the next commit. We can also add <files> and <.> for everything. |
|
||||
| git commit -m | `git commit -m "<message>"` | Commit the staged snapshot, use <message> to detail what is being committed. |
|
||||
| git add | `git add <directory>` | Stage all changes in \<directory> for the next commit. We can also add \<files> and \<.> for everything. |
|
||||
| git commit -m | `git commit -m "<message>"` | Commit the staged snapshot, use \<message> to detail what is being committed. |
|
||||
| git status | `git status` | List files that are staged, unstaged and untracked. |
|
||||
| git log | `git log` | Display all commit history using the default format. There are additional options with this command. |
|
||||
| git diff | `git diff` | Show unstaged changes between your index and working directory. |
|
||||
@ -83,8 +83,8 @@ I have taken these from [atlassian](https://www.atlassian.com/git/tutorials/atla
|
||||
|
||||
| Command | Example | Description |
|
||||
| ---------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git revert | `git revert <commit>` | Create a new commit that undoes all of the changes made in <commit> then apply it to the current branch. |
|
||||
| git reset | `git reset <file>` | Remove <file> from the staging area, but leave the working directory unchanged. This unstaged a file without overwriting any changes. |
|
||||
| git revert | `git revert <commit>` | Create a new commit that undoes all of the changes made in \<commit> then apply it to the current branch. |
|
||||
| git reset | `git reset <file>` | Remove \<file> from the staging area, but leave the working directory unchanged. This unstaged a file without overwriting any changes. |
|
||||
| git clean | `git clean -n` | Shows which files would be removed from the working directory. Use `-f` in place of `-n` to execute the clean. |
|
||||
|
||||
### Git Rewriting History
|
||||
@ -92,25 +92,25 @@ I have taken these from [atlassian](https://www.atlassian.com/git/tutorials/atla
|
||||
| Command | Example | Description |
|
||||
| ---------- | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git commit | `git commit --amend` | Replace the last commit with the staged changes and the last commit combined. Use with nothing staged to edit the last commit’s message. |
|
||||
| git rebase | `git rebase <base>` | Rebase the current branch onto <base>. <base> can be a commit ID, branch name, a tag, or a relative reference to HEAD. |
|
||||
| git rebase | `git rebase <base>` | Rebase the current branch onto \<base>. \<base> can be a commit ID, branch name, a tag, or a relative reference to HEAD. |
|
||||
| git reflog | `git reflog` | Show a log of changes to the local repository’s HEAD. Add --relative-date flag to show date info or --all to show all refs. |
|
||||
|
||||
### Git Branches
|
||||
|
||||
| Command | Example | Description |
|
||||
| ------------ | -------------------------- | ------------------------------------------------------------------------------------------------------------- |
|
||||
| git branch | `git branch` | List all of the branches in your repo. Add a <branch> argument to create a new branch with the name <branch>. |
|
||||
| git checkout | `git checkout -b <branch>` | Create and check out a new branch named <branch>. Drop the -b flag to checkout an existing branch. |
|
||||
| git merge | `git merge <branch>` | Merge <branch> into the current branch. |
|
||||
| git branch | `git branch` | List all of the branches in your repo. Add a \<branch> argument to create a new branch with the name \<branch>. |
|
||||
| git checkout | `git checkout -b <branch>` | Create and check out a new branch named \<branch>. Drop the -b flag to checkout an existing branch. |
|
||||
| git merge | `git merge <branch>` | Merge \<branch> into the current branch. |
|
||||
|
||||
### Git Remote Repositories
|
||||
|
||||
| Command | Example | Description |
|
||||
| -------------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git remote add | `git remote add <name> <url>` | Create a new connection to a remote repo. After adding a remote, you can use <name> as a shortcut for <url> in other commands. |
|
||||
| git fetch | `git fetch <remote> <branch>` | Fetches a specific <branch>, from the repo. Leave off <branch> to fetch all remote refs. |
|
||||
| git remote add | `git remote add <name> <url>` | Create a new connection to a remote repo. After adding a remote, you can use \<name> as a shortcut for \<url> in other commands. |
|
||||
| git fetch | `git fetch <remote> <branch>` | Fetches a specific \<branch>, from the repo. Leave off \<branch> to fetch all remote refs. |
|
||||
| git pull | `git pull <remote>` | Fetch the specified remote’s copy of current branch and immediately merge it into the local copy. |
|
||||
| git push | `git push <remote> <branch>` | Push the branch to <remote>, along with necessary commits and objects. Creates named branch in the remote repo if it doesn’t exist. |
|
||||
| git push | `git push <remote> <branch>` | Push the branch to \<remote>, along with necessary commits and objects. Creates named branch in the remote repo if it doesn’t exist. |
|
||||
|
||||
### Git Diff
|
||||
|
||||
@ -123,23 +123,23 @@ I have taken these from [atlassian](https://www.atlassian.com/git/tutorials/atla
|
||||
|
||||
| Command | Example | Description |
|
||||
| ---------------------------------------------------- | ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git config --global user.name <name> | `git config --global user.name <name>` | Define the author name to be used for all commits by the current user. |
|
||||
| git config --global user.email <email> | `git config --global user.email <email>` | Define author email to be used for all commits by the current user. |
|
||||
| git config --global alias <alias-name> <git-command> | `git config --global alias <alias-name> <git-command>` | Create shortcut for a git command . |
|
||||
| git config --system core.editor <editor> | `git config --system core.editor <editor>` | Set the text editor to be used by commands for all users on the machine. <editor> arg should be the comamnd that launches the desired editor. |
|
||||
| git config --global user.name \<name> | `git config --global user.name <name>` | Define the author name to be used for all commits by the current user. |
|
||||
| git config --global user.email \<email> | `git config --global user.email <email>` | Define author email to be used for all commits by the current user. |
|
||||
| git config --global alias \<alias-name> \<git-command> | `git config --global alias <alias-name> <git-command>` | Create shortcut for a git command . |
|
||||
| git config --system core.editor \<editor> | `git config --system core.editor <editor>` | Set the text editor to be used by commands for all users on the machine. \<editor> arg should be the comamnd that launches the desired editor. |
|
||||
| git config --global --edit | `git config --global --edit ` | Open the global configuration file in a text editor for manual editing. |
|
||||
|
||||
### Git Rebase
|
||||
|
||||
| Command | Example | Description |
|
||||
| -------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git rebase -i <base> | `git rebase -i <base>` | Interactively rebase current branch onto <base>. Launches editor to enter commands for how each commit will be transferred to the new base. |
|
||||
| git rebase -i \<base> | `git rebase -i <base>` | Interactively rebase current branch onto \<base>. Launches editor to enter commands for how each commit will be transferred to the new base. |
|
||||
|
||||
### Git Pull
|
||||
|
||||
| Command | Example | Description |
|
||||
| -------------------------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git pull --rebase <remote> | `git pull --rebase <remote>` | Fetch the remote’s copy of current branch and rebases it into the local copy. Uses git rebase instead of the merge to integrate the branches. |
|
||||
| git pull --rebase \<remote> | `git pull --rebase <remote>` | Fetch the remote’s copy of current branch and rebases it into the local copy. Uses git rebase instead of the merge to integrate the branches. |
|
||||
|
||||
### Git Reset
|
||||
|
||||
@ -147,16 +147,16 @@ I have taken these from [atlassian](https://www.atlassian.com/git/tutorials/atla
|
||||
| ------------------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git reset | `git reset ` | Reset the staging area to match the most recent commit but leave the working directory unchanged. |
|
||||
| git reset --hard | `git reset --hard` | Reset staging area and working directory to match most recent commit and overwrites all changes in the working directory |
|
||||
| git reset <commit> | `git reset <commit>` | Move the current branch tip backwards to <commit>, reset the staging area to match, but leave the working directory alone |
|
||||
| git reset --hard <commit> | `git reset --hard <commit>` | Same as previous, but resets both the staging area & working directory to match. Deletes uncommitted changes, and all commits after <commit>. |
|
||||
| git reset \<commit> | `git reset <commit>` | Move the current branch tip backwards to \<commit>, reset the staging area to match, but leave the working directory alone |
|
||||
| git reset --hard \<commit> | `git reset --hard <commit>` | Same as previous, but resets both the staging area & working directory to match. Deletes uncommitted changes, and all commits after \<commit>. |
|
||||
|
||||
### Git Push
|
||||
|
||||
| Command | Example | Description |
|
||||
| ------------------------- | --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git push <remote> --force | `git push <remote> --force` | Forces the git push even if it results in a non-fast-forward merge. Do not use the --force flag unless you’re sure you know what you’re doing. |
|
||||
| git push <remote> --all | `git push <remote> --all` | Push all of your local branches to the specified remote. |
|
||||
| git push <remote> --tags | `git push <remote> --tags` | Tags aren’t automatically pushed when you push a branch or use the --all flag. The --tags flag sends all of your local tags to the remote repo. |
|
||||
| git push \<remote> --force | `git push <remote> --force` | Forces the git push even if it results in a non-fast-forward merge. Do not use the --force flag unless you’re sure you know what you’re doing. |
|
||||
| git push \<remote> --all | `git push <remote> --all` | Push all of your local branches to the specified remote. |
|
||||
| git push \<remote> --tags | `git push <remote> --tags` | Tags aren’t automatically pushed when you push a branch or use the --all flag. The --tags flag sends all of your local tags to the remote repo. |
|
||||
|
||||
## Resources
|
||||
|
||||
|
@ -95,7 +95,7 @@ I think it is important to touch on some of the differences between Ansible and
|
||||
| Language | Ansible follows procedural language | Terraform follows a declarative language |
|
||||
| Provisioning | Ansible provides partial provisioning (VM, Network, Storage) | Terraform provides extensive provisioning (VM, Network, Storage) |
|
||||
| Packaging | Ansible provides complete support for packaging & templating | Terraform provides partial support for packaging & templating |
|
||||
| Lifecycle Mgmt | Ansible does not have lifecycle management | Terraform is heavily dependent on lifecycle and state mgmt |
|
||||
| Lifecycle Mgmt | Ansible does not have lifecycle management | Terraform is heavily dependent on lifecycle and state management |
|
||||
|
||||
## Resources
|
||||
|
||||
|
@ -37,7 +37,7 @@ Before we then start to look at controlling other nodes in our environment, we c
|
||||
|
||||

|
||||
|
||||
Or an actual real-life use for a module might be something like `ansible webservers --m service -a "name=httpd state=started"` this will tell us if all of our webservers have the httpd service running. I have glossed over the webservers term used in that command.
|
||||
Or an actual real-life use for a module might be something like `ansible webservers -m service -a "name=httpd state=started"` this will tell us if all of our webservers have the httpd service running. I have glossed over the webservers term used in that command.
|
||||
|
||||
### hosts
|
||||
|
||||
|
@ -12,7 +12,7 @@ id: 1048747
|
||||
|
||||

|
||||
|
||||
Data Management is by no means a new wall to climb, although we do know that data is more important than it maybe was a few years ago. Valuable and ever-changing it can also be a massive nightmare when we are talking about automation and continuously integrating, testing and deploying frequent software releases. Enter the persistent data and underlying data services are often the main culprit when things go wrong.
|
||||
Data Management is by no means a new wall to climb, although we do know that data is more important than it may be was a few years ago. Valuable and ever-changing it can also be a massive nightmare when we are talking about automation and continuously integrating, testing and deploying frequent software releases. Enter the persistent data and underlying data services are often the main culprit when things go wrong.
|
||||
|
||||
But before I get into Cloud-Native Data Management, we need to go up a level. We have touched on many different platforms throughout this challenge. Be it Physical, Virtual, Cloud or Cloud-Native obviously including Kubernetes there is none of these platforms that provide the lack of requirement for data management.
|
||||
|
||||
|
BIN
2022/es/Days/Images/Day41_Git16.png
Normal file
BIN
2022/es/Days/Images/Day41_Git16.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 642 KiB |
@ -1,138 +1,140 @@
|
||||
## Installing & Configuring Git
|
||||
## Instalación y configuración de Git
|
||||
|
||||
Git is an open source, cross-platform tool for version control. If you are like me, using Ubuntu or most Linux environments you might find that you already have git installed but we are going to run through the install and configuration.
|
||||
Git es una herramienta multiplataforma de código abierto para el control de versiones. En la mayoría de entornos Linux viene instalado por defecto, pero de todas formas vamos a repasar la instalación y configuración.
|
||||
|
||||
Even if you already have git installed on your system it is also a good idea to make sure we are up to date.
|
||||
Incluso si ya tienes git instalado en tu sistema es una buena idea asegurarse de que está actualizado.
|
||||
|
||||
### Installing Git
|
||||
### Instalación de Git
|
||||
|
||||
As already mentioned Git is cross-platform, we will be running through Windows and Linux but you can find macOS also listed [here](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
||||
Como ya se ha mencionado Git es multiplataforma, vamos a ver Windows y Linux, pero también puedes encontrar macOS en la lista de [descargas](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
|
||||
|
||||
For [Windows](https://git-scm.com/download/win) we can grab our installers from the official site.
|
||||
Para [Windows](https://git-scm.com/download/win) podemos obtener nuestros instaladores desde el sitio oficial o también puedes usar `winget`, Windows Application Package Manager.
|
||||
|
||||
You could also use `winget` on your Windows machine, think of this as your Windows Application Package Manager.
|
||||
|
||||
Before we install anything let's see what version we have on our Windows Machine. Open a PowerShell window and run `git --version`
|
||||
Antes de instalar nada vamos a ver qué versión tenemos en nuestra máquina Windows. Abre una ventana de PowerShell y ejecuta `git --version`.
|
||||
|
||||

|
||||
|
||||
We can also check our WSL Ubuntu version of Git as well.
|
||||
También podemos comprobar nuestra versión en el [WSL](https://es.wikipedia.org/wiki/Subsistema_de_Windows_para_Linux) Ubuntu.
|
||||
|
||||

|
||||
|
||||
At the time of writing the latest Windows release is `2.35.1` so we have some updating to do there which I will run through. I expect the same for Linux.
|
||||
En el momento de escribir esto la última versión de Windows es `2.35.1` por lo que tenemos que actualizarla. Lo mismo con Linux.
|
||||
|
||||
I went ahead and downloaded the latest installer and ran through the wizard and will document that here. The important thing to note is that git will uninstall previous versions before installing the latest.
|
||||
Descargué el último instalador y ejecuté el asistente. Lo importante a tener en cuenta es que git desinstalará las versiones anteriores antes de instalar la última. Lo que significa que el proceso que se muestra a continuación es también el mismo proceso en su mayor parte como si estuviera instalando por primera vez.
|
||||
|
||||
Meaning that the process shown below is also the same process for the most part as if you were installing from no git.
|
||||
|
||||
It is a very simple installation. Once downloaded double click and get started. Read through the GNU license agreement. But remember this is free and open-source software.
|
||||
Es una instalación muy sencilla. Una vez descargado haga doble clic y comience. Lea el acuerdo de licencia GNU. Pero recuerde que este es un software libre y de código abierto.
|
||||
|
||||

|
||||
|
||||
Now we can choose additional components that we would like to also install but also associate with git. On Windows, I always make sure I install Git Bash as this allows us to run bash scripts on Windows.
|
||||
Ahora podemos elegir componentes adicionales que nos gustaría también instalar para asociar con git. En Windows, siempre me aseguro de instalar Git Bash ya que nos permite ejecutar scripts bash en Windows.
|
||||
|
||||

|
||||
|
||||
We can then choose which SSH Executable we wish to use. IN leave this as the bundled OpenSSH that you might have seen in the Linux section.
|
||||
Podemos entonces elegir qué ejecutable SSH deseamos utilizar.
|
||||
|
||||

|
||||
|
||||
We then have experimental features that we may wish to enable, for me I don't need them so I don't enable them, you can always come back in through the installation and enable these later on.
|
||||
Luego tenemos características experimentales que podemos habilitar, yo no las necesito así que no las habilito, siempre puedes volver a la instalación y habilitarlas más tarde.
|
||||
|
||||

|
||||
|
||||
Installation complete, we can now choose to open Git Bash and or the latest release notes.
|
||||
Instalación completada, ahora podemos elegir abrir Git Bash y o las últimas notas de la versión.
|
||||
|
||||

|
||||
|
||||
The final check is to take a look in our PowerShell window at what version of git we have now.
|
||||
La comprobación final es echar un vistazo en PowerShell la versión actual de git.
|
||||
|
||||

|
||||
|
||||
Super simple stuff and now we are on the latest version. On our Linux machine, we seemed to be a little behind so we can also walk through that update process.
|
||||
Super simple y ahora estamos en la última versión.
|
||||
|
||||
I simply run the `sudo apt-get install git` command.
|
||||
En nuestra máquina Linux el proceso de actualización resulta más directo ejecutando el comando `sudo apt-get install git`.
|
||||
|
||||

|
||||
|
||||
You could also run the following which will add the git repository for software installations.
|
||||
También puedes añadir el repositorio git para las actualizaciones del software.
|
||||
|
||||
```
|
||||
```shell
|
||||
sudo add-apt-repository ppa:git-core/ppa -y
|
||||
sudo apt-get update
|
||||
sudo apt-get install git -y
|
||||
sudo apt-get install git -yinstalaciones
|
||||
git --version
|
||||
```
|
||||
|
||||
### Configuring Git
|
||||
### Configurando Git
|
||||
|
||||
When we first use git we have to define some settings,
|
||||
Cuando usamos git por primera vez tenemos que definir algunas configuraciones,
|
||||
|
||||
- Name
|
||||
- Email
|
||||
- Default Editor
|
||||
- Line Ending
|
||||
- Nombre de usuario
|
||||
- Correo electrónico
|
||||
- Editor por defecto
|
||||
- Fin de línea
|
||||
|
||||
This can be done at three levels
|
||||
Esto se puede hacer en tres niveles
|
||||
|
||||
- System = All users
|
||||
- Global = All repositories of the current user
|
||||
- Local = The current repository
|
||||
- Sistema = Todos los usuarios
|
||||
- Global = Todos los repositorios del usuario actual
|
||||
- Local = El repositorio actual
|
||||
|
||||
Example:
|
||||
`git config --global user.name "Michael Cade"`
|
||||
`git config --global user.email Michael.Cade@90DaysOfDevOPs.com"`
|
||||
Depending on your Operating System will determine the default text editor. In my Ubuntu machine without setting the next command is using nano. The below command will change this to visual studio code.
|
||||
Ejemplo:
|
||||
```shell
|
||||
git config --global user.name "Michael Cade"
|
||||
git config --global user.email "Michael.Cade@90DaysOfDevOPs.com"
|
||||
```
|
||||
Dependiendo del sistema operativo se determinará el editor de texto por defecto. En Ubuntu sin configurar el siguiente comando está utilizando nano. El siguiente comando cambiará esto a visual studio code.
|
||||
|
||||
`git config --global core.editor "code --wait"`
|
||||
```shell
|
||||
git config --global core.editor "code --wait"
|
||||
```
|
||||
|
||||
now if we want to be able to see all git configurations then we can use the following command.
|
||||
Podemos ver todas las configuraciones de git con el siguiente comando.
|
||||
|
||||
`git config --global -e`
|
||||
```shell
|
||||
git config --global -e
|
||||
```
|
||||
|
||||

|
||||
|
||||
On any machine this file will be named `.gitconfig` on my Windows machine you will find this in your user account directory.
|
||||
En cualquier máquina este archivo se llamará `.gitconfig`. En Windows lo encontrarás en el directorio de la cuenta de usuario.
|
||||
|
||||

|
||||
|
||||
### Git Theory
|
||||
### Teoría Git
|
||||
|
||||
I mentioned in the post yesterday that there were other version control types and we can split these down into two different types. One is Client Server and the other is Distributed.
|
||||
Mencioné en el post de ayer que había otros tipos de control de versiones y podemos dividirlos en dos tipos diferentes. Los que son Cliente-Servidor y los que son Distribuidos.
|
||||
|
||||
### Client-Server Version Control
|
||||
### Control de versiones Cliente-Servidor
|
||||
|
||||
Before git was around Client-Server was the defacto method for version control. An example of this would be [Apache Subversion](https://subversion.apache.org/) which is an open source version control system founded in 2000.
|
||||
Antes de que existiera git, el tipo de Cliente-Servidor era el método de facto para el control de versiones. Un ejemplo de esto sería [Apache Subversion](https://subversion.apache.org/) que es un sistema de control de versiones de código abierto fundado en el año 2000.
|
||||
|
||||
In this model of Client-Server version control, the first step the developer downloads the source code and the actual files from the server. This doesn't remove the conflicts but it does remove the complexity of the conflicts and how to resolve them.
|
||||
En este modelo de control de versiones Cliente-Servidor, el primer paso que da el desarrollador es descargar el código fuente y los archivos reales del servidor. Esto no elimina los conflictos, pero sí la complejidad de los conflictos y cómo resolverlos.
|
||||
|
||||

|
||||
|
||||
Now for example let's say we have two developers working on the same files and one wins the race and commits or uploads their file back to the server first with their new changes. When the second developer goes to update they have a conflict.
|
||||
Ahora, por ejemplo, digamos que tenemos dos desarrolladores trabajando en los mismos archivos y uno gana la carrera y confirma o sube su archivo de nuevo al servidor en primer lugar con sus nuevos cambios. Cuando el segundo desarrollador va a actualizar tiene un conflicto.
|
||||
|
||||

|
||||
|
||||
So now the Dev needs to pull down the first devs code change next to their check and then commit once those conflicts have been settled.
|
||||
Así que ahora el desarrollador tiene que tirar hacia abajo el primer cambio de código junto a su cheque y luego confirmar una vez que los conflictos se han resuelto.
|
||||
|
||||

|
||||
|
||||
### Distributed Version Control
|
||||
### Control de versiones distribuido
|
||||
|
||||
Git is not the only distributed version control system. But it is very much the defacto.
|
||||
Git no es el único sistema de control de versiones distribuido. Pero es en gran medida el defacto.
|
||||
|
||||
Some of the major benefits of Git are:
|
||||
Algunos de los principales beneficios de Git son:
|
||||
|
||||
- Fast
|
||||
- Smart
|
||||
- Rápido
|
||||
- Inteligente
|
||||
- Flexible
|
||||
- Safe & Secure
|
||||
- Seguro
|
||||
|
||||
Unlike the Client-Server version control model, each developer downloads the source repository meaning everything. History of commits, all the branches etc.
|
||||
A diferencia del modelo de control de versiones Cliente-Servidor, cada desarrollador descarga el repositorio fuente, es decir, todo. Historial de commits, todas las ramas, etc.
|
||||
|
||||

|
||||
|
||||
## Resources
|
||||
## Recursos
|
||||
|
||||
- [What is Version Control?](https://www.youtube.com/watch?v=Yc8sCSeMhi4)
|
||||
- [Types of Version Control System](https://www.youtube.com/watch?v=kr62e_n6QuQ)
|
||||
@ -140,5 +142,13 @@ Unlike the Client-Server version control model, each developer downloads the sou
|
||||
- [Git for Professionals Tutorial](https://www.youtube.com/watch?v=Uszj_k0DGsg)
|
||||
- [Git and GitHub for Beginners - Crash Course](https://www.youtube.com/watch?v=RGOj5yH7evk&t=8s)
|
||||
- [Complete Git and GitHub Tutorial](https://www.youtube.com/watch?v=apGV9Kg7ics)
|
||||
- [En español] [Comandos Git](https://gitea.vergaracarmona.es/man-linux/comandos-git)
|
||||
- [En español][Apuntes Curso de Git](https://vergaracarmona.es/wp-content/uploads/2022/10/Curso-git_vergaracarmona.es_.pdf) de [Juan Carlos Rubio](https://www.linkedin.com/in/juan-carlos-rubio-pineda/Curso-git_vergaracarmona-es).
|
||||
- [En español] En los [apuntes](https://vergaracarmona.es/apuntes/) del traductor:
|
||||
- ["Instalar git en ubuntu"](https://vergaracarmona.es/instalar-git-en-ubuntu/)
|
||||
- ["Comandos de git"](https://vergaracarmona.es/comandos-de-git/)
|
||||
- ["Estrategias de fusión en git: Ship / Show / Ask"](https://vergaracarmona.es/estrategias-bifurcacion-git-ship-show-ask/)
|
||||
- ["Resolver conflictos en Git. Merge, Squash, Rebase o Pull"](https://vergaracarmona.es/merge-squash-rebase-pull/)
|
||||
- ["Borrar commits de git: reset, rebase y cherry-pick"](https://vergaracarmona.es/reset-rebase-cherry-pick/)
|
||||
|
||||
See you on [Day 37](day37.md)
|
||||
Nos vemos en el [Día 37](day37.md)
|
||||
|
@ -1,154 +1,161 @@
|
||||
## Gitting to know Git
|
||||
## Conociendo a Git
|
||||
|
||||
Apologies for the terrible puns in the title and throughout. I am surely not the first person to turn Git into a dad joke!
|
||||
Pido disculpas por los terribles juegos de palabras del título (Título original: *Gitting to know Git*). Seguro que no soy la primera persona que convierte Git en un chiste de padres.
|
||||
|
||||
In the last two posts we learnt about version control systems, and some of the fundamental workflows of git as a version control system [Day 35](day35.md) Then we got git installed on our system, updated and configured. We also went a little deeper into the theory between the Client-Server version control system and Git which is a distributed version control system [Day 36](day36.md).
|
||||
En los dos últimos posts aprendimos acerca de los sistemas de control de versiones, y algunos de los flujos de trabajo fundamentales de git ([Día 35](day35.md)). Luego conseguimos instalar git en nuestro sistema, actualizarlo y configurarlo. También vimos algo de la teoría entre los tipos de sistema de control de versiones Cliente-Servidor y los distribuidos en el [Día 36](day36.md).
|
||||
|
||||
Now we are going to run through some of the commands and use cases that we will all commonly see with git.
|
||||
Ahora vamos a repasar algunos de los comandos y casos de uso habituales con git.
|
||||
|
||||
### Where to git help with git?
|
||||
### Git ayuda con git
|
||||
|
||||
There are going to be times when you just cannot remember or just don't know the command you need to get things done with git. You are going to need help.
|
||||
Habrá momentos en los que simplemente no recuerdes o no sepas el comando que necesitas para hacer algo con git. Necesitarás ayuda. Google o cualquier motor de búsqueda será probablemente tu primer puerto de escala cuando busques ayuda. (También las IAs)
|
||||
|
||||
Google or any search engine is likely to be your first port of call when searching for help.
|
||||
|
||||
Secondly, the next place is going to be the official git site and the documentation. [git-scm.com/docs](http://git-scm.com/docs) Here you will find not only a solid reference to all the commands available but also lots of different resources.
|
||||
El siguiente lugar, sobretodo a modo de confirmación, va a ser el sitio oficial de git y la documentación: [git-scm.com/docs](http://git-scm.com/docs). Aquí no sólo encontrarás una referencia sólida de todos los comandos disponibles, sino también un montón de recursos diferentes.
|
||||
|
||||

|
||||
|
||||
We can also access this same documentation which is super useful if you are without connectivity from the terminal. If we chose the `git add` command for example we can run `git add --help` and we see below the manual.
|
||||
También podemos acceder a esta misma documentación desde la terminal, lo cual es muy útil si trabajas sin conexión. Si elegimos el comando `git add` por ejemplo podemos ejecutar `git add --help` y veremos el manual concreto del subcomando.
|
||||
|
||||

|
||||
|
||||
We can also in the shell use `git add -h` which is going to give us a summary of the options we have available.
|
||||
También podemos usar en la shell `git add -h` que nos va a dar un resumen de las opciones que tenemos disponibles.
|
||||
|
||||

|
||||
|
||||
### Myths surrounding Git
|
||||
### Mitos en torno a Git
|
||||
|
||||
"Git has no access control" - You can empower a leader to maintain source code.
|
||||
"Git no tiene control de acceso" - Puedes autorizar a quien quieras a mantener el código fuente.
|
||||
|
||||
"Git is too heavy" - Git can provide shallow repositories which means a reduced amount of history if you have large projects.
|
||||
"Git es demasiado pesado" - Git puede proporcionar repositorios poco profundos, lo que significa una cantidad reducida de historial si tienes proyectos grandes.
|
||||
|
||||
### Real shortcomings
|
||||
### Deficiencias reales
|
||||
|
||||
Not ideal for Binary files. Great for source code but not great for executable files or videos for example.
|
||||
No es ideal para archivos binarios. Es ideal para código fuente, pero no para archivos ejecutables o vídeos, por ejemplo.
|
||||
|
||||
Git is not user-friendly, the fact that we have to spend time talking about commands and functions of the tool is probably a key sign of that.
|
||||
Git no es fácil de aprender, el hecho de que tengamos que pasar tiempo hablando de comandos y funciones de la herramienta es probablemente una señal de ello. Sin embargo, en general, git es difícil de aprender pero fácil de usar.
|
||||
|
||||
Overall though, git is hard to learn but easy to use.
|
||||
### El ecosistema git
|
||||
|
||||
### The git ecosystem
|
||||
Quiero cubrir brevemente el ecosistema alrededor de git pero no profundizar en estas áreas, pero creo que es importante señalarlas aquí a un alto nivel.
|
||||
|
||||
I want to briefly cover the ecosystem around git but not deep dive into some of these areas but I think it's important to note these here at a high level.
|
||||
Casi todas las herramientas de desarrollo modernas soportan Git.
|
||||
|
||||
Almost all modern development tools support Git.
|
||||
|
||||
- Developer tools - We have already mentioned visual studio code but you will find git plugins and integrations into sublime text and other text editors and IDEs.
|
||||
- Team tools - Also mentioned around tools like Jenkins from a CI/CD point of view, Slack from a messaging framework and Jira for project management and issue tracking.
|
||||
|
||||
- Cloud Providers - All the large cloud providers support git, Microsoft Azure, Amazon AWS, and Google Cloud Platform.
|
||||
- Git-Based services - Then we have GitHub, GitLab and BitBucket which we will cover in more detail later on. I have heard of these services as the social network for code!
|
||||
- **Herramientas para desarrolladores** - Ya hemos mencionado visual studio code pero encontrarás plugins de git e integraciones en sublime text y otros editores de texto e IDEs.
|
||||
- **Herramientas de equipo** - También se han mencionado herramientas como Jenkins desde un punto de vista de CI/CD, Slack desde un marco de mensajería y Jira para la gestión de proyectos y seguimiento de incidencias.
|
||||
- **Proveedores de nube** - Todos los grandes proveedores de nube soportan git: Microsoft Azure, Amazon AWS y Google Cloud Platform.
|
||||
- **Servicios basados en Git** - Luego tenemos GitHub, GitLab y BitBucket que cubriremos en más detalle más adelante. Estos servicios se conocen como las redes sociales del código.
|
||||
|
||||
### The Git Cheatsheet
|
||||
|
||||
We have not covered most of these commands but having looked at some cheat sheets available online I wanted to document some of the git commands and what their purpose is. We don't need to remember these all, and with more hands-on practice and use you will pick at least the git basics.
|
||||
No hemos cubierto la mayoría de comandos de git, ya que tiene un amplio abanico de posibilidades, pero después de haber mirado algunas hojas de trucos disponibles en línea vamos a documentar algunos de ellos y su propósito. No necesitamos recordarlos todos, ya que a través de la práctica y el uso aprenderás al menos mucho más de git.
|
||||
|
||||
I have taken these from [atlassian](https://www.atlassian.com/git/tutorials/atlassian-git-cheatsheet) but writing them down and reading the description is a good way to get to know what the commands are as well as getting hands-on in everyday tasks.
|
||||
Estos comandos se han sacado de [atlassian](https://www.atlassian.com/git/tutorials/atlassian-git-cheatsheet), escribirlos y leer la descripción es una buena forma de conocer su uso, así que manos a la obra en las tareas diarias:
|
||||
|
||||
### Git Basics
|
||||
- [Conceptos básicos de Git](#conceptos-básicos-de-git)
|
||||
- [Deshacer cambios Git](#deshacer-cambios-git)
|
||||
- [Historial de reescritura de Git](#historial-de-reescritura-de-git)
|
||||
- [Git Branches](#git-branches)
|
||||
- [Repositorios remotos Git](#repositorios-remotos-git)
|
||||
- [Git Diff](#git-diff)
|
||||
- [Git Config](#git-config)
|
||||
- [Git Rebase](#git-rebase)
|
||||
- [Git Pull](#git-pull)
|
||||
- [Git Reset](#git-reset)
|
||||
- [Git Push](#git-push)
|
||||
|
||||
| Command | Example | Description |
|
||||
| ------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git init | `git init <directory>` | Create an empty git repository in the specified directory. |
|
||||
| git clone | `git clone <repo>` | Clone repository located at <repo> onto local machine. |
|
||||
| git config | `git config user.name` | Define author name to be used for all commits in current repository `system`, `global`, `local` flag to set config options. |
|
||||
| git add | `git add <directory>` | Stage all changes in <directory> for the next commit. We can also add <files> and <.> for everything. |
|
||||
| git commit -m | `git commit -m "<message>"` | Commit the staged snapshot, use <message> to detail what is being committed. |
|
||||
| git status | `git status` | List files that are staged, unstaged and untracked. |
|
||||
| git log | `git log` | Display all commit history using the default format. There are additional options with this command. |
|
||||
| git diff | `git diff` | Show unstaged changes between your index and working directory. |
|
||||
### Conceptos básicos de Git
|
||||
|
||||
### Git Undoing Changes
|
||||
| Comando | Ejemplo | Descripción |
|
||||
| ------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------- |
|
||||
| git init | `git init <directory>` | Crea un repositorio git vacío en el directorio especificado. |
|
||||
| git clone | `git clone <repo>` | Clona el repositorio ubicado en <repo> en la máquina local. |
|
||||
| git config | `git config user.name` | Definir opciones que se usará para todos los commits según el entorno `system`, `global` o `local`. |
|
||||
| git add | `git add <directory>` | Prepara los cambios en <directorio> para la próxima confirmación. También podemos añadir <ficheros> y <.> para todo. |
|
||||
| git commit -m | `git commit -m "<message>"` | Confirmar la instantánea preparada, usando <mensaje> para detallar lo que se está confirmando. |
|
||||
| git status | `git status` | Lista los archivos que están organizados, no organizados y sin seguimiento. |
|
||||
| git log | `git log` | Muestra todo el historial de confirmaciones usando el formato por defecto. Hay opciones adicionales con este comando. |
|
||||
| git diff | `git diff` | Muestra los cambios no organizados entre tu índice y el directorio de trabajo. |
|
||||
|
||||
| Command | Example | Description |
|
||||
| ---------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git revert | `git revert <commit>` | Create a new commit that undoes all of the changes made in <commit> then apply it to the current branch. |
|
||||
| git reset | `git reset <file>` | Remove <file> from the staging area, but leave the working directory unchanged. This unstaged a file without overwriting any changes. |
|
||||
| git clean | `git clean -n` | Shows which files would be removed from the working directory. Use `-f` in place of `-n` to execute the clean. |
|
||||
### Deshacer cambios Git
|
||||
|
||||
### Git Rewriting History
|
||||
| Comando | Ejemplo | Descripción |
|
||||
| ---------- | --------------------- | ------------------------------------------------------------------------------------------------------------------ |
|
||||
| git revert | `git revert <commit>` | Crear un nuevo commit que deshaga todos los cambios realizados en <commit> y aplicarlo a la rama actual. |
|
||||
| git reset | `git reset <file>` | Elimina <fichero> del área de preparación dejando el directorio de trabajo sin cambios. |
|
||||
| git clean | `git clean -n` | Muestra qué archivos se eliminarán del directorio de trabajo. Usa `-f` en lugar de `-n` para ejecutar la limpieza. |
|
||||
|
||||
| Command | Example | Description |
|
||||
| ---------- | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git commit | `git commit --amend` | Replace the last commit with the staged changes and the last commit combined. Use with nothing staged to edit the last commit’s message. |
|
||||
| git rebase | `git rebase <base>` | Rebase the current branch onto <base>. <base> can be a commit ID, branch name, a tag, or a relative reference to HEAD. |
|
||||
| git reflog | `git reflog` | Show a log of changes to the local repository’s HEAD. Add --relative-date flag to show date info or --all to show all refs. |
|
||||
### Historial de reescritura de Git
|
||||
|
||||
| Comando | Ejemplo | Descripción |
|
||||
| ---------- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git commit | `git commit --amend` | Reemplazar el último commit con los cambios en staged y el último commit combinados. Editas el mensaje del último commit. |
|
||||
| git rebase | `git rebase <base>` | Rebase la rama actual en <base> que puede ser un commit ID, un nombre de rama, una etiqueta o una referencia relativa a HEAD. |
|
||||
| git reflog | `git reflog` | Muestra registro de cambios en el HEAD del repositorio local. Con --relative-date muestra información de fechas y --all para mostrar todas las referencias. |
|
||||
|
||||
### Git Branches
|
||||
|
||||
| Command | Example | Description |
|
||||
| ------------ | -------------------------- | ------------------------------------------------------------------------------------------------------------- |
|
||||
| git branch | `git branch` | List all of the branches in your repo. Add a <branch> argument to create a new branch with the name <branch>. |
|
||||
| git checkout | `git checkout -b <branch>` | Create and check out a new branch named <branch>. Drop the -b flag to checkout an existing branch. |
|
||||
| git merge | `git merge <branch>` | Merge <branch> into the current branch. |
|
||||
| Comando | Ejemplo | Descripción |
|
||||
| ------------ | -------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
|
||||
| git branch | `git branch` | Lista todas las ramas de tu repositorio. Añade un argumento <branch> para crear una nueva rama con el nombre <branch>. |
|
||||
| git checkout | `git checkout -b <branch>` | Crea y comprueba una nueva rama con el nombre <branch>. Elimina la opción -b para obtener una rama existent |
|
||||
| git merge | `git merge <branch>` | Fusiona <branch> en la rama actual. |
|
||||
|
||||
### Git Remote Repositories
|
||||
### Repositorios remotos Git
|
||||
|
||||
| Command | Example | Description |
|
||||
| -------------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git remote add | `git remote add <name> <url>` | Create a new connection to a remote repo. After adding a remote, you can use <name> as a shortcut for <url> in other commands. |
|
||||
| git fetch | `git fetch <remote> <branch>` | Fetches a specific <branch>, from the repo. Leave off <branch> to fetch all remote refs. |
|
||||
| git pull | `git pull <remote>` | Fetch the specified remote’s copy of current branch and immediately merge it into the local copy. |
|
||||
| git push | `git push <remote> <branch>` | Push the branch to <remote>, along with necessary commits and objects. Creates named branch in the remote repo if it doesn’t exist. |
|
||||
| Comando | Ejemplo | Descripción |
|
||||
| -------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git remote add | `git remote add <name> <url>` | Crea una nueva conexión a un repositorio remoto. Después de añadir un remoto, puedes usar <nombre> como atajo para <url> en otros comandos. |
|
||||
| git fetch | `git fetch <remote> <branch>` | Obtiene un <branch> específico del repositorio. Deja <branch> para obtener todas las referencias remotas. |
|
||||
| git pull | `git pull <remote>` | Obtiene la copia remota especificada de la rama actual e inmediatamente la fusiona con la copia local. |
|
||||
| git push | `git push <remote> <branch>` | Empuja la rama a <remote>, junto con los commits y objetos necesarios. Crea la rama con el nombre en el repositorio remoto si no existe. |
|
||||
|
||||
### Git Diff
|
||||
|
||||
| Command | Example | Description |
|
||||
| ----------------- | ------------------- | ---------------------------------------------------------------------- |
|
||||
| git diff HEAD | `git diff HEAD` | Show the difference between the working directory and the last commit. |
|
||||
| git diff --cached | `git diff --cached` | Show difference between staged changes and last commit |
|
||||
| Comando | Ejemplo | Descripción |
|
||||
| ----------------- | ------------------- | ------------------------------------------------------------------------ |
|
||||
| git diff HEAD | `git diff HEAD` | Muestra la diferencia entre el directorio de trabajo y el último commit. |
|
||||
| git diff --cached | `git diff --cached` | Muestra la diferencia entre los cambios realizados y el último commit. |
|
||||
|
||||
### Git Config
|
||||
|
||||
| Command | Example | Description |
|
||||
| ---------------------------------------------------- | ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git config --global user.name <name> | `git config --global user.name <name>` | Define the author name to be used for all commits by the current user. |
|
||||
| git config --global user.email <email> | `git config --global user.email <email>` | Define author email to be used for all commits by the current user. |
|
||||
| git config --global alias <alias-name> <git-command> | `git config --global alias <alias-name> <git-command>` | Create shortcut for a git command . |
|
||||
| git config --system core.editor <editor> | `git config --system core.editor <editor>` | Set the text editor to be used by commands for all users on the machine. <editor> arg should be the comamnd that launches the desired editor. |
|
||||
| git config --global --edit | `git config --global --edit ` | Open the global configuration file in a text editor for manual editing. |
|
||||
| Comando | Ejemplo | Descripción |
|
||||
| ---------------------------------------------------- | ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git config --global user.name <name> | `git config --global user.name <name>` | Define el nombre de autor que se usará para todos los commits del usuario actual. |
|
||||
| git config --global user.email <email> | `git config --global user.email <email>` | Define el email del autor que se usará para todas las confirmaciones del usuario actual. |
|
||||
| git config --global alias <alias-name> <git-command> | `git config --global alias <alias-name> <git-command>` | Crear un acceso directo para un comando git. |
|
||||
| git config --system core.editor <editor> | `git config --system core.editor <editor>` | Establece el editor de texto que usarán todos los usuarios de la máquina. <editor> arg debe ser el comando que lanza el editor deseado. |
|
||||
| git config --global --edit | `git config --global --edit ` | Abrir el archivo de configuración global en un editor de texto para su edición manual. |
|
||||
|
||||
### Git Rebase
|
||||
|
||||
| Command | Example | Description |
|
||||
| -------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git rebase -i <base> | `git rebase -i <base>` | Interactively rebase current branch onto <base>. Launches editor to enter commands for how each commit will be transferred to the new base. |
|
||||
| Comando | Ejemplo | Descripción |
|
||||
| -------------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git rebase -i <base> | `git rebase -i <base>` | Rebase interactivamente la rama actual en <base>. Inicia el editor para introducir comandos sobre cómo se transferirá cada confirmación a la nueva base. |
|
||||
|
||||
### Git Pull
|
||||
|
||||
| Command | Example | Description |
|
||||
| -------------------------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git pull --rebase <remote> | `git pull --rebase <remote>` | Fetch the remote’s copy of current branch and rebases it into the local copy. Uses git rebase instead of the merge to integrate the branches. |
|
||||
| Comando | Ejemplo | Descripción |
|
||||
| -------------------------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git pull --rebase <remote> | `git pull --rebase <remote>` | Obtiene la copia remota de la rama actual y la vuelve a basar en la copia local. Utiliza git rebase en lugar de merge para integrar las ramas. |
|
||||
|
||||
### Git Reset
|
||||
|
||||
| Command | Example | Description |
|
||||
| ------------------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git reset | `git reset ` | Reset the staging area to match the most recent commit but leave the working directory unchanged. |
|
||||
| git reset --hard | `git reset --hard` | Reset staging area and working directory to match most recent commit and overwrites all changes in the working directory |
|
||||
| git reset <commit> | `git reset <commit>` | Move the current branch tip backwards to <commit>, reset the staging area to match, but leave the working directory alone |
|
||||
| git reset --hard <commit> | `git reset --hard <commit>` | Same as previous, but resets both the staging area & working directory to match. Deletes uncommitted changes, and all commits after <commit>. |
|
||||
| Comando | Ejemplo | Descripción |
|
||||
| ------------------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git reset | `git reset ` | Restablece el área de preparación para que coincida con la confirmación más reciente, pero deja el directorio de trabajo sin cambios. |
|
||||
| git reset --hard | `git reset --hard` | Restablece el área de preparación y el directorio de trabajo para que coincidan con la confirmación más reciente y sobreescribe todos los cambios en el directorio de trabajo. |
|
||||
| git reset <commit> | `git reset <commit>` | Mueve la punta de la rama actual hacia atrás hasta <commit>, resetea el área de preparación para que coincida, pero deja el directorio de trabajo solo |
|
||||
| git reset --hard <commit> | `git reset --hard <commit>` | Igual que el anterior, pero reinicia tanto el área de preparación como el directorio de trabajo para que coincidan. Borra los cambios no comprometidos, y todos los commits posteriores a <commit>. |
|
||||
|
||||
### Git Push
|
||||
|
||||
| Command | Example | Description |
|
||||
| ------------------------- | --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git push <remote> --force | `git push <remote> --force` | Forces the git push even if it results in a non-fast-forward merge. Do not use the --force flag unless you’re sure you know what you’re doing. |
|
||||
| git push <remote> --all | `git push <remote> --all` | Push all of your local branches to the specified remote. |
|
||||
| git push <remote> --tags | `git push <remote> --tags` | Tags aren’t automatically pushed when you push a branch or use the --all flag. The --tags flag sends all of your local tags to the remote repo. |
|
||||
| Comando | Ejemplo | Descripción |
|
||||
| ------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| git push <remote> --force | `git push <remote> --force` | Fuerza el git push incluso si resulta en una fusión no rápida. No uses la opción --force a menos que estés seguro de lo que haces. |
|
||||
| git push <remote> --all | `git push <remote> --all` | Envía todas tus ramas locales a la remota especificada. |
|
||||
| git push <remote> --tags | `git push <remote> --tags` | Las etiquetas no se envían automáticamente cuando envías una rama o usas la opción --all. La opción --tags envía todas tus etiquetas locales al repositorio remoto. |
|
||||
|
||||
## Resources
|
||||
## Recursos
|
||||
|
||||
- [What is Version Control?](https://www.youtube.com/watch?v=Yc8sCSeMhi4)
|
||||
- [Types of Version Control System](https://www.youtube.com/watch?v=kr62e_n6QuQ)
|
||||
@ -157,5 +164,13 @@ I have taken these from [atlassian](https://www.atlassian.com/git/tutorials/atla
|
||||
- [Git and GitHub for Beginners - Crash Course](https://www.youtube.com/watch?v=RGOj5yH7evk&t=8s)
|
||||
- [Complete Git and GitHub Tutorial](https://www.youtube.com/watch?v=apGV9Kg7ics)
|
||||
- [Git cheatsheet](https://www.atlassian.com/git/tutorials/atlassian-git-cheatsheet)
|
||||
- [En español] [Comandos Git](https://gitea.vergaracarmona.es/man-linux/comandos-git)
|
||||
- [En español][Apuntes Curso de Git](https://vergaracarmona.es/wp-content/uploads/2022/10/Curso-git_vergaracarmona.es_.pdf) de [Juan Carlos Rubio](https://www.linkedin.com/in/juan-carlos-rubio-pineda/Curso-git_vergaracarmona-es).
|
||||
- [En español] En los [apuntes](https://vergaracarmona.es/apuntes/) del traductor:
|
||||
- ["Instalar git en ubuntu"](https://vergaracarmona.es/instalar-git-en-ubuntu/)
|
||||
- ["Comandos de git"](https://vergaracarmona.es/comandos-de-git/)
|
||||
- ["Estrategias de fusión en git: Ship / Show / Ask"](https://vergaracarmona.es/estrategias-bifurcacion-git-ship-show-ask/)
|
||||
- ["Resolver conflictos en Git. Merge, Squash, Rebase o Pull"](https://vergaracarmona.es/merge-squash-rebase-pull/)
|
||||
- ["Borrar commits de git: reset, rebase y cherry-pick"](https://vergaracarmona.es/reset-rebase-cherry-pick/)
|
||||
|
||||
See you on [Day 38](day38.md)
|
||||
Nos vemos en el [Día 38](day38.md)
|
||||
|
@ -1,110 +1,110 @@
|
||||
## Staging & Changing
|
||||
## Puesta en marcha (Staging) y cambios de git
|
||||
|
||||
We have already covered some of the basics but putting things into a walkthrough makes it better for me to learn and understand how and why we are doing it this way. Before we get into any git-based services such as GitHub, git has its powers that we can take advantage of on our local workstation.
|
||||
Ya hemos cubierto algunos de los conceptos básicos, pero poner las cosas en un tutorial hace que sea mejor para aprender y entender cómo y por qué lo estamos haciendo de esta manera en concreto. Antes de entrar en cualquier servicio basado en git como GitHub, git tiene superpoderes para aprovechar en local.
|
||||
|
||||
We are going to take the project folder we created at the start of the git session and we are going to walk through some of the simple steps we can do with git. We created a folder on our local machine and we initialised it with the `git init` command
|
||||
Vamos a verlos seleccionando la carpeta del proyecto que creamos al inicio de la sesión de git y veremos algunos de los sencillos y potentes pasos que podemos hacer con git. Creamos una carpeta en nuestra máquina local y la inicializamos con el comando `git init`.
|
||||
|
||||

|
||||
|
||||
We can also see now that we have initialised the folder we have a hidden folder in our directory.
|
||||
También podemos ver que después de inicializar tenemos una carpeta oculta en nuestro directorio: `.git`.
|
||||
|
||||

|
||||
|
||||
This is where the details of the git repository are stored as well as the information regarding our branches and commits.
|
||||
Aquí es donde se almacenan los detalles del repositorio git así como la información relativa a nuestras ramas y commits. ¡Donde habita toda la magía de git!
|
||||
|
||||
### Staging Files
|
||||
### Ficheros Staging
|
||||
|
||||
We then start working on our empty folder and maybe we add some source code on the first days of work. We create our readme.mdfile and we can see that file in the directory, next we check our `git status` and it knows about the new readme.mdfile but we have not committed the file yet.
|
||||
A continuación, empezamos a trabajar en nuestra carpeta vacía. Podemos añadir algo de código fuente de los primeros días de trabajo. Creamos nuestro fichero `readme.md` y comprobamos nuestro `git status`. Veremos el nuevo fichero `readme.md` pero sin confirmar todavía.
|
||||
|
||||

|
||||
|
||||
We can stage our readme.mdfile with the `git add README.md` command then we can see changes to be committed that we did not have before and a green new file.
|
||||
Con el comando `git add README.md` podremos ver en `git status` que el fichero está en verde, esto indica que tenemos los cambios preparados para confirmar.
|
||||
|
||||

|
||||
|
||||
Next up we want to commit this, our first commit or our first snapshot of our project. We can do this by using the `git commit -m "Meaningful message"` command so that we can easily see what has changed for each commit. Also, notice the yellow cross changes now to a green tick. This is something I have within my terminal with the theme I use, something we covered in the Linux section.
|
||||
A continuación vamos confirmar esto, que no quede pendiente, haremos nuestro primer commit o, visto de otra manera, la primera instantánea de nuestro proyecto. Esto lo hacemos con el comando `git commit -m "<Mensaje significativo>"` dejando un mensaje esclarecedor y conciso que describa los cambios que se incluyen a la rama. Además, observe que la cruz amarilla cambia ahora a una marca verde. Esto es algo que tengo dentro de mi terminal con el tema que uso, lo vimos en la sección de Linux.
|
||||
|
||||

|
||||
|
||||
### Committing Changes
|
||||
### Confirmando cambios
|
||||
|
||||
We are going to most likely want to add more files or even change the files we have in our directory. We have already done our first commit above. But now we are going to add more details and more files.
|
||||
O como maldecimos algunos en español "comiteando que es gerundio". Lo más probable es que queramos añadir más archivos o incluso cambiar los archivos que tenemos en nuestro directorio. Ya hemos hecho nuestro primer commit, pero ahora vamos a añadir más y más y más.
|
||||
|
||||
We could repeat our process from before, create or edit our file > `git add .` to add all files to the staging area then `git commit -m "meaningful message"` and this would work just fine. But to be able to offer a meaningful message on commit of what has changed you might not want to write something out like `git commit -m "Well, I changed some code because it did not work and when I fixed that I also added something new to the readme.mdto ensure everyone knew about the user experience and then I made a tea."` I mean this would work as well although probably make it descriptive but the preferred way here is to add this with a text editor.
|
||||
Podríamos repetir nuestro proceso de antes, crear o editar nuestro archivo con `git add .` para añadir todos los archivos a la zona de preparación y luego `git commit -m "mensaje significativo"` y esto funcionaría sin problemas. Pero para ser capaz de ofrecer un mensaje significativo en el commit de lo que ha cambiado puede que no quieras escribir algo como `git commit -m "Bueno, he cambiado algo de código porque no funcionaba y cuando lo arreglé también añadí algo nuevo al readme.mdpara asegurarme de que todo el mundo conocía la experiencia de usuario y luego hice un té."` Quiero decir que esto funcionaría también aunque probablemente lo haría descriptivo pero la forma preferida aquí es añadir esto con un editor de texto.
|
||||
|
||||
If we run `git commit` after running `git add` it will open our default text editor which in my case here is nano. Here are the steps I took to add some changes to the file, ran `git status` to show what is and what is not staged. Then I used `git add` to add the file to the staging area, then ran `git commit` which opened nano.
|
||||
Si ejecutamos `git commit` después de ejecutar `git add` se abrirá nuestro editor de texto por defecto que en mi caso es nano. Estos son los pasos que seguí para añadir algunos cambios al archivo, ejecuté `git status` para mostrar lo que está y lo que no está preparado. Luego usé `git add` para agregar el archivo al área de staging, luego ejecuté `git commit` que abrió nano.
|
||||
|
||||

|
||||
|
||||
When nano opens you can then add your short and long description and then save the file.
|
||||
Cuando se abra nano puedes añadir tu descripción corta y larga y luego guardar el archivo.
|
||||
|
||||

|
||||
|
||||
### Committing Best Practices
|
||||
### Mejores prácticas para el commit
|
||||
|
||||
There is a balance here between when to commit and commit often. We do not want to be waiting to be finished the project before committing, each commit should be meaningful and they also should not be coupled with non-relevant tasks with each other. If you have a bug fix and a typo make sure they are two separate commits as a best practice.
|
||||
Hay un equilibrio entre confirmar empaquetando cambios relacionados y confirmar a menudo. No queremos esperar a terminar un proyecto para nuestro primer commit y cada confirmación debe ser significativa. Tampoco debe estar asociada con tareas no relevantes entre sí. Si tienes una corrección de errores y un error tipográfico la mejor práctica es asegurarse de incluirlos en dos commits distintos. Así puedes abreviar y darle significado al mensaje del commit.
|
||||
|
||||
Make the commit message mean something.
|
||||
En términos de redacción, el equipo o tú mismo deberíais ceñiros a la misma redacción para cada confirmación. Por ejemplo, recomiendan que los mensajes comiencen con un verbo en infinitivo, como "añadir" o "eliminar". Esto ayuda a mantener la consistencia y a que los mensajes sean más fáciles de leer. En muchos proyectos se decide que sean en inglés. También se agradece la brevedad cuando repasas los logs de git 😅
|
||||
|
||||
In terms of wording, the team or yourself should be sticking to the same wording for each commit.
|
||||
### Saltarse la zona de preparación
|
||||
|
||||
### Skipping the Staging Area
|
||||
¿Tenemos que preparar siempre nuestros cambios antes de confirmarlos?
|
||||
|
||||
Do we always have to stage our changes before committing them?
|
||||
La respuesta es sí. Pero no lo veas como un handicap, es la manera de estar 100% seguro de que no vas a errar. Además, la práctica recomendada es evitar utilizar 'git add .' y en su lugar utilizar 'git add <file>' para añadir los cambios del archivo o archivos en concreto para ser más específico y asegurarte de que no estás añadiendo cambios que no quieres. ¿Conoces el dicho "Más vale prevenir que curar"? Pues eso.
|
||||
|
||||
The answer is yes but don't see this as a shortcut, you have to be sure 100% that you are not needing that snapshot to roll back to, it is a risky thing to do.
|
||||
También hay una forma de saltarse la zona de preparación y confirmar directamente con el comando `git commit -a -m "<Mensaje significativo>"`. Es útil cuando tienes un cambio pequeño y no quieres tener que pasar por el proceso de preparación y confirmación. Pero cuidadito, si tienes muchos cambios y no los has preparado, esto podría añadirlos todos a la confirmación.
|
||||
|
||||

|
||||
|
||||
### Removing Files
|
||||
### Eliminación de archivos
|
||||
|
||||
What about removing files from our project, maybe we have another file in our directory that we have committed but now the project no longer needs or using it, as a best practice we should remove it.
|
||||
Qué pasa con la eliminación de archivos de nuestro proyecto, tal vez tenemos otro archivo en nuestro directorio que hemos confirmado, pero ahora el proyecto ya no lo necesita o utiliza, como una mejor práctica debemos eliminarlo.
|
||||
|
||||
Just because we remove the file from the directory, git is still aware of this file and we also need to remove it from the repository. You can see the workflow for this below.
|
||||
Sólo porque eliminamos el archivo del directorio, git todavía es consciente de este archivo y también tenemos que eliminarlo del repositorio. Puedes ver el flujo de trabajo para esto a continuación.
|
||||
|
||||

|
||||
|
||||
That could be a bit of a pain to either remember or have to deal with if you have a large project which has many moving files and folders. We can do this with one command with `git rm oldcode.ps1`
|
||||
Esto podría ser un poco molesto de recordar o tener que lidiar con ello si tienes un proyecto grande que tiene muchos archivos y carpetas en movimiento. Podemos hacer esto con un comando con `git rm oldcode.ps1`.
|
||||
|
||||

|
||||
|
||||
### Renaming or Moving Files
|
||||
### Renombrar o Mover Archivos
|
||||
|
||||
Within our operating system, we can rename and move our files. We will no doubt need to do this from time to time with our projects. Similar to removing though there is a two-step process, we change our files on our OS and then we have to modify and make sure that the staging area or that the files are added correctly. Steps as follows:
|
||||
Dentro de nuestro sistema operativo podemos renombrar y mover nuestros archivos. Sin duda necesitaremos hacer esto de vez en cuando con nuestros proyectos. Similar a eliminar aunque hay un proceso de dos pasos, cambiamos nuestros archivos en nuestro sistema operativo y luego tenemos que modificar y asegurarnos de que la zona de montaje o que los archivos se añaden correctamente. Los pasos son los siguientes:
|
||||
|
||||

|
||||
|
||||
However, like removing files from the operating system and then the git repository we can perform this rename using a git command too.
|
||||
Sin embargo, al igual que eliminamos archivos del sistema operativo y luego del repositorio git podemos realizar este renombrado utilizando también un comando git.
|
||||
|
||||

|
||||
|
||||
### Ignoring Files
|
||||
### Ignorando Archivos
|
||||
|
||||
We may have the requirement to ignore files or folders within our project that we might be using locally or that will be just wasted space if we were to share with the overall project, a good example of this could be logs. I also think using this for secrets that you do not want to be shared out in public or across teams.
|
||||
Podemos tener la necesidad de ignorar los archivos o carpetas dentro de nuestro proyecto que podríamos estar utilizando a nivel local o que sólo sería un desperdicio de espacio si tuviéramos que compartir con el proyecto en general, un buen ejemplo de esto podría ser registros. También creo que el uso de este para los secretos que no quieren ser compartidos en público o entre los equipos.
|
||||
|
||||
We can ignore files by adding folders or files to the `.gitignore` file in our project directory.
|
||||
Podemos ignorar archivos añadiendo carpetas o archivos al archivo `.gitignore` en el directorio de nuestro proyecto.
|
||||
|
||||

|
||||
|
||||
You can then open the `.gitignore` file and see that we have the logs/ directory present. But we could also add additional files and folders here to ignore.
|
||||
Podemos abrir el archivo `.gitignore` y ver que tenemos el directorio logs/ presente. Pero también podríamos añadir aquí archivos y carpetas adicionales para ignorar.
|
||||
|
||||

|
||||
|
||||
We can then see `git status` and then see what has happened.
|
||||
A continuación podemos ver `git status` y ver qué ha pasado.
|
||||
|
||||

|
||||
|
||||
There are also ways in which you might need to go back and ignore files and folders, maybe you did want to share the logs folder but then later realised that you didn't want to. You will have to use `git rm --cached ` to remove files and folders from the staging area if you have a previously tracked folder that you now want to ignore.
|
||||
También hay formas en las que podrías necesitar volver atrás e ignorar archivos y carpetas, quizás querías compartir la carpeta de logs pero luego te diste cuenta de que no querías hacerlo. Tendrás que usar `git rm --cached ` para eliminar archivos y carpetas del área de preparación si tienes una carpeta previamente rastreada que ahora quieres ignorar.
|
||||
|
||||
### Short Status
|
||||
### Estado breve
|
||||
|
||||
We have been using `git status` a lot to understand what we have in our staging area and what we do not, it's a very comprehensive command with lots of detail. Most of the time you will just want to know what has been modified or what is new? We can use `git status -s` for a short status of this detail. I would usually set an alias on my system to just use `git status -s` vs the more detailed command.
|
||||
Hemos estado usando mucho `git status` para entender lo que tenemos en nuestra área de preparación y lo que no, es un comando muy completo con muchos detalles. La mayoría de las veces sólo querrás saber qué ha sido modificado o qué hay de nuevo. Podemos usar `git status -s` para un breve estado de este detalle. Yo normalmente establecería un alias en mi sistema para usar `git status -s` en lugar del comando más detallado.
|
||||
|
||||

|
||||
|
||||
In the post tomorrow we will continue to look through these short examples of these common git commands.
|
||||
En el post de mañana seguiremos viendo estos breves ejemplos de estos comandos comunes de git.
|
||||
|
||||
## Resources
|
||||
## Recursos
|
||||
|
||||
- [What is Version Control?](https://www.youtube.com/watch?v=Yc8sCSeMhi4)
|
||||
- [Types of Version Control System](https://www.youtube.com/watch?v=kr62e_n6QuQ)
|
||||
@ -113,5 +113,14 @@ In the post tomorrow we will continue to look through these short examples of th
|
||||
- [Git and GitHub for Beginners - Crash Course](https://www.youtube.com/watch?v=RGOj5yH7evk&t=8s)
|
||||
- [Complete Git and GitHub Tutorial](https://www.youtube.com/watch?v=apGV9Kg7ics)
|
||||
- [Git cheatsheet](https://www.atlassian.com/git/tutorials/atlassian-git-cheatsheet)
|
||||
- [En español] [Comandos Git](https://gitea.vergaracarmona.es/man-linux/comandos-git)
|
||||
- [En español][Apuntes Curso de Git](https://vergaracarmona.es/wp-content/uploads/2022/10/Curso-git_vergaracarmona.es_.pdf) de [Juan Carlos Rubio](https://www.linkedin.com/in/juan-carlos-rubio-pineda/Curso-git_vergaracarmona-es).
|
||||
- [En español] En los [apuntes](https://vergaracarmona.es/apuntes/) del traductor:
|
||||
- ["Instalar git en ubuntu"](https://vergaracarmona.es/instalar-git-en-ubuntu/)
|
||||
- ["Comandos de git"](https://vergaracarmona.es/comandos-de-git/)
|
||||
- ["Estrategias de fusión en git: Ship / Show / Ask"](https://vergaracarmona.es/estrategias-bifurcacion-git-ship-show-ask/)
|
||||
- ["Resolver conflictos en Git. Merge, Squash, Rebase o Pull"](https://vergaracarmona.es/merge-squash-rebase-pull/)
|
||||
- ["Borrar commits de git: reset, rebase y cherry-pick"](https://vergaracarmona.es/reset-rebase-cherry-pick/)
|
||||
- [Ejemplos README.md para tus proyectos](https://gitea.vergaracarmona.es/manuelver/plantillas-README)
|
||||
|
||||
See you on [Day 39](day39.md)
|
||||
Nos vemos en el [Día 39](day39.md).
|
||||
|
@ -1,194 +1,190 @@
|
||||
## Viewing, unstaging, discarding & restoring
|
||||
## Visualización, desescalado, descarte y restauración
|
||||
|
||||
Continuing from where we finished yesterday around some of the commands that we have with git and how to leverage git with your projects. Remember we have not touched GitHub or any other git-based services yet this is all to help you keep control of your projects locally at the moment, but they will all become useful when we start to integrate into those tools.
|
||||
Vamos a continuar donde lo dejamos ayer en torno a algunos de los comandos que tenemos con git y cómo aprovechar git con sus proyectos. Recuerde que no hemos tocado GitHub o cualquier otro servicio basado en git todavía, estamos viendo como mantener el control de los proyectos a nivel local por el momento, pero todos ellos serán útiles cuando empezamos a integrar esas herramientas.
|
||||
|
||||
### Viewing the Staged and Unstaged Changes
|
||||
### Viendo los Cambios Staged y Unstaged
|
||||
|
||||
It is good practice to make sure you view the staged and unstaged code before committing. We can do this by running the `git diff --staged` command
|
||||
Es una buena práctica asegurarse de ver el código preparado y no preparado antes de confirmar. Podemos hacerlo ejecutando el comando `git diff --staged`
|
||||
|
||||

|
||||
|
||||
This then shows us all the changes we have made and all new files we have added or deleted.
|
||||
Esto nos muestra todos los cambios que hemos hecho y todos los archivos nuevos que hemos añadido o borrado.
|
||||
|
||||
changes in the modified files are indicated with `---` or `+++` you can see below that we just added +add some text below which means they are new lines.
|
||||
Los cambios en los archivos modificados se indican con `---` o `+++` puedes ver abajo que acabamos de añadir +añadir algo de texto debajo lo que significa que son nuevas líneas.
|
||||
|
||||

|
||||
|
||||
We can also run `git diff` to compare our staging area with our working directory. If we make some changes to our newly added file code.txt and add some lines of text.
|
||||
También podemos ejecutar `git diff` para comparar nuestra área de staging con nuestro directorio de trabajo. Si hacemos algunos cambios en nuestro archivo recién añadido code.txt y añadimos algunas líneas de texto.
|
||||
|
||||

|
||||
|
||||
If we then run `git diff` we compare and see the output below.
|
||||
Si luego ejecutamos `git diff` comparamos y vemos la salida de abajo.
|
||||
|
||||

|
||||
|
||||
### Visual Diff Tools
|
||||
### Herramientas visuales Diff
|
||||
|
||||
For me, the above is more confusing so I would much rather use a visual tool,
|
||||
|
||||
To name a few visual diff tools:
|
||||
Para mí, lo anterior es algo confuso, así que prefiero utilizar una herramienta visual. Por nombrar algunas de ellas:
|
||||
|
||||
- KDiff3
|
||||
- P4Merge
|
||||
- WinMerge (Windows Only)
|
||||
- WinMerge (Sólo Windows)
|
||||
- VSCode
|
||||
|
||||
To set this in git we run the following command `git config --global diff.tool vscode`
|
||||
Para configurar esto en git ejecutamos el siguiente comando `git config --global diff.tool vscode`.
|
||||
|
||||
We are going to run the above and we are going to set some parameters when we launch VScode.
|
||||
Vamos a ejecutar lo anterior y vamos a establecer algunos parámetros cuando lancemos VScode.
|
||||
|
||||

|
||||
|
||||
We can also check our configuration with `git config --global -e`
|
||||
También podemos comprobar nuestra configuración con `git config --global -e`.
|
||||
|
||||

|
||||
|
||||
We can then use `git difftool` to now open our diff visual tool.
|
||||
Podemos usar `git difftool` para abrir nuestra herramienta visual diff.
|
||||
|
||||

|
||||
|
||||
Which then opens our VScode editor on the diff page and compares the two, we have only modified one file from nothing to now adding a line of code on the right side.
|
||||
Esto abre nuestro editor VScode en la página diff y compara los dos. Veremos que sólo hemos modificado un archivo añadiendo una línea de código en el lado derecho.
|
||||
|
||||

|
||||
|
||||
I find this method much easier to track changes and this is something similar to what we will see when we look into git-based services such as GitHub.
|
||||
Encuentro este método mucho más fácil para rastrear cambios y es algo similar a lo que veremos cuando busquemos en servicios basados en git como GitHub.
|
||||
|
||||
We can also use `git difftool --staged` to compare stage with committed files.
|
||||
También podemos usar `git difftool --staged` para comparar el stage con los archivos confirmados.
|
||||
|
||||

|
||||
|
||||
Then we can cycle through our changed files before we commit.
|
||||
Entonces podemos ver el ciclo a través de nuestros archivos cambiados antes de confirmar.
|
||||
|
||||

|
||||
|
||||
I am using VScode as my IDE and like most IDEs they have this functionality built in it is very rare you would need to run these commands from the terminal, although helpful if you don't have an IDE installed for some reason.
|
||||
Estoy usando VScode como mi IDE y como la mayoría de los IDEs tienen esta funcionalidad incorporada. Es muy raro que necesites ejecutar estos comandos desde la terminal, aunque es útil si no tienes un IDE instalado por alguna razón.
|
||||
|
||||
### Viewing the History
|
||||
### Viendo el Historial
|
||||
|
||||
We previously touched on `git log` which will provide us with a comprehensive view of all commits we have made in our repository.
|
||||
Anteriormente hemos tocado `git log` que nos proporcionará una visión completa de todos los commits que hemos hecho en nuestro repositorio.
|
||||
|
||||

|
||||
|
||||
Each commit has its hexadecimal string, unique to the repository. Here you can see which branch we are working on and then also the author, date and commit message.
|
||||
Cada commit tiene su cadena hexadecimal, única para el repositorio. Aquí puedes ver en qué rama estamos trabajando y también el autor, la fecha y el mensaje de confirmación.
|
||||
|
||||
We also have `git log --oneline` and this gives us a much smaller version of the hexadecimal string which we can use in other `diff` commands. We also only have the one-line description or commit message.
|
||||
También tenemos `git log --oneline` que nos devuelve una versión mucho más pequeña de la cadena hexadecimal que podemos usar en otros comandos `diff`. También tenemos sólo la descripción de una línea o el mensaje de commit.
|
||||
|
||||

|
||||
|
||||
We can reverse this into a start with the first commit by running `git log --oneline --reverse` and now we see our first commit at the top of our page.
|
||||
Podemos revertir esto en un inicio con el primer commit ejecutando `git log --oneline --reverse` y ahora vemos nuestro primer commit en la parte superior de nuestra página.
|
||||
|
||||

|
||||
|
||||
### Viewing a Commit
|
||||
### Ver un commit
|
||||
|
||||
Being able to look at the commit message is great if you have been conscious about following best practices and you have added a meaningful commit message, however, there is also `git show` command which allows us to inspect and view a commit.
|
||||
|
||||
We can use `git log --oneline --reverse` to get a list of our commits. and then we can take those and run `git show <commit ID>`
|
||||
Ser capaz de mirar el mensaje de confirmación es genial si has sido consciente de seguir las mejores prácticas y has añadido un mensaje de confirmación significativo, sin embargo, también existe el comando `git show` si queremos inspeccionar un commit concreto. Podemos utilizar `git log --oneline --reverse` para obtener una lista de nuestros commits. y luego podemos tomarlos y ejecutar `git show <commit ID>`.
|
||||
|
||||

|
||||
|
||||
The output of that command will look like below with the detail of the commit, author and what changed.
|
||||
La salida de ese comando se verá como abajo con el detalle del commit, autor y lo que cambió.
|
||||
|
||||

|
||||
|
||||
We can also use `git show HEAD~1` where 1 is how many steps back from the current version we want to get back to.
|
||||
También podemos usar `git show HEAD~1` donde 1 es el número de pasos hacia atrás desde la versión actual a la que queremos volver.
|
||||
|
||||
This is great if you want some detail on your files, but if we want to list all the files in a tree for the whole snapshot directory. We can achieve this by using the `git ls-tree HEAD~1` command, again going back one snapshot from the last commit. We can see below we have two blobs, these indicate files whereas the tree would indicate a directory. You can also see commits and tags in this information.
|
||||
Esto es genial si queremos algún detalle de nuestros archivos, pero si queremos listar todos los archivos de un árbol para todo el directorio de la instantánea. Podemos conseguirlo usando el comando `git ls-tree HEAD~1`, de nuevo retrocediendo una instantánea desde el último commit. Podemos ver abajo que tenemos dos blobs, estos indican archivos mientras que el árbol indicaría un directorio. También puedes ver commits y tags en esta información.
|
||||
|
||||

|
||||
|
||||
We can then use the above to drill in and see the contents of our file (blobs) using the `git show` command.
|
||||
Podemos usar lo anterior para ver el contenido de nuestro archivo (blobs) usando el comando `git show`.
|
||||
|
||||

|
||||
|
||||
Then the contents of that specific version of the file will be shown.
|
||||
Entonces se mostrará el contenido de esa versión específica del archivo.
|
||||
|
||||

|
||||
|
||||
### Unstaging Files
|
||||
### Unstaging archivos
|
||||
|
||||
There will be a time when you have maybe used `git add .` but there are files you do not wish to commit to that snapshot just yet. In this example below I have added newfile.txt to my staging area but I am not ready to commit this file so I am going to use the `git restore --staged newfile.txt` to undo the `git add` step.
|
||||
Habrá un momento en el que quizás haya usado `git add .` pero hay archivos que no desea confirmar en esa instantánea todavía. En este ejemplo he añadido newfile.txt a mi área de staging pero no estoy listo para confirmar este archivo así que voy a usar `git restore --staged newfile.txt` para deshacer el paso `git add`.
|
||||
|
||||

|
||||
|
||||
We can also do the same to modified files such as main.js and unstage the commit, see above we have a greem M for modified and then below we are unstaging those changes.
|
||||
También podemos hacer lo mismo con archivos modificados como main.js y deshacer el commit, mira arriba tenemos una M en verde y abajo hemos deshecho esos cambios.
|
||||
|
||||

|
||||
|
||||
I have found this command quite useful during the 90DaysOfDevOps as I sometimes work ahead of the days where I feel I want to make notes for the following day but I don't want to commit and push to the public GitHub repository.
|
||||
He encontrado este comando bastante útil durante los 90DaysOfDevOps ya que a veces trabajo antes de los días en los que siento que quiero hacer anotaciones para el día siguiente pero no quiero hacer commit y push al repositorio público de GitHub.
|
||||
|
||||
### Discarding Local Changes
|
||||
### Descartando Cambios Locales
|
||||
|
||||
Sometimes we might make changes but we are not happy with those changes and we want to throw them away. We are going to use the `git restore` command again and we are going to be able to restore files from our snapshots or previous versions. We can run `git restore .` against our directory and we will restore everything from our snapshot but notice that our untracked file is still present. There is no previous file being tracked called newfile.txt.
|
||||
A veces podemos hacer cambios pero no estamos contentos con esos cambios y queremos desecharlos. Vamos a utilizar el comando `git restore` de nuevo y vamos a poder restaurar archivos de nuestras snapshots o versiones anteriores. Podemos ejecutar `git restore .` contra nuestro directorio y restauraremos todo desde nuestra instantánea, pero observa que nuestro archivo no rastreado sigue presente. No hay ningún archivo anterior siendo rastreado llamado newfile.txt.
|
||||
|
||||

|
||||
|
||||
Now to remove newfile.txt or any untracked files. We can use `git clean` we will get a warning alone.
|
||||
Ahora para eliminar newfile.txt o cualquier archivo no rastreado. Podemos usar `git clean` solo obtendremos una advertencia.
|
||||
|
||||

|
||||
|
||||
Or if we know the consequences then we might want to run `git clean -fd` to force and remove all directories.
|
||||
O si conocemos las consecuencias podemos ejecutar `git clean -fd` para forzar y eliminar todos los directorios.
|
||||
|
||||

|
||||
|
||||
### Restoring a File to an Earlier Version
|
||||
### Restaurar un archivo a una versión anterior
|
||||
|
||||
As we have alluded to throughout a big portion of what Git can help with is being able to restore copies of your files from your snapshots (this is not a backup but it is a very fast restore point) My advice is that you also save copies of your code in other locations using a backup solution for this.
|
||||
Como hemos aludido, lo que Git nos puede ayudar es a restaurar copias de tus archivos desde tus instantáneas (esto no es una copia de seguridad, pero es un punto de restauración muy rápido). Es recomendable que también guardes copias de tu código en otros lugares utilizando una solución de copia de seguridad expresamente para esto.
|
||||
|
||||
As an example let's go and delete our most important file in our directory, notice we are using Unix-based commands to remove this from the directory, not git commands.
|
||||
Como ejemplo vamos a borrar nuestro archivo más importante en nuestro directorio, pero utilizando comandos basados en Unix para eliminar el directorio, no comandos de git.
|
||||
|
||||

|
||||
|
||||
Now we have no readme.mdin our working directory. We could have used `git rm readme.md` and this would then be reflected in our git database. Let's also delete it from here to simulate it being removed completely.
|
||||
Ahora no tenemos readme.md en nuestro directorio de trabajo. Podríamos haber usado `git rm readme.md` y esto se reflejaría en nuestra base de datos de git. Así que lo borramos también así para simular la eliminación por completo.
|
||||
|
||||

|
||||
|
||||
Let's now commit this with a message and prove that we no longer have anything in our working directory or staging area.
|
||||
Ahora confirmemos esto con un mensaje y probemos que ya no tenemos nada en nuestro directorio de trabajo o área de preparación.
|
||||
|
||||

|
||||
|
||||
Mistakes were made and we now need this file back!
|
||||
¡Se cometieron errores y ahora necesitamos recuperar ese archivo! 😱
|
||||
|
||||
We could use the `git undo` command which will undo the last commit, but what if it was a while back? We can use our `git log` command to find our commits and then we find that our file is in the last commit but we don't all of those commits to be undone so we can then use this command `git restore --source=HEAD~1 README.md` to specifically find the file and restore it from our snapshot.
|
||||
Podríamos usar el comando `git undo` que deshará el último commit, pero ¿qué pasa si fue hace tiempo? Podemos usar nuestro comando `git log` para encontrar el commit concreto pero no queremos que todos los commits que haya por el medio se deshagan, así que vamos a especificar el fichero con el comando `git restore --source=HEAD~1 README.md` y restaurarlo desde nuestro snapshot.
|
||||
|
||||
You can see using this process we now have the file back in our working directory.
|
||||
Puedes ver que usando este proceso ahora tenemos el archivo de vuelta en nuestro directorio de trabajo 😅
|
||||
|
||||

|
||||
|
||||
We now have a new untracked file and we can use our commands previously mentioned to track, stage and commit our files and changes.
|
||||
Ahora tenemos un nuevo archivo no rastreado y podemos usar los comandos mencionados anteriormente para rastrear, preparar y comitear nuestros cambios.
|
||||
|
||||
### Rebase vs Merge
|
||||
|
||||
This seems to be the biggest headache when it comes to Git and when to use rebase vs using merge on your git repositories.
|
||||
Este parece ser el mayor dolor de cabeza cuando se trata de Git, cuando usar rebase o merge en tus repositorios git.
|
||||
|
||||
The first thing to know is that both `git rebase` and `git merge` solve the same problem. Both are to integrate changes from one branch into another branch. However, they do this in different ways.
|
||||
Lo primero que hay que saber es que tanto `git rebase` como `git merge` resuelven el mismo problema. Ambos sirven para integrar cambios de una rama en otra rama. Sin embargo, lo hacen de formas diferentes.
|
||||
|
||||
Let's start with a new feature in a new dedicated branch. The Main branch continues with new commits.
|
||||
Empecemos con una nueva característica en una nueva rama dedicada. La rama principal continúa con nuevos commits.
|
||||
|
||||

|
||||
|
||||
The easy option here is to use `git merge feature main` which will merge the main branch into the feature branch.
|
||||
La opción fácil es usar `git merge feature main` que fusionará la rama principal en la rama feature.
|
||||
|
||||

|
||||
|
||||
Merging is easy because it is non-destructive. The existing branches are not changed in any way. However, this also means that the feature branch will have an irrelevant merge commit every time you need to incorporate upstream changes. If the main is very busy or active this will or can pollute the feature branch history.
|
||||
La fusión es fácil porque no es destructiva. Las ramas existentes no se modifican. Sin embargo, esto también significa que la rama principal tendrá un commit de fusión irrelevante cada vez que necesites incorporar cambios de la rama principal. Si la main está muy ocupada o activa esto podría contaminar el historial de la rama feature.
|
||||
|
||||
As an alternate option, we can rebase the feature branch onto the main branch using
|
||||
Como opción alternativa, podemos volver a basar la rama de características en la rama principal utilizando:
|
||||
|
||||
```
|
||||
git checkout feature
|
||||
git rebase main
|
||||
```
|
||||
|
||||
This moves the feature branch (the entire feature branch) effectively incorporating all of the new commits in the main. But, instead of using a merge commit, rebasing re-writes the project history by creating brand new commits for each commit in the original branch.
|
||||
Esto mueve la rama feature (toda la rama feature) incorporando efectivamente todos los nuevos commits en la main. Pero, en lugar de usar un commit merge, rebasing reescribe la historia del proyecto creando nuevos commits para cada commit en la rama original.
|
||||
|
||||

|
||||
|
||||
The biggest benefit of rebasing is a much cleaner project history. It also eliminates unnecessary merge commits. and as you compare the last two images, you can follow arguably a much cleaner linear project history.
|
||||
El mayor beneficio de rebase es un historial del proyecto mucho más limpio. También elimina commits de fusión innecesarios. Si comparas las dos últimas imágenes, puedes seguir una historia del proyecto lineal mucho más limpia.
|
||||
|
||||
Although it's still not a foregone conclusion, choosing the cleaner history also comes with tradeoffs, If you do not follow the [The Golden rule of rebasing](https://www.atlassian.com/git/tutorials/merging-vs-rebasing#the-golden-rule-of-rebasing) re-writing project history can be potentially catastrophic for your collaboration workflow. And, less importantly, rebasing loses the context provided by a merge commit—you can’t see when upstream changes were incorporated into the feature.
|
||||
Aunque todavía no es una conclusión inevitable, la elección del historial más limpio también viene con desventajas, si no sigues [La regla de oro de rebasing](hhttps://www.atlassian.com/git/tutorials/merging-vs-rebasing#the-golden-rule-of-rebasing) y vuelves a escribir el historial del proyecto puede ser potencialmente catastrófico para su flujo de trabajo de colaboración. Y por otro lado, con menos importancia pero también presente, al realizar rebase se pierde el contexto proporcionado por un commit de fusión: no puedes ver cuándo se incorporaron realmente los cambios de la línea ascendente en la feature.
|
||||
|
||||
## Resources
|
||||
## Recursos
|
||||
|
||||
- [What is Version Control?](https://www.youtube.com/watch?v=Yc8sCSeMhi4)
|
||||
- [Types of Version Control System](https://www.youtube.com/watch?v=kr62e_n6QuQ)
|
||||
@ -198,5 +194,13 @@ Although it's still not a foregone conclusion, choosing the cleaner history also
|
||||
- [Complete Git and GitHub Tutorial](https://www.youtube.com/watch?v=apGV9Kg7ics)
|
||||
- [Git cheatsheet](https://www.atlassian.com/git/tutorials/atlassian-git-cheatsheet)
|
||||
- [Exploring the Git command line – A getting started guide](https://veducate.co.uk/exploring-the-git-command-line/)
|
||||
- [En español] [Comandos Git](https://gitea.vergaracarmona.es/man-linux/comandos-git)
|
||||
- [En español][Apuntes Curso de Git](https://vergaracarmona.es/wp-content/uploads/2022/10/Curso-git_vergaracarmona.es_.pdf) de [Juan Carlos Rubio](https://www.linkedin.com/in/juan-carlos-rubio-pineda/Curso-git_vergaracarmona-es).
|
||||
- [En español] En los [apuntes](https://vergaracarmona.es/apuntes/) del traductor:
|
||||
- ["Instalar git en ubuntu"](https://vergaracarmona.es/instalar-git-en-ubuntu/)
|
||||
- ["Comandos de git"](https://vergaracarmona.es/comandos-de-git/)
|
||||
- ["Estrategias de fusión en git: Ship / Show / Ask"](https://vergaracarmona.es/estrategias-bifurcacion-git-ship-show-ask/)
|
||||
- ["Resolver conflictos en Git. Merge, Squash, Rebase o Pull"](https://vergaracarmona.es/merge-squash-rebase-pull/)
|
||||
- ["Borrar commits de git: reset, rebase y cherry-pick"](https://vergaracarmona.es/reset-rebase-cherry-pick/)
|
||||
|
||||
See you on [Day40](day40.md)
|
||||
Nos vemos en el [Día 40](day40.md)
|
||||
|
@ -1,191 +1,195 @@
|
||||
## Social Network for code
|
||||
## Red social para el código
|
||||
|
||||
Exploring GitHub | GitLab | BitBucket
|
||||
Explorando GitHub | GitLab | BitBucket 🚀
|
||||
|
||||
Today I want to cover some of the git-based services that we have likely all heard of and expect we also use daily.
|
||||
Hoy veremos algunos de los servicios basados en git de los que probablemente hemos oído hablar. Utilizaremos algunos de nuestros conocimientos adquiridos para mover copias de nuestros datos a cada uno de los principales servicios.
|
||||
|
||||
We will then use some of our prior session knowledge to move copies of our data to each of the main services.
|
||||
|
||||
I called this section "Social Network for Code" let me explain why?
|
||||
He llamado a esta sección "Red Social para el Código", ya verás por qué...
|
||||
|
||||
### GitHub
|
||||
|
||||
Most common at least for me is GitHub, GitHub is a web-based hosting service for git. It is most commonly used by software developers to store their code. Source Code Management with the git version control features as well as a lot of additional features. It allows for teams or open contributors to easily communicate and provides a social aspect to coding. (hence the social networking title) Since 2018 GitHub is part of Microsoft.
|
||||
El más común es GitHub, un servicio de alojamiento basado en web para git. Es muy utilizado por los desarrolladores de software para almacenar código. Tienes la gestión del código fuente centralizada en un repositorio remoto y distribuida gracias a las características de control de versiones git, así como un montón de características adicionales. Permite a los equipos y colaboradores comunicarse fácilmente y proporciona un aspecto social a la codificación. Desde 2018 GitHub forma parte de Microsoft (A golpe de talonario).
|
||||
|
||||
GitHub has been around for quite some time and was founded in 2007/2008. With Over 40 million users on the platform today.
|
||||
GitHub fue fundada en 2007/2008. Con Más de 40 millones de usuarios en la plataforma a día de hoy.
|
||||
|
||||
GitHub Main Features
|
||||
Características principales de GitHub
|
||||
|
||||
- Code Repository
|
||||
- Pull Requests
|
||||
- Project Management toolset - Issues
|
||||
- CI / CD Pipeline - GitHub Actions
|
||||
- Repositorio de código
|
||||
- Solicitudes de Pull
|
||||
- Herramientas de gestión de proyectos - Issues
|
||||
- Canalización CI / CD - Acciones GitHub
|
||||
|
||||
In terms of pricing, GitHub has different levels of pricing for its users. More can be found on [Pricing](https://github.com/pricing)
|
||||
En términos de precios, GitHub tiene diferentes niveles de precios para sus usuarios. Puedes encontrar más información en [Pricing](https://github.com/pricing)
|
||||
|
||||
For this, we will cover the free tier.
|
||||
Aquí veremos tan solo el nivel gratuito.
|
||||
|
||||
I am going to be using my already created GitHub account during this walkthrough, if you do not have an account then on the opening GitHub page there is a sign-up option and some easy steps to get set up.
|
||||
Voy a utilizar mi cuenta de GitHub ya creada durante este tutorial, si no tienes una cuenta, en la página de apertura de GitHub hay una opción de registro y algunos pasos sencillos para configurarla.
|
||||
|
||||
### GitHub opening page
|
||||
### Página de inicio de GitHub
|
||||
|
||||
When you first log in to your GitHub account you get a page containing a lot of widgets giving you options of where and what you would like to see or do. First up we have the "All Activity" this is going to give you a look into what is happening with your repositories or activity in general associated with your organisation or account.
|
||||
La primera vez que accedes a tu cuenta de GitHub aparece una página que contiene un montón de widgets que te dan opciones de dónde y qué te gustaría ver o hacer. En primer lugar tenemos "Toda la actividad", que te dará una visión de lo que está sucediendo con tus repositorios o actividad en general asociada a tu organización o cuenta.
|
||||
|
||||

|
||||
|
||||
Next, we have our Code Repositories, either our own or repositories that we have interacted with recently. We can also quickly create new repositories or search repositories.
|
||||
A continuación, tenemos nuestros repositorios de código, ya sean propios o repositorios con los que hemos interactuado recientemente. También podemos crear rápidamente nuevos repositorios o buscar repositorios.
|
||||
|
||||

|
||||
|
||||
We then have our recent activity, these for me are issues and pull requests that I have created or contributed to recently.
|
||||
Luego tenemos nuestra actividad reciente, que para mí son temas y pull requests que he creado o contribuido recientemente.
|
||||
|
||||

|
||||
|
||||
Over on the right side of the page, we have some referrals for repositories that we might be interested in, most likely based on your recent activity or own projects.
|
||||
En la parte derecha tenemos algunas referencias de repositorios en los que podríamos estar interesados, probablemente basados en tu actividad reciente o en tus propios proyectos.
|
||||
|
||||

|
||||
|
||||
To be honest I am very rarely on my home page that we just saw and described, although I now see that the feed could be really useful to help interact with the community a little better on certain projects.
|
||||
Para ser honesto no suelo entrar en mi propia página de inicio, veo que el feed podría ser realmente útil para ayudar a interactuar mejor con la comunidad en ciertos proyectos.
|
||||
|
||||
Next up if we want to head into our GitHub Profile we can navigate to the top right corner and on your image, there is a drop-down which allows you to navigate through your account. From here to access your Profile select "Your Profile"
|
||||
A continuación, si queremos entrar en nuestro perfil de GitHub podemos navegar a la esquina superior derecha y en tu imagen, hay un desplegable que te permite navegar a través de tu cuenta. Desde aquí para acceder a tu Perfil selecciona "Tu Perfil"
|
||||
|
||||

|
||||
|
||||
Next, your profile page will appear, by default, unless you change your configuration you are not going to see what I have, I have added some functionality that shows my recent blog posts over on [vZilla](https://vzilla.co.uk) and then also my latest videos on my [YouTube](https://m.youtube.com/c/MichaelCade1) Channel.
|
||||
A continuación, aparecerá tu página de perfil, por defecto, a menos que cambies tu configuración no vas a ver lo que yo tengo, he añadido alguna funcionalidad que muestra mis últimas entradas de blog en [vZilla](https://vzilla.co.uk) y también mis últimos vídeos en mi canal de [YouTube](https://m.youtube.com/c/MichaelCade1) Channel.
|
||||
|
||||
You are not going to be spending much time looking at your profile, but this is a good profile page to share around your network so they can see the cool projects you are working on.
|
||||
No vas a pasar mucho tiempo mirando tu perfil, pero esta es una buena página de perfil para compartir en tu red para que puedan ver los proyectos interesantes en los que estás trabajando.
|
||||
|
||||
Si quieres ver algunos ejemplos de páginas de inicio:
|
||||
- Página del autor [Michael Cade](https://github.com/MichaelCade/MichaelCade)
|
||||
- Página del traductor [manuelver](https://github.com/manuelver/manuelver)
|
||||
|
||||

|
||||
|
||||
We can then drill down into the building block of GitHub, the repositories. Here you are going to see your repositories and if you have private repositories they are also going to be shown in this long list.
|
||||
A continuación, podemos profundizar en el bloque de construcción de GitHub, los repositorios. Aquí vas a ver tus repositorios y si tienes repositorios privados también se mostrarán en esta larga lista.
|
||||
|
||||

|
||||
|
||||
As the repository is so important to GitHub let me choose a pretty busy one of late and run through some of the core functionality that we can use here on top of everything I am already using when it comes to editing our "code" in git on my local system.
|
||||
El repositorio es muy importante en GitHub, así que elijo uno bastante movido últimamente para ejecutar algunas de las funciones básicas que podemos utilizar.
|
||||
|
||||
First of all, from the previous window, I have selected the 90DaysOfDevOps repository and we get to see this view. You can see from this view we have a lot of information, we have our main code structure in the middle showing our files and folders that are stored in our repository. We have our readme. mdbeing displayed down at the bottom. Over to the right of the page, we have an about section where the repository has a description and purpose. Then we have a lot of information underneath this showing how many people have starred in the project, forked, and watched.
|
||||
Desde la ventana anterior, he seleccionado el repositorio 90DaysOfDevOps. Se puede ver en esta vista que tenemos una gran cantidad de información, tenemos nuestra estructura de código principal en el centro mostrando nuestros archivos y carpetas que se almacenan en nuestro repositorio. Tenemos nuestro readme.md que se muestra en la parte inferior y le da más importancia al fichero, ya que es nuestra presentación del proyecto. A la derecha de la página, tenemos una sección con una descripción y propósito del proyecto. Luego tenemos un montón de información debajo de esto que muestra cuántas personas han destacado en el proyecto con una star, cuántas lo han visto y cuántas lo han bifurcado.
|
||||
|
||||

|
||||
|
||||
If we scroll down a little further you will also see that we have Released, these are from the golang part of the challenge. We do not have any packages in our project, we have our contributors listed here. (Thank you community for assisting in my spelling and fact checking) We then have languages used again these are from different sections in the challenge.
|
||||
Si nos desplazamos un poco más abajo también veremos que tenemos Releases, estos son de la parte golang del desafío. No tenemos ningún paquete en nuestro proyecto en este momento, y también vemos a nuestros colaboradores listados. (Gracias comunidad por ayudar en mi ortografía y otras correcciones) Luego tenemos lenguajes utilizados.
|
||||
|
||||

|
||||
|
||||
A the top of the page you are going to see a list of tabs. These may vary and these can be modified to only show the ones you require. You will see here that I am not using all of these and I should remove them to make sure my whole repository is tidy.
|
||||
En la parte superior de la página verás una lista de pestañas. Éstas pueden variar y pueden modificarse para mostrar sólo las que necesites. Aquí verás que no estoy usando todas y que debería quitarlas para asegurarme de que todo mi repositorio está ordenado y limpio.
|
||||
|
||||
First up we had the code tab which we just discussed but these tabs are always available when navigating through a repository which is super useful so we can jump between sections quickly and easily. Next, we have the issues tab.
|
||||
En primer lugar tenemos la pestaña de código, de la que acabamos de hablar, pero estas pestañas están siempre disponibles cuando se navega a través de un repositorio, lo que es muy útil para que podamos saltar entre las secciones de forma rápida y sencilla. A continuación, tenemos la pestaña de problemas.
|
||||
|
||||
Issues let you track your work on GitHub, where development happens. In this specific repository you can see I have some issues focused on adding diagrams or typos but also we have an issue stating a need or requirement for a Chinese version of the repository.
|
||||
Las incidencias te permiten hacer un seguimiento de tu trabajo en GitHub, donde tiene lugar el desarrollo. En este repositorio específico se puede ver que tengo algunas cuestiones centradas en la adición de diagramas o errores tipográficos, pero también tenemos una cuestión que indica una necesidad o requisito para una versión china del repositorio.
|
||||
|
||||
If this was a code repository then this is a great place to raise concerns or issues with the maintainers, but remember to be mindful and detailed about what you are reporting, and give as much detail as possible.
|
||||
Si esto fuera un repositorio de código, entonces este es un gran lugar para plantear inquietudes o problemas con los mantenedores, pero recuerde que debe ser consciente y detallado acerca de lo que está informando, y dar tantos detalles como sea posible.
|
||||
|
||||

|
||||
|
||||
The next tab is Pull Requests, Pull requests let you tell others about changes you've pushed to a branch in a repository. This is where someone may have forked your repository, made changes such as bug fixes or feature enhancements or just typos in a lot of the cases in this repository.
|
||||
La siguiente pestaña es Pull Requests. Permite informar a otros sobre los cambios que ha empujado a una rama en un repositorio. Aquí es donde alguien puede haber bifurcado el repositorio en otra rama, sea del mismo proyecto o de un fork, ha hecho cambios como correcciones de errores o mejoras de características o simplemente errores tipográficos, y luego ha solicitado que se fusionen esos cambios en la rama principal del proyecto.
|
||||
|
||||
We will cover forking later on.
|
||||
Cubriremos el forking con más detalle más adelante.
|
||||
|
||||

|
||||
|
||||
I believe the next tab is quite new? But I thought for a project like #90DaysOfDevOps this could help guide the content journey but also help the community as they walk through their learning journey. I have created some discussion groups for each section of the challenge so people can jump in and discuss.
|
||||
La siguiente pestaña es bastante nueva, pero se ha creado para #90DaysOfDevOps porque no solo puede ayudar a guiar en el viaje por el contenido, sino que también ayuda a la comunidad a medida que caminan a través de su aprendizaje. Dentro hay grupos de discusión para cada sección del desafío para que quien quiera pueda entrar y comentar, a modo de foro.
|
||||
|
||||

|
||||
|
||||
The Actions tab is going to enable you to build, test and deploy code and a lot more right from within GitHub. GitHub Actions will be something we cover in the CI/CD section of the challenge but this is where we can set some configuration here to automate steps for us.
|
||||
La pestaña de Actions te permitirá construir, probar, desplegar código y mucho más. GitHub Actions lo veremos en la sección de CI/CD del desafío. Como info previa, es aquí donde podemos establecer automatizaciones de tareas repetitivas para que se hagan por si solas con un disparador.
|
||||
|
||||
On my main GitHub Profile, I am using GitHub Actions to fetch the latest blog posts and YouTube videos to keep things up to date on that home screen.
|
||||
Por ejemplo, en mi perfil principal de GitHub utilizo las Actions para obtener las últimas entradas del blog y vídeos de YouTube y mantener al día mi página de perfil Github.
|
||||
|
||||

|
||||
|
||||
I mentioned above how GitHub is not just a source code repository but is also a project management tool, The Project tab enables us to build out project tables kanban type boards so that we can link issues and PRs to better collaborate on the project and have visibility of those tasks.
|
||||
Ya he mencionado que GitHub no es sólo un repositorio de código fuente, sino también una herramienta de gestión de proyectos. La pestaña Projects nos permite crear tablas de proyecto tipo kanban para que podamos vincular las incidencias y PRs para colaborar mejor en el proyecto y tener visibilidad/transparencia de las tareas.
|
||||
|
||||

|
||||
|
||||
I know that issues to me seem like a good place to log feature requests and they are but the wiki page allows for a comprehensive roadmap for the project to be outlined with the current status and in general better document your project is it troubleshooting or how-to type content.
|
||||
La página wiki permite una hoja de ruta completa para el proyecto que se describe con el estado actual y, en general, documentar mejor el proyecto.
|
||||
|
||||

|
||||
|
||||
Not so applicable to this project but the Security tab is there to make sure that contributors know how to deal with certain tasks, we can define a policy here but also code scanning add-ons to make sure your code for example does not contain secret environment variables.
|
||||
No es tan aplicable a este proyecto, pero la pestaña de Security está ahí para asegurarse de que los contribuyentes saben cómo hacer frente a ciertas tareas, podemos definir una política aquí, pero también complementos de escaneo de código para asegurarse de que su código, por ejemplo, no contiene variables de entorno con contraseñas.
|
||||
|
||||

|
||||
|
||||
For me the insights tab is great, it provides so much information about the repository from how much activity has been going on down to commits and issues, but it also reports on traffic to the repository. You can see a list on the left side that allows you to go into great detail about metrics on the repository.
|
||||
Para mí la pestaña de Insights es genial ya que proporciona mucha información sobre el repositorio. Desde cuantificar la actividad que ha habido hasta los commits e issues, pasando también por informes sobre el tráfico del repositorio. Puedes ver una lista en el lado izquierdo que te permite entrar en gran detalle sobre las métricas del repositorio.
|
||||
|
||||

|
||||
|
||||
Finally, we have the Settings tab, this is where we can get into the details of how we run our repository, I am currently the only maintainer of the repository but we could share this responsibility here. We can define integrations and other such tasks here.
|
||||
Por último, tenemos la pestaña Configuración donde podemos entrar en los detalles de cómo personalizar nuestro repositorio. Actualmente soy el único mantenedor del repositorio pero podríamos compartir esta responsabilidad aquí. Podemos definir integraciones, políticas de ramas y otras tareas.
|
||||
|
||||

|
||||
|
||||
This was a super quick overview of GitHub, I think there are some other areas that I might have mentioned that need explaining in a little more detail. As mentioned GitHub houses millions of repositories mostly these are holding source code and these can be public or privately accessible.
|
||||
Como se mencionó GitHub alberga millones de repositorios, en su mayoría son código fuente y estos pueden ser de acceso público o privado.
|
||||
|
||||
Hemos echado un vistazo súper rápido de GitHub, creo que se podría detallar mucho más, pero por ahora no somos comerciales de la herramienta, así que vamos a la parte técnica.
|
||||
|
||||
### Forking
|
||||
|
||||
I am going to get more into Open-Source in the session tomorrow but a big part of any code repository is the ability to collaborate with the community. Let's think of the scenario I want a copy of a repository because I want to make some changes to it, maybe I want to fix a bug or maybe I want to change something to use it for a use case that I have that was maybe not the intended use case for the original maintainer of the code. This is what we would call forking a repository. A fork is a copy of a repository. Forking a repository allows you to freely experiment with changes without affecting the original project.
|
||||
Voy a entrar más en Open-Source en la sesión de mañana, pero una gran parte de cualquier repositorio de código es la capacidad de colaborar con la comunidad. Pensemos en el escenario que quiero una copia de un repositorio porque quiero hacer algunos cambios en él, tal vez quiero corregir un error o tal vez quiero cambiar algo para utilizarlo para un caso de uso que tengo que tal vez no era el caso de uso previsto para el mantenedor original del código. Esto es lo que llamaríamos bifurcar un repositorio. Un fork es una copia de un repositorio. La bifurcación de un repositorio permite experimentar libremente con los cambios sin afectar al proyecto original.
|
||||
|
||||
Let me head back to the opening page after login and see one of those suggested repositories.
|
||||
Permíteme volver a la página de inicio después de iniciar sesión y ver uno de esos repositorios sugeridos.
|
||||
|
||||

|
||||
|
||||
If we click on that repository we are going to get the same look as we have just walked through on the 90DaysOfDevOps repository.
|
||||
Si hacemos click en ese repositorio vamos a obtener el mismo aspecto que acabamos de ver en el repositorio 90DaysOfDevOps.
|
||||
|
||||

|
||||
|
||||
If we notice below we have 3 options, we have watch, fork and star.
|
||||
Si nos fijamos a continuación tenemos 3 opciones:
|
||||
|
||||
- Watch - Updates when things happen to the repository.
|
||||
- Fork - a copy of a repository.
|
||||
- Star - "I think your project is cool"
|
||||
- Watch - Se actualiza con los visitante al repositorio.
|
||||
- Fork - Las copias del repositorio.
|
||||
- Star - "Creo que tu proyecto es genial".
|
||||
|
||||

|
||||
|
||||
Given our scenario of wanting a copy of this repository to work on we are going to hit the fork option. If you are a member of multiple organisations then you will have to choose where the fork will take place, I am going to choose my profile.
|
||||
Vamos a darle a la opción fork para hacer una copia en la que trabajar. Si eres miembro de varias organizaciones entonces tendrás que elegir donde se realizará el fork, yo voy a elegir mi perfil.
|
||||
|
||||

|
||||
|
||||
Now we have our copy of the repository that we can freely work on and change as we see fit. This would be the start of the pull request process that we mentioned briefly before but we will cover it in more detail tomorrow.
|
||||
Ahora ya tenemos nuestra copia del repositorio sobre la que podemos trabajar libremente y modificarla a nuestro antojo. Este sería el comienzo del proceso de pull request que mencionamos brevemente antes pero que cubriremos con más detalle mañana.
|
||||
|
||||

|
||||
|
||||
Ok, I hear you say, but how do I make changes to this repository and code if it's on a website, well you can go through and edit on the website but it's not going to be the same as using your favourite IDE on your local system with your favourite colour theme. For us to get a copy of this repository on our local machine we will perform a clone of the repository. This will allow us to work on things locally and then push our changes back into our forked copy of the repository.
|
||||
Ok, te oigo decir, pero ¿cómo puedo hacer cambios en este repositorio y el código si está en un sitio web? Bueno, puedes editarlo directamente en el página Github, pero no va a ser lo mismo que usar tu IDE favorito en local. Para obtener una copia de este repositorio en local vamos a realizar un clon del repositorio. Esto nos permitirá trabajar localmente y luego empujar/pushear nuestros cambios de nuevo en nuestra copia bifurcada en el repositorio remoto.
|
||||
|
||||
We have several options when it comes to getting a copy of this code as you can see below.
|
||||
Tenemos varias opciones cuando se trata de obtener una copia de este código como se puede ver a continuación.
|
||||
|
||||
There is a local version available of GitHub Desktop which gives you a visual desktop application to track changes and push and pull changes between local and GitHub.
|
||||
Hay una versión local disponible de GitHub Desktop que le da una aplicación de escritorio visual para realizar un seguimiento de los cambios y empujar/pushear y tirar/pullear los cambios entre el local y GitHub.
|
||||
|
||||
For this little demo, I am going to use the HTTPS URL we see on there.
|
||||
Para esta pequeña demostración, voy a utilizar la URL HTTPS.
|
||||
|
||||

|
||||
|
||||
Now on our local machine, I am going to navigate to a directory I am happy to download this repository to and then run `git clone url`
|
||||
Ahora, en nuestra máquina local, voy a navegar al directorio donde quiero descargar el repositorio y luego ejecutar `git clone url`.
|
||||
|
||||

|
||||
|
||||
Now we could take it to VScode to make some changes to this.
|
||||
Podemos llevarlo a VScode para hacer algunos cambios.
|
||||
|
||||

|
||||
|
||||
Let's now make some changes, I want to make a change to all those links and replace that with something else.
|
||||
Vamos a hacer algunos cambios, quiero hacer un cambio en todos esos enlaces y sustituirlos por otra cosa.
|
||||
|
||||

|
||||
|
||||
Now if we check back on GitHub and we find our readme.mdin that repository, you should be able to see a few changes that I made to the file.
|
||||
Si nos fijamos de nuevo en GitHub y encontramos nuestro readme.md, deberías ser capaz de ver algunos cambios que he hecho en el archivo.
|
||||
|
||||

|
||||
|
||||
At this stage, this might be complete and we might be happy with our change as we are the only people going to use our new change but maybe it was a bug change and if that is the case then we will want to contribute via a Pull Request to notify the original repository maintainers of our change and see if they accept our changes.
|
||||
En esta etapa, esto podría estar completo y podríamos estar contentos con nuestro cambio, ya que somos las únicas personas que van a utilizar nuestro nuevo cambio, pero tal vez fue un cambio de error y si ese es el caso, entonces vamos a querer contribuir a través de un Pull Request para notificar a los mantenedores del repositorio original de nuestro cambio y ver si aceptan nuestros cambios.
|
||||
|
||||
We can do this by using the contribute button highlighted below. I will cover more on this tomorrow when we look into Open-Source workflows.
|
||||
Podemos hacer esto utilizando el botón de contribución que se muestra a continuación. Mañana con los flujos de trabajo Open-Source veremos más sobre esto.
|
||||
|
||||

|
||||
|
||||
I have spent a long time looking through GitHub and I hear some of you cry but what about other options!
|
||||
Me han dicho muchos: ¿qué pasa con las otras opciones de repositorios remotos?
|
||||
|
||||
Well, there are and I am going to find some resources that cover the basics for some of those as well. You are going to come across GitLab and BitBucket amongst others in your travels and whilst they are git-based services they have their differences.
|
||||
Bueno, voy a dejar algunos recursos que cubren los conceptos básicos para el resto de opciones. En tus viajes te encontrarás con GitLab y BitBucket, entre otros, y aunque son servicios basados en Git, tienen sus diferencias.
|
||||
|
||||
You will also come across hosted options. Most commonly here I have seen GitLab as a hosted version vs GitHub Enterprise (Don't believe there is a free hosted GitHub?)
|
||||
También encontrarás opciones alojadas, la más común es GitLab frente a GitHub Enterprise. El traductor recomienda la opcíon de código libre gitea.io.
|
||||
|
||||
## Resources
|
||||
## Recursos
|
||||
|
||||
- [Learn GitLab in 3 Hours | GitLab Complete Tutorial For Beginners](https://www.youtube.com/watch?v=8aV5AxJrHDg)
|
||||
- [BitBucket Tutorials Playlist](https://www.youtube.com/watch?v=OMLh-5O6Ub8&list=PLaD4FvsFdarSyyGl3ooAm-ZyAllgw_AM5)
|
||||
@ -196,5 +200,14 @@ You will also come across hosted options. Most commonly here I have seen GitLab
|
||||
- [Git and GitHub for Beginners - Crash Course](https://www.youtube.com/watch?v=RGOj5yH7evk&t=8s)
|
||||
- [Complete Git and GitHub Tutorial](https://www.youtube.com/watch?v=apGV9Kg7ics)
|
||||
- [Git cheatsheet](https://www.atlassian.com/git/tutorials/atlassian-git-cheatsheet)
|
||||
- [En español] [Comandos Git](https://gitea.vergaracarmona.es/man-linux/comandos-git)
|
||||
- [En español][Apuntes Curso de Git](https://vergaracarmona.es/wp-content/uploads/2022/10/Curso-git_vergaracarmona.es_.pdf) de [Juan Carlos Rubio](https://www.linkedin.com/in/juan-carlos-rubio-pineda/Curso-git_vergaracarmona-es).
|
||||
- [En español] En los [apuntes](https://vergaracarmona.es/apuntes/) del traductor:
|
||||
- ["Instalar git en ubuntu"](https://vergaracarmona.es/instalar-git-en-ubuntu/)
|
||||
- ["Comandos de git"](https://vergaracarmona.es/comandos-de-git/)
|
||||
- ["Estrategias de fusión en git: Ship / Show / Ask"](https://vergaracarmona.es/estrategias-bifurcacion-git-ship-show-ask/)
|
||||
- ["Resolver conflictos en Git. Merge, Squash, Rebase o Pull"](https://vergaracarmona.es/merge-squash-rebase-pull/)
|
||||
- ["Borrar commits de git: reset, rebase y cherry-pick"](https://vergaracarmona.es/reset-rebase-cherry-pick/)
|
||||
- [GitHub Profile README Generator](https://github.com/rahuldkjain/github-profile-readme-generator)
|
||||
|
||||
See you on [Day 41](day41.md)
|
||||
Nos vemos en el [Día 41](day41.md)
|
||||
|
@ -1,118 +1,106 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - The Open Source Workflow - Day 41'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - The Open Source Workflow
|
||||
tags: 'DevOps, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048806
|
||||
---
|
||||
## El flujo de trabajo del Open Source
|
||||
|
||||
## The Open Source Workflow
|
||||
Esperemos que a través de las últimas 7 secciones de Git tengamos una mejor comprensión de lo que es git. También en GitHub cómo un servicio online que se integra con git para proporcionar un repositorio de código fuente, además de una forma en que la comunidad en general puede colaborar en el código y los proyectos abiertos.
|
||||
|
||||
Hopefully, through the last 7 sections of Git, we have a better understanding of what git is and then how a git-based service such as GitHub integrates with git to provide a source code repository but also a way in which the wider community can collaborate on code and projects together.
|
||||
Cuando pasamos a través de los fundamentos de GitHub fuimos a través del proceso de bifurcación de un proyecto al azar y hacer un cambio en nuestro repositorio local. Aquí queremos ir un paso más allá y contribuir a un proyecto de código abierto.
|
||||
|
||||
When we went through the GitHub fundamentals we went through the process of forking a random project and making a change to our local repository. Here we want to go one step further and contribute to an open-source project. Remember that contributing doesn't need to be bug fixes or coding features but it could also be documentation. Every little helps and it also allows you to get hands-on with some of the git functionality we have covered.
|
||||
Recuerda que contribuir no tiene por qué ser corregir errores o codificar características, sino que también puede ser documentación, traducción, propuestas de mejoras, etc. Todo ayuda a mejorar los proyectos comunitarios. Además permite ponerte manos a la obra con algunas de las funcionalidades de git que hemos cubierto o con las tecnologías que contienen los repositorios.
|
||||
|
||||
## Fork a Project
|
||||
## Bifurcar un proyecto
|
||||
|
||||
The first thing we have to do is find a project we can contribute to. I have recently been presenting on the [Kanister Project](https://github.com/kanisterio/kanister) and I would like to share my presentations that are now on YouTube to the main readme.mdfile in the project.
|
||||
Lo primero que tenemos que hacer es encontrar un proyecto en el que podamos contribuir. Recientemente he estado presentando en el [Proyecto Kanister](https://github.com/kanisterio/kanister) y me gustaría compartir mis presentaciones que ahora están en YouTube al fichero readme.md principal del proyecto.
|
||||
|
||||
First of all, we need to fork the project. Let's run through that process. I am going to navigate to the link shared above and fork the repository.
|
||||
En primer lugar, tenemos que bifurcar el proyecto como vimos en el día de ayer. Voy a navegar hasta el enlace mencionado y hacer un fork del repositorio.
|
||||
|
||||

|
||||
|
||||
We now have our copy of the whole repository.
|
||||
Ahora tenemos nuestra copia de todo el repositorio.
|
||||
|
||||

|
||||
|
||||
For reference on the Readme.mdfile the original Presentations listed are just these two so we need to fix this with our process.
|
||||
En el archivo Readme.md las presentaciones originales listadas son solo estas dos por lo que vamos a aportar más.
|
||||
|
||||

|
||||
|
||||
## Clones to a local machine
|
||||
## Clona a una máquina local
|
||||
|
||||
Now we have our fork we can bring that down to our local and we can then start making our edits to the files. Using the code button on our repo we can grab the URL and then use `git clone url` in a directory we wish to place the repository.
|
||||
Ahora que tenemos nuestro fork podemos bajarlo a nuestra máquina local y empezar a editar los archivos. Usando el botón de código en nuestro repositorio podemos coger la URL y luego usar `git clone url` en un directorio en el que queramos colocar el repositorio. Personalmente, me gusta llamar al directorio con el mismo nombre del proyecto.
|
||||
|
||||

|
||||
|
||||
## Make our changes
|
||||
## Realizamos nuestros cambios
|
||||
|
||||
We have our project local so we can open VSCode or an IDE or text editor of your choice to add your modifications.
|
||||
Tenemos nuestro proyecto en local así que podemos abrir VSCode o un IDE o editor de texto de nuestra elección para añadir las modificaciones.
|
||||
|
||||

|
||||
|
||||
The readme.mdfile is written in markdown language and because I am modifying someone else's project I am going to follow the existing project formatting to add our content.
|
||||
El archivo readme.md está escrito en lenguaje markdown y como estoy modificando el proyecto de otra persona voy a seguir el formato del proyecto existente para añadir nuestro contenido. Quiero decir con esto que es importante seguir la línea editorial de un proyecto y hacer cambios que encajen con el proyecto para no dificurtar su futura lectura y la comprobación de cambios por el autor.
|
||||
|
||||

|
||||
|
||||
## Test your changes
|
||||
## Prueba tus cambios
|
||||
|
||||
We must as a best practice test our changes, this makes total sense if this was a code change to an application you would want to ensure that the application still functions after a code change, well we also must make sure that documentation is formatted and looks correct.
|
||||
Como buena práctica debemos probar nuestros cambios, esto tiene sentido total si se tratara de un cambio de código a una aplicación que desea asegurarse de que la aplicación sigue funcionando después de un cambio de código, así que también debemos asegurarnos de que la documentación tiene el formato y el aspecto correcto. Ni se te ocurra pedir cambios en una pull request con errores porque no se te aceptará y puede que en muchos casos simplemente seas ignorado.
|
||||
|
||||
In vscode we can add a lot of plugins one of these is the ability to preview markdown pages.
|
||||
En vscode podemos añadir un montón de plugins para previsualizar páginas markdown.
|
||||
|
||||

|
||||
|
||||
## Push changes back to our forked repository
|
||||
Personalmente utilizo [markdown](https://marketplace.visualstudio.com/items?itemName=starkwang.markdown) y [markdown all in one](https://marketplace.visualstudio.com/items?itemName=yzhang.markdown-all-in-one), que me permite previsualizar el archivo markdown y mucho más.
|
||||
|
||||
We do not have the authentication to push our changes directly back to the Kanister repository so we have to take this route. Now that I am happy with our changes we can run through some of those now well-known git commands.
|
||||
## Enviar los cambios a nuestro repositorio fork
|
||||
|
||||
No tenemos la autenticación para pushear cambios directamente al repositorio Kanister así que tenemos que tomar otra ruta. En el momento que estoy satisfecho con los cambios y lo he comprobado las veces necesarias para estar seguro que no tiene errores, podemos ejecutar los comandos git que ya tenemos en nuestro haber.
|
||||
|
||||

|
||||
|
||||
Now we go back to GitHub to check the changes once more and then contribute back to the master project.
|
||||
Ahora volvemos a GitHub para comprobar los cambios una vez más, no dejes de comprobarlo, los errores no vendrán por hacer las cosas mal, eso es normal, los errores vendrán por no comprobar las suficientes veces. En este punto, ya podemos contribuir al proyecto original.
|
||||
|
||||
Looks good.
|
||||
Tiene buena pinta.
|
||||
|
||||

|
||||
|
||||
Now we can go back to the top of our forked repository for Kanister and we can see that we are 1 commit ahead of the kanisterio:master branch.
|
||||
Ahora podemos volver a la parte superior de nuestro repositorio bifurcado para Kanister y podemos ver que estamos 1 commit por delante de la rama kanisterio:master.
|
||||
|
||||

|
||||
|
||||
Next, we hit that contribute button highlighted above. We see the option to "Open Pull Request"
|
||||
A continuación, pulsamos el botón de contribuir resaltado arriba, la opción "Open Pull Request".
|
||||
|
||||

|
||||
|
||||
## Open a pull request
|
||||
## Abrir un pull request
|
||||
|
||||
There is quite a bit going on in this next image, top left you can now see we are in the original or the master repository. then you can see what we are comparing and that is the original master and our forked repository. We then have a create pull request button which we will come back to shortly. We have our single commit but if this was more changes you might have multiple commits here. then we have the changes we have made in the readme.mdfile.
|
||||
Atento, en la siguiente imagen hay bastantes cosas sucediendo, arriba a la izquierda puedes ver que estamos en el repositorio original master. Luego puedes ver lo que estamos comparando y que es el repositorio original y nuestro repositorio bifurcado. A continuación, tenemos un botón de crear pull request al que vamos a volver en breve. Tenemos nuestra único commit, pero si se tratara de más cambios se podrían ver todos los commits aquí. Vemos los cambios realizados en readme.md.
|
||||
|
||||

|
||||
|
||||
We have reviewed the above changes and we are ready to create a pull request by hitting the green button.
|
||||
Hemos revisado los cambios anteriores y estamos listos para crear un pull request dándole al botón verde.
|
||||
|
||||
Then depending on how the maintainer of a project has set out their Pull Request functionality on their repository you may or may not have a template that gives you pointers on what the maintainer wants to see.
|
||||
Entonces, dependiendo de cómo el mantenedor de un proyecto ha establecido su funcionalidad Pull Request, puede o no tener una plantilla que le da indicaciones sobre lo que el mantenedor quiere ver.
|
||||
|
||||
This is again where you want to make a meaningful description of what you have done, clear and concise but with enough detail. You can see I have made a simple change overview and I have ticked documentation.
|
||||
Aquí es donde puedes hacer una descripción significativa de lo que has hecho, clara y concisa, pero con suficiente detalle. Puedes ver que he hecho un simple resumen de cambios y he marcado documentación.
|
||||
|
||||

|
||||
|
||||
## Create a pull request
|
||||
## Crear un pull request
|
||||
|
||||
We are now ready to create our pull request. After hitting the "Create Pull Request" at the top of the page you will get a summary of your pull request.
|
||||
Ya estamos listos para crear nuestro pull request. Después de pulsar "Create Pull Request" en la parte superior de la página obtendrás un resumen de tu pull request.
|
||||
|
||||

|
||||
|
||||
Scrolling down you are likely to see some automation taking place, in this instance, we require a review and some checks are taking place. We can see that Travis CI is in progress and a build has started and this will check our update, making sure that before anything is merged we are not breaking things with our additions.
|
||||
Desplazándote hacia abajo es probable que veas que sucede alguna automatización, en este caso, requerimos una revisión y algunas comprobaciones que se están llevando a cabo. Podemos ver que Travis CI está en progreso y una construcción ha comenzado y esto comprobará nuestra actualización, asegurándose de que no estamos rompiendo nada con nuestras adiciones antes de que se fusione.
|
||||
|
||||

|
||||
|
||||
Another thing to note here is that the red in the screenshot above, can look a little daunting and look as if you have made mistakes! Don't worry you have not broken anything, my biggest tip here is this process is there to help you and the maintainers of the project. If you have made a mistake at least from my experience the maintainer will contact and advise on what to do next.
|
||||
Otra cosa a tener en cuenta aquí es que el rojo en la captura de pantalla anterior, puede parecer un poco desalentador, parece como si hubieras cometido errores. Nada más lejos, no te preocupes, no has roto nada, mi mayor consejo aquí es que este proceso está ahí para ayudarte a ti y a los mantenedores del proyecto. Si usted ha cometido un error, al menos desde mi experiencia, el mantenedor se pondrá en contacto y le aconsejará sobre qué hacer a continuación.
|
||||
|
||||
This pull request is now public for everyone to see [added Kanister presentation/resource #1237](https://github.com/kanisterio/kanister/pull/1237)
|
||||

|
||||
|
||||
I am going to publish this before the merge and pull requests are accepted so maybe we can get a little prize for anyone that is still following along and can add a picture of the successful PR?
|
||||
Este pull request es ahora público para que todo el mundo lo vea: [added Kanister presentation/resource #1237](https://github.com/kanisterio/kanister/pull/1237)
|
||||
|
||||
1. Fork this repository to your own GitHub account
|
||||
2. Add your picture and possibly text
|
||||
3. Push the changes to your forked repository
|
||||
4. Create a PR that I will see and approve.
|
||||
5. I will think of some sort of prize
|
||||
Con esto terminamos nuestro repaso a Git y GitHub. A continuación nos sumergiremos en los contenedores, que comienza con una visión general de cómo y por qué contenedores y también una mirada a la virtualización y cómo hemos llegado hasta aquí.
|
||||
|
||||
This then wraps up our look into Git and GitHub, next we are diving into containers which starts with a big picture look into how, and why containers and also a look into virtualisation and how we got here.
|
||||
|
||||
## Resources
|
||||
## Recursos
|
||||
|
||||
- [Learn GitLab in 3 Hours | GitLab Complete Tutorial For Beginners](https://www.youtube.com/watch?v=8aV5AxJrHDg)
|
||||
- [BitBucket Tutorials Playlist](https://www.youtube.com/watch?v=OMLh-5O6Ub8&list=PLaD4FvsFdarSyyGl3ooAm-ZyAllgw_AM5)
|
||||
@ -123,5 +111,13 @@ This then wraps up our look into Git and GitHub, next we are diving into contain
|
||||
- [Git and GitHub for Beginners - Crash Course](https://www.youtube.com/watch?v=RGOj5yH7evk&t=8s)
|
||||
- [Complete Git and GitHub Tutorial](https://www.youtube.com/watch?v=apGV9Kg7ics)
|
||||
- [Git cheatsheet](https://www.atlassian.com/git/tutorials/atlassian-git-cheatsheet)
|
||||
- [En español] [Comandos Git](https://gitea.vergaracarmona.es/man-linux/comandos-git)
|
||||
- [En español][Apuntes Curso de Git](https://vergaracarmona.es/wp-content/uploads/2022/10/Curso-git_vergaracarmona.es_.pdf) de [Juan Carlos Rubio](https://www.linkedin.com/in/juan-carlos-rubio-pineda/Curso-git_vergaracarmona-es).
|
||||
- [En español] En los [apuntes](https://vergaracarmona.es/apuntes/) del traductor:
|
||||
- ["Instalar git en ubuntu"](https://vergaracarmona.es/instalar-git-en-ubuntu/)
|
||||
- ["Comandos de git"](https://vergaracarmona.es/comandos-de-git/)
|
||||
- ["Estrategias de fusión en git: Ship / Show / Ask"](https://vergaracarmona.es/estrategias-bifurcacion-git-ship-show-ask/)
|
||||
- ["Resolver conflictos en Git. Merge, Squash, Rebase o Pull"](https://vergaracarmona.es/merge-squash-rebase-pull/)
|
||||
- ["Borrar commits de git: reset, rebase y cherry-pick"](https://vergaracarmona.es/reset-rebase-cherry-pick/)
|
||||
|
||||
See you on [Day 42](day42.md)
|
||||
Nos vemos en el [Día 42](day42.md)
|
||||
|
@ -1,128 +1,129 @@
|
||||
## The Big Picture: Containers
|
||||
## El panorama: Contenedores
|
||||
|
||||
We are now starting the next section and this section is going to be focused on containers in particular we are going to be looking into Docker getting into some of the key areas to understand more about Containers.
|
||||
Empezamos nueva sección en la que nos centraremos en los contenedores. En particular vamos a mirar Docker para entender algunas claves de los contenedores.
|
||||
|
||||
I will also be trying to get some hands-on here to create the container that we can use during this section but also in future sections later on in the challenge.
|
||||
Pasaremos por un poco de práctica para crear el contenedor que utilizaremos durante esta sección y en futuras secciones del desafío.
|
||||
|
||||
As always this first post is going to be focused on the big picture of how we got here and what it all means.
|
||||
Como siempre, este primer post se va a centrar en el panorama general de cómo hemos llegado hasta aquí y lo que todo esto significa.
|
||||
|
||||
#History of platforms and application development
|
||||
#do we want to talk about Virtualisation & Containerisation
|
||||
### ¿Por qué otra forma de ejecutar aplicaciones?
|
||||
|
||||
### Why another way to run applications?
|
||||
Lo primero que tenemos que plantearnos es por qué necesitamos otra forma de ejecutar software o aplicaciones. La elección es grande, podemos ejecutar nuestras aplicaciones de muchas formas diferentes, por ejemplo, podríamos ver las aplicaciones desplegadas en hardware físico con un sistema operativo y una sola aplicación desplegada allí, y podríamos verlas en máquina virtual o instancias IaaS basadas en la nube ejecutando nuestra aplicación, que luego se integran en una base de datos de nuevo en una MV o como PaaS ofreciendo en la nube pública. O, como vamos a ver, podemos ver nuestras aplicaciones ejecutándose en contenedores.
|
||||
|
||||
The first thing we have to take a look at is why do we need another way to run our software or applications? Well it is just that choice is great, we can run our applications in many different forms, we might see applications deployed on physical hardware with an operating system and a single application deployed there, and we might see the virtual machine or cloud-based IaaS instances running our application which then integrate into a database again in a VM or as PaaS offering in the public cloud. Or we might see our applications running in containers.
|
||||
Ninguna de las opciones anteriores es incorrecta o correcta, pero cada una tiene sus razones para escogerla y seguramente ninguna de ellas desaparecezca. He visto una gran cantidad de contenido sobre Contenedores vs Máquinas Virtuales y realmente no debería haber un argumento, ya que son como argumentos de manzanas vs peras en el que ambos son frutas (formas de ejecutar nuestras aplicaciones), pero no son lo mismo.
|
||||
|
||||
None of the above options is wrong or right, but they each have their reasons to exist and I also strongly believe that none of these is going away. I have seen a lot of content that walks into Containers vs Virtual Machines and there really should not be an argument as that is more like apples vs pears argument where they are both fruit (ways to run our applications) but they are not the same.
|
||||
También diría que si estás empezando y estás desarrollando una aplicación deberías inclinarte hacia los contenedores, más adelante lo veremos en detalle pero en resumen se trata de eficiencia, velocidad y tamaño. Pero esto tiene un precio, si no tienes ni idea de contenedores va a ser una curva de aprendizaje demasiado inclinada, te obligará a entender el por qué y entrar en esta mentalidad. Si has desarrollado tus aplicaciones de una forma particular o no estás en un entorno totalmente nuevo, puede que tengas que enfrentarte a más problemas incluso antes de considerar los contenedores.
|
||||
|
||||
I would also say that if you were starting and you were developing an application you should lean towards containers simply because we will get into some of these areas later, but it's about efficiency, speed and size. But that also comes with a price, if you have no idea about containers then it's going to be a learning curve to force yourself to understand the why and get into that mindset. If you have developed your applications a particular way or you are not in a greenfield environment then you might have more pain points to deal with before even considering containers.
|
||||
|
||||
We have many different choices then when it comes to downloading a given piece of software, there are a variety of different operating systems that we might be using. And specific instructions for what we need to do to install our applications.
|
||||
Tenemos muchas opciones diferentes a la hora de descargar un determinado software, hay una variedad de sistemas operativos diferentes que podríamos utilizar. E instrucciones específicas sobre lo que tenemos que hacer para instalar nuestras aplicaciones.
|
||||
|
||||

|
||||
|
||||
More and more recently I am finding that the applications we might have once needed a full server OS, A VM, Physical or cloud instance are now releasing container-based versions of their software. I find this interesting as this opens the world of containers and then Kubernetes to everyone and not just a focus on application developers.
|
||||
Cada vez nos encontramos más que las aplicaciones que una vez podrían haber necesitado un sistema operativo de servidor completo (una MV, instancia física o en la nube), ahora están lanzando versiones su software basadas en contenedores. Es interesante ya que esto abre las posibilidades de los contenedores y de Kubernetes a todo el mundo, y no sólo un enfoque en los desarrolladores de aplicaciones.
|
||||
|
||||

|
||||
|
||||
As you can probably tell as I have said before, I am not going to advocate that the answer is containers, what's the question! But I would like to discuss how this is another option for us to be aware of when we deploy our applications.
|
||||
Podrás deducir por lo que se ha dicho antes que no se va defender los contenedores como el mejor sistema para desplegar aplicaciones, pero desde luego existe el espacio para el debate.
|
||||
|
||||

|
||||
|
||||
We have had container technology for a long time, so why now over the last say 10 years has this become popular, I would say even more popular in the last 5. We have had containers for decades. It comes down to the challenge of containers or should I say images as well, to how we distribute our software, because if we just have container technology, then we still will have many of the same problems we've had with software management.
|
||||
Hemos tenido la tecnología de contenedores durante mucho tiempo, así que ¿por qué en los últimos 10 años se ha hecho tan popular? Diría que incluso mucho más populares en los últimos 5.
|
||||
|
||||
If we think about Docker as a tool, the reason that it took off, is because of the ecosystem of images that are easy to find and use. Simple to get on your systems and get up and running. A major part of this is consistency across the entire space, of all these different challenges that we face with software. It doesn't matter if it's MongoDB or nodeJS, the process to get either of those up and running will be the same. The process to stop either of those is the same. All of these issues will still exist, but the nice thing is, when we bring good container and image technology together, we now have a single set of tools to help us tackle all of these different problems. Some of those issues are listed below:
|
||||
Hemos tenido contenedores durante décadas. ¿Se reduce al desafío de los contenedores o debería decir imágenes también? Porque si sólo tenemos la tecnología de contenedores, entonces todavía tendremos muchos de los mismos problemas que hemos tenido con la gestión de software.
|
||||
|
||||
- We first have to find software on the internet.
|
||||
- We then have to download this software.
|
||||
- Do we trust the source?
|
||||
- Do we then need a license? Which License?
|
||||
- Is it compatible with different platforms?
|
||||
- What is the package? binary? Executable? Package manager?
|
||||
- How do we configure the software?
|
||||
- Dependencies? Did the overall download have us covered or do we need them as well?
|
||||
- Dependencies of Dependencies?
|
||||
- How do we start the application?
|
||||
- How do we stop the application?
|
||||
- Will it auto-restart?
|
||||
- Start on boot?
|
||||
- Resource conflicts?
|
||||
- Conflicting libraries?
|
||||
- Port Conflicts
|
||||
- Security for the software?
|
||||
- Software updates?
|
||||
- How can I remove the software?
|
||||
Si pensamos en Docker como una herramienta, la razón por la que despegó es al ecosistema de imágenes que son fáciles de conseguir y de poner en marcha. Una parte importante de esto es la coherencia en todo el espacio, de todos estos diferentes desafíos que enfrentamos con el software. No importa si es MongoDB o nodeJS, el proceso para poner en marcha cualquiera de ellos será el mismo. El proceso para detener cualquiera de ellos es el mismo. Todos estos problemas seguirán existiendo, pero lo bueno es que, cuando unimos una buena tecnología de contenedores e imágenes conseguiremos un único conjunto de herramientas para ayudarnos a abordar todos estos problemas diferentes. Algunos de esos problemas son:
|
||||
|
||||
We can split the above into 3 areas of the complexity of the software that containers and images do help with these.
|
||||
- Primero tenemos que encontrar software en Internet.
|
||||
- Luego tenemos que descargarlo.
|
||||
- ¿Confiamos en la fuente?
|
||||
- ¿Necesitamos una licencia? ¿Qué licencia?
|
||||
- ¿Es compatible con diferentes plataformas?
|
||||
- ¿Cuál es el paquete? ¿Binario? ¿Ejecutable? ¿Gestor de paquetes?
|
||||
- ¿Cómo se configura el software?
|
||||
- ¿Dependencias? ¿La descarga general nos ha cubierto o también las necesitamos?
|
||||
- ¿Dependencias de dependencias?
|
||||
- ¿Cómo iniciamos la aplicación?
|
||||
- ¿Cómo detenemos la aplicación?
|
||||
- ¿Se reiniciará automáticamente?
|
||||
- ¿Se iniciará al arrancar?
|
||||
- ¿Conflictos de recursos?
|
||||
- ¿Conflictos de librerías?
|
||||
- Conflictos de puertos
|
||||
- ¿Seguridad del software?
|
||||
- ¿Actualizaciones del software?
|
||||
- ¿Cómo puedo eliminar el software?
|
||||
|
||||
| Distribution | Installation | Operation |
|
||||
| ------------ | ------------- | ------------------ |
|
||||
| Find | Install | Start |
|
||||
| Download | Configuration | Security |
|
||||
| License | Uninstall | Ports |
|
||||
| Package | Dependencies | Resource Conflicts |
|
||||
| Trust | Platform | Auto-Restart |
|
||||
| Find | Libraries | Updates |
|
||||
Podemos dividir lo anterior en 3 áreas de la complejidad del software que los contenedores y las imágenes ayudan con estos.
|
||||
|
||||
Containers and images are going to help us remove some of these challenges that we have with possibly other software and applications.
|
||||
| Distribución | Instalación | Funcionamiento |
|
||||
| ------------ | -------------- | ------------------- |
|
||||
| Buscar | Instalar | Iniciar |
|
||||
| Descargar | Configuración | Seguridad |
|
||||
| Licencia | Desinstalación | Puertos |
|
||||
| Paquete | Dependencias | Conflictos Recursos |
|
||||
| Confianza | Plataforma | Reinicio automático |
|
||||
| Buscar | Bibliotecas | Actualizaciones |
|
||||
|
||||
At a high level we could move installation and operation into the same list, Images are going to help us from a distribution point of view and containers help with the installation and operations.
|
||||
Los contenedores y las imágenes nos van a ayudar a eliminar algunos de estos retos que tenemos posiblemente con otro software y aplicaciones.
|
||||
|
||||
Ok, probably sounds great and exciting but we still need to understand what is a container and now I have mentioned images so let's cover those areas next.
|
||||
En un alto nivel podríamos mover la instalación y el funcionamiento en la misma lista, las imágenes nos van a ayudar desde el punto de vista de la distribución y los contenedores ayudan con la instalación y las operaciones.
|
||||
|
||||
Another thing you might have seen a lot when we talk about Containers for software development is the analogy used alongside shipping containers, shipping containers are used to ship various goods across the seas using large vessels.
|
||||
Ok, probablemente suena muy bien y emocionante, pero todavía tenemos que entender lo que es un contenedor y ahora he mencionado imágenes así que vamos a verlo a continuación.
|
||||
|
||||
Otra cosa que habrás visto a menudo cuando hablamos de contenedores para el desarrollo de software es la analogía utilizada con los contenedores marítimos, los contenedores marítimos se utilizan para transportar diversas mercancías a través de los mares utilizando grandes buques.
|
||||
|
||||

|
||||
|
||||
What does this have to do with our topic of containers? Think about the code that software developers write, how can we ship that particular code from one machine to another machine?
|
||||
¿Qué tiene que ver con nuestro tema de los contenedores? Piensa en el código que escriben los desarrolladores de software, ¿cómo podemos enviar ese código concreto de una máquina a otra?
|
||||
|
||||
If we think about what we touched on before about software distribution, installation and operations but now we start to build this out into an environment visual. We have hardware and an operating system where you will run multiple applications. For example, nodejs has certain dependencies and needs certain libraries. If you then want to install MySQL then it needs its required libraries and dependencies. Each software application will have its library and dependency. We might be massively lucky and not have any conflicts between any of our applications where specific libraries and dependencies are clashing causing issues but the more applications the more chance or risk of conflicts. However, this is not about that one deployment when everything fixes your software applications are going to be updated and then we can also introduce these conflicts.
|
||||
Si pensamos en lo que hemos tocado antes sobre la distribución de software, instalación y operaciones, pero ahora empezamos a construir esto en un entorno visual. Tenemos hardware y un sistema operativo donde se ejecutarán múltiples aplicaciones. Por ejemplo, nodejs tiene ciertas dependencias y necesita ciertas bibliotecas. Si a continuación, desea instalar MySQL entonces necesita sus bibliotecas y sus dependencias propias. Cada aplicación de software tendrá sus bibliotecas y dependencias. Podríamos tener mucha suerte y no tener ningún conflicto entre cualquiera de nuestras aplicaciones donde las bibliotecas y dependencias específicas están chocando causando problemas, pero cuantas más aplicaciones más posibilidades o riesgo de conflictos. Sin embargo, se trata de que un despliegue se producirá muchas veces, y no puede esperar a que todo este arreglado, porque en cada actualización se podrían introducir estos conflictos.
|
||||
|
||||

|
||||
|
||||
Containers can help solve this problem. Containers help **build** your application, **ship** the application, **deploy** and **scale** these applications with ease independently. let's look at the architecture, you will have hardware and operating system then on top of it you will have a container engine like docker which we will cover later. The container engine software helps create containers that package the libraries and dependencies along with it so that you can move this container seamlessly from one machine to another machine without worrying about the libraries and dependencies since they come as a part of a package which is nothing but the container so you can have different containers this container can be moved across the systems without worrying about the underlying dependencies that the application
|
||||
needs to run because everything the application needs to run is packaged as
|
||||
a container that you can move.
|
||||
Los contenedores pueden ayudar a resolver este problema. Los contenedores ayudan a **construir**, a **enviar**, a **desplegar** y a **escalar** estas aplicaciones con facilidad de forma independiente. echemos un vistazo a la arquitectura, tendrás hardware y sistema operativo y luego encima tendrás un motor de contenedores como docker que veremos en breve. El software de motor de contenedores ayuda a crear contenedores que empaquetan las bibliotecas y dependencias junto con él para que pueda mover este contenedor sin problemas de una máquina a otra sin preocuparse por las bibliotecas y dependencias, ya que vienen como parte de un paquete en el contenedor. Con lo cual, se puede mover a través de los sistemas sin preocuparse por las dependencias subyacentes que la aplicación necesita para funcionar.
|
||||
|
||||

|
||||
|
||||
### The advantages of these containers
|
||||
### Las ventajas de estos contenedores
|
||||
|
||||
- Containers help package all the dependencies within the container and
|
||||
isolate it.
|
||||
- Los contenedores ayudan a empaquetar todas las dependencias dentro del contenedor y aislarlas.
|
||||
|
||||
- It is easy to manage the containers
|
||||
- Es fácil gestionar.
|
||||
|
||||
- The ability to move from one system to another.
|
||||
- Se puede pasar de un sistema a otro.
|
||||
|
||||
- Containers help package the software and you can easily ship it without any duplicate efforts
|
||||
- Los contenedores ayudan a empaquetar el software y se puede enviar fácilmente sin duplicar esfuerzos.
|
||||
|
||||
- Containers are easily scalable.
|
||||
- Los contenedores son fácilmente escalables.
|
||||
|
||||
Using containers you can scale independent containers and use a load balancer
|
||||
or a service which helps split the traffic and you can scale the applications horizontally. Containers offer a lot of flexibility and ease in how you manage your applications
|
||||
Usando contenedores puedes escalar contenedores independientes y usar un equilibrador de carga
|
||||
o un servicio que ayude a dividir el tráfico y puedas escalar las aplicaciones horizontalmente. Los contenedores ofrecen mucha flexibilidad y facilidad a la hora de gestionar las aplicaciones.
|
||||
|
||||
### What is a container?
|
||||
### ¿Qué es un contenedor?
|
||||
|
||||
When we run applications on our computer, this could be the web browser or VScode that you are using to read this post. That application is running as a process or what is known as a process. On our laptops or systems, we tend to run multiple applications or as we said processes. When we open a new application or click on the application icon this is an application we would like to run, sometimes this application might be a service that we just want to run in the background, our operating system is full of services that are running in the background providing you with the user experience you get with your system.
|
||||
Cuando ejecutamos aplicaciones en nuestro ordenador, podría ser en el navegador o en el VScode que quizá estés utilizando para leer este post, esa aplicación se ejecuta como un proceso. En nuestros portátiles o sistemas tendemos a ejecutar múltiples aplicaciones o, como hemos dicho, procesos. Cuando abrimos una nueva aplicación o hacemos clic en el icono de la aplicación, a veces podría ser un servicio que sólo queremos ejecutar en segundo plano, nuestro sistema operativo está lleno de servicios que se ejecutan en segundo plano y que proporcionan la experiencia de usuario final.
|
||||
|
||||
That application icon represents a link to an executable somewhere on your file system, the operating system then loads that executable into memory. Interestingly, that executable is sometimes referred to as an image when we're talking about a process.
|
||||
Ese icono de aplicación representa un enlace a un ejecutable en algún lugar de tu sistema de archivos, el sistema operativo entonces carga ese ejecutable en la memoria. Curiosamente, a veces nos referimos a ese ejecutable como una imagen cuando hablamos de un proceso.
|
||||
|
||||
Containers are processes, A container is a standard unit of software that packages up code and all its dependencies so the application runs quickly and reliably from one computing environment to another.
|
||||
Un contenedor es una unidad estándar de software que empaqueta el código y todas sus dependencias para que la aplicación se ejecute de forma rápida y fiable de un entorno informático a otro como lo hacen las aplicaciones.
|
||||
|
||||
Containerised software will always run the same, regardless of the infrastructure. Containers isolate software from its environment and ensure that it works uniformly despite differences for instance between development and staging.
|
||||
El software en contenedores siempre se ejecutará igual, independientemente de la infraestructura. Los contenedores aíslan el software en su entorno mínimo viable y garantizan que funcione de manera uniforme a pesar de las diferencias, por ejemplo, entre el desarrollo y la puesta en escena.
|
||||
|
||||
I mentioned images in the last section when it comes to how and why containers and images combined made containers popular in our ecosystem.
|
||||
He mencionado las imágenes en la última sección cuando se trata de cómo y por qué la combinación de contenedores e imágenes ha hecho que los contenedores sean populares en nuestro ecosistema.
|
||||
|
||||
### What is an Image?
|
||||
### ¿Qué es una imagen?
|
||||
|
||||
A container image is a lightweight, standalone, executable package of software that includes everything needed to run an application: code, runtime, system tools, system libraries and settings. Container images become containers at runtime.
|
||||
Una imagen de contenedor es un paquete de software ligero, independiente y ejecutable que incluye todo lo necesario para ejecutar una aplicación: código, tiempo de ejecución, herramientas del sistema, bibliotecas del sistema y configuraciones. Las imágenes de contenedor se convierten en contenedores en tiempo de ejecución.
|
||||
|
||||
## Resources
|
||||
## Recursos
|
||||
|
||||
- [TechWorld with Nana - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=3c-iBn73dDE)
|
||||
- [Programming with Mosh - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=pTFZFxd4hOI)
|
||||
- [Docker Tutorial for Beginners - What is Docker? Introduction to Containers](https://www.youtube.com/watch?v=17Bl31rlnRM&list=WL&index=128&t=61s)
|
||||
- [Introduction to Container By Red Hat](https://www.redhat.com/en/topics/containers)
|
||||
- [En español] En los [apuntes](https://vergaracarmona.es/apuntes/) del traductor:
|
||||
- [Preparación de entorno de pruebas local para docker](https://vergaracarmona.es/preparacion-de-entorno-de-pruebas-local-para-docker/)
|
||||
- [Uso básico de docker](https://vergaracarmona.es/uso-basico-de-docker/)
|
||||
- [Una breve historia sobre contenedores](https://vergaracarmona.es/breve-historia-de-contenedores/)
|
||||
- [Desplegar con docker-compose los servicios Traefik y Portainer](https://vergaracarmona.es/desplegar-con-docker-compose-los-servicios-traefik-y-portainer/)
|
||||
|
||||
See you on [Day 43](day43.md)
|
||||
Nos vemos en el [Día 43](day43.md)
|
||||
|
@ -1,62 +1,67 @@
|
||||
## What is Docker & Getting installed
|
||||
## Qué es Docker y cómo instalarlo
|
||||
|
||||
In the previous post, I mentioned Docker at least once and that is because Docker is innovative in making containers popular even though they have been around for such a long time.
|
||||
En el post anterior, he mencionado Docker al menos una vez y eso es porque Docker es el culpable en gran parte de la popularización de los contenedores, a pesar de que han existido desde hace mucho tiempo.
|
||||
|
||||
We are going to be using and explaining docker here but we should also mention the [Open Container Initiative (OCI)](https://www.opencontainers.org/) which is an industry standards organization that encourages innovation while avoiding the danger of vendor lock-in. Thanks to the OCI, we have a choice when choosing a container toolchain, including Docker, [CRI-O](https://cri-o.io/), [Podman](http://podman.io/), [LXC](https://linuxcontainers.org/), and others.
|
||||
Vamos a utilizar y explicar un poco Docker, pero también debemos mencionar la [Open Container Initiative (OCI)](https://www.opencontainers.org/), que es una organización de estándares de la industria que fomenta la innovación, evitando el peligro de la dependencia del proveedor. Gracias a la OCI, tenemos donde elegir entre las herramientas de contenedores, incluyendo Docker, [CRI-O](https://cri-o.io/), [Podman](http://podman.io/), [LXC](https://linuxcontainers.org/), entre otros.
|
||||
|
||||
Docker is a software framework for building, running, and managing containers. The term "docker" may refer to either the tools (the commands and a daemon) or the Dockerfile file format.
|
||||
Docker es un framework de software para construir, ejecutar y gestionar contenedores. El término "docker" puede referirse tanto a las herramientas (los comandos y un daemon) como al formato de archivo Dockerfile.
|
||||
|
||||
We are going to be using Docker Personal here which is free (for education and learning). This includes all the essentials that we need to cover to get a good foundation of knowledge of containers and tooling.
|
||||
Utilizaremos Docker Personal, que es gratuito (para la educación y el aprendizaje). Esto incluye todo lo esencial que necesitamos para obtener una buena base de conocimientos de los contenedores y herramientas.
|
||||
|
||||
It is probably worth breaking down some of the "docker" tools that we will be using and what they are used for. The term docker can be referring to the docker project overall, which is a platform for devs and admins to develop, ship and run applications. It might also be a reference to the docker daemon process running on the host which manages images and containers also called Docker Engine.
|
||||
Probablemente vale la pena desglosar algunas de las herramientas "docker" para saber por qué se utilizan. El término docker puede referirse al proyecto docker en general, que es una plataforma para que los desarrolladores y administradores desarrollen, envíen y ejecuten aplicaciones. También puede ser una referencia al daemon Docker que se ejecuta en el host que gestiona las imágenes y contenedores también llamado Docker Engine.
|
||||
|
||||
### Docker Engine
|
||||
|
||||
Docker Engine is an open-source containerization technology for building and containerizing your applications. Docker Engine acts as a client-server application with:
|
||||
Docker Engine es una tecnología de contenerización de código abierto para construir y contenerizar tus aplicaciones. Docker Engine actúa como una aplicación cliente-servidor con:
|
||||
|
||||
- A server with a long-running daemon process dockerd.
|
||||
- APIs specify interfaces that programs can use to talk to and instruct the Docker daemon.
|
||||
- A command line interface (CLI) client docker.
|
||||
- Un servidor con un proceso demonio de larga ejecución dockerd.
|
||||
- Las API especifican interfaces que los programas pueden utilizar para hablar con el demonio Docker y darle instrucciones.
|
||||
- Una interfaz de línea de comandos (CLI) docker cliente.
|
||||
|
||||
The above was taken from the official Docker documentation and the specific [Docker Engine Overview](https://docs.docker.com/engine/)
|
||||
Lo anterior fue tomado de la documentación oficial de Docker y el específico [Docker Engine Overview](https://docs.docker.com/engine/)
|
||||
|
||||
### Docker Desktop
|
||||
|
||||
We have a docker desktop for both Windows and macOS systems. An easy-to-install, lightweight docker development environment. A native OS application that leverages virtualisation capabilities on the host operating system.
|
||||
Disponemos de un Docker Desktop para sistemas Windows y macOS. Un entorno de desarrollo docker ligero y fácil de instalar. Una aplicación nativa del sistema operativo que aprovecha las capacidades de virtualización en el sistema operativo anfitrión. Nadie lo utiliza, pero es una buena opción para comenzar.
|
||||
|
||||
It’s the best solution if you want to build, debug, test, package, and ship Dockerized applications on Windows or macOS.
|
||||
Puedes construir, depurar, probar, empaquetar y enviar aplicaciones Dockerizadas en Windows o macOS.
|
||||
|
||||
On Windows, we can also take advantage of WSL2 and Microsoft Hyper-V. We will cover some of the WSL2 benefits as we go through.
|
||||
En Windows, también podemos aprovechar WSL2 y Microsoft Hyper-V. Veremos algunas de las ventajas de WSL2 a medida que avancemos, ya que como Windows no llega lo mejor es utilizar las opciones Linux.
|
||||
|
||||
Because of the integration with hypervisor capabilities on the host operating system docker provides the ability to run your containers with Linux Operating systems.
|
||||
Debido a la difícil integración con las capacidades del hipervisor en el sistema operativo anfitrión, docker proporciona la capacidad de ejecutar sus contenedores con sistemas operativos Linux que no dan tantos problemas.
|
||||
|
||||
### Docker Compose
|
||||
|
||||
Docker compose is a tool that allows you to run more complex apps over multiple containers. With the benefit of being able to use a single file and command to spin up your application.
|
||||
Docker compose es una herramienta que te permite ejecutar aplicaciones más complejas sobre múltiples contenedores. Con la ventaja de ser capaz de utilizar un único archivo y comando para hacer girar su aplicación. Es el principio de la orquestación de contenedores, un concepto que tendremos que interiorizar para dejar de tratar a nuestras máquinas como mascotas y comenzar a verlas como ganado.
|
||||
|
||||
### Docker Hub
|
||||
|
||||
A centralised resource for working with Docker and its components. Most commonly known as a registry to host docker images. But there are a lot of additional services here which can be used in part with automation or integrated into GitHub as well as security scanning.
|
||||
Un recurso centralizado para trabajar con Docker y sus componentes, un registro de imágenes que nos facilitará mucho la existencia. Hay un montón de servicios adicionales que pueden ser utilizados en parte con la automatización o integrados en GitHub, así como el escaneo de seguridad.
|
||||
|
||||
### Dockerfile
|
||||
|
||||
A dockerfile is a text file that contains commands you would normally execute manually to build a docker image. Docker can build images automatically by reading the instructions we have in our dockerfile.
|
||||
Un dockerfile es un archivo de texto que contiene comandos que también se pueden ejecutar manualmente para construir una imagen docker. Docker puede construir imágenes automáticamente leyendo las instrucciones que tenemos en nuestro dockerfile gracias al lenguaje declarativo.
|
||||
|
||||
## Installing Docker Desktop
|
||||
## Instalando Docker Desktop
|
||||
|
||||
The [docker documenation](https://docs.docker.com/engine/install/) is amazing and if you are only just diving in then you should take a look and have a read-through. We will be using Docker Desktop on Windows with WSL2. I had already run through the installation on the machine we are using here.
|
||||
La [documenación de Docker](https://docs.docker.com/engine/install/) es asombrosa y si quieres aprender de verdad deberías echarle un vistazo y tenerla como referencia. Vamos a utilizar Docker Desktop en Windows con WSL2. Ya he ejecutado la instalación en la máquina que estamos utilizando.
|
||||
|
||||

|
||||
|
||||
Take note before you go ahead and install at the system requirements, [Install Docker Desktop on Windows](https://docs.docker.com/desktop/windows/install/) if you are using macOS including the M1-based CPU architecture you can also take a look at [Install Docker Desktop on macOS](https://docs.docker.com/desktop/mac/install/)
|
||||
Toma nota antes de seguir adelante en los requisitos del sistema antes de [Instalar Docker Desktop en Windows](https://docs.docker.com/desktop/windows/install/). Si estás usando macOS, inclusive para la arquitectura de CPU basada en M1, puedes echar un vistazo a [Instalar Docker Desktop en macOS](https://docs.docker.com/desktop/mac/install/). Linux también puede ejecutar Docker Desktop virtualizado: https://docs.docker.com/desktop/install/linux-install/
|
||||
|
||||
I will run through the Docker Desktop installation for Windows on another Windows Machine and log the process down below.
|
||||
Voy a ejecutar a través de la instalación de Docker Desktop para Windows en otra máquina Windows y registrar el proceso de abajo.
|
||||
|
||||
## Resources
|
||||
## Recursos
|
||||
|
||||
- [TechWorld with Nana - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=3c-iBn73dDE)
|
||||
- [Programming with Mosh - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=pTFZFxd4hOI)
|
||||
- [Docker Tutorial for Beginners - What is Docker? Introduction to Containers](https://www.youtube.com/watch?v=17Bl31rlnRM&list=WL&index=128&t=61s)
|
||||
- [WSL 2 with Docker getting started](https://www.youtube.com/watch?v=5RQbdMn04Oc)
|
||||
- [En español] En los [apuntes](https://vergaracarmona.es/apuntes/) del traductor:
|
||||
- [Preparación de entorno de pruebas local para docker](https://vergaracarmona.es/preparacion-de-entorno-de-pruebas-local-para-docker/)
|
||||
- [Uso básico de docker](https://vergaracarmona.es/uso-basico-de-docker/)
|
||||
- [Una breve historia sobre contenedores](https://vergaracarmona.es/breve-historia-de-contenedores/)
|
||||
- [Desplegar con docker-compose los servicios Traefik y Portainer](https://vergaracarmona.es/desplegar-con-docker-compose-los-servicios-traefik-y-portainer/)
|
||||
|
||||
See you on [Day 44](day44.md)
|
||||
Nos vemos en el [Día 44](day44.md)
|
||||
|
@ -1,132 +1,145 @@
|
||||
## Docker Images & Hands-On with Docker Desktop
|
||||
## Imágenes Docker y Manos a la Obra con Docker Desktop
|
||||
|
||||
We now have Docker Desktop installed on our system. (If you are running Linux then you still have options but no GUI but docker does work on Linux.)[Install Docker Engine on Ubuntu](https://docs.docker.com/engine/install/ubuntu/) (Other distributions also available.)
|
||||
Ahora tenemos Docker Desktop instalado en nuestro sistema. (Si estás ejecutando Linux, tienes más opciones pero no el GUI.)[Instalar Docker Engine en Ubuntu](https://docs.docker.com/engine/install/ubuntu/) (También está disponible para otras distribuciones.)
|
||||
|
||||
In this post, we are going to get started with deploying some images into our environment. A recap on what a Docker Image is - A Docker image is a file used to execute code in a Docker container. Docker images act as a set of instructions to build a Docker container, like a template. Docker images also act as the starting point when using Docker.
|
||||
En este post, vamos a empezar con el despliegue de algunas imágenes en nuestro entorno. Una imagen Docker es un archivo utilizado para ejecutar código en un contenedor Docker. Las imágenes Docker actúan como un conjunto de instrucciones para construir un contenedor Docker, como una plantilla. Las imágenes Docker también actúan como el punto de partida cuando se utiliza Docker.
|
||||
|
||||
Now is a good time to go and create your account on [DockerHub](https://hub.docker.com/)
|
||||
Ahora es un buen momento para crear tu cuenta en [DockerHub](https://hub.docker.com/)
|
||||
|
||||

|
||||
|
||||
DockerHub is a centralised resource for working with Docker and its components. Most commonly known as a registry to host docker images. But there are a lot of additional services here which can be used in part with automation or integrated into GitHub as well as security scanning.
|
||||
DockerHub es un recurso centralizado para trabajar con Docker y sus componentes. Más comúnmente conocido como un registro para alojar imágenes Docker. Pero hay un montón de servicios adicionales que se pueden utilizar en parte con la automatización o integración en GitHub, así como el escaneo de seguridad.
|
||||
|
||||
If you scroll down once logged in you are going to see a list of container images, You might see database images for MySQL, hello-world etc. Think of these as great baseline images or you might just need a database image and you are best to use the official one which means you don't need to create your own.
|
||||
Desplazándote hacia abajo una vez logueado verás una lista de imágenes de contenedores, es posible que veas imágenes de bases de datos MySQL, hello-world, etc. Piensa en estas como las imágenes de referencia, puede que sólo necesites una imagen de BBDD MySQL y la mejor sea utilizar la oficial, lo que significa que no es necesario crear una propia personalizada.
|
||||
|
||||

|
||||
|
||||
We can drill deeper into the view of available images and search across categories, operating systems and architectures. The one thing I highlight below is the Official Image, this should give you peace of mind about the origin of this container image.
|
||||
Podemos profundizar en la vista de imágenes disponibles y buscar por categorías, sistemas operativos y arquitecturas. Hay que destacar la Imagen Oficial, porque esta debería darte tranquilidad sobre su origen. Para nada recomiendo utilizar imágenes no oficiales, sobretodo en producción. En caso de que lo hagas, asegúrate al menos de que son de un editor verificado.
|
||||
|
||||

|
||||
|
||||
We can also search for a specific image, for example, WordPress might be a good base image that we want we can do that at the top and find all container images related to WordPress. Below are notices that we also have verified publisher.
|
||||
|
||||
- Official Image - Docker Official images are a curated set of Docker open source and "drop-in" solution repositories.
|
||||
|
||||
- Verified Publisher - High-quality Docker content from verified publishers. These products are published and maintained directly by a commercial entity.
|
||||
Por otra parte, podemos buscar una imagen específica, por ejemplo, WordPress podría ser una buena imagen de base que incluye todas las imágenes de contenedores relacionados que necesite la aplicación. Ten en cuenta que existe diferencias entre imagen oficial y editor verificado.
|
||||
- **Imagen Oficial** - Las imágenes Oficiales de Docker son un conjunto curado de código abierto de Docker y repositorios de soluciones "drop-in".
|
||||
- **Editor verificado** - Contenido Docker de alta calidad de editores verificados. Estos productos son publicados y mantenidos directamente por una entidad comercial.
|
||||
|
||||

|
||||
|
||||
### Exploring Docker Desktop
|
||||
### Explorando Docker Desktop
|
||||
|
||||
We have Docker Desktop installed on our system and if you open this I expect unless you had this already installed you will see something similar to the image below. As you can see we have no containers running and our docker engine is running.
|
||||
Tenemos Docker Desktop instalado en nuestro equipo windows. Si lo abres por primera vez verás algo similar a la imagen de abajo. Como puedes ver no tenemos ningún contenedor ejecutándose y nuestro motor docker está funcionando.
|
||||
|
||||

|
||||
|
||||
Because this was not a fresh install for me, I do have some images already downloaded and available on my system. You will likely see nothing in here.
|
||||
Debido a que esta no fue la primera instalación, tengo algunas imágenes ya descargadas y disponibles en mi sistema. Es probable que lo veas diferente.
|
||||
|
||||

|
||||
|
||||
Under remote repositories, this is where you will find any container images you have stored in your docker hub. You can see from the below I do not have any images.
|
||||
En los repositorios remotos es donde encontrarás cualquier imagen de contenedor que hayas almacenado en tu docker hub. Puedes ver en la imagen de abajo que no tengo ninguna imagen.
|
||||
|
||||

|
||||
|
||||
We can also clarify this on our dockerhub site and confirm that we have no repositories there.
|
||||
Hay que confirmarlo en nuestro sitio dockerhub y confirmar que no tenemos repositorios allí.
|
||||
|
||||

|
||||
|
||||
Next, we have the Volumes tab, If you have containers that require persistence then this is where we can add these volumes to your local file system or a shared file system.
|
||||
A continuación, tenemos la pestaña Volumes. Si tienes contenedores que requieren persistencia será aquí donde podemos añadir estos volúmenes al sistema de archivos local o a un sistema de archivos compartido.
|
||||
|
||||

|
||||
|
||||
At the time of writing, there is also a Dev Environments tab, this is going to help you collaborate with your team instead of moving between different git branches. We won't be covering this.
|
||||
En el momento de escribir esto, también hay una pestaña de Entornos de Desarrollo, esto va a ayudarte a colaborar con tu equipo en lugar de moverte entre diferentes ramas de git. No vamos a cubrir esto.
|
||||
|
||||

|
||||
|
||||
Going back to the first tab you can see that there is a command we can run which is a getting started container. Let's run `docker run -d -p 80:80 docker/getting-started` in our terminal.
|
||||
Volviendo a la primera pestaña puedes ver que hay un comando que podemos ejecutar para iniciar el contenedor. Ejecutamos en nuestro terminal:
|
||||
|
||||
```shell
|
||||
docker run -d -p 80:80 docker/getting-started
|
||||
```
|
||||
|
||||

|
||||
|
||||
If we go and check our docker desktop window again, we are going to see that we have a running container.
|
||||
Si comprobamos nuestro docker desktop veremos que ya tenemos un contenedor en ejecución.
|
||||
|
||||

|
||||
|
||||
You might have noticed that I am using WSL2 and for you to be able to use that you will need to make sure this is enabled in the settings.
|
||||
Te habrás dado cuenta de que estoy usando WSL2. Para usarlo tendrás que asegurarte de que está activado en la configuración.
|
||||
|
||||

|
||||
|
||||
If we now go and check our Images tab again, you should now see an in-use image called docker/getting-started.
|
||||
Si ahora comprobamos nuestra pestaña Imágenes deberías ver una imagen en uso llamada docker/getting-started.
|
||||
|
||||

|
||||
|
||||
Back to the Containers/Apps tab, click on your running container. You are going to see the logs by default and along the top, you have some options to choose from, in our case I am pretty confident that this is going to be a web page running in this container so we are going to choose the open in the browser.
|
||||
De vuelta a la pestaña Contenedores/Apps, haz click en tu contenedor en ejecución. Verás los registros por defecto y en la parte superior tiene algunas opciones para elegir. En nuestro caso no va a ser una web que se ejecute en este contenedor por lo que vamos a elegir la apertura en el navegador.
|
||||
|
||||

|
||||
|
||||
When we hit that button above sure enough a web page should open hitting your localhost and display something similar to below.
|
||||
Cuando pulsemos el botón de arriba, se abrirá una web que mostrará algo similar a lo que se muestra a continuación.
|
||||
|
||||
This container also has some more detail on our containers and images.
|
||||
Este contenedor también tiene algunos detalles más sobre nuestros contenedores e imágenes.
|
||||
|
||||

|
||||
|
||||
We have now run our first container. Nothing too scary just yet. What about if we wanted to pull one of the container images down from DockerHub? Maybe there is a `hello world` docker container we could use.
|
||||
Ya hemos ejecutado nuestro primer contenedor. Nada demasiado aterrador todavía. ¿Y si quisiéramos bajar una de las imágenes de contenedor de DockerHub? Podemos usar un contenedor docker llamado `hello world` para comprobarlo.
|
||||
|
||||
I went ahead and stopped the getting started container not that it's taking up any mass amount of resources but for tidiness, as we walk through some more steps.
|
||||
Me adelanté y detuve el contenedor de inicio, no es que esté ocupando una cantidad masiva de recursos, sino para mantener un orden mientras vemos algunos pasos más.
|
||||
|
||||
Back in our terminal let's go ahead and run `docker run hello-world` and see what happens.
|
||||
De vuelta en nuestro terminal vamos a seguir adelante y ejecutar `docker run hello-world` y a ver qué pasa.
|
||||
|
||||
You can see we did not have the image locally so we pulled that down and then we got a message that is written into the container image with some information on what it did to get up and running and some links to reference points.
|
||||
Puedes ver que no teníamos la imagen localmente así que la bajamos y entonces tenemos un mensaje que está escrito en la imagen del contenedor con alguna información sobre lo que hizo para ponerse en marcha y algunos enlaces a puntos de referencia.
|
||||
|
||||

|
||||
|
||||
However, if we go and look in Docker Desktop now we have no running containers but we do have an exited container that used the hello-world message, meaning it came up, delivered the message and then is terminated.
|
||||
Sin embargo, si vamos y miramos en Docker Desktop ahora no tenemos ningún contenedor en ejecución, pero sí tenemos un contenedor que utilizó el mensaje hola-mundo, lo que significa que apareció, entregó el mensaje y luego se terminó.
|
||||
|
||||

|
||||
|
||||
And for the last time, let's just go and check the images tab and see that we have a new hello-world image locally on our system, meaning that if we run the `docker run hello-world` command again in our terminal we would not have to pull anything unless a version changes.
|
||||
Y para terminar vamos a comprobar la pestaña images de nuevo en la que tendremos una nueva imagen hello-world localmente, lo que significa que si ejecutamos de nuevo el comando `docker run hello-world` en nuestro terminal no tendríamos que descargar nada a menos de que cambie la versión.
|
||||
|
||||

|
||||
|
||||
The message from the hello-world container set down the challenge of running something a little more ambitious.
|
||||
El mensaje del contenedor hello-world nos planteó el reto de ejecutar algo un poco más ambicioso.
|
||||
|
||||
Challenge Accepted!
|
||||
¡Reto aceptado!
|
||||
|
||||

|
||||
|
||||
In running `docker run -it ubuntu bash` in our terminal we are going to run a containerised version of Ubuntu well not a full copy of the Operating system. You can find out more about this particular image on [DockerHub](https://hub.docker.com/_/ubuntu)
|
||||
Al ejecutar `docker run -it ubuntu bash` en nuestro terminal vamos a ejecutar una versión en un contenedor de Ubuntu, que no es una copia completa del sistema operativo. Puedes encontrar más información sobre esta imagen en particular en [DockerHub](https://hub.docker.com/_/ubuntu)
|
||||
|
||||
You can see below when we run the command we now have an interactive prompt (`-it`) and we have a bash shell into our container.
|
||||
Puedes ver a continuación cuando ejecutamos el comando que ahora tenemos un símbolo del sistema interactivo (`-it`) y tenemos un shell bash en nuestro contenedor.
|
||||
|
||||

|
||||
|
||||
We have a bash shell but we don't have much more which is why this container image is less than 30MB.
|
||||
Tenemos una shell bash pero no tenemos mucho más, piensa que la imagen de este contenedor pesa menos de 30MB.
|
||||
|
||||

|
||||
|
||||
But we can still use this image and we can still install software using our apt package manager, we can update our container image and upgrade also.
|
||||
Pero con esta imagen podemos, por ejemplo:
|
||||
- Instalar todo el software que necesitemos usando nuestro gestor de paquetes apt.
|
||||
- Actualizar nuestra imagen de contenedor
|
||||
- Crear un nuevo contenedor a partir de esta imagen
|
||||
- Utilizar el contenedor interactivo para pruebas.
|
||||
|
||||
Y todo lo que imaginemos.
|
||||
|
||||

|
||||
|
||||
Or maybe we want to install some software into our container, I have chosen a really bad example here as pinta is an image editor and it's over 200MB but hopefully you get where I am going with this. This would increase the size of our container considerably but still, we are going to be in the MB and not in the GB.
|
||||
He instalado algún software en el contenedor, he elegido un ejemplo muy malo aquí ya que `pinta` es un editor de imágenes de más de 200 MB, pero espero que entiendas a dónde voy con esto. Esto aumentaría el tamaño de nuestro contenedor considerablemente pero aún así, vamos a estar en unos MB sin llegar al GB.
|
||||
|
||||

|
||||
|
||||
I wanted that to hopefully give you an overview of Docker Desktop and the not-so-scary world of containers when you break it down with simple use cases, we do need to cover some networking, security and other options we have vs just downloading container images and using them like this. By the end of the section, we want to have made something and uploaded it to our DockerHub repository and be able to deploy it.
|
||||
Quería que esto te diera una visión general de Docker Desktop y el mundo no tan aterrador de los contenedores cuando lo desglosas con casos de uso simples. Ahora tenemos que ver algo de redes, de seguridad y otras opciones mínimas que necesitamos de base.
|
||||
|
||||
## Resources
|
||||
## Recursos
|
||||
|
||||
- [TechWorld with Nana - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=3c-iBn73dDE)
|
||||
- [Programming with Mosh - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=pTFZFxd4hOI)
|
||||
- [Docker Tutorial for Beginners - What is Docker? Introduction to Containers](https://www.youtube.com/watch?v=17Bl31rlnRM&list=WL&index=128&t=61s)
|
||||
- [WSL 2 with Docker getting started](https://www.youtube.com/watch?v=5RQbdMn04Oc)
|
||||
- [En español] En los [apuntes](https://vergaracarmona.es/apuntes/) del traductor:
|
||||
- [Preparación de entorno de pruebas local para docker](https://vergaracarmona.es/preparacion-de-entorno-de-pruebas-local-para-docker/)
|
||||
- [Uso básico de docker](https://vergaracarmona.es/uso-basico-de-docker/)
|
||||
- [Una breve historia sobre contenedores](https://vergaracarmona.es/breve-historia-de-contenedores/)
|
||||
- [Desplegar con docker-compose los servicios Traefik y Portainer](https://vergaracarmona.es/desplegar-con-docker-compose-los-servicios-traefik-y-portainer/)
|
||||
|
||||
See you on [Day 45](day45.md)
|
||||
Nos vemos en el [Día 45](day45.md)
|
||||
|
@ -1,66 +1,67 @@
|
||||
## The anatomy of a Docker Image
|
||||
## La anatomía de una imagen Docker
|
||||
|
||||
In the last session, we covered some basics of how we can use Docker Desktop combined with DockerHub to deploy and run some verified images. A recap on what an image is, you won't forget things if I keep mentioning them.
|
||||
En la última sesión, vimos algunos aspectos básicos de cómo podemos utilizar Docker Desktop combinado con DockerHub para desplegar y ejecutar algunas imágenes verificadas. Una recapitulación sobre lo que es una imagen, no olvidarás cosas si sigo mencionándolas.
|
||||
|
||||
A Docker image is a read-only template that contains a set of instructions for creating a container that can run on the Docker platform. It provides a convenient way to package up applications and preconfigured server environments, which you can use for your private use or share publicly with other Docker users. Docker images are also the starting point for anyone using Docker for the first time.
|
||||
Una imagen Docker es una plantilla de sólo lectura que contiene un conjunto de instrucciones para crear un contenedor que se puede ejecutar en la plataforma Docker. Proporciona una forma práctica de empaquetar aplicaciones y entornos de servidor preconfigurados, que puedes utilizar para tu uso privado o compartir públicamente con otros usuarios de Docker. Las imágenes Docker son también el punto de partida para cualquiera que utilice Docker por primera vez.
|
||||
|
||||
What happens if we want to create our own Docker image? For us to do this we would create a Dockerfile. You saw how we could take that Ubuntu container image and we could add our software and we would have our container image with the software that we wanted and everything is good, however, if that container is shut down or thrown away then all those software updates and installations go away there is no repeatable version of what we had done. So that is great for showing off the capabilities but it doesn't help with the transport of images across multiple environments with the same set of software installed each time the container is run.
|
||||
¿Qué ocurre si queremos crear nuestra propia imagen Docker? Para ello crearíamos un Dockerfile. Ya viste cómo podríamos tomar esa imagen de contenedor Ubuntu y añadir nuestro software. Con lo que tendríamos nuestra imagen de contenedor con el software que queremos, sin embargo, si ese contenedor se apaga o se destruye todas esas actualizaciones de software y las instalaciones desaparecen, perdemos los cambios sin una versión repetible. Así que eso es genial para mostrar las capacidades, pero no ayuda con el transporte de imágenes a través de múltiples entornos con el mismo conjunto de software instalado cada vez que se ejecuta el contenedor, que es la potencia de docker.
|
||||
|
||||
### What is a Dockerfile
|
||||
### ¿Qué es un Dockerfile?
|
||||
|
||||
A dockerfile is a text file that contains commands you would normally execute manually to build a docker image. Docker can build images automatically by reading the instructions we have in our dockerfile.
|
||||
Un dockerfile es un archivo de texto que contiene comandos que normalmente ejecutarías manualmente para construir una imagen docker. Docker puede construir imágenes automáticamente leyendo las instrucciones que tenemos en nuestro dockerfile.
|
||||
|
||||
Each of the files that make up a docker image is known as a layer. these layers form a series of images, built on top of each other in stages. Each layer is dependent on the layer immediately below it. The order of your layers is key to the efficiency of the lifecycle management of your docker images.
|
||||
Cada uno de los archivos que componen una imagen docker se conoce como una capa. Estas capas forman una serie de imágenes, construidas unas sobre otras por etapas. Cada capa depende de la capa inmediatamente inferior. El orden de tus capas es clave para la eficiencia de la gestión del ciclo de vida de tus imágenes docker.
|
||||
|
||||
We should organise our layers that change most often as high in the stack as possible, this is because when you make changes to a layer in your image, Docker not only rebuilds that particular layer but all layers built from it. Therefore a change to a layer at the top involves the least amount of work to rebuild the entire image.
|
||||
Debemos organizar nuestras capas que cambian más a menudo lo más alto posible en la pila, esto se debe a que cuando se realizan cambios en una capa de la imagen, Docker no sólo reconstruye esa capa en particular, sino todas las capas construidas a partir de ella. Por lo tanto, un cambio en una capa en la parte superior implica la menor cantidad de trabajo para reconstruir toda la imagen.
|
||||
|
||||
Each time docker launches a container from an image (like we ran yesterday) it adds a writeable layer, known as the container layer. This stores all changes to the container throughout its runtime. This layer is the only difference between a live operational container and the source image itself. Any number of like-for-like containers can share access to the same underlying image while maintaining their state.
|
||||
Cada vez que docker lanza un contenedor desde una imagen (como hicimos ayer) añade una capa escribible, conocida como la capa del contenedor. Esto almacena todos los cambios en el contenedor a lo largo de su tiempo de ejecución. Esta capa es la única diferencia entre un contenedor operativo en vivo y la propia imagen de origen. Cualquier número de contenedores similares pueden compartir el acceso a la misma imagen subyacente, manteniendo su estado.
|
||||
|
||||
Back to the example, we used yesterday with the Ubuntu image. We could run that same command multiple times and on the first container we could go and install pinta and on the second we could install figlet with two different applications, different purposes, different sizes etc. Each container that we deployed shares the same image but not the same state and then that state is then gone when we remove the container.
|
||||
Volviendo al ejemplo que utilizamos ayer con la imagen de Ubuntu. Podríamos ejecutar ese mismo comando múltiples veces y en el primer contenedor podríamos instalar pinta y en el segundo podríamos instalar figlet con dos aplicaciones diferentes, diferentes propósitos, diferentes tamaños, etc. Cada contenedor que desplegamos comparte la misma imagen pero no el mismo estado y luego ese estado desaparece cuando eliminamos el contenedor.
|
||||
|
||||

|
||||
|
||||
Following the example above with the Ubuntu image, but also many other ready-built container images available on DockerHub and other third-party repositories. These images are generally known as the parent image. It is the foundation upon which all other layers are built and provides the basic building blocks for our container environments.
|
||||
Estas imágenes se conocen generalmente como la imagen padre. Es la base sobre la que se construyen todas las demás capas y proporciona los bloques de construcción básicos para nuestros entornos de contenedores.
|
||||
|
||||
Together with a set of individual layer files, a Docker image also includes an additional file known as a manifest. This is essentially a description of the image in JSON format and comprises information such as image tags, a digital signature, and details on how to configure the container for different types of host platforms.
|
||||
Junto con un conjunto de archivos de capas individuales, una imagen Docker también incluye un archivo adicional conocido como manifiesto. Se trata básicamente de una descripción de la imagen en formato JSON y contiene información como las etiquetas de la imagen, una firma digital y detalles sobre cómo configurar el contenedor para distintos tipos de plataformas host.
|
||||
|
||||

|
||||
|
||||
### How to create a docker image
|
||||
### Cómo crear una imagen docker
|
||||
|
||||
There are two ways we can create a docker image. We can do it a little on the fly with the process that we started yesterday, we pick our base image spin up that container, and install all of the software and dependencies that we wish to have on our container.
|
||||
Hay dos maneras en que podemos crear una imagen docker. Podemos hacerlo un poco sobre la marcha con el proceso que empezamos ayer, elegimos nuestra imagen base, giramos ese contenedor e instalamos todo el software y las dependencias que deseamos tener en nuestro contenedor.
|
||||
|
||||
Then we can use the `docker commit container name` then we have a local copy of this image under docker images and in our docker desktop images tab.
|
||||
Luego podemos usar el `docker commit container name` entonces tenemos una copia local de esta imagen bajo docker images y en nuestra pestaña docker desktop images.
|
||||
|
||||
Super simple, I would not recommend this method unless you want to understand the process, it is going to be very difficult to manage lifecycle management this way and a lot of manual configuration/reconfiguration. But it is the quickest and most simple way to build a docker image. Great for testing, troubleshooting, validating dependencies etc.
|
||||
Con este método no entenderás el proceso y será muy difícil manejar la gestión del ciclo de vida, además de tener un montón de configuraciones manuales/reconfiguraciones. Pero se entiende que es la forma más rápida y sencilla de construir una imagen docker. Aunque no sea recomendable puede resultar ideal para pruebas, resolución de problemas, validación de dependencias, etc.
|
||||
|
||||
The way we intend to build our image is through a dockerfile. Which gives us a clean, compact and repeatable way to create our images. Much easier lifecycle management and easy integration into Continous Integration and Continuous delivery processes. But as you might gather it is a little more difficult than the first mentioned process.
|
||||
La mejor práctica de construir imágenes es a través de un dockerfile. Lo que nos da una forma limpia, compacta y repetible para crear nuestras imágenes con unas pocas líneas. La gestión del ciclo de vida es mucho más fácil, así como la integración en procesos de CI/CD. Pero como se puede deducir, implica un aprendizaje. El saber no ocupa lugar.
|
||||
|
||||
Using the dockerfile method is much more in tune with real-world, enterprise-grade container deployments.
|
||||
El uso del método dockerfile está mucho más en sintonía con el mundo real, los despliegues de contenedores de nivel empresarial.
|
||||
|
||||
A dockerfile is a three-step process whereby you create the dockerfile and add the commands you need to assemble the image.
|
||||
Un dockerfile es un proceso de tres pasos mediante el cual se crea el dockerfile y se añaden los comandos necesarios para montar la imagen.
|
||||
|
||||
The following table shows some of the dockerfile statements we will be using or that you will most likely be using.
|
||||
La siguiente tabla muestra algunas de las sentencias dockerfile que utilizaremos o que probablemente necesitarás.
|
||||
|
||||
| Command | Purpose |
|
||||
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| FROM | To specify the parent image. |
|
||||
| WORKDIR | To set the working directory for any commands that follow in the Dockerfile. |
|
||||
| RUN | To install any applications and packages required for your container. |
|
||||
| COPY | To copy over files or directories from a specific location. |
|
||||
| ADD | As COPY, but also able to handle remote URLs and unpack compressed files. |
|
||||
| ENTRYPOINT | Command that will always be executed when the container starts. If not specified, the default is /bin/sh -c |
|
||||
| CMD | Arguments passed to the entrypoint. If ENTRYPOINT is not set (defaults to /bin/sh -c), the CMD will be the commands the container executes. |
|
||||
| EXPOSE | To define which port through which to access your container application. |
|
||||
| LABEL | To add metadata to the image. |
|
||||
| Comando | Propósito |
|
||||
| ---------- | --------------------------------------------------------------------------------------------------------------------------- |
|
||||
| FROM | Para especificar la imagen base. |
|
||||
| WORKDIR | Para establecer el directorio de trabajo para cualquier comando que siga en el Dockerfile. |
|
||||
| RUN | Para instalar las aplicaciones y paquetes necesarios para su contenedor. |
|
||||
| COPY | Para copiar archivos o directorios desde una ubicación específica. |
|
||||
| ADD | Como COPY, pero también capaz de manejar URLs remotas y desempaquetar archivos comprimidos. |
|
||||
| ENTRYPOINT | Comando que se ejecutará siempre cuando se inicie el contenedor. Si no se especifica, el valor por defecto es `/bin/sh -c` |
|
||||
| CMD | Argumentos pasados al punto de entrada. Si no se establece ENTRYPOINT, el CMD serán los comandos que ejecute el contenedor. |
|
||||
| EXPOSE | Para definir el puerto a través del cual acceder a su aplicación contenedora. |
|
||||
| LABEL | Para añadir metadatos a la imagen. |
|
||||
|
||||
Now we have the detail on how to build our first dockerfile we can create a working directory and create our dockerfile. I have created a working directory within this repository where you can see the files and folders I have to walk through. [Containers](Containers)
|
||||
Con estos detalles ya podemos crear un directorio de trabajo para construir el primer dockerfile. En este repositorio puedes encontrar el directorio de trabajo con los archivos y carpetas que veremos: [Containers](Containers)
|
||||
|
||||
In this directory, I am going to create a .dockerignore file similar to the .gitignore we used in the last section. This file will list any files that would otherwise be created during the Docker build process, which you want to exclude from the final build.
|
||||
En este directorio tendré el archivo `.dockerignore` que es similar al `.gitignore`, ¿Lo recuerdas?. Este archivo enumerará todos los archivos que se desean excluir en el proceso de construcción de Docker, para evitarlos en la construcción final.
|
||||
|
||||
Remember everything about containers is about being compact, as fast as possible with no bloat.
|
||||
Recuerda, en la creación de los contenedores es importante ser compacto, tan rápido como sea posible sin bloat (código hinchado).
|
||||
|
||||
Así que haremos un Dockerfile muy simple con el siguiente diseño:
|
||||
|
||||
I want to create a very simple Dockerfile with the below layout also can be found in the folder linked above.
|
||||
|
||||
```
|
||||
# Use the official Ubuntu 18.04 as base
|
||||
@ -71,33 +72,33 @@ RUN apt-get install -y nginx curl
|
||||
RUN rm -rf /var/lib/apt/lists/*
|
||||
```
|
||||
|
||||
Navigate to this directory in your terminal, and then run `docker build -t 90daysofdevops:0.1 .` we are using the `-t` and then setting an image name and tag.
|
||||
Es importante que le fichero se llame `Dockerfile` para que docker lo pueda reconocer. Cuando lo tengas ejecuta `docker build -t 90daysofdevops:0.1 .`. Fíjate que usamos el punto para que busque el Dockerfile en el directorio donde estamos ubicados. Con el anterior comando estamos usando la `-t` y luego estableciendo un nombre de imagen y una etiqueta.
|
||||
|
||||

|
||||
|
||||
Now we have created our image we can then go and run our image using Docker Desktop or we could use the docker command line. I have used Docker Desktop I have fired up a container and you can see that we have `curl` available to us in the cli of the container.
|
||||
Ahora que hemos creado nuestra imagen podemos ir y ejecutar nuestra imagen utilizando Docker Desktop o podríamos utilizar la línea de comandos docker. He utilizado Docker Desktop, he lanzado un contenedor y puedes ver que tenemos `curl` disponible para nosotros en el cli del contenedor.
|
||||
|
||||

|
||||
|
||||
Whilst in Docker Desktop there is also the ability to leverage the UI to do some more tasks with this new image.
|
||||
Mientras que en Docker Desktop también existe la posibilidad de aprovechar la interfaz de usuario para hacer algunas tareas más con esta nueva imagen.
|
||||
|
||||

|
||||
|
||||
We can inspect our image, in doing so you see very much of the dockerfile and the lines of code that we wanted to run within our container.
|
||||
Podemos inspeccionar nuestra imagen, al hacerlo se ve gran parte del dockerfile y las líneas de código que queríamos ejecutar dentro de nuestro contenedor.
|
||||
|
||||

|
||||
|
||||
We have a pull option, now this would fail for us because this image is not hosted anywhere so we would get that as an error. However, we do have a Push to hub which would enable us to push our image to DockerHub.
|
||||
Tenemos una opción pull, ahora esto fallaría porque la imagen no está alojada en ningún lugar por lo que obtendríamos un error. Sin embargo, tenemos una opción Push al hub que nos permitiría enviar nuestra imagen a nuestro registro DockerHub.
|
||||
|
||||
If you are using the same `docker build` we ran earlier then this would not work either, you would need the build command to be `docker build -t {{username}}/{{imagename}}:{{version}}`
|
||||
Si estás usando el mismo `docker build` que ejecutamos antes, esto tampoco funcionaría, necesitarías que el comando de compilación fuera `docker build -t {{username}}/{{imagename}}:{{version}}`.
|
||||
|
||||

|
||||
|
||||
Then if we go and take a look in our DockerHub repository you can see that we just pushed a new image. Now in Docker Desktop, we would be able to use that pull tab.
|
||||
A continuación, si echamos un vistazo a nuestro repositorio DockerHub se puede ver que acabamos de subir una nueva imagen. Ahora en Docker Desktop, seríamos capaces de utilizar la pestaña pull.
|
||||
|
||||

|
||||
|
||||
## Resources
|
||||
## Recursos
|
||||
|
||||
- [TechWorld with Nana - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=3c-iBn73dDE)
|
||||
- [Programming with Mosh - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=pTFZFxd4hOI)
|
||||
@ -105,5 +106,10 @@ Then if we go and take a look in our DockerHub repository you can see that we ju
|
||||
- [WSL 2 with Docker getting started](https://www.youtube.com/watch?v=5RQbdMn04Oc)
|
||||
- [Blog on gettng started building a docker image](https://stackify.com/docker-build-a-beginners-guide-to-building-docker-images/)
|
||||
- [Docker documentation for building an image](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/)
|
||||
- [En español] En los [apuntes](https://vergaracarmona.es/apuntes/) del traductor:
|
||||
- [Preparación de entorno de pruebas local para docker](https://vergaracarmona.es/preparacion-de-entorno-de-pruebas-local-para-docker/)
|
||||
- [Uso básico de docker](https://vergaracarmona.es/uso-basico-de-docker/)
|
||||
- [Una breve historia sobre contenedores](https://vergaracarmona.es/breve-historia-de-contenedores/)
|
||||
- [Desplegar con docker-compose los servicios Traefik y Portainer](https://vergaracarmona.es/desplegar-con-docker-compose-los-servicios-traefik-y-portainer/)
|
||||
|
||||
See you on [Day 46](day46.md)
|
||||
Nos vemos en el [Día 46](day46.md)
|
||||
|
@ -1,42 +1,40 @@
|
||||
## Docker Compose
|
||||
|
||||
The ability to run one container could be great if you have a self-contained image that has everything you need for your single use case, where things get interesting is when you are looking to build multiple applications between different container images. For example, if I had a website front end but required a backend database I could put everything in one container but better and more efficient would be to have its container for the database.
|
||||
La capacidad de ejecutar un contenedor puede ser muy grande si tienes una imagen auto-contenida que tiene todo lo que necesita para su caso de uso único. Donde las cosas se ponen interesantes es cuando estás buscando construir múltiples aplicaciones entre diferentes imágenes de contenedores. Por ejemplo, si tuvieras un sitio web front-end, pero requiere una base de datos back-end podría poner todo en un contenedor, aunque lo más eficiente es tener un contenedor propio para la base de datos.
|
||||
|
||||
This is where Docker compose comes in which is a tool that allows you to run more complex apps over multiple containers. With the benefit of being able to use a single file and command to spin up your application. The example I am going to the walkthrough in this post is from the [Docker QuickStart sample apps (Quickstart: Compose and WordPress)](https://docs.docker.com/samples/wordpress/).
|
||||
Aquí es donde entra en juego Docker compose, una herramienta que permite ejecutar aplicaciones más complejas en varios contenedores. Con el beneficio de ser capaz de utilizar un único archivo y comando para hacer girar su aplicación. El ejemplo que voy a mostrar en este día es de [Docker QuickStart sample apps (Quickstart: Compose and WordPress)](https://docs.docker.com/samples/wordpress/).
|
||||
|
||||
In this first example we are going to:
|
||||
Veremos cómo:
|
||||
|
||||
- Use Docker compose to bring up WordPress and a separate MySQL instance.
|
||||
- Use a YAML file which will be called `docker-compose.yml`
|
||||
- Build the project
|
||||
- Configure WordPress via a Browser
|
||||
- Shutdown and Clean up
|
||||
- Usar Docker Compose para traer WordPress y una instancia separada de MySQL.
|
||||
- Utilizar un archivo YAML que se llamará `docker-compose.yml`.
|
||||
- Construir el proyecto
|
||||
- Configurar WordPress a través de un navegador
|
||||
- Apagar y limpiar
|
||||
|
||||
### Install Docker Compose
|
||||
### Instalar Docker Compose
|
||||
|
||||
As mentioned Docker Compose is a tool, If you are on macOS or Windows then compose is included in your Docker Desktop installation. However, you might be wanting to run your containers on a Windows server host or Linux server and in which case you can install using these instructions [Install Docker Compose](https://docs.docker.com/compose/install/)
|
||||
Como se ha mencionado Docker Compose es una herramienta, si estás en macOS o Windows entonces compose está incluido en tu instalación de Docker Desktop, así como en las últimas versiones de docker para linux. Sin embargo, es posible que desees ejecutar tus contenedores con una versión de docker más antigua, en cuyo caso puedes instalarlo siguiendo estas instrucciones [Install Docker Compose](https://docs.docker.com/compose/install/)
|
||||
|
||||
To confirm we have `docker-compose` installed on our system we can open a terminal and simply type the above command.
|
||||
Para confirmar que tenemos `docker-compose` instalado en nuestro sistema podemos abrir un terminal y simplemente escribir el comando anterior. En la últimas versiones se está dejando de usar el guión medio: `docker compose`.
|
||||
|
||||

|
||||
|
||||
### Docker-Compose.yml (YAML)
|
||||
|
||||
The next thing to talk about is the docker-compose.yml which you can find in the container folder of the repository. But more importantly, we need to discuss YAML, in general, a little.
|
||||
Lo siguiente de lo que hablar es de como construir el fichero docker-compose.yml, pero realmente es más importante de que hablemos un poco de YAML, en general.
|
||||
|
||||
YAML could almost have its session as you are going to find it in so many different places. But for the most part
|
||||
YAML casi podría tener su propio día en #90DaysOfDevOps, ya que lo vas a encontrar en muchos lugares diferentes. Pero en general "YAML es un lenguaje de serialización de datos amigable para todos los lenguajes de programación", al igual que JSON o TOML.
|
||||
|
||||
"YAML is a human-friendly data serialization language for all programming languages."
|
||||
Se utiliza habitualmente para archivos de configuración y en algunas aplicaciones en las que se almacenan o transmiten datos. Sin duda te habrás encontrado con archivos XML que suelen ofrecer ese mismo archivo de configuración. YAML proporciona una sintaxis mínima pero está orientado a esos mismos casos de uso.
|
||||
|
||||
It is commonly used for configuration files and in some applications where data is being stored or transmitted. You have no doubt come across XML files that tend to offer that same configuration file. YAML provides a minimal syntax but is aimed at those same use cases.
|
||||
YAML no es un lenguaje de marcas, como se ha mencionado es un lenguaje de serialización y ha ido ganando popularidad en los últimos años. Las capacidades de serialización de objetos lo convierten en un sustituto viable de lenguajes como JSON.
|
||||
|
||||
YAML Ain't Markup Language (YAML) is a serialisation language that has steadily increased in popularity over the last few years. The object serialisation abilities make it a viable replacement for languages like JSON.
|
||||
El acrónimo YAML era la abreviatura de Yet Another Markup Language. Pero los mantenedores lo renombraron a YAML Ain't Markup Language para poner más énfasis en sus características orientadas a los datos.
|
||||
|
||||
The YAML acronym was shorthand for Yet Another Markup Language. But the maintainers renamed it to YAML Ain't Markup Language to place more emphasis on its data-oriented features.
|
||||
De todos modos, volvamos al archivo docker-compose.yml. Este es un archivo de configuración de lo que queremos hacer cuando se trata de múltiples contenedores que se despliegan en nuestro único sistema.
|
||||
|
||||
Anyway, back to the docker-compose.yml file. This is a configuration file of what we want to do when it comes to multiple containers being deployed on our single system.
|
||||
|
||||
Straight from the tutorial linked above you can see the contents of the file looks like this:
|
||||
Directamente desde el tutorial vinculado anteriormente se puede ver el contenido del archivo se parece a esto:
|
||||
|
||||
```
|
||||
version: "3.9"
|
||||
@ -72,95 +70,93 @@ volumes:
|
||||
wordpress_data: {}
|
||||
```
|
||||
|
||||
We declare a version and then a large part of this docker-compose.yml file is made up of our services, we have a DB service and a WordPress service. You can see each of those has an image defined with a version tag associated. We are now also introducing state into our configuration unlike our first walkthroughs, but now we are going to create volumes so we can store our databases there.
|
||||
Declaramos una versión y luego una gran parte de este archivo docker-compose.yml se compone de nuestros servicios, tenemos un servicio DB y un servicio de WordPress. Puedes ver que cada uno de ellos tiene una imagen definida con una etiqueta de versión asociada. Ahora también estamos introduciendo el estado en nuestra configuración a diferencia de nuestros primeros paseos, pero ahora vamos a crear volúmenes para que podamos almacenar nuestras bases de datos allí.
|
||||
|
||||
We then have some environmental variables such as passwords and usernames. These files can get very complicated but the YAML configuration file simplifies what these look like overall.
|
||||
Luego tenemos algunas variables de entorno como contraseñas y nombres de usuario. Estos archivos pueden llegar a ser muy complicados, pero el archivo de configuración YAML simplifica su aspecto general.
|
||||
|
||||
### Build the project
|
||||
### Construir el proyecto
|
||||
|
||||
Next up we can head back into our terminal and we can use some commands with our docker-compose tool. Navigate to your directory, where your docker-compose.yml file is located.
|
||||
A continuación podemos volver a nuestro terminal y podemos utilizar algunos comandos con nuestra herramienta docker-compose. Asegurate de estar ubicado en el directorio donde se encuentra el archivo docker-compose.yml.
|
||||
|
||||
From the terminal, we can simply run `docker-compose up -d` this will start the process of pulling those images and standing up your multi-container application.
|
||||
Desde el terminal, podemos simplemente ejecutar `docker-compose up -d` esto iniciará el proceso de extracción de las imágenes y la puesta en marcha de su aplicación multi-contenedor.
|
||||
|
||||
The `-d` in this command means detached mode, which means that the Run command is or will be in the background.
|
||||
La `-d` en este comando significa modo separado, lo que significa que el comando Run estará en segundo plano.
|
||||
|
||||

|
||||
|
||||
If we now run the `docker ps` command, you can see we have 2 containers running, one being WordPress and the other being MySQL.
|
||||
Si ahora ejecutamos el comando `docker ps`, podemos ver que tenemos 2 contenedores ejecutándose, uno es WordPress y el otro es MySQL.
|
||||
|
||||

|
||||
|
||||
Next, we can validate that we have WordPress up and running by opening a browser and going to `http://localhost:8000` and you should see the WordPress set-up page.
|
||||
A continuación, podemos verificar que tenemos WordPress funcionando abriendo un navegador y yendo a `http://localhost:8000`. Deberías ver la página de configuración de WordPress.
|
||||
|
||||

|
||||
|
||||
We can run through the setup of WordPress, and then we can start building our website as we see fit in the console below.
|
||||
Podemos ejecutar la configuración de WordPress, y luego podemos empezar a construir nuestro sitio web como mejor nos parezca en la consola de abajo.
|
||||
|
||||

|
||||
|
||||
If we then open a new tab and navigate to that same address we did before `http://localhost:8000` we will now see a simple default theme with our site title "90DaysOfDevOps" and then a sample post.
|
||||
Si a continuación abrimos una nueva pestaña y navegamos a la misma dirección que antes `http://localhost:8000` veremos ahora un sencillo tema por defecto con el título de nuestro sitio "90DaysOfDevOps" y a continuación un post de ejemplo.
|
||||
|
||||

|
||||
|
||||
Before we make any changes, open Docker Desktop and navigate to the volumes tab and here you will see two volumes associated with our containers, one for WordPress and one for DB.
|
||||
Antes de hacer ningún cambio, abre Docker Desktop y navega hasta la pestaña de volúmenes y aquí verás dos volúmenes asociados a nuestros contenedores, uno para WordPress y otro para DB.
|
||||
|
||||

|
||||
|
||||
My Current wordpress theme is "Twenty Twenty-Two" and I want to change this to "Twenty Twenty" Back in the dashboard we can make those changes.
|
||||
Mi tema actual de wordpress es "Twenty Twenty-Two" y quiero cambiarlo por "Twenty Twenty". De vuelta en el dashboard podemos hacer esos cambios.
|
||||
|
||||

|
||||
|
||||
I am also going to add a new post to my site, and here below you see the latest version of our new site.
|
||||
También voy a añadir un nuevo post a mi sitio, y aquí abajo se ve la última versión de nuestro nuevo sitio.
|
||||
|
||||

|
||||
|
||||
### Clean Up or not
|
||||
### Limpiar o no limpiar
|
||||
|
||||
If we were now to use the command `docker-compose down` this would bring down our containers. But will leave our volumes in place.
|
||||
Si ahora usáramos el comando `docker-compose down` esto bajaría nuestros contenedores. Pero dejará nuestros volúmenes en su sitio.
|
||||
|
||||

|
||||
|
||||
We can just confirm in Docker Desktop that our volumes are still there though.
|
||||
Podemos confirmar en Docker Desktop que nuestros volúmenes siguen ahí.
|
||||
|
||||

|
||||
|
||||
If we then want to bring things back up then we can issue the `docker up -d` command from within the same directory and we have our application back up and running.
|
||||
Si luego queremos volver a poner las cosas en marcha, podemos ejecutar el comando `docker up -d` desde el mismo directorio y ya tenemos nuestra aplicación de nuevo en marcha.
|
||||
|
||||

|
||||
|
||||
We then navigate in our browser to that same address of `http://localhost:8000` and notice that our new post and our theme change are all still in place.
|
||||
A continuación, navegamos en nuestro navegador a la misma dirección de `http://localhost:8000` y observamos que nuestro nuevo post y nuestro cambio de tema siguen en su lugar.
|
||||
|
||||

|
||||
|
||||
If we want to get rid of the containers and those volumes then issuing the `docker-compose down --volumes` will also destroy the volumes.
|
||||
Si queremos deshacernos de los contenedores y de esos volúmenes, al ejecutar `docker-compose down --volumes` también destruiremos los volúmenes.
|
||||
|
||||

|
||||
|
||||
Now when we use `docker-compose up -d` again we will be starting, however, the images will still be local on our system so you won't need to re-pull them from the DockerHub repository.
|
||||
Ahora cuando usemos `docker-compose up -d` de nuevo estaremos arrancando, sin embargo, las imágenes seguirán siendo locales en nuestro sistema por lo que no será necesario volver a extraerlas del repositorio de DockerHub.
|
||||
|
||||
I know that when I started diving into docker-compose and its capabilities I was then confused as to where this sits alongside or with Container Orchestration tools such as Kubernetes, well everything we have done here in this short demo is focused on one host we have WordPress and DB running on the local desktop machine. We don't have multiple virtual machines or multiple physical machines, we also can't easily scale up and down the requirements of our application.
|
||||
Sé que cuando empecé a bucear en docker-compose y sus capacidades estaba confundido en cuanto las diferencias con otras herramientas de orquestación de contenedores como Kubernetes. Por ahora lo que hemos hecho en esta breve demostración se centra en un host que tenemos WordPress y DB se ejecuta en la máquina de escritorio local. No tenemos múltiples máquinas virtuales o múltiples máquinas físicas, tampoco podemos escalar fácilmente hacia arriba y hacia abajo los requisitos de nuestra aplicación.
|
||||
|
||||
Our next section is going to cover Kubernetes but we have a few more days of Containers in general first.
|
||||
En la sección de Kubernetes despejaremos algunas dudas, por ahora tenemos algunos días más de Contenedores en general.
|
||||
|
||||
This is also a great resource for samples of docker-compose applications with multiple integrations. [Awesome-Compose](https://github.com/docker/awesome-compose)
|
||||
Este es también un gran recurso para muestras de aplicaciones docker-compose con múltiples integraciones. [Awesome-Compose](https://github.com/docker/awesome-compose)
|
||||
|
||||
In the above repository, there is a great example which will deploy an Elasticsearch, Logstash, and Kibana (ELK) in single-node.
|
||||
|
||||
I have uploaded the files to the [Containers folder](2022/Days/Containers/elasticsearch-logstash-kibana/) When you have this folder locally, navigate there and you can simply use `docker-compose up -d`
|
||||
En el repositorio hay un gran ejemplo que desplegará un Elasticsearch, Logstash, y Kibana (ELK) en single-node. Podrás encontrar los ficheros en la carpeta [Containers](2022/Days/Containers/elasticsearch-logstash-kibana/). Si tienes esta carpeta en local, tan solo navega hasta allí y usa `docker-compose up -d`.
|
||||
|
||||

|
||||
|
||||
We can then check we have those running containers with `docker ps`
|
||||
Podrás comprobar que tenemos esos contenedores en ejecución con `docker ps`. Estos mantendrán el mismo entorno que en mi pc.
|
||||
|
||||

|
||||
|
||||
Now we can open a browser for each of the containers:
|
||||
Ahora podemos abrir un navegador para cada uno de los contenedores:
|
||||
|
||||

|
||||
|
||||
To remove everything we can use the `docker-compose down` command.
|
||||
Como en la anterior práctica, para eliminar todo podemos usar el comando `docker-compose down`.
|
||||
|
||||
## Resources
|
||||
## Recursos
|
||||
|
||||
- [TechWorld with Nana - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=3c-iBn73dDE)
|
||||
- [Programming with Mosh - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=pTFZFxd4hOI)
|
||||
@ -169,5 +165,11 @@ To remove everything we can use the `docker-compose down` command.
|
||||
- [Blog on getting started building a docker image](https://stackify.com/docker-build-a-beginners-guide-to-building-docker-images/)
|
||||
- [Docker documentation for building an image](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/)
|
||||
- [YAML Tutorial: Everything You Need to Get Started in Minute](https://www.cloudbees.com/blog/yaml-tutorial-everything-you-need-get-started)
|
||||
- [En español] En los [apuntes](https://vergaracarmona.es/apuntes/) del traductor:
|
||||
- [Preparación de entorno de pruebas local para docker](https://vergaracarmona.es/preparacion-de-entorno-de-pruebas-local-para-docker/)
|
||||
- [Uso básico de docker](https://vergaracarmona.es/uso-basico-de-docker/)
|
||||
- [Una breve historia sobre contenedores](https://vergaracarmona.es/breve-historia-de-contenedores/)
|
||||
- [Desplegar con docker-compose los servicios Traefik y Portainer](https://vergaracarmona.es/desplegar-con-docker-compose-los-servicios-traefik-y-portainer/)
|
||||
- [Comparando TOML, JSON y YAML](https://vergaracarmona.es/comparando-toml-json-y-yaml/)
|
||||
|
||||
See you on [Day 47](day47.md)
|
||||
Nos vemos en el [Día 47](day47.md)
|
||||
|
@ -1,92 +1,92 @@
|
||||
## Docker Networking & Security
|
||||
|
||||
During this container session so far we have made things happen but we have not looked at how things have worked behind the scenes either from a networking point of view also we have not touched on security, that is the plan for this session.
|
||||
Hasta ahora hemos visto como desplegar contenedores, pero no sabemos aún cómo funcionan las redes y cuál es la seguridad mínima que necesitan. Cómo bien anuncia el título, este es el plan de hoy.
|
||||
|
||||
### Docker Networking Basics
|
||||
|
||||
Open a terminal, and type the command `docker network` this is the main command for configuring and managing container networks.
|
||||
Vamos al grano, abre un terminal y escribe el comando `docker network`. Este es el comando principal para configurar y gestionar redes de los contenedores.
|
||||
|
||||
From the below, you can see this is how we can use the command, and all of the sub-commands available. We can create new networks, list existing ones, and inspect and remove networks.
|
||||
Puedes ver como podemos usar el comando y todos los sub-comandos disponibles. Podemos crear nuevas redes, listar las existentes, inspeccionarlas y eliminarlas.
|
||||
|
||||

|
||||
|
||||
Let's take a look at the existing networks we have since our installation, so the out-of-box Docker networking looks like using the `docker network list` command.
|
||||
Vamos a echar un vistazo a las redes existentes que tenemos desde nuestra instalación usando el comando `docker network list`.
|
||||
|
||||
Each network gets a unique ID and NAME. Each network is also associated with a single driver. Notice that the "bridge" network and the "host" network have the same name as their respective drivers.
|
||||
Cada red tiene un ID y un NOMBRE únicos. Cada red también está asociada a un único controlador. Observa que la red "bridge" y la red "host" tienen el mismo nombre que sus respectivos controladores.
|
||||
|
||||

|
||||
|
||||
Next, we can take a deeper look into our networks with the `docker network inspect` command.
|
||||
A continuación, podemos echar un vistazo más profundo a nuestras redes con el comando `docker network inspect`.
|
||||
|
||||
With me running `docker network inspect bridge` I can get all the configuration details of that specific network name. This includes name, ID, drivers, connected containers and as you can see quite a lot more.
|
||||
Si ejecuto `docker network inspect bridge` puedo obtener todos los detalles de configuración de ese nombre de red específico. Esto incluye nombre, ID, controladores, contenedores conectados y mucho más como puedes ver.
|
||||
|
||||

|
||||
|
||||
### Docker: Bridge Networking
|
||||
|
||||
As you have seen above a standard installation of Docker Desktop gives us a pre-built network called `bridge` If you look back up to the `docker network list` command, you will see that the network called bridge is associated with the `bridge` driver. Just because they have the same name doesn't they are the same thing. Connected but not the same thing.
|
||||
Como has visto arriba una instalación estándar de Docker Desktop nos da una red pre-construida llamada `bridge` Si vuelves a mirar el comando `docker network list`, verás que la red llamada bridge está asociada con el driver `bridge`. Que tengan el mismo nombre no quiere decir que sean la misma cosa. Están conectadas pero no son lo mismo.
|
||||
|
||||
The output above also shows that the bridge network is scoped locally. This means that the network only exists on this Docker host. This is true of all networks using the bridge driver - the bridge driver provides single-host networking.
|
||||
La salida anterior también muestra que la red bridge tiene un ámbito local. Esto significa que la red sólo existe en este host Docker. Esto es cierto para todas las redes que utilizan el controlador bridge que proporciona la red de un solo host.
|
||||
|
||||
All networks created with the bridge driver are based on a Linux bridge (a.k.a. a virtual switch).
|
||||
Todas las redes creadas con el controlador bridge se basan en un bridge Linux (también conocido como conmutador virtual).
|
||||
|
||||
### Connect a Container
|
||||
### Conectar un Contenedor
|
||||
|
||||
By default the bridge network is assigned to new containers, meaning unless you specify a network all containers will be connected to the bridge network.
|
||||
Por defecto la red bridge es asignada a los nuevos contenedores, lo que significa que a menos que especifiques una red todos los contenedores serán conectados a la red bridge.
|
||||
|
||||
Let's create a new container with the command `docker run -dt ubuntu sleep infinity`
|
||||
Vamos a crear un nuevo contenedor con el comando `docker run -dt ubuntu sleep infinity`.
|
||||
|
||||
The sleep command above is just going to keep the container running in the background so we can mess around with it.
|
||||
El comando sleep de arriba sólo va a mantener el contenedor funcionando en segundo plano para que podamos trastear con él.
|
||||
|
||||

|
||||
|
||||
If we then check our bridge network with `docker network inspect bridge` you will see that we have a container matching what we have just deployed because we did not specify a network.
|
||||
Si a continuación comprobamos nuestra red bridge con `docker network inspect bridge` veremos que tenemos un contenedor que coincide con lo que acabamos de desplegar porque no hemos especificado ninguna red.
|
||||
|
||||

|
||||
|
||||
We can also dive into the container using `docker exec -it 3a99af449ca2 bash` you will have to use `docker ps` to get your container ID.
|
||||
También podemos bucear en el contenedor usando `docker exec -it 3a99af449ca2 bash`, tendrás que usar `docker ps` para obtener el ID del contenedor que has creado.
|
||||
|
||||
From here our image doesn't have anything to ping so we need to run the following command.`apt-get update && apt-get install -y iputils-ping` then ping an external interfacing address. `ping -c5 www.90daysofdevops.com`
|
||||
En principio, nuestra imagen no tiene nada con lo que hacer ping, así que tenemos que ejecutar el siguiente comando: `apt-get update && apt-get install -y iputils-ping`. Luego vamos a hacer ping a una dirección de interfaz externa, a ver que pasa: `ping -c5 www.90daysofdevops.com`
|
||||
|
||||

|
||||
|
||||
To clear this up we can run `docker stop 3a99af449ca2` again and use `docker ps` to find your container ID but this will remove our container.
|
||||
Ahora podemos parar el contenedor con `docker stop 3a99af449ca2` y utilizar `docker ps` para buscar su ID de contenedor, veremops que esto eliminará nuestro contenedor.
|
||||
|
||||
### Configure NAT for external connectivity
|
||||
### Configurar NAT para conectividad externa
|
||||
|
||||
In this step, we'll start a new NGINX container and map port 8080 on the Docker host to port 80 inside of the container. This means that traffic that hits the Docker host on port 8080 will be passed on to port 80 inside the container.
|
||||
En este paso, iniciaremos un nuevo contenedor NGINX y asignaremos el puerto 8080 en el host Docker al puerto 80 dentro del contenedor. Esto significa que el tráfico que llega al host Docker en el puerto 8080 pasará al puerto 80 dentro del contenedor.
|
||||
|
||||
Start a new container based on the official NGINX image by running `docker run --name web1 -d -p 8080:80 nginx`
|
||||
Inicie un nuevo contenedor basado en la imagen oficial de NGINX ejecutando `docker run --name web1 -d -p 8080:80 nginx`.
|
||||
|
||||

|
||||
|
||||
Review the container status and port mappings by running `docker ps`
|
||||
Revise el estado del contenedor y las asignaciones de puertos ejecutando `docker ps`.
|
||||
|
||||

|
||||
|
||||
The top line shows the new web1 container running NGINX. Take note of the command the container is running as well as the port mapping - `0.0.0.0:8080->80/tcp` maps port 8080 on all host interfaces to port 80 inside the web1 container. This port mapping is what effectively makes the container's web service accessible from external sources (via the Docker hosts IP address on port 8080).
|
||||
La línea superior muestra el nuevo contenedor web1 ejecutando NGINX. Fíjate en el output del contenedor en la asignación de puertos - `0.0.0.0:8080->80/tcp`. Asigna el puerto 8080 en todas las interfaces del host al puerto 80 dentro del contenedor web1. Esta asignación de puertos es lo que hace que el servicio web del contenedor sea accesible desde fuentes externas (a través de la dirección IP de los hosts Docker en el puerto 8080).
|
||||
|
||||
Now we need our IP address for our actual host, we can do this by going into our WSL terminal and using the `IP addr` command.
|
||||
Ahora necesitamos nuestra dirección IP para nuestro host anfitrión, podemos hacer esto yendo a nuestro terminal WSL y utilizando el comando `ip addr`.
|
||||
|
||||

|
||||
|
||||
Then we can take this IP and open a browser and head to `http://172.25.218.154:8080/` Your IP might be different. This confirms that NGINX is accessible.
|
||||
Entonces podemos tomar esta IP y abrir un navegador y dirigirnos a `http://172.25.218.154:8080/` (Ten en cuenta que tiene que se tu IP, seguramente sea diferente). Esto confirma que NGINX es accesible.
|
||||
|
||||

|
||||
|
||||
I have taken these instructions from this site from way back in 2017 DockerCon but they are still relevant today. However, the rest of the walkthrough goes into Docker Swarm and I am not going to be looking into that here. [Docker Networking - DockerCon 2017](https://github.com/docker/labs/tree/master/dockercon-us-2017/docker-networking)
|
||||
Estas instrucciones se han sacado de "Docker Networking - DockerCon 2017". Aun siendo de la DockerCon 2017 sigue estando vigente a día de hoy. En ese tutorial siguen explicando otros conceptos de redes incluyyendo Docker Swarm, pero no lo veremos aquí. No obstante, aquí tenéis el enlace por si queréis echarle un vistazo: [Docker Networking - DockerCon 2017](https://github.com/docker/labs/tree/master/dockercon-us-2017/docker-networking)
|
||||
|
||||
### Securing your containers
|
||||
### Asegurando tus contenedores
|
||||
|
||||
Containers provide a secure environment for your workloads vs a full server configuration. They offer the ability to break up your applications into much smaller, loosely coupled components each isolated from one another which helps reduce the attack surface overall.
|
||||
Los contenedores proporcionan un entorno seguro para las cargas de trabajo frente a una configuración de servidor completa. Ofrecen la capacidad de dividir aplicaciones en componentes mucho más pequeños y poco acoplados, cada uno aislado del otro, lo que ayuda a reducir la superficie de ataque en general.
|
||||
|
||||
But they are not immune from hackers that are looking to exploit systems. We still need to understand the security pitfalls of the technology and maintain best practices.
|
||||
Pero no son inmunes a los hackers que buscan explotar los sistemas. Todavía tenemos que entender las trampas de seguridad de la tecnología y mantener las mejores prácticas.
|
||||
|
||||
### Move away from root permission
|
||||
### Alejarse del permiso de root
|
||||
|
||||
All of the containers we have deployed have been using the root permission to the process within your containers. This means they have full administrative access to your container and host environments. Now to walk through we knew these systems were not going to be up and running for long. But you saw how easy it was to get up and running.
|
||||
Todos los contenedores que hemos desplegado han estado utilizando el permiso root al proceso dentro de sus contenedores. Esto significa que tienen pleno acceso administrativo a su contenedor y entornos de acogida. Ahora a recorrer sabíamos que estos sistemas no iban a estar en funcionamiento por mucho tiempo. Pero ya has visto lo fácil que es ponerlo en marcha.
|
||||
|
||||
We can add a few steps to our process to enable non-root users to be our preferred best practice. When creating our dockerfile we can create user accounts. You can find this example also in the containers folder in the repository.
|
||||
Podemos añadir algunos pasos a nuestro proceso para permitir que los usuarios no root sean quienes administren el contenedor, siguiendo así una buena práctica de seguridad. Al crear nuestro dockerfile podemos crear cuentas de usuario. Puedes encontrar este ejemplo también en la carpeta [containers](containers) del repositorio.
|
||||
|
||||
```
|
||||
# Use the official Ubuntu 18.04 as base
|
||||
@ -96,27 +96,27 @@ RUN groupadd -g 1000 basicuser && useradd -r -u 1000 -g basicuser basicuser
|
||||
USER basicuser
|
||||
```
|
||||
|
||||
We can also use `docker run --user 1009 ubuntu` the Docker run command overrides any user specified in your Dockerfile. Therefore, in the following example, your container will always run with the least privilege—provided user identifier 1009 also has the lowest permission level.
|
||||
También podemos usar `docker run --user 1009 ubuntu` el comando Docker run anula cualquier usuario especificado en tu Dockerfile. Por lo tanto, en el siguiente ejemplo, su contenedor siempre se ejecutará con el identificador de usuario 1009 con menos privilegios, con un nivel de permisos más bajo.
|
||||
|
||||
However, this method doesn’t address the underlying security flaw of the image itself. Therefore it’s better to specify a non-root user in your Dockerfile so your containers always run securely.
|
||||
Sin embargo, este método no aborda el fallo de seguridad subyacente de la propia imagen. Por lo tanto, es mejor especificar un usuario no root en tu Dockerfile para que tus contenedores siempre se ejecuten de forma segura.
|
||||
|
||||
### Private Registry
|
||||
### Registro Privado
|
||||
|
||||
Another area we have used heavily in public registries in DockerHub, with a private registry of container images set up by your organisation means that you can host where you wish or there are managed services for this as well, but all in all, this gives you complete control of the images available for you and your team.
|
||||
Hasta ahora hemos utilizado registros públicos en DockerHub. Con un registro privado de imágenes de contenedores establecido por la organización podremos evitar problemas de curiosos. Se puede alojar la imágen donde desees, existen registros OpenSources y también administrados por terceros. Esto da un control completo de las imágenes disponibles para el equipo de trabajo.
|
||||
|
||||
DockerHub is great to give you a baseline, but it's only going to be providing you with a basic service where you have to put a lot of trust into the image publisher.
|
||||
DockerHub está muy bien para darte una base, pero sólo te va a proporcionar un servicio básico en el que tienes que confiar mucho en el editor de imágenes.
|
||||
|
||||
### Lean & Clean
|
||||
### Liviano y limpio
|
||||
|
||||
Have mentioned this throughout, although not related to security. But the size of your container can also affect security in terms of attack surface if you have resources you do not use in your application then you do not need them in your container.
|
||||
He mencionado esto en todo momento sin relacionarlo con la seguridad. Pero el tamaño del contenedor puede afectar a la seguridad en términos de superficie de ataque. Si tienes recursos que no usas en tu aplicación entonces no los necesitas en tu contenedor, los puedes eliminar.
|
||||
|
||||
This is also my major concern with pulling the `latest` images because that can bring a lot of bloat to your images as well. DockerHub does show the compressed size for each of the images in a repository.
|
||||
Esta es mi mayor preocupación con la extracción de las imágenes `latest` porque eso puede traer un montón de bloat (hinchazón) a sus imágenes. DockerHub muestra el tamaño comprimido para cada una de las imágenes en un repositorio.
|
||||
|
||||
Checking `docker image` is a great command to see the size of your images.
|
||||
En definitiva, busca siempre de que tus imágenes sean lo más pequeñas posibles. `docker image` es el comando para comprobar el tamaño de las imágenes en local.
|
||||
|
||||

|
||||
|
||||
## Resources
|
||||
## Recursos
|
||||
|
||||
- [TechWorld with Nana - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=3c-iBn73dDE)
|
||||
- [Programming with Mosh - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=pTFZFxd4hOI)
|
||||
@ -125,5 +125,10 @@ Checking `docker image` is a great command to see the size of your images.
|
||||
- [Blog on getting started building a docker image](https://stackify.com/docker-build-a-beginners-guide-to-building-docker-images/)
|
||||
- [Docker documentation for building an image](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/)
|
||||
- [YAML Tutorial: Everything You Need to Get Started in Minute](https://www.cloudbees.com/blog/yaml-tutorial-everything-you-need-get-started)
|
||||
- [En español] En los [apuntes](https://vergaracarmona.es/apuntes/) del traductor:
|
||||
- [Preparación de entorno de pruebas local para docker](https://vergaracarmona.es/preparacion-de-entorno-de-pruebas-local-para-docker/)
|
||||
- [Uso básico de docker](https://vergaracarmona.es/uso-basico-de-docker/)
|
||||
- [Una breve historia sobre contenedores](https://vergaracarmona.es/breve-historia-de-contenedores/)
|
||||
- [Desplegar con docker-compose los servicios Traefik y Portainer](https://vergaracarmona.es/desplegar-con-docker-compose-los-servicios-traefik-y-portainer/)
|
||||
|
||||
See you on [Day 48](day48.md)
|
||||
Nos vemos en el [Día 48](day48.md)
|
||||
|
@ -1,96 +1,94 @@
|
||||
## Alternatives to Docker
|
||||
## Alternativas a Docker
|
||||
|
||||
I did say at the very beginning of this section that we were going to be using Docker, simply because resource wise there is so much and the community is very big, but also this was really where the indents to making containers popular came from. I would encourage you to go and watch some of the history around Docker and how it came to be, I found it very useful.
|
||||
Dije al principio de esta sección que íbamos a usar Docker, simplemente porque tiene muchos recursos ya que la comunidad es muy grande, pero también porque fue de aquí de donde vinieron los impulsos para popularizar los contenedores. Te animo a que veas algo de la [historia de los contenedores](https://vergaracarmona.es/breve-historia-de-contenedores/), me pareció muy útil para entender todos los conceptos que trae.
|
||||
|
||||
But as I have alluded to there are other alternatives to Docker. If we think about what Docker is and what we have covered. It is a platform for developing, testing, deploying, and managing applications.
|
||||
Pero como he aludido existen alternativas a Docker si pensamos en lo que es Docker y de qué se ocupa: una plataforma para desarrollar, probar, desplegar y gestionar aplicaciones.
|
||||
|
||||
I want to highlight a few alternatives to Docker that you might or will in the future see out in the wild.
|
||||
Quiero destacar algunas alternativas a Docker que podrías ver o verás en el futuro.
|
||||
|
||||
### Podman
|
||||
|
||||
What is Podman? Podman is a daemon-less container engine for developing, managing, and running OCI Containers on your Linux System. Containers can either be run as root or in rootless mode.
|
||||
¿Qué es Podman? [Podman](https://podman.io/) es un motor de contenedores sin demonio para desarrollar, gestionar y ejecutar contenedores OCI en tu sistema Linux. Los contenedores se pueden ejecutar como root o en modo rootless.
|
||||
|
||||
I am going to be looking at this from a Windows point of view but know that like Docker there is no requirement for virtualisation there as it will use the underlying OS which is cannot do in the Windows world.
|
||||
Al igual que Docker no hay ningún requisito para la virtualización, pero utilizará el sistema operativo subyacente y por eso no se puede ejecutar en Windows a pelo. Se puede ejecutar bajo WSL2 pero no es tan visual como la experiencia con Docker Desktop, que está hecho para quienes usan el ratón.
|
||||
|
||||
Podman can be run under WSL2 although not as sleek as the experience with Docker Desktop. There is also a Windows remote client where you can connect to a Linux VM where your containers will run.
|
||||
|
||||
My Ubuntu on WSL2 is the 20.04 release. Following the next steps will enable you to install Podman on your WSL instance.
|
||||
También hay un cliente remoto de Windows donde se puede conectar a una máquina virtual Linux donde se ejecutarán los contenedores. Con el Ubuntu en WSL2 de la versión 20.04, siguiendo los siguientes pasos podrás instalar Podman en tu instancia WSL.
|
||||
|
||||
```Shell
|
||||
echo "deb https://download.opensuse.org/repositories/devel:/kubic:/libcontainers:/stable/xUbuntu_20.04/ /" |
|
||||
sudo tee /etc/apt/sources.list.d/devel:kubic:libcontainers:stable.list
|
||||
```
|
||||
|
||||
Add the GPG Key
|
||||
Para añadir la clave GPG:
|
||||
|
||||
```Shell
|
||||
curl -L "https://download.opensuse.org/repositories/devel:/kubic:\
|
||||
/libcontainers:/stable/xUbuntu_20.04/Release.key" | sudo apt-key add -
|
||||
```
|
||||
|
||||
Run a system update and upgrade with the `sudo apt-get update && sudo apt-get upgrade` command. Finally, we can install podman using `sudo apt install podman`
|
||||
Ejecute una actualización del sistema con `sudo apt-get update && sudo apt-get upgrade`. Por último, podemos instalar podman usando `sudo apt install podman`. Espero que os déis cuenta de la incomodidad que es usar un sistema operativo que no sea Linux para trabajar con contenedores. Suele pasar con la mayoría de aplicaciones de Sistemas o desarrollo. Así como hemos visto la optimización de los contenedores, deberéis tener en cuenta que el sistema operativo anfitrión también es importante.
|
||||
|
||||
We can now use a lot of the same commands we have been using for docker, note that we do not have that nice docker desktop UI. You can see below I used `podman images` and I have nothing after installation then I used `podman pull ubuntu` to pull down the ubuntu container image.
|
||||
Ahora podemos utilizar muchos de los mismos comandos que hemos estado utilizando para docker. Como puedes ver a continuación, he utilizado `podman images` y no tengo nada después de la instalación. Luego, he utilizado `podman pull ubuntu` para bajar la imagen del contenedor ubuntu.
|
||||
|
||||

|
||||
|
||||
We can then run our Ubuntu image using `podman run -dit ubuntu` and `podman ps` to see our running image.
|
||||
Podemos ejecutar nuestra imagen de Ubuntu usando `podman run -dit ubuntu` y `podman ps` para ver nuestra imagen en ejecución.
|
||||
|
||||

|
||||
|
||||
To then get into that container we can run `podman attach dazzling_darwin` your container name will most likely be different.
|
||||
Para entrar en ese contenedor podemos ejecutar `podman attach dazzling_darwin` el nombre de tu contenedor seguramente será diferente.
|
||||
|
||||

|
||||
|
||||
If you are moving from docker to podman it is also common to change your config file to have `alias docker=podman` that way any command you run with docker will use podman.
|
||||
Si te estás moviendo de docker a podman también es común cambiar el archivo de configuración para tener `alias docker=podman` de esa manera cualquier comando que ejecute con docker utilizará podman.
|
||||
|
||||
### LXC
|
||||
|
||||
LXC is a containerisation engine that enables users again to create multiple isolated Linux container environments. Unlike Docker, LXC acts as a hypervisor for creating multiple Linux machines with separate system files, and networking features. Was around before Docker and then made a short comeback due to Docker's shortcomings.
|
||||
LXC es un motor de contenedorización que permite a los usuarios crear múltiples entornos de contenedores Linux aislados. A diferencia de Docker, LXC actúa como un hipervisor para crear múltiples máquinas Linux con archivos de sistema separados, y características de red. Existió antes que Docker y volvió a aparecer debido a las deficiencias de Docker.
|
||||
|
||||
LXC is as lightweight though as docker and easily deployed.
|
||||
Sin embargo, LXC es tan ligero como Docker y fácil de desplegar.
|
||||
|
||||
### Containerd
|
||||
|
||||
A standalone container runtime. Containerd brings simplicity and robustness as well as of course portability. Containerd was formerly a tool that runs as part of Docker container services until Docker decided to graduate its components into standalone components.
|
||||
Un runtime de contenedor independiente. Containerd aporta simplicidad y robustez, así como, por supuesto, portabilidad. Containerd era antes una herramienta que se ejecutaba como parte de los servicios de contenedores Docker hasta que Docker decidió graduar sus componentes en componentes independientes.
|
||||
|
||||
A project in the Cloud Native Computing Foundation, placing it in the same class as popular container tools like Kubernetes, Prometheus, and CoreDNS.
|
||||
Es un proyecto de la Cloud Native Computing Foundation, lo que lo sitúa en la misma clase que herramientas de contenedores populares como Kubernetes, Prometheus y CoreDNS. De hecho, a partir de la versión 1.11, Kubernetes utiliza containerd como su runtime de contenedor predeterminado mientras que antes era Docker.
|
||||
|
||||
### Other Docker tooling
|
||||
### Otras herramientas Docker
|
||||
|
||||
We could also mention toolings and options around Rancher, and VirtualBox but we can cover them in more detail another time.
|
||||
También podríamos mencionar herramientas y opciones alrededor de Rancher, y VirtualBox pero podemos cubrirlas en más detalle en otra ocasión.
|
||||
|
||||
[**Gradle**](https://gradle.org/)
|
||||
|
||||
- Build scans allow teams to collaboratively debug their scripts and track the history of all builds.
|
||||
- Execution options give teams the ability to continuously build so that whenever changes are inputted, the task is automatically executed.
|
||||
- The custom repository layout gives teams the ability to treat any file directory structure as an artefact repository.
|
||||
- Las exploraciones de construcción permiten a los equipos depurar sus scripts de forma colaborativa y realizar un seguimiento del historial de todas las construcciones.
|
||||
- Las opciones de ejecución dan a los equipos la capacidad de construir continuamente de modo que cada vez que se introducen cambios, la tarea se ejecuta automáticamente.
|
||||
- El diseño personalizado del repositorio ofrece a los equipos la posibilidad de tratar cualquier estructura de directorios de archivos como un repositorio de artefactos.
|
||||
|
||||
[**Packer**](https://packer.io/)
|
||||
|
||||
- Ability to create multiple machine images in parallel to save developer time and increase efficiency.
|
||||
- Teams can easily debug builds using Packer’s debugger, which inspects failures and allows teams to try out solutions before restarting builds.
|
||||
- Support with many platforms via plugins so teams can customize their builds.
|
||||
- Posibilidad de crear varias imágenes de máquina en paralelo para ahorrar tiempo a los desarrolladores y aumentar la eficacia.
|
||||
- Los equipos pueden depurar fácilmente las compilaciones mediante el depurador de Packer, que inspecciona los fallos y permite a los equipos probar soluciones antes de reiniciar las compilaciones.
|
||||
- Compatibilidad con muchas plataformas mediante plugins para que los equipos puedan personalizar sus compilaciones.
|
||||
|
||||
[**Logspout**](https://github.com/gliderlabs/logspout)
|
||||
|
||||
- Logging tool - The tool’s customizability allows teams to ship the same logs to multiple destinations.
|
||||
- Teams can easily manage their files because the tool only requires access to the Docker socket.
|
||||
- Completely open-sourced and easy to deploy.
|
||||
- Herramienta de registro: la capacidad de personalización de la herramienta permite a los equipos enviar los mismos registros a varios destinos.
|
||||
- Los equipos pueden gestionar fácilmente sus archivos porque la herramienta sólo requiere acceso al socket Docker.
|
||||
- Completamente de código abierto y fácil de desplegar.
|
||||
|
||||
[**Logstash**](https://www.elastic.co/products/logstash)
|
||||
|
||||
- Customize your pipeline using Logstash’s pluggable framework.
|
||||
- Easily parse and transform your data for analysis and to deliver business value.
|
||||
- Logstash’s variety of outputs lets you route your data where you want.
|
||||
- Personaliza tu pipeline utilizando el marco de trabajo pluggable de Logstash.
|
||||
- Analice y transforme fácilmente sus datos para el análisis y para ofrecer valor empresarial.
|
||||
- La variedad de salidas de Logstash le permite dirigir sus datos hacia donde desee.
|
||||
|
||||
[**Portainer**](https://www.portainer.io/)
|
||||
|
||||
- Utilise pre-made templates or create your own to deploy applications.
|
||||
- Create teams and assign roles and permissions to team members.
|
||||
- Know what is running in each environment using the tool’s dashboard.
|
||||
- Utilice plantillas prediseñadas o cree las suyas propias para desplegar aplicaciones.
|
||||
- Cree equipos y asigne funciones y permisos a sus miembros.
|
||||
- Sepa qué se está ejecutando en cada entorno mediante el panel de control de la herramienta.
|
||||
|
||||
## Resources
|
||||
## Recursos
|
||||
|
||||
- [TechWorld with Nana - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=3c-iBn73dDE)
|
||||
- [Programming with Mosh - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=pTFZFxd4hOI)
|
||||
@ -101,5 +99,10 @@ We could also mention toolings and options around Rancher, and VirtualBox but we
|
||||
- [YAML Tutorial: Everything You Need to Get Started in Minute](https://www.cloudbees.com/blog/yaml-tutorial-everything-you-need-get-started)
|
||||
- [Podman | Daemonless Docker | Getting Started with Podman](https://www.youtube.com/watch?v=Za2BqzeZjBk)
|
||||
- [LXC - Guide to building an LXC Lab](https://www.youtube.com/watch?v=cqOtksmsxfg)
|
||||
- [En español] En los [apuntes](https://vergaracarmona.es/apuntes/) del traductor:
|
||||
- [Preparación de entorno de pruebas local para docker](https://vergaracarmona.es/preparacion-de-entorno-de-pruebas-local-para-docker/)
|
||||
- [Uso básico de docker](https://vergaracarmona.es/uso-basico-de-docker/)
|
||||
- [Una breve historia sobre contenedores](https://vergaracarmona.es/breve-historia-de-contenedores/)
|
||||
- [Desplegar con docker-compose los servicios Traefik y Portainer](https://vergaracarmona.es/desplegar-con-docker-compose-los-servicios-traefik-y-portainer/)
|
||||
|
||||
See you on [Day 49](day49.md)
|
||||
Nos vemos en el [Día 49](day49.md)
|
||||
|
@ -1,224 +1,199 @@
|
||||
## The Big Picture: Kubernetes
|
||||
## El panorama: Kubernetes
|
||||
|
||||
In the last section we covered Containers, Containers fall short when it comes to scale and orchestration alone. The best we can do is use docker-compose to bring up multiple containers together. When it comes to Kubernetes which is a Container Orchestrator, this gives us the ability to scale up and down in an automated way or based on a load of your applications and services.
|
||||
En la última sección vimos los Contenedores. Los contenedores se quedan cortos cuando se trata de escalar y de orquestación, no pueden por sí solos. Lo mejor que podemos hacer es utilizar docker-compose para reunir varios contenedores. Cuando se trata de Kubernetes, que es un orquestador de contenedores, esto nos da la capacidad de escalar hacia arriba y hacia abajo de manera automatizada o basada en una carga de sus aplicaciones y servicios.
|
||||
|
||||
As a platform Kubernetes offers the ability to orchestrate containers according to your requirements and desired state. We are going to cover Kubernetes in this section as it is growing rapidly as the next wave of infrastructure. I would also suggest that from a DevOps perspective Kubernetes is just one platform that you will need to have a basic understanding of, you will also need to understand bare metal, virtualisation and most likely cloud-based services as well. Kubernetes is just another option to run our applications.
|
||||
Como plataforma, Kubernetes ofrece la capacidad de orquestar contenedores de acuerdo a sus necesidades y el estado deseado. Vamos a cubrir Kubernetes en esta sección, ya que está creciendo rápidamente como la próxima ola de infraestructura. También me gustaría sugerir que, desde una perspectiva DevOps, Kubernetes es sólo una plataforma de las que tendrás que tener al menos un conocimiento básico. También tendrá que entender el bare metal, la virtualización y muy probablemente también los servicios basados en cloud. Kubernetes es sólo otra opción para ejecutar nuestras aplicaciones y se puede aplicar en estás dos mencionadas.
|
||||
|
||||
### What is Container Orchestration?
|
||||
### ¿Qué es la orquestación de contenedores?
|
||||
|
||||
I have mentioned Kubernetes and I have mentioned Container Orchestration, Kubernetes is the technology whereas container orchestration is the concept or the process behind the technology. Kubernetes is not the only Container Orchestration platform we also have Docker Swarm, HashiCorp Nomad and others. But Kubernetes is going from strength to strength so I want to cover Kubernetes but wanted to say that it is not the only one out there.
|
||||
He mencionado Kubernetes y he mencionado orquestación de contenedores, Kubernetes es la tecnología mientras que la orquestación de contenedores es el concepto o el proceso detrás de esta tecnología. Kubernetes no es la única plataforma de orquestación de contenedores, también tenemos las mencionadas anteriormente docker compose y Docker Swarm, o otras como HashiCorp Nomad. Pero Kubernetes va viento en popa, es la más utilizada, así que nos centraremos en ella.
|
||||
|
||||
### What is Kubernetes?
|
||||
### ¿Qué es Kubernetes?
|
||||
|
||||
The first thing you should read if you are new to Kubernetes is the official documentation, My experience of really deep diving into Kubernetes a little over a year ago was that this is going to be a steep learning curve. Coming from a virtualisation and storage background I was thinking about how daunting this felt.
|
||||
Lo primero que debes leer si eres nuevo en Kubernetes es la documentación oficial, es el mejor tutorial para aprender y además la van utilizando con más ejemplos o nuevas implementaciones. Mi experiencia de buceo realmente profundo en Kubernetes fue una curva de aprendizaje empinada. Viniendo de un fondo de virtualización y almacenamiento pensaba en lo desalentador que esto se sentía, pero el camino se hace al andar.
|
||||
|
||||
But the community, free learning resources and documentation are amazing. [Kubernetes.io](https://kubernetes.io/docs/concepts/overview/what-is-kubernetes/)
|
||||
La comunidad, los recursos de aprendizaje gratuitos y la documentación son increíbles, no dejes de empaparte en ella: [Kubernetes.io](https://kubernetes.io/docs/concepts/overview/what-is-kubernetes/)
|
||||
|
||||
_Kubernetes is a portable, extensible, open-source platform for managing containerized workloads and services, that facilitates both declarative configuration and automation. It has a large, rapidly growing ecosystem. Kubernetes services, support, and tools are widely available._
|
||||
Ahora al pastel. Kubernetes es una plataforma portátil, extensible y de código abierto para gestionar cargas de trabajo y servicios en contenedores. Facilita tanto la configuración declarativa como la automatización. Cuenta con un ecosistema amplio y de rápido crecimiento. Los servicios, el soporte y las herramientas de Kubernetes están ampliamente disponibles.
|
||||
|
||||
Important things to note from the above quote, Kubernetes is Open-Source with a rich history that goes back to Google who donated the project to the Cloud Native Computing Foundation (CNCF) and it has now been progressed by the open-source community as well as large enterprise vendors contributing to making Kubernetes what it is today.
|
||||
Cosas importantes a tener en cuenta de la cita anterior, Kubernetes es de código abierto con una rica historia que se remonta a cuando Google donó el proyecto a la Cloud Native Computing Foundation (CNCF). Ahora está siendo desarrollado por la comunidad de código abierto, así como grandes proveedores empresariales que contribuyen a hacer Kubernetes lo que es hoy.
|
||||
|
||||
I mentioned above that containers are great and in the previous section, we spoke about how containers and container images have changed and accelerated the adoption of cloud-native systems. But containers alone are not going to give you the production-ready experience you need from your application. Kubernetes gives us the following:
|
||||
Antes he mencionado que los contenedores son geniales y, en la sección anterior, hemos hablado de cómo los contenedores y las imágenes de contenedores han cambiado y acelerado la adopción de sistemas nativos de la nube. Pero los contenedores por sí solos no van a darte la experiencia lista para producción que necesitas de tu aplicación. Kubernetes nos proporciona estas soluciones:
|
||||
|
||||
- **Service discovery and load balancing** Kubernetes can expose a container using the DNS name or using their IP address. If traffic to a container is high, Kubernetes can load balance and distribute the network traffic so that the deployment is stable.
|
||||
- **Descubrimiento de servicios y equilibrio de carga** - Kubernetes puede exponer un contenedor utilizando el nombre DNS o su dirección IP. Si el tráfico a un contenedor es alto, Kubernetes puede equilibrar la carga y distribuir el tráfico de red para que el despliegue sea estable.
|
||||
- **Orquestación de almacenamiento** - Kubernetes permite montar automáticamente un sistema de almacenamiento de su elección, como almacenamiento local, proveedores de nubes públicas, etc.
|
||||
- **Rollouts y rollbacks automatizados** - Puedes describir el estado deseado para los contenedores desplegados utilizando Kubernetes, y puedes cambiar el estado actual al estado deseado a un ritmo controlado. Por ejemplo, puedes automatizar Kubernetes para crear nuevos contenedores para su despliegue, eliminar los contenedores existentes y adoptar todos sus recursos al nuevo contenedor.
|
||||
- **Empaquetado automático de contenedores** - Proporcionas a Kubernetes un clúster de nodos que pueda utilizar para ejecutar tareas en contenedores, indicas cuánta CPU y memoria (RAM) necesitas para cada contenedor y Kubernetes puede acomodar los contenedores en sus nodos para hacer el mejor uso de los recursos.
|
||||
- **Auto-reparación** - Kubernetes reinicia los contenedores que fallan, reemplaza los contenedores, mata los contenedores que no responden a su chequeo de salud definido por el usuario y no los anuncia a los clientes hasta que estén listos para servir.
|
||||
- **Gestión de secretos y configuración** - Kubernetes permite almacenar y gestionar información confidencial, como contraseñas, tokens OAuth y claves SSH. Puede desplegar y actualizar secretos y la configuración de la aplicación sin reconstruir sus imágenes de contenedor, y sin exponer secretos en la configuración de su pila.
|
||||
|
||||
- **Storage orchestration** Kubernetes allows you to automatically mount a storage system of your choice, such as local storage, public cloud providers, and more.
|
||||
Kubernetes proporciona un marco para ejecutar sistemas distribuidos de forma resiliente.
|
||||
|
||||
- **Automated rollouts and rollbacks** You can describe the desired state for your deployed containers using Kubernetes, and it can change the actual state to the desired state at a controlled rate. For example, you can automate Kubernetes to create new containers for your deployment, remove existing containers and adopt all their resources to the new container.
|
||||
La orquestación de contenedores gestiona el despliegue, la colocación y el ciclo de vida de los contenedores.
|
||||
|
||||
- **Automatic bin packing** You provide Kubernetes with a cluster of nodes that it can use to run containerized tasks. You tell Kubernetes how much CPU and memory (RAM) each container needs. Kubernetes can fit containers onto your nodes to make the best use of your resources.
|
||||
También tiene muchas otras responsabilidades:
|
||||
|
||||
- **Self-healing** Kubernetes restarts containers that fail, replaces containers, kills containers that don't respond to your user-defined health check, and doesn't advertise them to clients until they are ready to serve.
|
||||
- La gestión de clústeres federa hosts en un objetivo.
|
||||
- La gestión de la programación distribuye los contenedores entre los nodos a través del programador.
|
||||
- El descubrimiento de servicios sabe dónde se encuentran los contenedores y distribuye las solicitudes de los clientes entre ellos.
|
||||
- La replicación garantiza la disponibilidad del número adecuado de nodos y contenedores para la carga de trabajo solicitada.
|
||||
- La gestión de la salud detecta y reemplaza los contenedores y nodos no saludables.
|
||||
|
||||
- **Secret and configuration management** Kubernetes lets you store and manage sensitive information, such as passwords, OAuth tokens, and SSH keys. You can deploy and update secrets and application configuration without rebuilding your container images, and without exposing secrets in your stack configuration.
|
||||
### Principales componentes de Kubernetes
|
||||
|
||||
Kubernetes provides you with a framework to run distributed systems resiliently.
|
||||
Kubernetes es un orquestador de contenedores para aprovisionar, gestionar y escalar aplicaciones. Puede utilizarlo para gestionar el ciclo de vida de aplicaciones en contenedores en un clúster de nodos, que es una colección de máquinas de trabajo como VMs o máquinas físicas.
|
||||
|
||||
Container Orchestration manages the deployment, placement, and lifecycle of containers.
|
||||
Es posible que sus aplicaciones necesiten muchos otros recursos para ejecutarse, como volúmenes, redes y secretos que pueden ayudarle a conectarse a bases de datos, comunicarse con back-ends con firewalls y proteger claves. Con Kubernetes, puede añadir estos recursos a su aplicación. Los recursos de infraestructura que sus aplicaciones necesitan que se gestionen de forma declarativa.
|
||||
|
||||
It also has many other responsibilities:
|
||||
El paradigma clave de Kubernetes es su modelo declarativo. Usted proporciona el estado que desea y Kubernetes lo hace posible. Si necesita cinco instancias, no inicie cinco instancias separadas por su cuenta. En su lugar, le dice a Kubernetes que necesita cinco instancias, y Kubernetes reconcilia automáticamente el estado. Si algo sale mal con una de sus instancias y falla, Kubernetes aún conoce el estado que usted desea y crea instancias en un nodo disponible.
|
||||
|
||||
- Cluster management federates hosts into one target.
|
||||
|
||||
- Schedule management distributes containers across nodes through the scheduler.
|
||||
- Service discovery knows where containers are located and distributes client requests across them.
|
||||
|
||||
- Replication ensures that the right number of nodes and containers are available for the requested workload.
|
||||
|
||||
- Health management detects and replaces unhealthy containers and nodes.
|
||||
|
||||
### Main Kubernetes Components
|
||||
|
||||
Kubernetes is a container orchestrator to provision, manage, and scale apps. You can use it to manage the lifecycle of containerized apps in a cluster of nodes, which is a collection of worker machines such as VMs or physical machines.
|
||||
|
||||
Your apps might need many other resources to run, such as volumes, networks, and secrets that can help you connect to databases, talk to firewalled back ends, and secure keys. With Kubernetes, you can add those resources to your app. Infrastructure resources that your apps need are managed declaratively.
|
||||
|
||||
The key paradigm of Kubernetes is its declarative model. You provide the state that you want and Kubernetes makes it happen. If you need five instances, you don't start five separate instances on your own. Instead, you tell Kubernetes that you need five instances, and Kubernetes automatically reconciles the state. If something goes wrong with one of your instances and it fails, Kubernetes still knows the state that you want and creates instances on an available node.
|
||||
|
||||
### Node
|
||||
### Nodo
|
||||
|
||||
#### Control Plane
|
||||
|
||||
Every Kubernetes cluster requires a Control Plane node, the control plane's components make global decisions about the cluster (for example, scheduling), as well as detecting and responding to cluster events.
|
||||
Cada clúster Kubernetes requiere un nodo de Control Plane, los componentes del Control Plane toman decisiones globales sobre el clúster, por ejemplo la programación, así como la detección y respuesta a los eventos del clúster.
|
||||
|
||||

|
||||
|
||||
#### Worker Node
|
||||
|
||||
A worker machine that runs Kubernetes workloads. It can be a physical (bare metal) machine or a virtual machine (VM). Each node can host one or more pods. Kubernetes nodes are managed by a control plane
|
||||
Un Worker machine que ejecuta cargas de trabajo Kubernetes. Puede ser una máquina física (bare metal) o una máquina virtual (VM). Cada nodo puede alojar uno o más pods. Los nodos Kubernetes son gestionados por un plano de control.
|
||||
|
||||

|
||||
|
||||
There are other node types but I won't be covering them here.
|
||||
Existen otros tipos de nodos pero no los trataré aquí.
|
||||
|
||||
#### kubelet
|
||||
|
||||
An agent that runs on each node in the cluster. It makes sure that containers are running in a Pod.
|
||||
Un agente que se ejecuta en cada nodo del clúster. Se asegura de que los contenedores se ejecutan en un Pod.
|
||||
|
||||
The kubelet takes a set of PodSpecs that are provided through various mechanisms and ensures that the containers described in those PodSpecs are running and healthy. The kubelet doesn't manage containers which were not created by Kubernetes.
|
||||
El kubelet toma un conjunto de PodSpecs que se proporcionan a través de diversos mecanismos y se asegura de que los contenedores descritos en los PodSpecs se están ejecutando y en buen estado. El kubelet no gestiona contenedores que no hayan sido creados por Kubernetes.
|
||||
|
||||

|
||||
|
||||
#### kube-proxy
|
||||
|
||||
kube-proxy is a network proxy that runs on each node in your cluster, implementing part of the Kubernetes Service concept.
|
||||
kube-proxy es un proxy de red que se ejecuta en cada nodo de su clúster, implementando parte del concepto de Servicio Kubernetes.
|
||||
|
||||
kube-proxy maintains network rules on nodes. These network rules allow network communication to your Pods from network sessions inside or outside of your cluster.
|
||||
kube-proxy mantiene reglas de red en los nodos. Estas reglas de red permiten la comunicación de red a sus Pods desde sesiones de red dentro o fuera de su cluster.
|
||||
|
||||
kube-proxy uses the operating system packet filtering layer if there is one and it's available. Otherwise, kube-proxy forwards the traffic itself.
|
||||
kube-proxy utiliza la capa de filtrado de paquetes del sistema operativo si existe y está disponible. De lo contrario, kube-proxy reenvía el tráfico por sí mismo.
|
||||
|
||||

|
||||
|
||||
#### Container runtime
|
||||
|
||||
The container runtime is the software that is responsible for running containers.
|
||||
El container runtime es el software responsable de ejecutar los contenedores.
|
||||
|
||||
Kubernetes supports several container runtimes: Docker, containerd, CRI-O, and any implementation of the Kubernetes CRI (Container Runtime Interface).
|
||||
Kubernetes soporta varios container runtime: Docker, containerd, CRI-O, y cualquier implementación del CRI (Container Runtime Interface) de Kubernetes.
|
||||
|
||||

|
||||
|
||||
### Cluster
|
||||
|
||||
A cluster is a group of nodes, where a node can be a physical machine or a virtual machine. Each of the nodes will have the container runtime (Docker) and will also be running a kubelet service, which is an agent that takes in the commands from the Master controller (more on that later) and a Proxy, that is used to proxy connections to the Pods from another component (Services, that we will see later).
|
||||
Un cluster es un grupo de nodos, donde un nodo puede ser una máquina física o una máquina virtual. Cada uno de los nodos tendrá el tiempo de ejecución del contenedor (Docker) y también estará ejecutando un servicio kubelet, que es un agente que recibe los comandos del controlador Maestro (veremos más sobre esto más adelante) y un Proxy, que se utiliza para proxy conexiones a los Pods de otro componente (Servicios, que veremos más adelante).
|
||||
|
||||
Our control plane which can be made highly available will contain some unique roles compared to the worker nodes, the most important will be the kube API server, this is where any communication will take place to get information or push information to our Kubernetes cluster.
|
||||
Nuestro control plane, que se puede hacer altamente disponible, contendrá algunos roles únicos en comparación con los nodos Workers, el más importante será el servidor API kube, aquí es donde cualquier comunicación se llevará a cabo para obtener información o enviar información a nuestro clúster Kubernetes.
|
||||
|
||||
#### Kube API-Server
|
||||
#### Servidor API Kube
|
||||
|
||||
The Kubernetes API server validates and configures data for the API objects which include pods, services, replication controllers, and others. The API Server services REST operations and provide the frontend to the cluster's shared state through which all other components interact.
|
||||
El servidor API de Kubernetes valida y configura los datos para los objetos API que incluyen pods, servicios, controladores de replicación y otros. El servidor API da servicio a las operaciones REST y proporciona el frontend al estado compartido del cluster a través del cual interactúan el resto de componentes.
|
||||
|
||||
#### Scheduler
|
||||
#### Planificador (Scheduler)
|
||||
|
||||
The Kubernetes scheduler is a control plane process which assigns Pods to Nodes. The scheduler determines which Nodes are valid placements for each Pod in the scheduling queue according to constraints and available resources. The scheduler then ranks each valid Node and binds the Pod to a suitable Node.
|
||||
El programador de Kubernetes es un proceso del control plane que asigna Pods a Nodos. El programador determina qué Nodos son válidos para cada Pod en la cola de programación de acuerdo con las restricciones y los recursos disponibles. A continuación, el planificador clasifica cada Nodo válido y vincula el Pod a un Nodo adecuado.
|
||||
|
||||
#### Controller Manager
|
||||
#### Gestor de Controladores
|
||||
|
||||
The Kubernetes controller manager is a daemon that embeds the core control loops shipped with Kubernetes. In applications of robotics and automation, a control loop is a non-terminating loop that regulates the state of the system. In Kubernetes, a controller is a control loop that watches the shared state of the cluster through the apiserver and makes changes attempting to move the current state towards the desired state.
|
||||
El gestor de controladores de Kubernetes es un demonio que incorpora los bucles de control centrales incluidos en Kubernetes. En aplicaciones de robótica y automatización, un bucle de control es un bucle no terminal que regula el estado del sistema. En Kubernetes, un controlador es un bucle de control que observa el estado compartido del cluster a través del apiserver y realiza cambios intentando mover el estado actual hacia el estado deseado.
|
||||
|
||||
#### etcd
|
||||
|
||||
Consistent and highly-available key value store used as Kubernetes' backing store for all cluster data.
|
||||
Almacén de valores clave consistente y de alta disponibilidad utilizado como almacén de respaldo de Kubernetes para todos los datos del clúster.
|
||||
|
||||

|
||||
|
||||
#### kubectl
|
||||
|
||||
To manage this from a CLI point of view we have kubectl, kubectl interacts with the API server.
|
||||
Para gestionar esto desde un punto de vista CLI tenemos kubectl, kubectl interactúa con el servidor API.
|
||||
|
||||
The Kubernetes command-line tool, kubectl, allows you to run commands against Kubernetes clusters. You can use kubectl to deploy applications, inspect and manage cluster resources, and view logs.
|
||||
La herramienta de línea de comandos de Kubernetes, kubectl, le permite ejecutar comandos contra clústeres Kubernetes. Puede utilizar kubectl para desplegar aplicaciones, inspeccionar y gestionar recursos de clúster y ver registros.
|
||||
|
||||

|
||||
|
||||
### Pods
|
||||
|
||||
A Pod is a group of containers that form a logical application. E.g. If you have a web application that is running a NodeJS container and also a MySQL container, then both these containers will be located in a single Pod. A Pod can also share common data volumes and they also share the same networking namespace. Remember that Pods are ephemeral and they could be brought up and down by the Master Controller. Kubernetes uses a simple but effective means to identify the Pods via the concepts of Labels (name – values).
|
||||
Un Pod es un grupo de contenedores que forman una aplicación lógica. Por ejemplo, si tienes una aplicación web que está ejecutando un contenedor NodeJS y también un contenedor MySQL, entonces ambos contenedores pueden estar ubicados en un único Pod, aunque no es lo aconsejable. Un Pod también puede compartir volúmenes de datos comunes y también comparten el mismo espacio de nombres de red. Recuerda que los Pods son efímeros y pueden ser subidos y bajados por el Controlador Maestro. Kubernetes utiliza un medio simple pero eficaz para identificar los Pods a través de los conceptos de Labels (nombre - valor).
|
||||
|
||||
- Pods handle Volumes, Secrets, and configuration for containers.
|
||||
|
||||
- Pods are ephemeral. They are intended to be restarted automatically when they die.
|
||||
|
||||
- Pods are replicated when the app is scaled horizontally by the ReplicationSet. Each Pod will run the same container code.
|
||||
|
||||
- Pods live on Worker Nodes.
|
||||
Algunas características importantes de los Pods:
|
||||
- Los Pods son la unidad más pequeña de Kubernetes.
|
||||
- Los Pods manejan Volúmenes, Secretos y configuración para los contenedores.
|
||||
- Los Pods son efímeros. Están pensados para reiniciarse automáticamente cuando mueren.
|
||||
- Los Pods se replican cuando la aplicación se escala horizontalmente mediante el ReplicationSet. Cada Pod ejecutará el mismo código de contenedor.
|
||||
- Los Pods viven en Nodos Workers.
|
||||
- Los Pods pueden comunicarse entre sí usando localhost.
|
||||
|
||||

|
||||
|
||||
### Deployments
|
||||
|
||||
- You can just decide to run Pods but when they die they die.
|
||||
Puedes decidir ejecutar Pods pero cuando mueren, mueren. Los Deployments son una forma de ejecutar Pods de forma continua. Los Deployments también le permiten actualizar una aplicación en ejecución sin tiempo de inactividad.
|
||||
|
||||
- A Deployment will enable your pod to run continuously.
|
||||
|
||||
- Deployments allow you to update a running app without downtime.
|
||||
|
||||
- Deployments also specify a strategy to restart Pods when they die
|
||||
- Un Deployment permitirá que tu pod se ejecute continuamente.
|
||||
- Los Deployments le permiten actualizar una aplicación en ejecución sin tiempo de inactividad.
|
||||
- Los Deployments también especifican una estrategia para reiniciar Pods cuando mueren.
|
||||
- Los Deployments son la forma recomendada de administrar Pods en producción.
|
||||
- Los Deployments son una abstracción de alto nivel que maneja la creación de Pods y ReplicaSets.
|
||||
- Los Deployments son declarativos, como todo en Kubernetes, esto significa que describe el estado deseado en su clúster y Kubernetes se encarga de cambiar el estado real para que coincida con el estado deseado.
|
||||
|
||||

|
||||
|
||||
### ReplicaSets
|
||||
|
||||
- The Deployment can also create the ReplicaSet
|
||||
Como se ha comentado, el Deployment también puede crear el ReplicaSet. Un ReplicaSet es un objeto que define un conjunto de Pods idénticos. Un ReplicaSet garantiza que un número especificado de réplicas de un Pod se estén ejecutando en todo momento. Si hay demasiados Pods, el ReplicaSet eliminará los Pods adicionales. Si hay muy pocos Pods, el ReplicaSet creará más. Los ReplicaSets son la forma recomendada de administrar Pods en producción.
|
||||
|
||||
- A ReplicaSet ensures your app has the desired number of Pods
|
||||
|
||||
- ReplicaSets will create and scale Pods based on the Deployment
|
||||
|
||||
- Deployments, ReplicaSets, and Pods are not exclusive but can be
|
||||
- Un ReplicaSet asegura que su aplicación tiene el número deseado de Pods
|
||||
- Los ReplicaSets crearán y escalarán Pods basándose en el Deployment
|
||||
- Los Deployments, ReplicaSets y Pods no son excluyentes, pero pueden ser
|
||||
|
||||
### StatefulSets
|
||||
|
||||
- Does your App require you to keep information about its state?
|
||||
¿Necesita tu App mantener información sobre su estado? Por ejemplo, una base de datos necesita estado. Los StatefulSets son la forma de ejecutar aplicaciones que necesitan mantener un estado. Los StatefulSets son similares a los Deployments, pero tienen algunas diferencias importantes:
|
||||
|
||||
- A database needs state
|
||||
|
||||
- A StatefulSet’s Pods are not interchangeable.
|
||||
|
||||
- Each pod has a unique, persistent identifier that the controller maintains over any rescheduling.
|
||||
- Los Pods de un StatefulSet no son intercambiables.
|
||||
- Cada pod tiene un identificador único y persistente que el controlador mantiene por encima de cualquier reprogramación.
|
||||
- Los Pods de un StatefulSet se crean en orden secuencial, uno a la vez.
|
||||
- Los Pods de un StatefulSet tienen un nombre DNS estable y predecible. Mantienen el mismo nombre a través de las reprogramaciones.
|
||||
- Los volúmenes pueden ser persistentes.
|
||||
|
||||

|
||||
|
||||
### DaemonSets
|
||||
|
||||
- DaemonSets are for continuous process
|
||||
|
||||
- They run one Pod per Node.
|
||||
|
||||
- Each new node added to the cluster gets a pod started
|
||||
|
||||
- Useful for background tasks such as monitoring and log collection
|
||||
|
||||
- Each pod has a unique, persistent identifier that the controller maintains over any rescheduling.
|
||||
- Los DaemonSets son para procesos continuos que se ejecutan en todos los nodos. Un Pod por Nodo.
|
||||
- Cada nuevo nodo añadido al cluster hace que se inicie un pod.
|
||||
- Útiles para tareas en segundo plano como monitorización y recogida de logs.
|
||||
- Cada pod tiene un identificador único y persistente que el controlador mantiene por encima de cualquier reprogramación.
|
||||
|
||||

|
||||
|
||||
### Services
|
||||
### Servicios
|
||||
|
||||
- A single endpoint to access Pods
|
||||
Características de los Servicios:
|
||||
- Un único punto final para acceder a los Pods
|
||||
- Una forma unificada de dirigir el tráfico a un cluster y eventualmente a una lista de Pods.
|
||||
- Usando un Servicio, los Pods pueden ser subidos y bajados sin afectar a nada.
|
||||
- Los Servicios pueden ser expuestos interna o externamente. También pueden ser expuestos en diferentes puertos.
|
||||
|
||||
- a unified way to route traffic to a cluster and eventually to a list of Pods.
|
||||
|
||||
- By using a Service, Pods can be brought up and down without affecting anything.
|
||||
|
||||
This is just a quick overview and notes around the fundamental building blocks of Kubernetes, we can take this knowledge and add in some other areas around Storage and Ingress to enhance our applications but we then also have a lot of choices on where our Kubernetes cluster runs. The next session will focus on those options on where can I run a Kubernetes cluster, whilst also exploring some specifics around Storage.
|
||||
Esto es sólo una visión general rápida y notas sobre los bloques de construcción fundamentales de Kubernetes, podemos tomar este conocimiento y añadir en algunas otras áreas alrededor de almacenamiento y de entrada para mejorar nuestras aplicaciones, pero entonces también tenemos un montón de opciones sobre dónde se ejecuta nuestro clúster Kubernetes. La siguiente sesión se centrará en esas opciones sobre dónde se puede ejecutar un clúster Kubernetes, mientras que también exploraremos algunos detalles sobre el almacenamiento.
|
||||
|
||||

|
||||
|
||||
### What we will cover in the series on Kubernetes
|
||||
|
||||
- Kubernetes Architecture
|
||||
- Kubectl Commands
|
||||
- Kubernetes YAML
|
||||
- Kubernetes Ingress
|
||||
- Kubernetes Services
|
||||
- Helm Package Manager
|
||||
- Persistent Storage
|
||||
- Stateful Apps
|
||||
|
||||
## Resources
|
||||
## Recursos
|
||||
|
||||
- [Kubernetes Documentation](https://kubernetes.io/docs/home/)
|
||||
- [TechWorld with Nana - Kubernetes Tutorial for Beginners [FULL COURSE in 4 Hours]](https://www.youtube.com/watch?v=X48VuDVv0do)
|
||||
- [TechWorld with Nana - Kubernetes Crash Course for Absolute Beginners](https://www.youtube.com/watch?v=s_o8dwzRlu4)
|
||||
- [Kunal Kushwaha - Kubernetes Tutorial for Beginners | What is Kubernetes? Architecture Simplified!](https://www.youtube.com/watch?v=KVBON1lA9N8)
|
||||
|
||||
See you on [Day 50](day50.md)
|
||||
Nos vemos en el [Día 50](day50.md)
|
||||
|
@ -1,42 +1,46 @@
|
||||
## Choosing your Kubernetes platform
|
||||
## Elegir tu plataforma Kubernetes
|
||||
|
||||
I wanted to use this session to break down some of the platforms or maybe distributions is a better term to use here, one thing that has been a challenge in the Kubernetes world is removing complexity.
|
||||
En esta sesión se va a desglosar algunas de las plataformas o tal vez distribuciones es un mejor término a utilizar aquí. Una cosa que ha sido un reto en el mundo Kubernetes es eliminar la complejidad.
|
||||
|
||||
Kubernetes the hard way walks through how to build out from nothing to a full-blown functional Kubernetes cluster this is to the extreme but more and more at least the people I am speaking to are wanting to remove that complexity and run a managed Kubernetes cluster. The issue there is that it costs more money but the benefits could be if you use a managed service do you need to know the underpinning node architecture and what is happening from a Control Plane node point of view when generally you do not have access to this.
|
||||
Kubernetes the hard way (el camino difícil) explica cómo construir desde la nada un clúster Kubernetes completamente funcional. Esto es extremo, pero cada vez más, al menos las personas con las que hablo, quieren eliminar esa complejidad y ejecutar un clúster Kubernetes gestionado. El problema es que cuesta más dinero, pero las ventajas podrían ser que, si se utiliza un servicio gestionado, es necesario conocer la arquitectura de los nodos y lo que ocurre desde el punto de vista del control plane, algo a lo que generalmente no se tiene acceso.
|
||||
|
||||
Then we have the local development distributions that enable us to use our systems and run a local version of Kubernetes so developers can have the full working environment to run their apps in the platform they are intended for.
|
||||
Luego tenemos las distribuciones de desarrollo local que nos permiten utilizar nuestros sistemas y ejecutar una versión local de Kubernetes para que los desarrolladores puedan tener el entorno de trabajo completo para ejecutar sus aplicaciones en la plataforma para la que están destinadas.
|
||||
|
||||
The general basis of all of these concepts is that they are all a flavour of Kubernetes which means we should be able to freely migrate and move our workloads where we need them to suit our requirements.
|
||||
La base general de todos estos conceptos es que todos son una variante de Kubernetes, lo que significa que deberíamos poder migrar y mover libremente nuestras cargas de trabajo donde las necesitemos para adaptarlas a nuestras necesidades.
|
||||
|
||||
A lot of our choice will also depend on what investments have been made. I mentioned the developer experience as well but some of those local Kubernetes environments that run our laptops are great for getting to grips with the technology without spending any money.
|
||||
Gran parte de nuestra elección dependerá también de las inversiones realizadas. También he mencionado la experiencia de los desarrolladores, pero algunos de esos entornos locales de Kubernetes que ejecutan nuestros portátiles son estupendos para familiarizarse con la tecnología sin gastar dinero.
|
||||
|
||||
### Bare-Metal Clusters
|
||||
### Clusters Bare-Metal
|
||||
|
||||
An option for many could be running your Linux OS straight onto several physical servers to create our cluster, it could also be Windows but I have not heard much about the adoption rate around Windows, Containers and Kubernetes. If you are a business and you have made a CAPEX decision to buy your physical servers then this might be how you go when building out your Kubernetes cluster, the management and admin side here means you are going to have to build yourself and manage everything from the ground up.
|
||||
Una opción para muchos podría ser ejecutar su sistema operativo Linux directamente en varios servidores físicos para crear nuestro clúster, también podría ser Windows pero no he oído hablar mucho de la tasa de adopción en entornos Windows, puede ser anecdótica.
|
||||
|
||||
### Virtualisation
|
||||
Si en tu empresa se ha tomado la decisión de CAPEX para comprar sus servidores físicos, entonces esto podría ser una forma en la que construir la arquitectura, un clúster Kubernetes. La gestión y administración de lado significa que la vas a tener que construir tu mismo y gestionarlo todo desde el principio.
|
||||
|
||||
Regardless of test and learning environments or enterprise-ready Kubernetes clusters virtualisation is a great way to go, typically the ability to spin up virtual machines to act as your nodes and then cluster those together. You have the underpinning architecture, efficiency and speed of virtualisation as well as leveraging that existing spend. VMware for example offers a great solution for both Virtual Machines and Kubernetes in various flavours.
|
||||
### Virtualización
|
||||
|
||||
My first ever Kubernetes cluster was built based on Virtualisation using Microsoft Hyper-V on an old server that I had which was capable of running a few VMs as my nodes.
|
||||
Independientemente de si se trata de entornos de prueba y aprendizaje o de clústeres Kubernetes listos para la funcionar, la virtualización es una gran opción, ya que permite crear máquinas virtuales que actúan como nodos y, a continuación, agruparlos en clústeres. Dispones de la arquitectura de apoyo, la eficiencia y la velocidad de la virtualización, además de aprovechar el gasto existente. VMware, por ejemplo, ofrece una gran solución tanto para máquinas virtuales como para Kubernetes en varias versiones.
|
||||
|
||||
### Local Desktop options
|
||||
Mi primer clúster Kubernetes se construyó sobre la base de la virtualización utilizando Microsoft Hyper-V en un servidor antiguo que tenía que era capaz de ejecutar algunas máquinas virtuales como mis nodos. Esto me permitió construir un clúster Kubernetes y empezar a jugar con él.
|
||||
|
||||
There are several options when it comes to running a local Kubernetes cluster on your desktop or laptop. This as previously said gives developers the ability to see what their app will look like without having to have multiple costly or complex clusters. Personally, this has been one that I have used a lot and in particular, I have been using minikube. It has some great functionality and adds-ons which changes the way you get something up and running.
|
||||
### Opciones de escritorio local
|
||||
|
||||
### Kubernetes Managed Services
|
||||
Hay varias opciones cuando se trata de ejecutar un clúster local de Kubernetes en su ordenador de sobremesa o portátil. Esto, como se dijo anteriormente, ofrece a los desarrolladores la posibilidad de ver cómo se verá su aplicación sin tener que tener múltiples clústeres costosos o complejos. Personalmente, he utilizado mucho minikube. Tiene una gran funcionalidad y complementos que cambian la forma de poner algo en marcha.
|
||||
|
||||
I have mentioned virtualisation, and this can be achieved with hypervisors locally but we know from previous sections we could also leverage VMs in the public cloud to act as our nodes. What I am talking about here with Kubernetes managed services are the offerings we see from the large hyperscalers but also from MSPs removing layers of management and control away from the end user, this could be removing the control plane from the end user this is what happens with Amazon EKS, Microsoft AKS and Google Kubernetes Engine. (GKE)
|
||||
### Servicios gestionados Kubernetes
|
||||
|
||||
### Overwhelming choice
|
||||
He mencionado la virtualización, y esto se puede lograr con hipervisores a nivel local, pero sabemos por secciones anteriores que también podríamos aprovechar las máquinas virtuales en la nube pública para actuar como nuestros nodos. De lo que estoy hablando aquí con los servicios gestionados Kubernetes son las ofertas que vemos de los grandes hiperescaladores, pero también de los MSP eliminando capas de gestión y control lejos del usuario final, esto podría ser eliminar el plano de control del usuario final, esto es lo que sucede con Amazon EKS, Microsoft AKS y Google Kubernetes Engine. (GKE)
|
||||
|
||||
I mean the choice is great but there is a point where things become overwhelming and this is not a depth look into all options within each category listed above. On top of the above, we also have OpenShift which is from Red Hat and this option can be run across the options above in all the major cloud providers and probably today gives the best overall useability to the admins regardless of where clusters are deployed.
|
||||
### Elección abrumadora
|
||||
|
||||
So where do you start from your learning perspective, as I said I started with the virtualisation route but that was because I had access to a physical server which I could use for the purpose, I appreciate and in fact, since then I no longer have this option.
|
||||
Quiero decir que la elección es grande, pero hay un punto en el que las cosas se vuelven abrumadoras y esto no es una mirada en profundidad a todas las opciones dentro de cada categoría enumerada anteriormente.
|
||||
|
||||
My actual advice now would be to use Minikube as a first option or Kind (Kubernetes in Docker) but Minikube gives us some additional benefits which almost abstracts the complexity out as we can just use add-ons and get things built out quickly and we can then blow it away when we are finished, we can run multiple clusters, we can run it almost anywhere, cross-platform and hardware agnostic.
|
||||
No podemos olvidar que además de lo anterior también tenemos OpenShift que es de Red Hat. Esta opción se puede ejecutar a través de las opciones anteriores en todos los principales proveedores de nube y, probablemente, hoy en día ofrece la mejor facilidad de uso general para los administradores, independientemente de donde se despliegan los clusters.
|
||||
|
||||
I have been through a bit of a journey with my learning around Kubernetes so I am going to leave the platform choice and specifics here to list out the options that I have tried to give me a better understanding of Kubernetes the platform and where it can run. What I might do with the below blog posts is take another look at these update them and bring them more into here vs them being linked to blog posts.
|
||||
Por lo tanto, ¿por dónde empezar desde la perspectiva del aprendizaje? Como he dicho yo empecé por la ruta de la virtualización, pero eso fue porque tenía acceso a un servidor físico que podía utilizar para este fin, lo agradezco muchísimo.
|
||||
|
||||
Mi consejo actual sería utilizar Minikube como primera opción o Kind (Kubernetes en Docker), pero Minikube nos da algunos beneficios adicionales que casi abstrae la complejidad, ya que sólo podemos utilizar complementos y hacer las cosas rápidamente y luego podemos volarlo cuando hayamos terminado, podemos ejecutar múltiples clusters, podemos ejecutarlo casi en cualquier lugar, multiplataforma y agnóstico de hardware.
|
||||
|
||||
He estado a través de un poco de un viaje con mi aprendizaje en torno a Kubernetes así que voy a dejar la elección de la plataforma y los detalles aquí para enumerar las opciones que he probado para darme una mejor comprensión de Kubernetes la plataforma y donde se puede ejecutar. Lo que podría hacer con las siguientes entradas de blog es echar otro vistazo a estos actualizarlos y traerlos más aquí frente a ellos están vinculados a las entradas del blog.
|
||||
|
||||
- [Kubernetes playground – How to choose your platform](https://vzilla.co.uk/vzilla-blog/building-the-home-lab-kubernetes-playground-part-1)
|
||||
- [Kubernetes playground – Setting up your cluster](https://vzilla.co.uk/vzilla-blog/building-the-home-lab-kubernetes-playground-part-2)
|
||||
@ -48,22 +52,11 @@ I have been through a bit of a journey with my learning around Kubernetes so I a
|
||||
- [Getting started with CIVO Cloud](https://vzilla.co.uk/vzilla-blog/getting-started-with-civo-cloud)
|
||||
- [Minikube - Kubernetes Demo Environment For Everyone](https://vzilla.co.uk/vzilla-blog/project_pace-kasten-k10-demo-environment-for-everyone)
|
||||
|
||||
### What we will cover in the series on Kubernetes
|
||||
|
||||
- Kubernetes Architecture
|
||||
- Kubectl Commands
|
||||
- Kubernetes YAML
|
||||
- Kubernetes Ingress
|
||||
- Kubernetes Services
|
||||
- Helm Package Manager
|
||||
- Persistent Storage
|
||||
- Stateful Apps
|
||||
|
||||
## Resources
|
||||
## Recursos
|
||||
|
||||
- [Kubernetes Documentation](https://kubernetes.io/docs/home/)
|
||||
- [TechWorld with Nana - Kubernetes Tutorial for Beginners [FULL COURSE in 4 Hours]](https://www.youtube.com/watch?v=X48VuDVv0do)
|
||||
- [TechWorld with Nana - Kubernetes Crash Course for Absolute Beginners](https://www.youtube.com/watch?v=s_o8dwzRlu4)
|
||||
- [Kunal Kushwaha - Kubernetes Tutorial for Beginners | What is Kubernetes? Architecture Simplified!](https://www.youtube.com/watch?v=KVBON1lA9N8)
|
||||
|
||||
See you on [Day 51](day51.md)
|
||||
Nos vemos en el [Día 51](day51.md)
|
||||
|
@ -1,135 +1,136 @@
|
||||
## Deploying your first Kubernetes Cluster
|
||||
## Despliegue del primer clúster de Kubernetes
|
||||
|
||||
In this post we are going to get a Kubernetes cluster up and running on our local machine using minikube, this will give us a baseline Kubernetes cluster for the rest of the Kubernetes section, although we will look at deploying a Kubernetes cluster also in VirtualBox later on. The reason for choosing this method vs spinning a managed Kubernetes cluster up in the public cloud is that this is going to cost money even with the free tier, I shared some blogs though if you would like to spin up that environment in the previous section [Day 50](day50.md).
|
||||
En esta publicación, vamos a poner en marcha un clúster de Kubernetes en nuestra máquina local utilizando minikube. Esto nos proporcionará un clúster de Kubernetes básico para el resto de la sección de Kubernetes, aunque también veremos cómo implementar un clúster de Kubernetes en VirtualBox más adelante. La razón por la que elegimos este método en lugar de crear un clúster de Kubernetes administrado en la nube pública es que esto va a costar dinero incluso con el nivel gratuito. Sin embargo, compartí algunos blogs en la sección anterior [Día 50](day50.md) si deseas crear ese entorno.
|
||||
|
||||
### What is Minikube?
|
||||
### ¿Qué es Minikube?
|
||||
|
||||
> “minikube quickly sets up a local Kubernetes cluster on macOS, Linux, and Windows. We proudly focus on helping application developers and new Kubernetes users.”
|
||||
> "Minikube configura rápidamente un clúster local de Kubernetes en macOS, Linux y Windows. Nos enfocamos en ayudar a los desarrolladores de aplicaciones y a los nuevos usuarios de Kubernetes".
|
||||
|
||||
You might not fit into the above but I have found minikube is a great little tool if you just want to test something out in a Kubernetes fashion, you can easily deploy an app and they have some amazing add-ons which I will also cover.
|
||||
Es posible que no encajes en la descripción anterior, pero he descubierto que Minikube es una excelente herramienta si solo quieres probar algo con Kubernetes. Puedes implementar fácilmente una aplicación y también tienen algunos complementos increíbles que también cubriré.
|
||||
|
||||
To begin with, regardless of your workstation OS, you can run minikube. First, head over to the [project page here](https://minikube.sigs.k8s.io/docs/start/). The first option you have is choosing your installation method. I did not use this method, but you might choose to vs my way (my way is coming up).
|
||||
Para empezar, independientemente de tu sistema operativo de trabajo, puedes ejecutar Minikube. Primero, dirígete a la [página del proyecto aquí](https://minikube.sigs.k8s.io/docs/start/). La primera opción que tienes es elegir el método de instalación. No utilicé este método, pero puedes elegir usarlo en lugar del mío (mi método se explicará a continuación).
|
||||
|
||||
mentioned below it states that you need to have a “Container or virtual machine managers, such as Docker, Hyper kit, Hyper-V, KVM, Parallels, Podman, VirtualBox, or VMware” this is where MiniKube will run and the easy option and unless stated in the repository I am using Docker. You can install Docker on your system using the following [link](https://docs.docker.com/get-docker/).
|
||||
A continuación, se indica que debes tener "contenedores o administradores de máquinas virtuales, como Docker, HyperKit, Hyper-V, KVM, Parallels, Podman, VirtualBox o VMware". Aquí es donde se ejecutará Minikube, y la opción más sencilla, a menos que se indique lo contrario en el repositorio que estoy utilizando, es Docker. Puedes instalar Docker en tu sistema utilizando el siguiente [enlace](https://docs.docker.com/get-docker/).
|
||||
|
||||

|
||||

|
||||
|
||||
### My way of installing minikube and other prereqs…
|
||||
### Mi forma de instalar Minikube y otros requisitos previos...
|
||||
|
||||
I have been using arkade for some time now to get all those Kubernetes tools and CLIs, you can see the installation steps on this [github repository](https://github.com/alexellis/arkade) for getting started with Arkade. I have also mentioned this in other blog posts where I needed something installed. The simplicity of just hitting arkade get and then seeing if your tool or cli is available in handy. In the Linux section, we spoke about package manager and the process for getting our software, you can think about Arkade as that marketplace for all your apps and CLIs for Kubernetes. A very handy little tool to have on your systems, written in Golang and cross-platform.
|
||||
He estado utilizando Arkade durante algún tiempo para obtener todas esas herramientas y CLIs de Kubernetes. Puedes ver los pasos de instalación en este [repositorio de GitHub](https://github.com/alexellis/arkade) para comenzar con Arkade. También he mencionado esto en otras publicaciones de blog donde necesitaba instalar algo. La simplicidad de simplemente ejecutar `arkade get` y luego verificar si tu herramienta o CLI está disponible es muy útil. En la sección de Linux, hablamos sobre el administrador de paquetes y el proceso para obtener nuestro software. Puedes pensar en Arkade como ese mercado de aplicaciones y CLIs para Kubernetes. Es una herramienta muy útil para tener en tus sistemas, escrita en Golang y multiplataforma.
|
||||
|
||||

|
||||

|
||||
|
||||
As part of the long list of available apps within arkade minikube is one of them so with a simple `arkade get minikube` command we are now downloading the binary and we are good to go.
|
||||
Como parte de la larga lista de aplicaciones disponibles en Arkade, Minikube es una de ellas. Por lo tanto, con un simple comando `arkade get minikube`, ahora estamos descargando el binario y listos para continuar.
|
||||
|
||||

|
||||

|
||||
|
||||
We will also need kubectl as part of our tooling so you can also get this via arkade or I believe that the minikube documentation brings this down as part of the curl commands mentioned above. We will cover more on kubectl later on in the post.
|
||||
También necesitaremos kubectl como parte de nuestras herramientas, por lo que también puedes obtenerlo a través de Arkade o creo que la documentación de Minikube lo descarga mediante los comandos curl mencionados anteriormente. Hablaremos más sobre kubectl más adelante en la publicación.
|
||||
|
||||
### Getting a Kubernetes cluster up and running
|
||||
### Poner en marcha un clúster de Kubernetes
|
||||
|
||||
For this particular section, I want to cover the options available to us when it comes to getting a Kubernetes cluster up and running on your local machine. We could simply run the following command and it would spin up a cluster for you to use.
|
||||
En esta sección en particular, quiero cubrir las opciones disponibles para poner en marcha un clúster de Kubernetes en tu máquina local. Simplemente podríamos ejecutar el siguiente comando y se crearía un clúster para que lo utilices.
|
||||
|
||||
minikube is used on the command line, and simply put once you have everything installed you can run `minikube start` to deploy your first Kubernetes cluster. You will see below that the Docker Driver is the default as to where we will be running our nested virtualisation node. I mentioned at the start of the post the other options available, the other options help when you want to expand what this local Kubernetes cluster needs to look like.
|
||||
Minikube se utiliza en la línea de comandos y, simplemente, una vez que tienes todo instalado, puedes ejecutar `minikube start` para implementar tu primer clúster de Kubernetes. A continuación, verás que el controlador de Docker es el predeterminado para ejecutar nuestro nodo de virtualización anidado. Mencioné al principio de la publicación las otras opciones disponibles, las cuales te ayudarán cuando desees ampliar cómo debe verse este clúster de Kubernetes local.
|
||||
|
||||
A single Minikube cluster is going to consist of a single docker container in this instance which will have the control plane node and worker node in one instance. Whereas typically you would separate those nodes. Something we will cover in the next section where we look at still home lab type Kubernetes environments but a little closer to production architecture.
|
||||
Un clúster de Minikube consistirá en un solo contenedor de Docker en este caso, el cual tendrá el nodo del plano de control y el nodo de trabajo en una sola instancia. Por lo general, separaríamos esos nodos. Esto es algo que cubriremos en la siguiente sección, donde veremos entornos de Kubernetes tipo laboratorio doméstico, pero un poco más cercanos a la arquitectura de producción.
|
||||
|
||||

|
||||

|
||||
|
||||
I have mentioned this a few times now, I like minikube because of the add-ons available, the ability to deploy a cluster with a simple command including all the required addons from the start helps me deploy the same required setup every time.
|
||||
He mencionado esto varias veces antes, me gusta Minikube debido a los complementos disponibles, la capacidad de implementar un clúster con un simple comando, incluidos todos los complementos requeridos desde el principio, me ayuda a implementar la misma configuración requerida cada vez.
|
||||
|
||||
Below you can see a list of those add-ons, I generally use the `CSI-host path-driver` and the `volumesnapshots` addons but you can see the long list below. Sure these addons can generally be deployed using Helm again something we will cover later on in the Kubernetes section but this makes things much simpler.
|
||||
A continuación, puedes ver una lista de esos complementos. Por lo general, utilizo los complementos `CSI-host path-driver` y `volumesnapshots`, pero puedes ver la lista completa a continuación. Estos complementos generalmente se pueden implementar utilizando Helm, algo que también cubriremos más adelante en la sección de Kubernetes, pero esto hace las cosas mucho más simples.
|
||||
|
||||

|
||||

|
||||
|
||||
I am also defining in our project some additional configuration, apiserver is set to 6433 instead of a random API port, and I define the container runtime also to containerd however docker is default and CRI-O is also available. I am also setting a specific Kubernetes version.
|
||||
También estoy definiendo en nuestro proyecto alguna configuración adicional. El servidor de API se establece en 6433 en lugar de un puerto API aleatorio, y también defino el tiempo de ejecución del contenedor como containerd. Sin embargo, Docker es el valor predeterminado y CRI-O también está disponible. También estoy estableciendo una versión específica de Kubernetes.
|
||||
|
||||

|
||||

|
||||
|
||||
Now we are ready to deploy our first Kubernetes cluster using minikube. I mentioned before though that you will also need `kubectl` to interact with your cluster. You can get kubectl installed using arkade with the command `arkade get kubectl`
|
||||
Ahora estamos listos para implementar nuestro primer clúster de Kubernetes utilizando Minikube. Sin embargo, mencioné anteriormente que también necesitarás `kubectl` para interactuar con tu clúster. Puedes obtener kubectl instalado mediante Arkade con el comando `arkade get kubectl`
|
||||
|
||||

|
||||

|
||||
|
||||
or you can download cross-platform from the following
|
||||
o puedes descargarlo para varias plataformas desde los siguientes enlaces:
|
||||
|
||||
- [Linux](https://kubernetes.io/docs/tasks/tools/install-kubectl-linux)
|
||||
- [macOS](https://kubernetes.io/docs/tasks/tools/install-kubectl-macos)
|
||||
- [Windows](https://kubernetes.io/docs/tasks/tools/install-kubectl-windows)
|
||||
|
||||
Once you have kubectl installed we can then interact with our cluster with a simple command like `kubectl get nodes`
|
||||
Una vez que hayas instalado kubectl, puedes interactuar con tu clúster con un simple comando como `kubectl get nodes`
|
||||
|
||||

|
||||

|
||||
|
||||
### What is kubectl?
|
||||
### ¿Qué es kubectl?
|
||||
|
||||
We now have our minikube | Kubernetes cluster up and running and I have asked you to install both Minikube where I have explained at least what it does but I have not explained what kubectl is and what it does.
|
||||
Ahora tenemos nuestro clúster minikube | Kubernetes en funcionamiento y te he pedido que instales tanto Minikube, donde he explicado al menos qué hace, pero no he explicado qué es kubectl y qué hace.
|
||||
|
||||
kubectl is a cli that is used or allows you to interact with Kubernetes clusters, we are using it here for interacting with our minikube cluster but we would also use kubectl for interacting with our enterprise clusters across the public cloud.
|
||||
kubectl es una interfaz de línea de comandos que se utiliza para interactuar con clústeres de Kubernetes. Lo estamos utilizando aquí para interactuar con nuestro clúster minikube, pero también usaríamos kubectl para interactuar con nuestros clústeres empresariales en la nube pública.
|
||||
|
||||
We use kubectl to deploy applications and inspect and manage cluster resources. A much better [Overview of kubectl](https://kubernetes.io/docs/reference/kubectl/overview/) can be found here on the Kubernetes official documentation.
|
||||
Usamos kubectl para implementar aplicaciones, inspeccionar y gestionar recursos del clúster. Puedes encontrar una [Descripción general de kubectl](https://kubernetes.io/docs/reference/kubectl/overview/) mucho más detallada aquí en la documentación oficial de Kubernetes.
|
||||
|
||||
kubectl interacts with the API server found on the Control Plane node which we briefly covered in an earlier post.
|
||||
kubectl interactúa con el servidor de API que se encuentra en el nodo de plano de control, del cual hablamos brevemente en una publicación anterior.
|
||||
|
||||
### kubectl cheat sheet
|
||||
### Hoja de referencia de kubectl
|
||||
|
||||
Along with the official documentation, I have also found myself with this page open all the time when looking for kubectl commands. [Unofficial Kubernetes](https://unofficial-kubernetes.readthedocs.io/en/latest/)
|
||||
Además de la documentación oficial, también he encontrado que siempre tengo abierta esta página cuando busco comandos de kubectl. [Kubernetes no oficial](https://unofficial-kubernetes.readthedocs.io/en/latest/)
|
||||
|
||||
| Listing Resources | |
|
||||
| ------------------------ | ------------------------------------------ |
|
||||
| kubectl get nodes | List all nodes in cluster |
|
||||
| kubectl get namespaces | List all namespaces in cluster |
|
||||
| kubectl get pods | List all pods in default namespace cluster |
|
||||
| kubectl get pods -n name | List all pods in the "name" namespace |
|
||||
| Listar recursos | |
|
||||
| -------------------------- | --------------------------------------------------------------------------- |
|
||||
| kubectl get nodes | Listar todos los nodos en el clúster |
|
||||
| kubectl get namespaces | Listar todos los espacios de nombres en el clúster |
|
||||
| kubectl get pods | Listar todas las pods en el clúster en el espacio de nombres predeterminado |
|
||||
| kubectl get pods -n nombre | Listar todas las pods en el espacio de nombres "nombre" |
|
||||
|
||||
| Creating Resources | |
|
||||
| ----------------------------- | ------------------------------------------- |
|
||||
| kubectl create namespace name | Create a namespace called "name" |
|
||||
| kubectl create -f [filename] | Create a resource from a JSON or YAML file: |
|
||||
| Crear recursos | |
|
||||
| ------------------------------- | --------------------------------------------------- |
|
||||
| kubectl create namespace nombre | Crear un espacio de nombres llamado "nombre" |
|
||||
| kubectl create -f [archivo] | Crear un recurso a partir de un archivo JSON o YAML |
|
||||
|
||||
| Editing Resources | |
|
||||
| ---------------------------- | ----------------- |
|
||||
| kubectl edit svc/servicename | To edit a service |
|
||||
| Editar recursos | |
|
||||
| -------------------------------- | ------------------ |
|
||||
| kubectl edit svc/nombre-servicio | Editar un servicio |
|
||||
|
||||
| More detail on Resources | |
|
||||
| ------------------------ | ------------------------------------------------------- |
|
||||
| kubectl describe nodes | display the state of any number of resources in detail, |
|
||||
| Más detalles sobre los recursos | |
|
||||
| ------------------------------- | -------------------------------------------------------------- |
|
||||
| kubectl describe nodes | mostrar el estado de cualquier cantidad de recursos en detalle |
|
||||
|
||||
| Delete Resources | |
|
||||
| ------------------ | ------------------------------------------------ |
|
||||
| kubectl delete pod | Remove resources, this can be from stdin or file |
|
||||
| Eliminar recursos | |
|
||||
| ------------------ | ------------------------------------------------------------------------- |
|
||||
| kubectl delete pod | Eliminar recursos, puede ser desde la entrada estándar o desde un archivo |
|
||||
|
||||
You will find yourself wanting to know the short names for some of the kubectl commands, for example `-n` is the short name for `namespace` which makes it easier to type a command but also if you are scripting anything you can have much tidier code.
|
||||
Te encontrarás deseando conocer los nombres cortos para algunos de los comandos de kubectl. Por ejemplo, `-n` es el nombre corto para `namespace`, lo que facilita escribir un comando y, si estás escribiendo scripts, puedes tener un código más ordenado.
|
||||
|
||||
| Short name | Full name |
|
||||
| ---------- | -------------------------- |
|
||||
| csr | certificatesigningrequests |
|
||||
| cs | componentstatuses |
|
||||
| cm | configmaps |
|
||||
| ds | daemonsets |
|
||||
| deploy | deployments |
|
||||
| ep | endpoints |
|
||||
| ev | events |
|
||||
| hpa | horizontalpodautoscalers |
|
||||
| ing | ingresses |
|
||||
| limits | limitranges |
|
||||
| ns | namespaces |
|
||||
| no | nodes |
|
||||
| pvc | persistentvolumeclaims |
|
||||
| pv | persistentvolumes |
|
||||
| po | pods |
|
||||
| pdb | poddisruptionbudgets |
|
||||
| psp | podsecuritypolicies |
|
||||
| rs | replicasets |
|
||||
| rc | replicationcontrollers |
|
||||
| quota | resourcequotas |
|
||||
| sa | serviceaccounts |
|
||||
| svc | services |
|
||||
| Nombre corto | Nombre completo |
|
||||
| ------------ | -------------------------- |
|
||||
| csr | certificatesigningrequests |
|
||||
| cs | componentstatuses |
|
||||
| cm | configmaps |
|
||||
| ds | daemonsets |
|
||||
| deploy | deployments |
|
||||
| ep | endpoints |
|
||||
| ev | events |
|
||||
| hpa | horizontalpodautoscalers |
|
||||
| ing | ingresses |
|
||||
| limits | limitranges |
|
||||
| ns | namespaces |
|
||||
| no | nodes |
|
||||
| pvc | persistentvolumeclaims |
|
||||
| pv | persistentvolumes |
|
||||
| po | pods |
|
||||
| pdb | poddisruptionbudgets |
|
||||
| psp | podsecuritypolicies |
|
||||
| rs | replicasets |
|
||||
| rc | replicationcontrollers |
|
||||
| quota | resourcequotas |
|
||||
| sa | serviceaccounts |
|
||||
| svc | services |
|
||||
|
||||
The final thing to add here is that I created another project around minikube to help me quickly spin up demo environments to display data services and protect those workloads with Kasten K10, [Project Pace](https://github.com/MichaelCade/project_pace) can be found there and would love your feedback or interaction, it also displays or includes some automated ways of deploying your minikube clusters and creating different data services applications.
|
||||
Lo último que quiero añadir aquí es que he creado otro proyecto en torno a minikube para ayudarme a crear rápidamente entornos de demostración para mostrar servicios de datos y proteger esas cargas de trabajo con Kasten K10. Puedes encontrar [Project Pace](https://github.com/MichaelCade/project_pace) allí y me encantaría recibir tus comentarios o interactuar contigo. También muestra o incluye algunas formas automatizadas de implementar tus clústeres de minikube y crear diferentes aplicaciones de servicios de datos.
|
||||
|
||||
Next up, we will get into deploying multiple nodes into virtual machines using VirtualBox but we are going to hit the easy button there as we did in the Linux section where we used vagrant to quickly spin up the machines and deploy our software how we want them.
|
||||
A continuación, pasaremos a implementar varios nodos en máquinas virtuales utilizando VirtualBox, pero vamos a utilizar la opción fácil como lo hicimos en la sección de Linux, donde usamos Vagrant para crear rápidamente las máquinas y desplegar nuestro software según lo deseemos.
|
||||
|
||||
Añadí esta lista a la publicación de ayer, que son blogs explicativos que he hecho sobre la implementación de diferentes clústeres de Kubernetes.
|
||||
|
||||
I added this list to the post yesterday which are walkthrough blogs I have done around different Kubernetes clusters being deployed.
|
||||
|
||||
- [Kubernetes playground – How to choose your platform](https://vzilla.co.uk/vzilla-blog/building-the-home-lab-kubernetes-playground-part-1)
|
||||
- [Kubernetes playground – Setting up your cluster](https://vzilla.co.uk/vzilla-blog/building-the-home-lab-kubernetes-playground-part-2)
|
||||
@ -141,26 +142,13 @@ I added this list to the post yesterday which are walkthrough blogs I have done
|
||||
- [Getting started with CIVO Cloud](https://vzilla.co.uk/vzilla-blog/getting-started-with-civo-cloud)
|
||||
- [Minikube - Kubernetes Demo Environment For Everyone](https://vzilla.co.uk/vzilla-blog/project_pace-kasten-k10-demo-environment-for-everyone)
|
||||
|
||||
### What we will cover in the series on Kubernetes
|
||||
## Recursos
|
||||
|
||||
We have started covering some of these mentioned below but we are going to get more hands-on tomorrow with our second cluster deployment then we can start deploying applications into our clusters.
|
||||
|
||||
- Kubernetes Architecture
|
||||
- Kubectl Commands
|
||||
- Kubernetes YAML
|
||||
- Kubernetes Ingress
|
||||
- Kubernetes Services
|
||||
- Helm Package Manager
|
||||
- Persistent Storage
|
||||
- Stateful Apps
|
||||
|
||||
## Resources
|
||||
|
||||
If you have FREE resources that you have used then please feel free to add them here via a PR to the repository and I will be happy to include them.
|
||||
Si tienes recursos GRATUITOS que has utilizado, no dudes en agregarlos aquí a través de una solicitud de extracción (PR) al repositorio y estaré encantado de incluirlos.
|
||||
|
||||
- [Kubernetes Documentation](https://kubernetes.io/docs/home/)
|
||||
- [TechWorld with Nana - Kubernetes Tutorial for Beginners [FULL COURSE in 4 Hours]](https://www.youtube.com/watch?v=X48VuDVv0do)
|
||||
- [TechWorld with Nana - Kubernetes Crash Course for Absolute Beginners](https://www.youtube.com/watch?v=s_o8dwzRlu4)
|
||||
- [Kunal Kushwaha - Kubernetes Tutorial for Beginners | What is Kubernetes? Architecture Simplified!](https://www.youtube.com/watch?v=KVBON1lA9N8)
|
||||
|
||||
See you on [Day 52](day52.md)
|
||||
Nos vemos en el [Día 52](day52.md)
|
||||
|
@ -1,52 +1,52 @@
|
||||
## Setting up a multinode Kubernetes Cluster
|
||||
## Configuración de un clúster de Kubernetes multinodo
|
||||
|
||||
I wanted this title to be "Setting up a multinode Kubernetes cluster with Vagrant" but thought it might be a little too long!
|
||||
Quería que este título fuera "Configuración de un clúster de Kubernetes multinodo con Vagrant", pero pensé que podría ser un poco largo.
|
||||
|
||||
In the session yesterday we used a cool project to deploy our first Kubernetes cluster and get a little hands-on with the most important CLI tool you will come across when using Kubernetes (kubectl).
|
||||
En la sesión de ayer, utilizamos un proyecto interesante para implementar nuestro primer clúster de Kubernetes y tener un poco de práctica con la herramienta CLI más importante que encontrarás al usar Kubernetes (`kubectl`).
|
||||
|
||||
Here we are going to use VirtualBox as our base but as mentioned the last time we spoke about Vagrant back in the Linux section we can use any hypervisor or virtualisation tool supported. It was [Day 14](day14.md) when we went through and deployed an Ubuntu machine for the Linux section.
|
||||
Aquí vamos a utilizar VirtualBox como base, pero como mencioné la última vez que hablamos de Vagrant en la sección de Linux, podemos usar cualquier hipervisor o herramienta de virtualización compatible. Fue [Día 14](day14.md) cuando pasamos por el proceso de implementar una máquina Ubuntu para la sección de Linux.
|
||||
|
||||
### A quick recap on Vagrant
|
||||
### Un breve repaso sobre Vagrant
|
||||
|
||||
Vagrant is a CLI utility that manages the lifecycle of your virtual machines. We can use vagrant to spin up and down virtual machines across many different platforms including vSphere, Hyper-v, Virtual Box and also Docker. It does have other providers but we will stick with that we are using Virtual Box here so we are good to go.
|
||||
Vagrant es una utilidad de línea de comandos que gestiona el ciclo de vida de tus máquinas virtuales. Podemos usar Vagrant para crear y eliminar máquinas virtuales en diferentes plataformas, incluyendo vSphere, Hyper-V, VirtualBox y también Docker. Tiene otros proveedores, pero nos quedaremos con el que estamos usando aquí, que es VirtualBox.
|
||||
|
||||
I am going to be using a baseline this [blog and repository](https://devopscube.com/kubernetes-cluster-vagrant/) to walk through the configuration. I would however advise that if this is your first time deploying a Kubernetes cluster then maybe also look into how you would do this manually and then at least you know what this looks like. Although I will say that this Day 0 operations and effort is being made more efficient with every release of Kubernetes. I liken this very much to the days of VMware and ESX and how you would need at least a day to deploy 3 ESX servers now we can have that up and running in an hour. We are heading in that direction when it comes to Kubernetes.
|
||||
Voy a utilizar como referencia el [blog y repositorio](https://devopscube.com/kubernetes-cluster-vagrant/) para guiarme en la configuración. Sin embargo, te recomendaría que si es la primera vez que implementas un clúster de Kubernetes, también investigues cómo hacerlo manualmente, así al menos sabrás cómo se ve el proceso. Aunque debo decir que las operaciones del Día 0 y el esfuerzo se están volviendo más eficientes con cada versión de Kubernetes. Esto me recuerda mucho a los días de VMware y ESX, cuando necesitábamos al menos un día para implementar 3 servidores ESX, y ahora podemos tener todo funcionando en una hora. Nos estamos acercando a ese nivel en lo que respecta a Kubernetes.
|
||||
|
||||
### Kubernetes Lab environment
|
||||
### Entorno de laboratorio de Kubernetes
|
||||
|
||||
I have uploaded in [Kubernetes folder](Kubernetes) the vagrantfile that we will be using to build out our environment. Grab this and navigate to this directory in your terminal. I am again using Windows so I will be using PowerShell to perform my workstation commands with vagrant. If you do not have vagrant then you can use arkade, we covered this yesterday when installing minikube and other tools. A simple command `arkade get vagrant` should see your download and install the latest version of vagrant.
|
||||
He subido en la [carpeta de Kubernetes](Kubernetes) el archivo `vagrantfile` que usaremos para construir nuestro entorno. Descárgalo y navega hasta este directorio en tu terminal. En mi caso, estoy usando Windows, así que usaré PowerShell para ejecutar los comandos de mi estación de trabajo con Vagrant. Si no tienes Vagrant instalado, puedes usar arkade, que cubrimos ayer al instalar minikube y otras herramientas. Un simple comando `arkade get vagrant` debería descargar e instalar la última versión de Vagrant.
|
||||
|
||||
When you are in your directory then you can simply run `vagrant up` and if all is configured correctly then you should see the following kick-off in your terminal.
|
||||
Cuando estés en el directorio, simplemente ejecuta `vagrant up` y, si todo está configurado correctamente, deberías ver que se inicia el proceso en tu terminal.
|
||||
|
||||

|
||||

|
||||
|
||||
In the terminal, you are going to see several steps taking place, but in the meantime let's take a look at what we are building here.
|
||||
En la terminal, verás que se ejecutan varios pasos, pero mientras tanto, echemos un vistazo a lo que estamos construyendo aquí.
|
||||
|
||||

|
||||

|
||||
|
||||
From the above you can see that we are going to build out 3 virtual machines, we will have a control plane node and then two worker nodes. If you head back to [Day 49](day49.md) You will see some more descriptions of these areas we see in the image.
|
||||
Desde lo anterior, puedes ver que vamos a crear 3 máquinas virtuales. Tendremos un nodo de control y luego dos nodos de trabajo. Si vuelves al [Día 49](day49.md), verás más descripciones de estas áreas que vemos en la imagen.
|
||||
|
||||
Also in the image, we indicate that our kubectl access will come from outside of the cluster and hit that kube apiserver when in fact as part of the vagrant provisioning we are deploying kubectl on each of these nodes so that we can access the cluster from within each of our nodes.
|
||||
Además, en la imagen indicamos que nuestro acceso a `kubectl` vendrá desde fuera del clúster y llegará al `kube-apiserver`. En realidad, como parte de la provisión de Vagrant, estamos implementando `kubectl` en cada uno de estos nodos para poder acceder al clúster desde dentro de cada uno de ellos.
|
||||
|
||||
The process of building out this lab could take anything from 5 minutes to 30 minutes depending on your setup.
|
||||
El proceso de construcción de este laboratorio puede tardar entre 5 y 30 minutos, según la configuración que tengas.
|
||||
|
||||
I am going to cover the scripts shortly as well but you will notice if you look into the vagrant file that we are calling on 3 scripts as part of the deployment and this is really where the cluster is created. We have seen how easy it is to use vagrant to deploy our virtual machines and OS installations using vagrant boxes but having the ability to run a shell script as part of the deployment process is where it gets quite interesting around automating these lab build-outs.
|
||||
Voy a cubrir los scripts en breve, pero notarás que, si examinas el archivo Vagrant, estamos llamando a 3 scripts como parte de la implementación, y es aquí donde se crea realmente el clúster. Hemos visto lo fácil que es usar Vagrant para implementar nuestras máquinas virtuales e instalaciones del sistema operativo mediante cajas de Vagrant, pero la capacidad de ejecutar un script de shell como parte del proceso de implementación es lo que resulta interesante para automatizar la creación de estos laboratorios.
|
||||
|
||||
Once complete we can then ssh to one of our nodes `vagrant ssh master` from the terminal should get you access, the default username and password is `vagrant/vagrant`
|
||||
Una vez completado, podemos acceder a uno de nuestros nodos con `vagrant ssh master` desde la terminal. El nombre de usuario y contraseña predeterminados son `vagrant/vagrant`.
|
||||
|
||||
You can also use `vagrant ssh node01` and `vagrant ssh node02` to gain access to the worker nodes should you wish.
|
||||
También puedes usar `vagrant ssh node01` y `vagrant ssh node02` para acceder a los nodos de trabajo si así lo deseas.
|
||||
|
||||

|
||||

|
||||
|
||||
Now we are in one of the above nodes in our new cluster we can issue `kubectl get nodes` to show our 3 node cluster and the status of this.
|
||||
Ahora estamos en uno de los nodos anteriores de nuestro nuevo clúster y podemos ejecutar `kubectl get nodes` para mostrar nuestro clúster de 3 nodos y su estado.
|
||||
|
||||

|
||||

|
||||
|
||||
At this point, we have a running 3 node cluster, with 1 control plane node and 2 worker nodes.
|
||||
En este punto, tenemos un clúster de 3 nodos en funcionamiento, con 1 nodo de control y 2 nodos de trabajo.
|
||||
|
||||
### Vagrantfile and Shell Script walkthrough
|
||||
### Recorrido por el Vagrantfile y los scripts de shell
|
||||
|
||||
If we take a look at our vagrantfile, you will see that we are defining several worker nodes, networking IP addresses for the bridged network within VirtualBox and then some naming. Another you will notice is that we are also calling upon some scripts that we want to run on specific hosts.
|
||||
Si echamos un vistazo a nuestro Vagrantfile, verás que estamos definiendo varios nodos de trabajo, direcciones IP de red para la red puente dentro de VirtualBox y algunos nombres. Otra cosa que notarás es que también estamos llamando a algunos scripts que queremos ejecutar en hosts específicos.
|
||||
|
||||
```
|
||||
NUM_WORKER_NODES=2
|
||||
@ -91,51 +91,52 @@ Vagrant.configure("2") do |config|
|
||||
end
|
||||
```
|
||||
|
||||
Let's break down those scripts that are being run. We have three scripts listed in the above VAGRANTFILE to run on specific nodes.
|
||||
Vamos a analizar esos scripts que se están ejecutando. Tenemos tres scripts enumerados en el VAGRANTFILE anterior que se ejecutarán en nodos específicos.
|
||||
|
||||
`master.vm.provision "shell", path: "scripts/common.sh"`
|
||||
|
||||
This script above is going to focus on getting the nodes ready, it is going to be run on all 3 of our nodes and it will remove any existing Docker components and reinstall Docker and ContainerD as well kubeadm, kubelet and kubectl. This script will also update existing software packages on the system.
|
||||
Este script se centrará en preparar los nodos, se ejecutará en los 3 de nuestros nodos y eliminará cualquier componente de Docker existente y volverá a instalar Docker y ContainerD, así como kubeadm, kubelet y kubectl. Este script también actualizará los paquetes de software existentes en el sistema.
|
||||
|
||||
`master.vm.provision "shell", path: "scripts/master.sh"`
|
||||
|
||||
The master.sh script will only run on the control plane node, this script is going to create the Kubernetes cluster using kubeadm commands. It will also prepare the config context for access to this cluster which we will cover next.
|
||||
El script master.sh solo se ejecutará en el nodo del plano de control, este script creará el clúster de Kubernetes utilizando comandos de kubeadm. También preparará el contexto de configuración para acceder a este clúster, lo cual veremos a continuación.
|
||||
|
||||
`node.vm.provision "shell", path: "scripts/node.sh"`
|
||||
|
||||
This is simply going to take the config created by the master and join our nodes to the Kubernetes cluster, this join process again uses kubeadm and another script which can be found in the config folder.
|
||||
Esto simplemente tomará la configuración creada por el nodo maestro y unirá nuestros nodos al clúster de Kubernetes. Este proceso de unión también utiliza kubeadm y otro script que se puede encontrar en la carpeta de configuración.
|
||||
|
||||
### Access to the Kubernetes cluster
|
||||
### Acceso al clúster de Kubernetes
|
||||
|
||||
Now we have two clusters deployed we have the minikube cluster that we deployed in the previous section and we have the new 3 node cluster we just deployed to VirtualBox.
|
||||
Ahora que tenemos dos clústeres desplegados, el clúster minikube que desplegamos en la sección anterior y el nuevo clúster de 3 nodos que acabamos de desplegar en VirtualBox.
|
||||
|
||||
Also, that config file that you will also have access to on the machine, you ran vagrant from consists of how we can gain access to our cluster from our workstation.
|
||||
Además, ese archivo de configuración al que también tendrás acceso en la máquina desde la que ejecutaste Vagrant, consiste en cómo podemos acceder a nuestro clúster desde nuestro puesto de trabajo.
|
||||
|
||||
Before we show that let me touch on the context.
|
||||
Antes de mostrar eso, permíteme hablar sobre el contexto.
|
||||
|
||||

|
||||
|
||||
Context is important, the ability to access your Kubernetes cluster from your desktop or laptop is required. Lots of different options out there and people use different operating systems as their daily drivers.
|
||||
El contexto es importante, se requiere la capacidad de acceder a tu clúster de Kubernetes desde tu escritorio o portátil. Hay muchas opciones diferentes y las personas utilizan diferentes sistemas operativos como sus controladores diarios.
|
||||
|
||||
By default, the Kubernetes CLI client (kubectl) uses the C:\Users\username\.kube\config to store the Kubernetes cluster details such as endpoint and credentials. If you have deployed a cluster you will be able to see this file in that location. But if you have been using maybe the master node to run all of your kubectl commands so far via SSH or other methods then this post will hopefully help you get to grips with being able to connect with your workstation.
|
||||
Por defecto, el cliente de línea de comandos de Kubernetes (kubectl) utiliza el archivo C:\Users\nombredeusuario.kube\config para almacenar los detalles del clúster de Kubernetes, como el punto final y las credenciales. Si has desplegado un clúster, podrás ver este archivo en esa ubicación. Pero si hasta ahora has estado utilizando quizás el nodo maestro para ejecutar todos tus comandos de kubectl a través de SSH u otros métodos, esta publicación espero que te ayude a familiarizarte con la capacidad de conectarte desde tu estación de trabajo.
|
||||
|
||||
We then need to grab the kubeconfig file from the cluster or we can also get this from our config file once deployed, grab the contents of this file either via SCP or just open a console session to your master node and copy to the local windows machine.
|
||||
Luego debemos obtener el archivo kubeconfig del clúster, o también podemos obtenerlo de nuestro archivo de configuración una vez desplegado, obtener el contenido de este archivo ya sea mediante SCP o simplemente abrir una sesión de consola en tu nodo maestro y copiarlo a la máquina local de Windows.
|
||||
|
||||

|
||||
|
||||
We then want to take a copy of that config file and move it to our `$HOME/.kube/config` location.
|
||||
Luego queremos hacer una copia de ese archivo de configuración y moverlo a nuestra ubicación $HOME/.kube/config.
|
||||
|
||||

|
||||
|
||||
Now from your local workstation, you will be able to run `kubectl cluster-info` and `kubectl get nodes` to validate that you have access to your cluster.
|
||||
Ahora, desde tu estación de trabajo local, podrás ejecutar `kubectl cluster-info` y `kubectl get nodes` para validar que tienes acceso a tu clúster.
|
||||
|
||||

|
||||
|
||||
This not only allows for connectivity and control from your windows machine but this then also allows us to do some port forwarding to access certain services from our windows machine
|
||||
Esto no solo permite la conectividad y el control desde tu máquina con Windows, sino que también nos permite realizar un reenvío de puertos para acceder a ciertos servicios desde nuestra máquina con Windows.
|
||||
|
||||
If you are interested in how you would manage multiple clusters on your workstation then I have a more detailed walkthrough [here](https://vzilla.co.uk/vzilla-blog/building-the-home-lab-kubernetes-playground-part-6).
|
||||
Si te interesa saber cómo gestionar múltiples clústeres en tu estación de trabajo, tengo un tutorial más detallado [aquí](https://vzilla.co.uk/vzilla-blog/building-the-home-lab-kubernetes-playground-part-6).
|
||||
|
||||
He añadido esta lista de blogs explicativos que he realizado sobre el despliegue de diferentes clústeres de Kubernetes.
|
||||
|
||||
I have added this list which are walkthrough blogs I have done around different Kubernetes clusters being deployed.
|
||||
|
||||
- [Kubernetes playground – How to choose your platform](https://vzilla.co.uk/vzilla-blog/building-the-home-lab-kubernetes-playground-part-1)
|
||||
- [Kubernetes playground – Setting up your cluster](https://vzilla.co.uk/vzilla-blog/building-the-home-lab-kubernetes-playground-part-2)
|
||||
@ -147,26 +148,13 @@ I have added this list which are walkthrough blogs I have done around different
|
||||
- [Getting started with CIVO Cloud](https://vzilla.co.uk/vzilla-blog/getting-started-with-civo-cloud)
|
||||
- [Minikube - Kubernetes Demo Environment For Everyone](https://vzilla.co.uk/vzilla-blog/project_pace-kasten-k10-demo-environment-for-everyone)
|
||||
|
||||
### What we will cover in the series on Kubernetes
|
||||
## Recursos
|
||||
|
||||
We have started covering some of these mentioned below but we are going to get more hands-on tomorrow with our second cluster deployment then we can start deploying applications into our clusters.
|
||||
|
||||
- Kubernetes Architecture
|
||||
- Kubectl Commands
|
||||
- Kubernetes YAML
|
||||
- Kubernetes Ingress
|
||||
- Kubernetes Services
|
||||
- Helm Package Manager
|
||||
- Persistent Storage
|
||||
- Stateful Apps
|
||||
|
||||
## Resources
|
||||
|
||||
If you have FREE resources that you have used then please feel free to add them here via a PR to the repository and I will be happy to include them.
|
||||
Si tienes recursos GRATUITOS que has utilizado, no dudes en añadirlos aquí mediante un PR (Pull Request) al repositorio y estaré encantado de incluirlos.
|
||||
|
||||
- [Kubernetes Documentation](https://kubernetes.io/docs/home/)
|
||||
- [TechWorld with Nana - Kubernetes Tutorial for Beginners [FULL COURSE in 4 Hours]](https://www.youtube.com/watch?v=X48VuDVv0do)
|
||||
- [TechWorld with Nana - Kubernetes Crash Course for Absolute Beginners](https://www.youtube.com/watch?v=s_o8dwzRlu4)
|
||||
- [Kunal Kushwaha - Kubernetes Tutorial for Beginners | What is Kubernetes? Architecture Simplified!](https://www.youtube.com/watch?v=KVBON1lA9N8)
|
||||
|
||||
See you on [Day 53](day53.md)
|
||||
Nos vemos en el [Día 53](day53.md)
|
||||
|
@ -1,76 +1,76 @@
|
||||
## Rancher Overview - Hands On
|
||||
## Visión general de Rancher - Práctica
|
||||
|
||||
In this section we are going to take a look at Rancher, so far everything we have done has been in the cli and using kubectl but we have a few good UIs and multi-cluster management tools to give our operations teams good visibility into our cluster management.
|
||||
En esta sección vamos a echar un vistazo a Rancher. Hasta ahora, todo lo que hemos hecho ha sido en la línea de comandos (CLI) y usando `kubectl`, pero tenemos algunas buenas interfaces de usuario (UI) y herramientas de gestión de múltiples clústeres para proporcionar a nuestros equipos de operaciones una buena visibilidad de la gestión de nuestros clústeres.
|
||||
|
||||
Rancher is according to their [site](https://rancher.com/)
|
||||
Según su [sitio web](https://rancher.com/):
|
||||
|
||||
> Rancher is a complete software stack for teams adopting containers. It addresses the operational and security challenges of managing multiple Kubernetes clusters across any infrastructure while providing DevOps teams with integrated tools for running containerized workloads.
|
||||
> Rancher es una pila de software completa para equipos que adoptan contenedores. Aborda los desafíos operativos y de seguridad de la gestión de múltiples clústeres de Kubernetes en cualquier infraestructura, al tiempo que proporciona a los equipos de DevOps herramientas integradas para ejecutar cargas de trabajo en contenedores.
|
||||
|
||||
Rancher enables us to deploy production-grade Kubernetes clusters from pretty much any location and then provides centralised authentication, access control and observability. I mentioned in a previous section that there is almost an overwhelming choice when it comes to Kubernetes and where you should or could run them, looking at Rancher it doesn't matter where they are.
|
||||
Rancher nos permite implementar clústeres de Kubernetes de nivel de producción desde casi cualquier ubicación, y luego proporciona autenticación centralizada, control de acceso y observabilidad. Mencioné en una sección anterior que hay casi una abrumadora cantidad de opciones cuando se trata de Kubernetes y dónde se debería o podría ejecutar, pero con Rancher no importa dónde estén.
|
||||
|
||||
### Deploy Rancher
|
||||
### Implementar Rancher
|
||||
|
||||
The first thing we need to do is deploy Rancher on our local workstation, there are a few ways and locations you can choose to proceed with this step, for me I want to use my local workstation and run rancher as a docker container. By running the command below we will pull down a container image and then have access to the rancher UI.
|
||||
Lo primero que debemos hacer es implementar Rancher en nuestra estación de trabajo local. Hay algunas formas y ubicaciones que puedes elegir para realizar este paso. En mi caso, quiero usar mi estación de trabajo local y ejecutar Rancher como un contenedor de Docker. Al ejecutar el siguiente comando, descargaremos una imagen de contenedor y luego tendremos acceso a la interfaz de usuario de Rancher.
|
||||
|
||||
Other rancher deployment methods are available [Rancher Quick-Start-Guide](https://rancher.com/docs/rancher/v2.6/en/quick-start-guide/deployment/)
|
||||
También están disponibles otros métodos de implementación de Rancher. Puedes consultar la [Guía de inicio rápido de Rancher](https://rancher.com/docs/rancher/v2.6/en/quick-start-guide/deployment/).
|
||||
|
||||
`sudo docker run -d --restart=unless-stopped -p 80:80 -p 443:443 --privileged rancher/rancher`
|
||||
|
||||
As you can see in our Docker Desktop we have a running rancher container.
|
||||
Como puedes ver en nuestro Docker Desktop, tenemos un contenedor de Rancher en ejecución.
|
||||
|
||||

|
||||
|
||||
### Accessing Rancher UI
|
||||
### Acceder a la interfaz de usuario de Rancher
|
||||
|
||||
With the above container running we should be able to navigate to it via a web page. `https://localhost` will bring up a login page as per below.
|
||||
Con el contenedor anterior en ejecución, deberíamos poder acceder a él a través de una página web. Acceder a `https://localhost` nos mostrará una página de inicio de sesión como se muestra a continuación.
|
||||
|
||||

|
||||
|
||||
Follow the instructions below to get the password required. Because I am using Windows I chose to use bash for Windows because of the grep command required.
|
||||
Sigue las instrucciones a continuación para obtener la contraseña requerida. Como estoy usando Windows, elegí usar bash para Windows debido al comando `grep` necesario.
|
||||
|
||||

|
||||
|
||||
We can then take the above password and log in, the next page is where we can define a new password.
|
||||
Luego podemos tomar la contraseña anterior e iniciar sesión. La siguiente página es donde podemos definir una nueva contraseña.
|
||||
|
||||

|
||||
|
||||
Once we have done the above we will then be logged in and we can see our opening screen. As part of the Rancher deployment, we will also see a local K3s cluster provisioned.
|
||||
Una vez que hayamos hecho lo anterior, iniciaremos sesión y podremos ver nuestra pantalla de inicio. Como parte de la implementación de Rancher, también veremos un clúster local de K3s creado.
|
||||
|
||||

|
||||
|
||||
### A quick tour of rancher
|
||||
### un recorrido rápido por rancher
|
||||
|
||||
The first thing for us to look at is our locally deployed K3S cluster You can see below that we get a good visual of what is happening inside our cluster. This is the default deployment and we have not yet deployed anything to this cluster. You can see it is made up of 1 node and has 5 deployments. Then you can also see that there are some stats on pods, cores and memory.
|
||||
Lo primero que veremos es nuestro clúster K3S implementado localmente. Como se muestra a continuación, obtendremos una buena visualización de lo que está sucediendo dentro de nuestro clúster. Esta es la implementación predeterminada y aún no hemos implementado nada en este clúster. Podemos ver que está compuesto por 1 nodo y tiene 5 implementaciones. También podemos ver algunas estadísticas sobre pods, núcleos y memoria.
|
||||
|
||||

|
||||
|
||||
On the left-hand menu, we also have an Apps & Marketplace tab, this allows us to choose applications we would like to run on our clusters, as mentioned previously Rancher gives us the capability of running or managing several different clusters. With the marketplace, we can deploy our applications very easily.
|
||||
En el menú de la izquierda, también tenemos una pestaña "Apps & Marketplace" (Aplicaciones y Mercado). Esto nos permite elegir las aplicaciones que queremos ejecutar en nuestros clústeres. Como se mencionó anteriormente, Rancher nos brinda la capacidad de ejecutar o administrar varios clústeres diferentes. Con el marketplace, podemos implementar nuestras aplicaciones de manera muy sencilla.
|
||||
|
||||

|
||||
|
||||
Another thing to mention is that if you did need to get access to any cluster being managed by Rancher in the top right you can open a kubectl shell to the selected cluster.
|
||||
Otra cosa importante es que, si necesitamos acceder a cualquier clúster administrado por Rancher, podemos abrir una shell de kubectl en el clúster seleccionado.
|
||||
|
||||

|
||||
|
||||
### Create a new cluster
|
||||
### Crear un nuevo clúster
|
||||
|
||||
Over the past two sessions, we have created a minikube cluster locally and we have used Vagrant with VirtualBox to create a 3 node Kubernetes cluster, with Rancher we can also create clusters. In the [Rancher Folder](Kubernetes/Rancher) you will find additional vagrant files that will build out the same 3 nodes but without the steps for creating our Kubernetes cluster (we want Rancher to do this for us)
|
||||
En las últimas dos sesiones, hemos creado un clúster de minikube localmente y hemos utilizado Vagrant con VirtualBox para crear un clúster de Kubernetes de 3 nodos. Con Rancher, también podemos crear clústeres. En la [carpeta Rancher](Kubernetes/Rancher) encontrarás archivos adicionales de Vagrant que crearán los mismos 3 nodos, pero sin los pasos para crear nuestro clúster de Kubernetes (queremos que Rancher lo haga por nosotros).
|
||||
|
||||
We do however want docker installed and for the OS to be updated so you will still see the `common.sh` script being run on each of our nodes. This will also install Kubeadm, Kubectl etc. But it will not run the Kubeadm commands to create and join our nodes into a cluster.
|
||||
Sin embargo, es necesario tener Docker instalado y actualizar el sistema operativo. Aún verás que se ejecuta el script common.sh en cada uno de nuestros nodos. Esto también instalará Kubeadm, Kubectl, etc., pero no ejecutará los comandos de Kubeadm para crear y unir nuestros nodos en un clúster.
|
||||
|
||||
We can navigate to our vagrant folder location and we can simply run `vagrant up` and this will begin the process of creating our 3 VMs in VirtualBox.
|
||||
Podemos ir a la ubicación de nuestra carpeta de Vagrant y simplemente ejecutar vagrant up para comenzar el proceso de creación de nuestras 3 máquinas virtuales en VirtualBox.
|
||||
|
||||

|
||||
|
||||
Now that we have our nodes or VMs in place and ready, we can then use Rancher to create our new Kubernetes cluster. The first screen to create your cluster gives you some options as to where your cluster is, i.e are you using the public cloud managed Kubernetes services, vSphere or something else.
|
||||
Ahora que tenemos nuestros nodos o máquinas virtuales en su lugar y listos, podemos usar Rancher para crear nuestro nuevo clúster de Kubernetes. La primera pantalla para crear tu clúster te ofrece algunas opciones sobre dónde se encuentra tu clúster, es decir, si estás utilizando servicios administrados de Kubernetes en la nube pública, vSphere o cualquier otra opción integrada.
|
||||
|
||||

|
||||
|
||||
We will be choosing "custom" as we are not using one of the integrated platforms. The opening page is where you define your cluster name (it says local below but you cannot use local, our cluster is called vagrant.) you can define Kubernetes versions here, network providers and some other configuration options to get your Kubernetes cluster up and running.
|
||||
eleccionaremos "custom" ya que no estamos utilizando una de las plataformas integradas. La página de apertura es donde puedes definir el nombre de tu clúster (dice "local" a continuación, pero no puedes usar "local"; nuestro clúster se llama "vagrant"). Aquí puedes definir las versiones de Kubernetes, los proveedores de red y algunas otras opciones de configuración para poner en marcha tu clúster de Kubernetes.
|
||||
|
||||

|
||||
|
||||
The next page is going to give you the registration code that needs to be run on each of your nodes with the appropriate services to be enabled. etcd, control-plane and worker. For our master node, we want etcd and control-plane so the command can be seen below.
|
||||
La siguiente página te proporcionará el código de registro que debe ejecutarse en cada uno de tus nodos con los servicios apropiados habilitados: etcd, control-plane y worker. Para nuestro nodo maestro, queremos habilitar etcd y control-plane, por lo que el comando se muestra a continuación.
|
||||
|
||||

|
||||
|
||||
@ -78,11 +78,11 @@ The next page is going to give you the registration code that needs to be run on
|
||||
sudo docker run -d --privileged --restart=unless-stopped --net=host -v /etc/kubernetes:/etc/kubernetes -v /var/run:/var/run rancher/rancher-agent:v2.6.3 --server https://10.0.0.1 --token mpq8cbjjwrj88z4xmf7blqxcfmwdsmq92bmwjpphdkklfckk5hfwc2 --ca-checksum a81944423cbfeeb92be0784edebba1af799735ebc30ba8cbe5cc5f996094f30b --etcd --controlplane
|
||||
```
|
||||
|
||||
If networking is configured correctly then you should pretty quickly see the following in your rancher dashboard, indicating that the first master node is now being registered and the cluster is being created.
|
||||
Si la configuración de la red está correctamente, deberías ver rápidamente lo siguiente en tu panel de Rancher, lo que indica que el primer nodo maestro se está registrando y se está creando el clúster.
|
||||
|
||||

|
||||
|
||||
We can then repeat the registration process for each of the worker nodes with the following command and after some time you will have your cluster up and running with the ability to leverage the marketplace to deploy your applications.
|
||||
Luego, podemos repetir el proceso de registro para cada uno de los nodos de trabajo con el siguiente comando, y después de algún tiempo, tendrás tu clúster funcionando y podrás aprovechar el mercado para implementar tus aplicaciones.
|
||||
|
||||
```
|
||||
sudo docker run -d --privileged --restart=unless-stopped --net=host -v /etc/kubernetes:/etc/kubernetes -v /var/run:/var/run rancher/rancher-agent:v2.6.3 --server https://10.0.0.1 --token mpq8cbjjwrj88z4xmf7blqxcfmwdsmq92bmwjpphdkklfckk5hfwc2 --ca-checksum a81944423cbfeeb92be0784edebba1af799735ebc30ba8cbe5cc5f996094f30b --worker
|
||||
@ -90,30 +90,17 @@ sudo docker run -d --privileged --restart=unless-stopped --net=host -v /etc/kube
|
||||
|
||||

|
||||
|
||||
Over the last 3 sessions, we have used a few different ways to get up and running with a Kubernetes cluster, over the remaining days we are going to look at the application side of the platform arguably the most important. We will look into services and being able to provision and use our service in Kubernetes.
|
||||
Durante las últimas 3 sesiones, hemos utilizado diferentes formas para poner en marcha un clúster de Kubernetes. En los días restantes, vamos a centrarnos en el lado de la aplicación de la plataforma, que es posiblemente el aspecto más importante. Analizaremos los servicios y la capacidad de aprovisionar y utilizar nuestros servicios en Kubernetes.
|
||||
|
||||
I have been told since that the requirements around bootstrapping rancher nodes require those VMs to have 4GB ram or they will crash-loop, I have since updated as our worker nodes had 2GB.
|
||||
Me han informado que los requisitos para el inicio de los nodos de Rancher requieren que esas VM tengan 4 GB de RAM o entrarán en un bucle de reinicio. Desde entonces, he actualizado los nodos de trabajo, ya que tenían 2 GB.
|
||||
|
||||
### What we will cover in the series on Kubernetes
|
||||
## Recursos
|
||||
|
||||
We have started covering some of these mentioned below but we are going to get more hands-on tomorrow with our second cluster deployment then we can start deploying applications into our clusters.
|
||||
|
||||
- Kubernetes Architecture
|
||||
- Kubectl Commands
|
||||
- Kubernetes YAML
|
||||
- Kubernetes Ingress
|
||||
- Kubernetes Services
|
||||
- Helm Package Manager
|
||||
- Persistent Storage
|
||||
- Stateful Apps
|
||||
|
||||
## Resources
|
||||
|
||||
If you have FREE resources that you have used then please feel free to add them here via a PR to the repository and I will be happy to include them.
|
||||
Si tienes recursos GRATUITOS que has utilizado, por favor, siéntete libre de agregarlos aquí mediante una solicitud de extracción (PR) al repositorio, y estaré encantado de incluirlos.
|
||||
|
||||
- [Kubernetes Documentation](https://kubernetes.io/docs/home/)
|
||||
- [TechWorld with Nana - Kubernetes Tutorial for Beginners [FULL COURSE in 4 Hours]](https://www.youtube.com/watch?v=X48VuDVv0do)
|
||||
- [TechWorld with Nana - Kubernetes Crash Course for Absolute Beginners](https://www.youtube.com/watch?v=s_o8dwzRlu4)
|
||||
- [Kunal Kushwaha - Kubernetes Tutorial for Beginners | What is Kubernetes? Architecture Simplified!](https://www.youtube.com/watch?v=KVBON1lA9N8)
|
||||
|
||||
See you on [Day 54](day54.md)
|
||||
Nos vemos en el [Día 54](day54.md)
|
||||
|
@ -1,26 +1,28 @@
|
||||
## Kubernetes Application Deployment
|
||||
## Implementación de aplicaciones en Kubernetes
|
||||
|
||||
Now we finally get to deploying some applications into our clusters, some would say this is the reason Kubernetes exists, for Application delivery.
|
||||
Ahora finalmente vamos a implementar algunas aplicaciones en nuestros clústeres, algunos podrían decir que esta es la razón por la cual Kubernetes existe, para la entrega de aplicaciones.
|
||||
|
||||
The idea here is that we can take our container images and now deploy these as pods into our Kubernetes cluster to take advantage of Kubernetes as a container orchestrator.
|
||||
La idea aquí es que podemos tomar nuestras imágenes de contenedor y desplegarlas como pods en nuestro clúster de Kubernetes para aprovechar Kubernetes como un orquestador de contenedores.
|
||||
|
||||
### Deploying Apps into Kubernetes
|
||||
### Implementación de aplicaciones en Kubernetes
|
||||
|
||||
There are several ways in which we can deploy our applications into our Kubernetes cluster, we will cover two of the most common approaches which will be YAML files and Helm charts.
|
||||
Existen varias formas en las que podemos implementar nuestras aplicaciones en nuestro clúster de Kubernetes, cubriremos dos de los enfoques más comunes que son archivos YAML y gráficos Helm.
|
||||
|
||||
We will be using our minikube cluster for these application deployments. We will be walking through some of the previously mentioned components or building blocks of Kubernetes.
|
||||
Utilizaremos nuestro clúster minikube para estas implementaciones de aplicaciones. Repasaremos algunos de los componentes o bloques de construcción de Kubernetes mencionados anteriormente.
|
||||
|
||||
All through this section and the Container section we have discussed images and the benefits of Kubernetes and how we can handle scale quite easily on this platform.
|
||||
En esta sección y la sección de Contenedores, hemos discutido las imágenes y los beneficios de Kubernetes, y cómo podemos manejar fácilmente la escala en esta plataforma.
|
||||
|
||||
In this first step, we are simply going to create a stateless application within our minikube cluster. We will be using the defacto standard stateless application in our first demonstration `nginx` we will configure a Deployment, which will provide us with our pods and then we will also create a service which will allow us to navigate to the simple web server hosted by the nginx pod. All of this will be contained in a namespace.
|
||||
En este primer paso, simplemente vamos a crear una aplicación sin estado dentro de nuestro clúster minikube. Utilizaremos la aplicación sin estado de facto estándar en nuestra primera demostración: `nginx`. Configuraremos una Implementación (Deployment), que nos proporcionará nuestros pods, y luego también crearemos un servicio que nos permitirá acceder al servidor web simple alojado por el pod de nginx. Todo esto estará contenido en un espacio de nombres.
|
||||
|
||||

|
||||
|
||||
### Creating the YAML
|
||||
|
||||
In the first demo, we want to define everything we do with YAML, we could have a whole section on YAML but I am going to skim over this and leave some resources at the end that will cover YAML in more detail.
|
||||
Creación del archivo YAML
|
||||
|
||||
We could create the following as one YAML file or we could break this down for each aspect of our application, i.e this could be separate files for namespace, deployment and service creation but in this file, below we separate these by using `---` in one file. You can find this file located [here](Kubernetes) (File name:- nginx-stateless-demo.YAML)
|
||||
En la primera demostración, queremos definir todo lo que hacemos con YAML. Podríamos tener una sección completa sobre YAML, pero voy a pasar por alto esto y dejar algunos recursos al final que cubrirán YAML en más detalle.
|
||||
|
||||
Podemos crear lo siguiente como un archivo YAML o podemos dividir esto en cada aspecto de nuestra aplicación, es decir, podrían ser archivos separados para el espacio de nombres, la implementación y la creación del servicio, pero en este archivo, a continuación, separamos esto usando `---` en un solo archivo. Puede encontrar este archivo ubicado [aquí](Kubernetes) (File name:- nginx-stateless-demo.YAML)
|
||||
|
||||
```Yaml
|
||||
apiVersion: v1
|
||||
@ -66,113 +68,113 @@ spec:
|
||||
targetPort: 80
|
||||
```
|
||||
|
||||
### Checking our cluster
|
||||
### Verificando nuestro clúster
|
||||
|
||||
Before we deploy anything we should just make sure that we have no existing namespaces called `nginx` we can do this by running the `kubectl get namespace` command and as you can see below we do not have a namespace called `nginx`
|
||||
Antes de implementar cualquier cosa, debemos asegurarnos de que no tengamos ningún espacio de nombres existente llamado `nginx`. Podemos hacer esto ejecutando el comando kubectl get namespace y como puedes ver a continuación, no tenemos un espacio de nombres llamado `nginx`.
|
||||
|
||||

|
||||
|
||||
### Time to deploy our App
|
||||
### Hora de implementar nuestra aplicación
|
||||
|
||||
Now we are ready to deploy our application to our minikube cluster, this same process will work on any other Kubernetes cluster.
|
||||
Ahora estamos listos para implementar nuestra aplicación en nuestro clúster de minikube, este mismo proceso funcionará en cualquier otro clúster de Kubernetes.
|
||||
|
||||
We need to navigate to our YAML file location and then we can run `kubectl create -f nginx-stateless-demo.yaml` which you then see that 3 objects have been created, and we have a namespace, deployment and service.
|
||||
Necesitamos navegar hasta la ubicación de nuestro archivo YAML y luego podemos ejecutar kubectl `create -f nginx-stateless-demo.yaml`, lo que te mostrará que se han creado 3 objetos, y tenemos un espacio de nombres, una implementación y un servicio.
|
||||
|
||||

|
||||
|
||||
Let's run the command again to see our available namespaces in our cluster `kubectl get namespace` and you can now see that we have our new namespace.
|
||||
Ejecutemos el comando nuevamente para ver nuestros espacios de nombres disponibles en nuestro clúster `kubectl get namespace` y ahora puedes ver que tenemos nuestro nuevo espacio de nombres.
|
||||
|
||||

|
||||
|
||||
If we then check our namespace for pods using `kubectl get pods -n nginx` you will see that we have 1 pod in a ready and running state.
|
||||
Si luego verificamos nuestro espacio de nombres para los pods usando `kubectl get pods -n nginx`, verás que tenemos 1 pod en estado listo y en ejecución.
|
||||
|
||||

|
||||
|
||||
We can also check our service is created by running `kubectl get service -n nginx`
|
||||
También podemos verificar que nuestro servicio se haya creado ejecutando `kubectl get service -n nginx`.
|
||||
|
||||

|
||||
|
||||
Finally, we can then go and check our deployment, the deployment is where and how we keep our desired configuration.
|
||||
Finalmente, podemos verificar nuestra implementación, la implementación es donde y cómo mantenemos nuestra configuración deseada.
|
||||
|
||||

|
||||
|
||||
The above takes a few commands that are worth knowing but you can also use `kubectl get all -n nginx` to see everything we deployed with that one YAML file.
|
||||
Lo anterior requiere algunos comandos que vale la pena conocer, pero también puedes usar `kubectl get all -n nginx` para ver todo lo que implementamos con ese archivo YAML.
|
||||
|
||||

|
||||
|
||||
You will notice in the above that we also have a replicaset, in our deployment we define how many replicas of our image we would like to deploy. This was set to 1 initially, but if we wanted to quickly scale our application then we can do these several ways.
|
||||
Observarás que también tenemos un replicaset en la implementación. En nuestra implementación, definimos cuántas réplicas de nuestra imagen nos gustaría implementar. Inicialmente se estableció en 1, pero si quisiéramos escalar rápidamente nuestra aplicación, podemos hacerlo de varias formas.
|
||||
|
||||
We can edit our file using `kubectl edit deployment nginx-deployment -n nginx` which will open a text editor within your terminal and enable you to modify your deployment.
|
||||
Podemos editar nuestro archivo usando `kubectl edit deployment nginx-deployment -n nginx`, lo cual abrirá un editor de texto dentro de tu terminal y te permitirá modificar tu implementación.
|
||||
|
||||

|
||||
|
||||
Upon saving the above in your text editor within the terminal if there were no issues and the correct formatting was used then you should see additional deployed in your namespace.
|
||||
Al guardar lo anterior en tu editor de texto dentro de la terminal, si no hubo problemas y se utilizó el formato correcto, deberías ver que se implementan réplicas adicionales en tu espacio de nombres.
|
||||
|
||||

|
||||
|
||||
We can also make a change to the number of replicas using kubectl and the `kubectl scale deployment nginx-deployment --replicas=10 -n nginx`
|
||||
También podemos realizar un cambio en el número de réplicas utilizando `kubectl scale deployment nginx-deployment --replicas=10 -n nginx`.
|
||||
|
||||

|
||||
|
||||
We can equally use this method to scale our application down back to 1 again if we wish to use either method. I used the edit option but you can also use the scale command above.
|
||||
Del mismo modo, podemos utilizar este método para reducir la escala de nuestra aplicación nuevamente a 1 si deseamos utilizar cualquiera de los dos métodos. Yo utilicé la opción de edición, pero también puedes usar el comando de escala mencionado anteriormente.
|
||||
|
||||

|
||||
|
||||
Hopefully, here you can see the use case not only are things super fast to spin up and down but we have the ability to quickly scale up and down our applications. If this was a web server we could scale up during busy times and down when the load is quiet.
|
||||
Espero que aquí puedas ver el caso de uso. No solo es extremadamente rápido iniciar y detener las cosas, sino que también tenemos la capacidad de escalar rápidamente nuestras aplicaciones hacia arriba y hacia abajo. Si esto fuera un servidor web, podríamos escalar durante los momentos de alta demanda y reducirlo cuando la carga sea baja.
|
||||
|
||||
### Exposing our app
|
||||
### Exponiendo nuestra aplicación
|
||||
|
||||
But how do we access our web server?
|
||||
Pero ¿cómo accedemos a nuestro servidor web?
|
||||
|
||||
If you look above at our service you will see there is no External IP available so we cannot just open a web browser and expect this to be there magically. For access, we have a few options.
|
||||
Si observas arriba nuestro servicio, verás que no hay una IP externa disponible, por lo que no podemos abrir un navegador web y esperar que esté ahí mágicamente. Para acceder, tenemos algunas opciones.
|
||||
|
||||
**ClusterIP** - The IP you do see is a ClusterIP this is on an internal network on the cluster. Only things within the cluster can reach this IP.
|
||||
**ClusterIP** - La IP que ves es un ClusterIP, que se encuentra en una red interna del clúster. Solo los elementos dentro del clúster pueden acceder a esta IP.
|
||||
|
||||
**NodePort** - Exposes the service on the same port of each of the selected nodes in the cluster using NAT.
|
||||
**NodePort** - Expone el servicio en el mismo puerto de cada uno de los nodos seleccionados en el clúster utilizando NAT.
|
||||
|
||||
**LoadBalancer** - Creates an external load balancer in the current cloud, we are using minikube but also if you have built your own Kubernetes cluster i.e what we did in VirtualBox you would need to deploy a LoadBalancer such as metallb into your cluster to provide this functionality.
|
||||
**LoadBalancer** - Crea un balanceador de carga externo en la nube actual. Estamos utilizando minikube, pero si has creado tu propio clúster de Kubernetes, como lo hicimos en VirtualBox, necesitarías implementar un balanceador de carga como metallb en tu clúster para proporcionar esta funcionalidad.
|
||||
|
||||
**Port-Forward** - We also have the ability to Port Forward, which allows you to access and interact with internal Kubernetes cluster processes from your localhost. This option is only for testing and fault finding.
|
||||
**Port-Forward** - También tenemos la capacidad de reenvío de puertos, lo que te permite acceder e interactuar con los procesos internos del clúster de Kubernetes desde tu localhost. Esta opción solo se utiliza para pruebas y solución de problemas.
|
||||
|
||||
We now have a few options to choose from, Minikube has some limitations or differences I should say to a full-blown Kubernetes cluster.
|
||||
|
||||
We could simply run the following command to port forward our access using our local workstation.
|
||||
Ahora tenemos algunas opciones para elegir. Minikube tiene algunas limitaciones o diferencias, podríamos simplemente ejecutar el siguiente comando para redirigir nuestro acceso utilizando nuestra estación de trabajo local.
|
||||
|
||||
`kubectl port-forward deployment/nginx-deployment -n nginx 8090:80`
|
||||
|
||||

|
||||
|
||||
note that when you run the above command this terminal is now unusable as this is acting as your port forward to your local machine and port.
|
||||
Ten en cuenta que cuando ejecutas el comando anterior, esta terminal ya no es utilizable, ya que actúa como reenvío de puertos a tu máquina local y puerto.
|
||||
|
||||

|
||||
|
||||
We are now going to run through specifically with Minikube how we can expose our application. We can also use minikube to create a URL to connect to a service [More details](https://minikube.sigs.k8s.io/docs/commands/service/)
|
||||
Ahora vamos a explicar específicamente con Minikube cómo podemos exponer nuestra aplicación. También podemos usar minikube para crear una URL y conectarnos a un servicio [Más detalles](https://minikube.sigs.k8s.io/docs/commands/service/)
|
||||
|
||||
First of all, we will delete our service using `kubectl delete service nginx-service -n nginx`
|
||||
En primer lugar, eliminaremos nuestro servicio usando `kubectl delete service nginx-service -n nginx`
|
||||
|
||||
Next, we are going to create a new service using `kubectl expose deployment nginx-deployment --name nginx-service --namespace nginx --port=80 --type=NodePort` notice here that we are going to use the expose and change the type to NodePort.
|
||||
A continuación, crearemos un nuevo servicio utilizando `kubectl expose deployment nginx-deployment --name nginx-service --namespace nginx --port=80 --type=NodePort`. Observa que aquí estamos usando "expose" y cambiamos el tipo a NodePort.
|
||||
|
||||

|
||||
|
||||
Finally in a new terminal run `minikube --profile='mc-demo' service nginx-service --URL -n nginx` to create a tunnel for our service.
|
||||
Finalmente, en una nueva terminal, ejecuta `minikube --profile='mc-demo' service nginx-service --URL -n nginx` para crear un túnel para nuestro servicio.
|
||||
|
||||

|
||||
|
||||
Open a browser or control and click on the link in your terminal.
|
||||
Abre un navegador o haz clic en el enlace en tu terminal.
|
||||
|
||||
|
||||

|
||||
|
||||
### Helm
|
||||
|
||||
Helm is another way in which we can deploy our applications. Known as "The package manager for Kubernetes" You can find out more [here](https://helm.sh/)
|
||||
Helm es otra forma en la que podemos implementar nuestras aplicaciones. Conocido como "el administrador de paquetes para Kubernetes". Puedes obtener más información [aquí](https://helm.sh/).
|
||||
|
||||
Helm is a package manager for Kubernetes. Helm could be considered the Kubernetes equivalent of yum or apt. Helm deploys charts, which you can think of like a packaged application., it is a blueprint for your pre-configured application resources which can be deployed as one easy-to-use chart. You can then deploy another version of the chart with a different set of configurations.
|
||||
Helm es un administrador de paquetes para Kubernetes. Se podría considerar que Helm es el equivalente de Kubernetes a yum o apt. Helm implementa gráficos, que puedes pensar como una aplicación empaquetada. Es un modelo para los recursos de tu aplicación preconfigurada, que se pueden implementar como un gráfico fácil de usar. Luego, puedes implementar otra versión del gráfico con un conjunto diferente de configuraciones.
|
||||
|
||||
They have a site where you can browse all the Helm charts available and of course, you can create your own. The documentation is also clear and concise and not as daunting as when I first started hearing the term helm amongst all of the other new words in this space.
|
||||
Tienen un sitio web donde puedes explorar todos los gráficos de Helm disponibles y, por supuesto, puedes crear los tuyos propios. La documentación también es clara y concisa, no es tan abrumadora como cuando escuché el término "helm" por primera vez junto con todas las demás palabras nuevas en este espacio.
|
||||
|
||||
It is super simple to get Helm up and running or installed. Simply. You can find the binaries and download links here for pretty much all distributions including your RaspberryPi arm64 devices.
|
||||
Es muy sencillo poner en marcha o instalar Helm. Simplemente puedes encontrar los binarios y los enlaces de descarga aquí, para prácticamente todas las distribuciones, incluyendo dispositivos Raspberry Pi arm64.
|
||||
|
||||
O puedes utilizar un script de instalación, la ventaja aquí es que se descargará e instalará la última versión de Helm.
|
||||
|
||||
Or you can use an installer script, the benefit here is that the latest version of the helm will be downloaded and installed.
|
||||
|
||||
```Shell
|
||||
curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3
|
||||
@ -182,32 +184,23 @@ chmod 700 get_helm.sh
|
||||
./get_helm.sh
|
||||
```
|
||||
|
||||
Finally, there is also the option to use a package manager for the application manager, homebrew for mac, chocolatey for windows, apt with Ubuntu/Debian, snap and pkg also.
|
||||
Finalmente, también existe la opción de utilizar un administrador de paquetes para el administrador de aplicaciones, como Homebrew para Mac, Chocolatey para Windows, apt para Ubuntu/Debian, snap y pkg también.
|
||||
|
||||
Helm so far seems to be the go-to way to get different test applications downloaded and installed in your cluster.
|
||||
Hasta ahora, Helm parece ser la forma preferida de descargar e instalar diferentes aplicaciones de prueba en tu clúster.
|
||||
|
||||
A good resource to link here would be [ArtifactHUB](https://artifacthub.io/) which is a resource to find, install and publish Kubernetes packages. I will also give a shout-out to [KubeApps](https://kubeapps.com/) which is a UI to display helm charts.
|
||||
Un buen recurso para enlazar aquí sería [ArtifactHUB](https://artifacthub.io/), que es un recurso para encontrar, instalar y publicar paquetes de Kubernetes. También quiero mencionar [KubeApps](https://kubeapps.com/), que es una interfaz de usuario para mostrar gráficos de Helm.
|
||||
|
||||
### What we will cover in the series on Kubernetes
|
||||
## Recursos
|
||||
|
||||
We have started covering some of these mentioned below but we are going to get more hands-on tomorrow with our second cluster deployment then we can start deploying applications into our clusters.
|
||||
|
||||
- Kubernetes Architecture
|
||||
- Kubectl Commands
|
||||
- Kubernetes YAML
|
||||
- Kubernetes Ingress
|
||||
- Kubernetes Services
|
||||
- Helm Package Manager
|
||||
- Persistent Storage
|
||||
- Stateful Apps
|
||||
|
||||
## Resources
|
||||
|
||||
If you have FREE resources that you have used then please feel free to add them here via a PR to the repository and I will be happy to include them.
|
||||
Si tienes recursos GRATUITOS que has utilizado, siéntete libre de agregarlos aquí mediante un PR al repositorio y estaré encantado de incluirlos.
|
||||
|
||||
- [Kubernetes Documentation](https://kubernetes.io/docs/home/)
|
||||
- [TechWorld with Nana - Kubernetes Tutorial for Beginners [FULL COURSE in 4 Hours]](https://www.youtube.com/watch?v=X48VuDVv0do)
|
||||
- [TechWorld with Nana - Kubernetes Crash Course for Absolute Beginners](https://www.youtube.com/watch?v=s_o8dwzRlu4)
|
||||
- [Kunal Kushwaha - Kubernetes Tutorial for Beginners | What is Kubernetes? Architecture Simplified!](https://www.youtube.com/watch?v=KVBON1lA9N8)
|
||||
- [Guía Helm](https://gitea.vergaracarmona.es/man-linux/Guia-Tutorial-kubernetes/src/branch/main/guias/05-helm.md)
|
||||
- [Ejecutar Charts de Helm con helmfile](https://vergaracarmona.es/ejecutar-charts-de-helm-con-helmfile/)
|
||||
- [Helm Umbrella Charts](https://vergaracarmona.es/helm-umbrella-charts/)
|
||||
- [Apuntes de curso Helm](https://vergaracarmona.es/wp-content/uploads/2022/12/Curso_Helm_vergaracarmona.es_.pdf)
|
||||
|
||||
See you on [Day 55](day55.md)
|
||||
Nos vemos en el [Día 55](day55.md)
|
||||
|
@ -1,216 +1,216 @@
|
||||
## State and Ingress in Kubernetes
|
||||
## Estado e Ingress en Kubernetes
|
||||
|
||||
In this closing section of Kubernetes, we are going to take a look at State and ingress.
|
||||
En esta sección final de Kubernetes, vamos a echar un vistazo al estado e Ingress.
|
||||
|
||||
Everything we have said so far is about stateless, stateless is really where our applications do not care which network it is using and does not need any permanent storage. Whereas stateful apps and databases for example for such an application to function correctly, you’ll need to ensure that pods can reach each other through a unique identity that does not change (hostnames, IPs...etc.). Examples of stateful applications include MySQL clusters, Redis, Kafka, MongoDB and others. Basically, through any application that stores data.
|
||||
Todo lo que hemos dicho hasta ahora es acerca de stateless, stateless es realmente donde nuestras aplicaciones no se preocupan por qué red están utilizando y no necesitan ningún almacenamiento permanente. Mientras que las aplicaciones y bases de datos stateful, por ejemplo, para que dicha aplicación funcione correctamente, deberás asegurarte de que los pods puedan alcanzarse entre sí a través de una identidad única que no cambie (nombres de host, IP, etc.). Ejemplos de aplicaciones stateful incluyen clústeres MySQL, Redis, Kafka, MongoDB y otros. Básicamente, a través de cualquier aplicación que almacene datos.
|
||||
|
||||
### Stateful Application
|
||||
### Aplicación stateful
|
||||
|
||||
StatefulSets represent a set of Pods with unique, persistent identities and stable hostnames that Kubernetes maintains regardless of where they are scheduled. The state information and other resilient data for any given StatefulSet Pod are maintained in persistent disk storage associated with the StatefulSet.
|
||||
StatefulSets representan un conjunto de Pods con identidades únicas y persistentes y nombres de host estables que Kubernetes mantiene independientemente de dónde se programen. La información de estado y otros datos resilientes para cualquier Pod dado de StatefulSet se mantienen en almacenamiento de disco persistente asociado con StatefulSet.
|
||||
|
||||
### Deployment vs StatefulSet
|
||||
### DImplementación frente a StatefulSet
|
||||
|
||||
- Replicating stateful applications is more difficult.
|
||||
- Replicating our pods in a deployment (Stateless Application) is identical and interchangeable.
|
||||
- Create pods in random order with random hashes
|
||||
- One Service that load balances to any Pod.
|
||||
- Replicar aplicaciones stateful es más difícil.
|
||||
- Replicar nuestros pods en una implementación (aplicación sin estado) es idéntico e intercambiable.
|
||||
- Crea pods en orden aleatorio con hashes aleatorios
|
||||
- Un solo servicio que equilibra la carga a cualquier Pod.
|
||||
|
||||
When it comes to StatefulSets or Stateful Applications the above is more difficult.
|
||||
Cuando se trata de StatefulSets o aplicaciones stateful, lo anterior es más difícil.
|
||||
|
||||
- Cannot be created or deleted at the same time.
|
||||
- Can't be randomly addressed.
|
||||
- replica Pods are not identical
|
||||
- No se pueden crear ni eliminar al mismo tiempo.
|
||||
- No se pueden abordar aleatoriamente.
|
||||
- Los Pods de réplica no son idénticos.
|
||||
|
||||
Something you will see in our demonstration shortly is that each pod has its own identity. With a stateless Application, you will see random names. For example `app-7469bbb6d7-9mhxd` whereas a Stateful Application would be more aligned to `mongo-0` and then when scaled it will create a new pod called `mongo-1`.
|
||||
Algo que verás en nuestra demostración en breve es que cada pod tiene su propia identidad. Con una aplicación stateless, verás nombres aleatorios. Por ejemplo, `app-7469bbb6d7-9mhxd`, mientras que una aplicación stateful estaría más alineada con `mongo-0` y luego, cuando se escala, creará un nuevo pod llamado `mongo-1`.
|
||||
|
||||
These pods are created from the same specification, but they are not interchangeable. Each StatefulSet pod has a persistent identifier across any rescheduling. This is necessary because when we require stateful workloads such as a database where we require writing and reading to a database, we cannot have two pods writing at the same time with no awareness as this will give us data inconsistency. We need to ensure that only one of our pods is writing to the database at any given time however we can have multiple pods reading that data.
|
||||
Estos pods se crean a partir de la misma especificación, pero no son intercambiables. Cada pod de StatefulSet tiene un identificador persistente en cualquier reprogramación. Esto es necesario porque cuando requerimos cargas de trabajo stateful como una base de datos donde requerimos escribir y leer en una base de datos, no podemos tener dos pods escribiendo al mismo tiempo sin conciencia ya que esto nos dará inconsistencia de datos. Necesitamos asegurarnos de que solo uno de nuestros pods esté escribiendo en la base de datos en cualquier momento dado, sin embargo, podemos tener múltiples pods leyendo esos datos.
|
||||
|
||||
Each pod in a StatefulSet would have access to its persistent volume and replica copy of the database to read from, this is continuously updated from the master. It's also interesting to note that each pod will also store its pod state in this persistent volume, if then `mongo-0` dies then when a new one is provisioned it will take over the pod state stored in storage.
|
||||
Cada pod en un StatefulSet tendría acceso a su volumen persistente y copia de réplica de la base de datos para leer, esto se actualiza continuamente desde el maestro. También es interesante destacar que cada pod almacenará su estado de pod en este volumen persistente, si luego `mongo-0` muere, cuando se provisione uno nuevo, tomará el estado de pod almacenado en el almacenamiento.
|
||||
|
||||
TLDR; StatefulSets vs Deployments
|
||||
|
||||
- Predictable pod name = `mongo-0`
|
||||
- Fixed individual DNS name
|
||||
- Pod Identity - Retain State, Retain Role
|
||||
- Replicating stateful apps is complex
|
||||
- There are lots of things you must do:
|
||||
- Configure cloning and data synchronisation.
|
||||
- Make remote shared storage available.
|
||||
- Management & backup
|
||||
- Nombre predecible del pod = mongo-0
|
||||
- Nombre de DNS individual fijo
|
||||
- Identidad del pod: Mantener estado, mantener rol
|
||||
- Replicar aplicaciones con estado es complejo
|
||||
- Hay muchas cosas que debes hacer:
|
||||
- Configurar la clonación y la sincronización de datos.
|
||||
- Hacer que el almacenamiento compartido remoto esté disponible.
|
||||
- Gestión y copia de seguridad
|
||||
|
||||
### Persistant Volumes | Claims | StorageClass
|
||||
### Volúmenes Persistentes | Reclamaciones | StorageClass
|
||||
|
||||
How to persist data in Kubernetes?
|
||||
¿Cómo persistir datos en Kubernetes?
|
||||
|
||||
We mentioned above when we have a stateful application, we have to store the state somewhere and this is where the need for a volume comes in, out of the box Kubernetes does not provide persistence out of the box.
|
||||
Mencionamos anteriormente que cuando tenemos una aplicación con estado, debemos almacenar el estado en algún lugar y aquí es donde surge la necesidad de un volumen. Por defecto, Kubernetes no proporciona persistencia.
|
||||
|
||||
We require a storage layer that does not depend on the pod lifecycle. This storage should be available and accessible from all of our Kubernetes nodes. The storage should also be outside of the Kubernetes cluster to be able to survive even if the Kubernetes cluster crashes.
|
||||
Necesitamos una capa de almacenamiento que no dependa del ciclo de vida del pod. Este almacenamiento debe estar disponible y accesible desde todos los nodos de Kubernetes. El almacenamiento también debe estar fuera del clúster de Kubernetes para poder sobrevivir incluso si el clúster de Kubernetes falla.
|
||||
|
||||
### Persistent Volume
|
||||
### Volumen Persistente
|
||||
|
||||
- A cluster resource (like CPU and RAM) to store data.
|
||||
- Created via a YAML file
|
||||
- Needs actual physical storage (NAS)
|
||||
- External integration to your Kubernetes cluster
|
||||
- You can have different types of storage available in your storage.
|
||||
- PVs are not namespaced
|
||||
- Local storage is available but it would be specific to one node in the cluster
|
||||
- Database persistence should use remote storage (NAS)
|
||||
- Un recurso del clúster (como CPU y RAM) para almacenar datos.
|
||||
- Se crea mediante un archivo YAML.
|
||||
- Necesita almacenamiento físico real (NAS).
|
||||
- Integración externa en tu clúster de Kubernetes.
|
||||
- Puedes tener diferentes tipos de almacenamiento disponibles en tu almacenamiento.
|
||||
- Los PV no tienen espacio de nombres.
|
||||
- El almacenamiento local está disponible, pero estaría específico de un nodo en el clúster.
|
||||
- La persistencia de la base de datos debe usar almacenamiento remoto (NAS).
|
||||
|
||||
### Persistent Volume Claim
|
||||
|
||||
A persistent volume alone above can be there and available but unless it is claimed by an application it is not being used.
|
||||
Un volumen persistente por sí solo puede estar disponible, pero a menos que sea reclamado por una aplicación, no se está utilizando.
|
||||
|
||||
- Created via a YAML file
|
||||
- Persistent Volume Claim is used in pod configuration (volumes attribute)
|
||||
- PVCs live in the same namespace as the pod
|
||||
- Volume is mounted into the pod
|
||||
- Pods can have multiple different volume types (ConfigMap, Secret, PVC)
|
||||
- Se crea mediante un archivo YAML.
|
||||
- La reclamación de volumen persistente se utiliza en la configuración del pod (atributo de volúmenes).
|
||||
- Las PVCs (reclamaciones de volumen persistente) se encuentran en el mismo espacio de nombres que el pod.
|
||||
- El volumen se monta en el pod.
|
||||
- Los pods pueden tener múltiples tipos de volumen diferentes (ConfigMap, Secret, PVC).
|
||||
|
||||
Another way to think of PVs and PVCs is that
|
||||
Otra forma de pensar en los PV y PVCs es que:
|
||||
|
||||
PVs are created by the Kubernetes Admin
|
||||
PVCs are created by the user or application developer
|
||||
Los PV son creados por el administrador de Kubernetes.
|
||||
Los PVCs son creados por el usuario o el desarrollador de la aplicación.
|
||||
|
||||
We also have two other types of volumes that we will not get into detail on but are worth mentioning:
|
||||
También tenemos otros dos tipos de volúmenes de los que no entraremos en detalle pero que vale la pena mencionar
|
||||
|
||||
### ConfigMaps | Secrets
|
||||
|
||||
- Configuration file for your pod.
|
||||
- Certificate file for your pod.
|
||||
- Archivo de configuración para tu pod.
|
||||
- Archivo de certificado para tu pod.
|
||||
|
||||
### StorageClass
|
||||
|
||||
- Created via a YAML file
|
||||
- Provisions Persistent Volumes Dynamically when a PVC claims it
|
||||
- Each storage backend has its provisioner
|
||||
- Storage backend is defined in YAML (via provisioner attribute)
|
||||
- Abstracts underlying storage provider
|
||||
- Define parameters for that storage
|
||||
- Se crea mediante un archivo YAML.
|
||||
- Provee volúmenes persistentes dinámicamente cuando una PVC lo reclama.
|
||||
- Cada backend de almacenamiento tiene su proveedor.
|
||||
- El backend de almacenamiento se define en YAML (mediante el atributo provisioner).
|
||||
- Abstrae al proveedor de almacenamiento subyacente.
|
||||
- Define parámetros para ese almacenamiento.
|
||||
|
||||
### Walkthrough time
|
||||
|
||||
In the session yesterday we walked through creating a stateless application, here we want to do the same but we want to use our minikube cluster to deploy a stateful workload.
|
||||
En la sesión de ayer recorrimos la creación de una aplicación sin estado, ahora queremos hacer lo mismo pero utilizando nuestro clúster de minikube para implementar una carga de trabajo con estado.
|
||||
|
||||
A recap on the minikube command we are using to have the capability and addons to use persistence is `minikube start --addons volumesnapshots,csi-hostpath-driver --apiserver-port=6443 --container-runtime=containerd -p mc-demo --Kubernetes-version=1.21.2`
|
||||
Un resumen del comando de minikube que estamos utilizando para tener la capacidad y complementos para utilizar la persistencia es `minikube start --addons volumesnapshots,csi-hostpath-driver --apiserver-port=6443 --container-runtime=containerd -p mc-demo --Kubernetes-version=1.21.2`
|
||||
|
||||
This command uses the CSI-hostpath-driver which is what gives us our storageclass, something I will show later.
|
||||
Este comando utiliza el controlador CSI-hostpath-driver, que es lo que nos proporciona nuestra clase de almacenamiento, algo que mostraré más adelante.
|
||||
|
||||
The build-out of the application looks like the below:
|
||||
La construcción de la aplicación se ve así:
|
||||
|
||||

|
||||

|
||||
|
||||
You can find the YAML configuration file for this application here [pacman-stateful-demo.yaml](Kubernetes)
|
||||
Puedes encontrar el archivo de configuración YAML de esta aplicación aquí [pacman-stateful-demo.yaml](Kubernetes)
|
||||
|
||||
### StorageClass Configuration
|
||||
### Configuración de StorageClass
|
||||
|
||||
There is one more step though that we should run before we start deploying our application and that is to make sure that our storageclass (CSI-hostpath-sc) is our default one. We can firstly check this by running the `kubectl get storageclass` command but out of the box, the minikube cluster will be showing the standard storageclass as default so we have to change that with the following commands.
|
||||
Sin embargo, hay un paso más que debemos realizar antes de comenzar a implementar nuestra aplicación y es asegurarnos de que nuestra clase de almacenamiento (CSI-hostpath-sc) sea la predeterminada. Podemos verificar esto ejecutando el comando `kubectl get storageclass`, pero de forma predeterminada, el clúster de minikube mostrará la clase de almacenamiento estándar como predeterminada, por lo que debemos cambiarla con los siguientes comandos.
|
||||
|
||||
This first command will make our CSI-hostpath-sc storageclass our default.
|
||||
Este primer comando hará que nuestra clase de almacenamiento CSI-hostpath-sc sea la predeterminada.
|
||||
|
||||
`kubectl patch storageclass csi-hostpath-sc -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"true"}}}'`
|
||||
|
||||
This command will remove the default annotation from the standard StorageClass.
|
||||
Este comando eliminará la anotación predeterminada de la clase de almacenamiento estándar.
|
||||
|
||||
`kubectl patch storageclass standard -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"false"}}}'`
|
||||
|
||||

|
||||
|
||||
We start with no Pacman namespace in our cluster. `kubectl get namespace`
|
||||
Comenzamos sin un espacio de nombres de Pacman en nuestro clúster. `kubectl get namespace`
|
||||
|
||||

|
||||
|
||||
We will then deploy our YAML file. `kubectl create -f pacman-stateful-demo.yaml` you can see from this command we are creating several objects within our Kubernetes cluster.
|
||||
Luego implementaremos nuestro archivo YAML. `kubectl create -f pacman-stateful-demo.yaml`. Puedes ver que con este comando estamos creando varios objetos dentro de nuestro clúster de Kubernetes.
|
||||
|
||||

|
||||
|
||||
We now have our newly created namespace.
|
||||
Ahora tenemos nuestro espacio de nombres recién creado.
|
||||
|
||||

|
||||
|
||||
You can then see from the next image and command `kubectl get all -n pacman` that we have several things happening inside of our namespace. We have our pods running our NodeJS web front end, we have mongo running our backend database. There are services for both Pacman and mongo to access those pods. We have a deployment for Pacman and a statefulset for mongo.
|
||||
A continuación, puedes ver en la siguiente imagen y en el comando `kubectl get all -n pacman` que hay varias cosas sucediendo dentro de nuestro espacio de nombres. Tenemos nuestros pods ejecutando nuestra interfaz web NodeJS, tenemos mongo ejecutando nuestra base de datos de backend. Hay servicios tanto para Pacman como para mongo para acceder a esos pods. Tenemos una implementación para Pacman y un conjunto de estado para mongo.
|
||||
|
||||

|
||||
|
||||
We also have our persistent volume and persistent volume claim by running `kubectl get pv` will give us our non-namespaced persistent volumes and running `kubectl get pvc -n pacman` will give us our namespaced persistent volume claims.
|
||||
También tenemos nuestro volumen persistente y la solicitud de volumen persistente mediante el comando `kubectl get pv` nos mostrará nuestros volúmenes persistentes sin espacio de nombres y ejecutando `kubectl get pvc -n pacman` nos mostrará nuestras solicitudes de volumen persistente con espacio de nombres.
|
||||
|
||||

|
||||
|
||||
### Playing the game | I mean accessing our mission-critical application
|
||||
### Jugando el juego | Quiero decir, accediendo a nuestra aplicación crítica
|
||||
|
||||
Because we are using Minikube as mentioned in the stateless application we have a few hurdles to get over when it comes to accessing our application, however, we had access to ingress or a load balancer within our cluster the service is set up to automatically get an IP from that to gain access externally. (you can see this above in the image of all components in the Pacman namespace).
|
||||
Debido a que estamos utilizando Minikube, como se mencionó en la aplicación sin estado, tenemos algunos obstáculos para acceder a nuestra aplicación. Sin embargo, si tenemos acceso a un Ingress o a un balanceador de carga dentro de nuestro clúster, el servicio está configurado para obtener automáticamente una dirección IP de ellos para acceder externamente (puedes ver esto arriba en la imagen de todos los componentes en el espacio de nombres de Pacman).
|
||||
|
||||
For this demo, we are going to use the port forward method to access our application. By opening a new terminal and running the following `kubectl port-forward svc/pacman 9090:80 -n pacman` command, opening a browser we will now have access to our application. If you are running this in AWS or specific locations then this will also report on the cloud and zone as well as the host which equals your pod within Kubernetes, again you can look back and see this pod name in our screenshots above.
|
||||
Para esta demostración, vamos a utilizar el método de "port forwarding" para acceder a nuestra aplicación. Abriendo una nueva terminal y ejecutando el siguiente comando `kubectl port-forward svc/pacman 9090:80 -n pacman`, al abrir un navegador ahora tendremos acceso a nuestra aplicación. Si estás ejecutando esto en AWS u otras ubicaciones específicas, también se mostrará la nube y la zona, así como el host que corresponde a tu pod dentro de Kubernetes, nuevamente puedes volver atrás y ver este nombre de pod en nuestras capturas de pantalla anteriores.
|
||||
|
||||

|
||||

|
||||
|
||||
Now we can go and create a high score which will then be stored in our database.
|
||||
Ahora podemos ir y crear una puntuación alta que luego se almacenará en nuestra base de datos.
|
||||
|
||||

|
||||

|
||||
|
||||
Ok, great we have a high score but what happens if we go and delete our `mongo-0` pod? by running `kubectl delete pod mongo-0 -n pacman` I can delete that and if you are still in the app you will see that high score not available at least for a few seconds.
|
||||
¡Ok, genial! Tenemos una puntuación alta, pero ¿qué sucede si eliminamos nuestro pod `mongo-0`? ejecutando `kubectl delete pod mongo-0 -n pacman` puedo eliminarlo y si aún estás en la aplicación, verás que la puntuación alta no estará disponible, al menos por unos segundos.
|
||||
|
||||

|
||||

|
||||
|
||||
Now if I go back to my game I can create a new game and see my high scores. The only way you can truly believe me on this though is if you give it a try and share on social media your high scores!
|
||||
Ahora, si vuelvo a mi juego, puedo crear un nuevo juego y ver mis puntuaciones altas. La única forma en que realmente puedas creerme es si lo intentas tú mismo y compartes tus puntuaciones altas en las redes sociales.
|
||||
|
||||

|
||||

|
||||
|
||||
With the deployment, we can scale this up using the commands that we covered in the previous session but in particular here, especially if you want to host a huge Pacman party then you can scale this up using `kubectl scale deployment pacman --replicas=10 -n pacman`
|
||||
Con la implementación, podemos aumentar la escala utilizando los comandos que vimos en la sesión anterior, pero en particular aquí, especialmente si quieres organizar una gran fiesta de Pacman, puedes escalar esto usando `kubectl scale deployment pacman --replicas=10 -n pacman`
|
||||
|
||||

|
||||

|
||||
|
||||
### Ingress explained
|
||||
### Explicación de Ingress
|
||||
|
||||
Before we wrap things up with Kubernetes I also wanted to touch on a huge aspect of Kubernetes and that is ingress.
|
||||
Antes de terminar con Kubernetes, también quería mencionar un aspecto importante de Kubernetes: Ingress.
|
||||
|
||||
### What is ingress?
|
||||
### ¿Qué es Ingress?
|
||||
|
||||
So far with our examples, we have used port-forward or we have used specific commands within minikube to gain access to our applications but this in production is not going to work. We are going to want a better way of accessing our applications at scale with multiple users.
|
||||
Hasta ahora, con nuestros ejemplos, hemos utilizado "port-forward" o hemos utilizado comandos específicos dentro de Minikube para acceder a nuestras aplicaciones, pero esto no funcionará en producción. Queremos una mejor forma de acceder a nuestras aplicaciones a gran escala con múltiples usuarios.
|
||||
|
||||
We also spoke about NodePort being an option but again this should be only for test purposes.
|
||||
También hemos hablado sobre NodePort como una opción, pero nuevamente, esto debería ser solo para fines de prueba.
|
||||
|
||||
Ingress gives us a better way of exposing our applications, this allows us to define routing rules within our Kubernetes cluster.
|
||||
Ingress nos proporciona una mejor forma de exponer nuestras aplicaciones, lo cual nos permite definir reglas de enrutamiento dentro de nuestro clúster de Kubernetes.
|
||||
|
||||
For ingress, we would create a forward request to the internal service of our application.
|
||||
Con Ingress, crearíamos una solicitud de reenvío hacia el servicio interno de nuestra aplicación.
|
||||
|
||||
### When do you need ingress?
|
||||
### ¿Cuándo necesitas Ingress?
|
||||
|
||||
If you are using a cloud provider, a managed Kubernetes offering they most likely will have their ingress option for your cluster or they provide you with their load balancer option. You don't have to implement this yourself, one of the benefits of managed Kubernetes.
|
||||
Si estás utilizando un proveedor de servicios en la nube que ofrece Kubernetes administrado, es muy probable que tengan su opción de Ingress para tu clúster o te proporcionen su opción de balanceador de carga. No necesitas implementar esto tú mismo, es uno de los beneficios de Kubernetes administrado.
|
||||
|
||||
If you are running your cluster then you will need to configure an entrypoint.
|
||||
Si estás ejecutando tu propio clúster, entonces deberás configurar un punto de entrada.
|
||||
|
||||
### Configure Ingress on Minikube
|
||||
### Configurar Ingress en Minikube
|
||||
|
||||
On my particular running cluster called mc-demo, I can run the following command to get ingress enabled on my cluster.
|
||||
En mi clúster en ejecución llamado "mc-demo", puedo ejecutar el siguiente comando para habilitar Ingress en mi clúster.
|
||||
|
||||
`minikube --profile='mc-demo' addons enable ingress`
|
||||
|
||||

|
||||
|
||||
If we check our namespaces now you will see that we have a new ingress-nginx namespace. `kubectl get ns`
|
||||
Si verificamos nuestros espacios de nombres ahora, verás que tenemos un nuevo espacio de nombres "ingress-nginx". `kubectl get ns`
|
||||
|
||||

|
||||
|
||||
Now we must create our ingress YAML configuration to hit our Pacman service I have added this file to the repository [pacman-ingress.yaml](Kubernetes)
|
||||
Ahora debemos crear nuestra configuración YAML de Ingress para acceder a nuestro servicio Pacman. He agregado este archivo al repositorio [pacman-ingress.yaml](Kubernetes)
|
||||
|
||||
We can then create this in our ingress namespace with `kubectl create -f Pacman-ingress.yaml`
|
||||
Luego, podemos crear esto en nuestro espacio de nombres "ingress" con `kubectl create -f Pacman-ingress.yaml`
|
||||
|
||||

|
||||
|
||||
Then if we run `kubectl get ingress -n Pacman
|
||||
Luego, si ejecutamos `kubectl get ingress -n Pacman
|
||||
|
||||

|
||||
|
||||
I am then told because we are using minikube running on WSL2 in Windows we have to create the minikube tunnel using `minikube tunnel --profile=mc-demo`
|
||||
Luego se me informa que, debido a que estamos utilizando Minikube en WSL2 en Windows, debemos crear el túnel de Minikube usando `minikube tunnel --profile=mc-demo`
|
||||
|
||||
But I am still not able to gain access to 192.168.49.2 and play my Pacman game.
|
||||
Pero aún no puedo acceder a 192.168.49.2 y jugar a mi juego de Pacman.
|
||||
|
||||
If anyone has or can get this working on Windows and WSL I would appreciate the feedback. I will raise an issue on the repository for this and come back to it once I have time and a fix.
|
||||
Si alguien lo ha logrado o puede hacerlo funcionar en Windows y WSL, agradecería los comentarios. Abriré un problema en el repositorio para esto y volveré a él una vez que tenga tiempo y una solución.
|
||||
|
||||
UPDATE: I feel like this blog helps identify maybe the cause of this not working with WSL [Configuring Ingress to run Minikube on WSL2 using Docker runtime](https://hellokube.dev/posts/configure-minikube-ingress-on-wsl2/)
|
||||
ACTUALIZACIÓN: Siento que este blog ayuda a identificar quizás la causa de que esto no funcione con WSL [Configuring Ingress to run Minikube on WSL2 using Docker runtime](https://hellokube.dev/posts/configure-minikube-ingress-on-wsl2/)
|
||||
|
||||
## Resources
|
||||
## Recursos
|
||||
|
||||
If you have FREE resources that you have used then please feel free to add them here via a PR to the repository and I will be happy to include them.
|
||||
|
||||
@ -221,9 +221,10 @@ If you have FREE resources that you have used then please feel free to add them
|
||||
- [TechWorld with Nana - Kubernetes Tutorial for Beginners [FULL COURSE in 4 Hours]](https://www.youtube.com/watch?v=X48VuDVv0do)
|
||||
- [TechWorld with Nana - Kubernetes Crash Course for Absolute Beginners](https://www.youtube.com/watch?v=s_o8dwzRlu4)
|
||||
- [Kunal Kushwaha - Kubernetes Tutorial for Beginners | What is Kubernetes? Architecture Simplified!](https://www.youtube.com/watch?v=KVBON1lA9N8)
|
||||
- [WSL2 - Windows corriendo contenedores Linux??](https://youtu.be/_Hne4gm8plo)
|
||||
|
||||
This wraps up our Kubernetes section, there is so much additional content we could cover on Kubernetes and 7 days gives us foundational knowledge but people are running through [100DaysOfKubernetes](https://100daysofkubernetes.io/overview.html) where you can get really into the weeds.
|
||||
Aquí concluye la sección de Kubernetes, hay mucho contenido adicional que podríamos ver sobre Kubernetes y 7 días nos brinda conocimientos fundamentales, pero hay personas que están pasando por [100DaysOfKubernetes](https://100daysofkubernetes.io/overview.html) donde se puede profundizar más.
|
||||
|
||||
Next up we are going to be taking a look at Infrastructure as Code and the important role it plays from a DevOps perspective.
|
||||
A continuación, vamos a echar un vistazo a la Infraestructura como Código y el papel importante que desempeña desde una perspectiva de DevOps.
|
||||
|
||||
See you on [Day 56](day56.md)
|
||||
Nos vemos en el [Día 56](day56.md)
|
||||
|
@ -1,113 +1,114 @@
|
||||
## The Big Picture: IaC
|
||||
## El panorama: IaC
|
||||
|
||||
Humans make mistakes! Automation is the way to go!
|
||||
¡Los humanos cometen errores! ¡La automatización es el camino a seguir!
|
||||
|
||||
How do you build your systems today?
|
||||
¿Cómo construyes tus sistemas hoy en día?
|
||||
|
||||
What would be your plan if you were to lose everything today, Physical machines, Virtual Machines, Cloud VMs, Cloud PaaS etc etc.?
|
||||
¿Cuál sería tu plan si hoy perdieras todo, máquinas físicas, máquinas virtuales, VMs en la nube, PaaS en la nube, etc.?
|
||||
|
||||
How long would it take you to replace everything?
|
||||
¿Cuánto tiempo te tomaría reemplazar todo?
|
||||
|
||||
Infrastructure as code provides a solution to be able to do this whilst also being able to test this, we should not confuse this with backup and recovery but in terms of your infrastructure and environments, your platforms we should be able to spin them up and treat them as cattle vs pets.
|
||||
La infraestructura como código proporciona una solución para poder hacer esto, al mismo tiempo que también podemos probarlo. No debemos confundir esto con la copia de seguridad y recuperación, pero en términos de tu infraestructura y entornos, tus plataformas deberían poder ser creadas y tratadas como ganado en lugar de mascotas.
|
||||
|
||||
The TLDR; is that we can use code to rebuild our entire environment.
|
||||
En resumen, podemos usar código para reconstruir todo nuestro entorno.
|
||||
|
||||
If we also remember from the start we said about DevOps in general is a way in which to break down barriers to deliver systems into production safely and rapidly.
|
||||
Si también recordamos desde el principio, dijimos que DevOps en general es una forma de eliminar barreras para entregar sistemas de manera segura y rápida.
|
||||
|
||||
Infrastructure as code helps us deliver the systems, we have spoken a lot of processes and tools. IaC brings us more tools to be familiar with to enable this part of the process.
|
||||
La infraestructura como código nos ayuda a entregar los sistemas. Hemos hablado mucho sobre procesos y herramientas. IaC nos brinda más herramientas para familiarizarnos y habilitar esta parte del proceso.
|
||||
|
||||
We are going to concentrate on Infrastructure as code in this section. You might also hear this mentioned as Infrastructure from code or configuration as code. I think the most well-known term is likely Infrastructure as code.
|
||||
Nos vamos a centrar en la infraestructura como código en esta sección. Es posible que también escuches que se menciona como infraestructura desde el código o configuración como código. Creo que el término más conocido es probablemente infraestructura como código.
|
||||
|
||||
### Pets vs Cattle
|
||||
### Mascotas vs Ganado
|
||||
|
||||
If we take a look at pre-DevOps, if we had the requirement to build a new Application, we would need to prepare our servers manually for the most part.
|
||||
Si echamos un vistazo al tiempo anterior a DevOps, si teníamos el requisito de construir una nueva aplicación, tendríamos que preparar nuestros servidores manualmente en su mayor parte.
|
||||
|
||||
- Deploy VMs | Physical Servers and install the operating system
|
||||
- Configure networking
|
||||
- Create routing tables
|
||||
- Install software and updates
|
||||
- Configure software
|
||||
- Install database
|
||||
- Implementar VMs | Servidores físicos e instalar el sistema operativo.
|
||||
- Configurar la red.
|
||||
- Crear tablas de enrutamiento.
|
||||
- Instalar software y actualizaciones.
|
||||
- Configurar el software.
|
||||
- Instalar la base de datos.
|
||||
|
||||
This would be a manual process performed by Systems Administrators. The bigger the application the more resource and servers required the more manual effort it would take to bring up those systems. This would take a huge amount of human effort and time but also as a business you would have to pay for that resource to build out this environment. As I opened the section with "Humans make mistakes! Automation is the way to go!"
|
||||
Este sería un proceso manual realizado por administradores de sistemas. Cuanto más grande sea la aplicación y más recursos y servidores se requieran, más esfuerzo manual se necesitaría para poner en funcionamiento esos sistemas. Esto requeriría una gran cantidad de esfuerzo y tiempo humano, pero también como negocio tendrías que pagar por esos recursos para construir este entorno. Como comencé la sección con "¡Los humanos cometen errores! ¡La automatización es el camino a seguir!".
|
||||
|
||||
Ongoing from the above initial setup phase you then have maintenance of these servers.
|
||||
Después de la fase inicial de configuración mencionada anteriormente, también tendrías el mantenimiento de estos servidores.
|
||||
|
||||
- Update versions
|
||||
- Deploy new releases
|
||||
- Data Management
|
||||
- Recovery of Applications
|
||||
- Add, Remove and Scale Servers
|
||||
- Network Configuration
|
||||
- Actualizar versiones.
|
||||
- Implementar nuevas versiones.
|
||||
- Administración de datos.
|
||||
- Recuperación de aplicaciones.
|
||||
- Agregar, eliminar y escalar servidores.
|
||||
- Configuración de red.
|
||||
|
||||
Add the complexity of multiple test and dev environments.
|
||||
Agrega la complejidad de tener múltiples entornos de prueba y desarrollo.
|
||||
|
||||
This is where Infrastructure as Code comes in, the above was very much a time where we would look after those servers as if they were pets, people even called them servers pet names or at least named them something because they were going to be around for a while, they were going to hopefully be part of the "family" for a while.
|
||||
Aquí es donde entra en juego la infraestructura como código. Lo mencionado anteriormente era un tiempo en el que nos preocupábamos por esos servidores como si fueran mascotas, incluso les dábamos nombres cariñosos o al menos los nombrábamos de alguna manera porque iban a estar allí por un tiempo, iban a ser parte de la "familia" durante un tiempo.
|
||||
|
||||
With Infrastructure as Code, we can automate all these tasks end to end. Infrastructure as code is a concept and some tools carry out this automated provisioning of infrastructure, at this point if something bad happens to a server you throw it away and you spin up a new one. This process is automated and the server is exactly as defined in the code. At this point we don't care what they are called they are there in the field serving their purpose until they are no longer in the field and we have another to replace it either because of a failure or because we updated part or all of our application.
|
||||
Con la infraestructura como código, podemos automatizar todas estas tareas de principio a fin. La infraestructura como código es un concepto y algunas herramientas llevan a cabo esta provisión automatizada de infraestructura. En este punto, si algo malo le sucede a un servidor, lo desechas y creas uno nuevo. Este proceso es automatizado y el servidor es exactamente como se define en el código. En este punto, no nos importa cómo se llamen, están allí en el campo cumpliendo su propósito hasta que ya no estén en el campo y tengamos otro para reemplazarlo, ya sea debido a una falla o porque actualizamos parte o la totalidad de nuestra aplicación.
|
||||
|
||||
This can be used in almost all platforms, virtualisation, cloud-based workloads and also cloud-native infrastructures such as Kubernetes and containers.
|
||||
Esto se puede utilizar en casi todas las plataformas, cargas de trabajo basadas en virtualización, en la nube e infraestructuras nativas de la nube como Kubernetes y contenedores.
|
||||
|
||||
### Infrastructure Provisioning
|
||||
### Provisión de Infraestructura
|
||||
|
||||
Not all IaC cover all of the below, You will find that the tool we are going to be using during this section only really covers the first 2 areas below; Terraform is that tool we will be covering and this allows us to start from nothing and define in code what our infrastructure should look like and then deploy that, it will also enable us to manage that infrastructure and also initially deploy an application but at that point it is going to lose track of the application which is where the next section comes in and something like Ansible as a configuration management tool might work better on that front.
|
||||
No todas las herramientas de IaC cubren todo lo siguiente. Encontrarás que la herramienta que vamos a utilizar en esta sección solo cubre realmente las primeras 2 áreas a continuación; Terraform es esa herramienta que vamos a cubrir y nos permite partir de la nada y definir en código cómo debería ser nuestra infraestructura y luego implementarla. También nos permitirá administrar esa infraestructura y también implementar inicialmente una aplicación, pero en ese momento perderá el seguimiento de la aplicación, es ahí donde entra la siguiente sección y algo como Ansible como una herramienta de gestión de configuración podría funcionar mejor en ese sentido.
|
||||
|
||||
Without jumping ahead tools like chef, puppet and ansible are best suited to deal with the initial application setup and then manage those applications and their configuration.
|
||||
Sin adelantarnos, herramientas como Chef, Puppet y Ansible son las más adecuadas para lidiar con la configuración inicial de la aplicación y luego administrar esas aplicaciones y su configuración.
|
||||
|
||||
Initial installation & configuration of software
|
||||
Instalación y configuración inicial del software:
|
||||
|
||||
- Spinning up new servers
|
||||
- Network configuration
|
||||
- Creating load balancers
|
||||
- Configuration on the infrastructure level
|
||||
- Puesta en marcha de nuevos servidores.
|
||||
- Configuración de red.
|
||||
- Creación de balanceadores de carga.
|
||||
- Configuración a nivel de infraestructura.
|
||||
|
||||
### Configuration of provisioned infrastructure
|
||||
### Configuración de la infraestructura provisionada
|
||||
|
||||
- Installing applications on servers
|
||||
- Prepare the servers to deploy your application.
|
||||
- Instalación de aplicaciones en servidores.
|
||||
- Preparar los servidores para implementar tu aplicación.
|
||||
|
||||
### Deployment of Application
|
||||
### Despliegue de la aplicación
|
||||
|
||||
- Deploy and Manage Application
|
||||
- Maintain phase
|
||||
- Software updates
|
||||
- Reconfiguration
|
||||
- Implementar y gestionar la aplicación.
|
||||
- Fase de mantenimiento.
|
||||
- Actualizaciones de software.
|
||||
- Reconfiguración.
|
||||
|
||||
### Difference between IaC tools
|
||||
### Diferencia entre herramientas de IaC
|
||||
|
||||
Declarative vs procedural
|
||||
Declarativo vs Procedimental
|
||||
|
||||
Procedural
|
||||
Procedimental:
|
||||
|
||||
- Step-by-step instruction
|
||||
- Create a server > Add a server > Make this change
|
||||
- Instrucciones paso a paso.
|
||||
- Crear un servidor > Agregar un servidor > Hacer este cambio.
|
||||
|
||||
Declarative
|
||||
Declarativo:
|
||||
|
||||
- declare the result
|
||||
- 2 Servers
|
||||
- Declarar el resultado.
|
||||
- 2 servidores.
|
||||
|
||||
Mutable (pets) vs Immutable (cattle)
|
||||
Mutable (mascotas) vs Inmutable (ganado)
|
||||
|
||||
Mutable
|
||||
Mutable:
|
||||
|
||||
- Change instead of replacing
|
||||
- Generally long lived
|
||||
- Cambiar en lugar de reemplazar.
|
||||
- Generalmente tienen una larga vida útil.
|
||||
|
||||
Immutable
|
||||
Inmutable:
|
||||
|
||||
- Replace instead of change
|
||||
- Possibly short-lived
|
||||
- Reemplazar en lugar de cambiar.
|
||||
- Posiblemente de corta duración.
|
||||
|
||||
This is really why we have lots of different options for Infrastructure as Code because there is no one tool to rule them all.
|
||||
Esta es la razón por la cual tenemos muchas opciones diferentes para la infraestructura como código, porque no hay una herramienta que las gobierne todas.
|
||||
|
||||
We are going to be mostly using terraform and getting hands-on as this is the best way to start seeing the benefits of Infrastructure as Code when it is in action. Getting hands-on is also the best way to pick up the skills you are going to be writing code.
|
||||
Vamos a utilizar principalmente Terraform y a trabajar prácticamente, ya que esta es la mejor manera de comenzar a ver los beneficios de la infraestructura como código cuando está en acción. Trabajar prácticamente también es la mejor manera de adquirir las habilidades necesarias para escribir código.
|
||||
|
||||
Next up we will start looking into Terraform with a 101 before we get some hands-on getting used.
|
||||
Continuaremos analizando Terraform con una introducción antes de poner manos a la obra y acostumbrarnos a su uso.
|
||||
|
||||
## Resources
|
||||
## Recursos
|
||||
|
||||
A continuación, he enumerado muchos recursos y creo que este tema ha sido cubierto tantas veces, que si tienes recursos adicionales, asegúrate de enviar una solicitud de extracción (PR) con tus recursos y estaré encantado de revisarlos y agregarlos a la lista.
|
||||
|
||||
I have listed a lot of resources down below and I think this topic has been covered so many times out there, If you have additional resources be sure to raise a PR with your resources and I will be happy to review and add them to the list.
|
||||
|
||||
- [What is Infrastructure as Code? Difference of Infrastructure as Code Tools](https://www.youtube.com/watch?v=POPP2WTJ8es)
|
||||
- [Terraform Tutorial | Terraform Course Overview 2021](https://www.youtube.com/watch?v=m3cKkYXl-8o)
|
||||
@ -119,5 +120,6 @@ I have listed a lot of resources down below and I think this topic has been cove
|
||||
- [Terraform Simple Projects](https://terraform.joshuajebaraj.com/)
|
||||
- [Terraform Tutorial - The Best Project Ideas](https://www.youtube.com/watch?v=oA-pPa0vfks)
|
||||
- [Awesome Terraform](https://github.com/shuaibiyy/awesome-terraform)
|
||||
- [Herramientas para Terraform](https://vergaracarmona.es/herramientas-para-terraform/)
|
||||
|
||||
See you on [Day 57](day57.md)
|
||||
Nos vemos en el [Día 57](day57.md)
|
||||
|
@ -1,78 +1,79 @@
|
||||
## An intro to Terraform
|
||||
## Una introducción a Terraform
|
||||
|
||||
"Terraform is a tool for building, changing, and versioning infrastructure safely and efficiently"
|
||||
"Terraform es una herramienta para construir, cambiar y versionar infraestructura de manera segura y eficiente".
|
||||
|
||||
The above quote is from HashiCorp, HashiCorp is the company behind Terraform.
|
||||
La cita anterior es de HashiCorp, la empresa detrás de Terraform.
|
||||
|
||||
"Terraform is an open-source infrastructure as a code software tool that provides a consistent CLI workflow to manage hundreds of cloud services. Terraform codifies cloud APIs into declarative configuration files."
|
||||
"Terraform es una herramienta de código abierto para infraestructura como código que proporciona un flujo de trabajo de CLI consistente para gestionar cientos de servicios en la nube. Terraform codifica las API de la nube en archivos de configuración declarativos".
|
||||
|
||||
HashiCorp has a great resource in [HashiCorp Learn](https://learn.hashicorp.com/terraform?utm_source=terraform_io&utm_content=terraform_io_hero) which covers all of their products and gives some great walkthrough demos when you are trying to achieve something with Infrastructure as Code.
|
||||
HashiCorp tiene un excelente recurso en [HashiCorp Learn](https://learn.hashicorp.com/terraform?utm_source=terraform_io&utm_content=terraform_io_hero) que cubre todos sus productos y ofrece demos paso a paso cuando intentas lograr algo con Infraestructura como Código.
|
||||
|
||||
All cloud providers and on-prem platforms generally give us access to management consoles which enables us to create our resources via a UI, generally, these platforms also provide a CLI or API access to create the same resources but with an API we can provision fast.
|
||||
Todos los proveedores de la nube y las plataformas locales generalmente nos brindan acceso a consolas de administración que nos permiten crear nuestros recursos a través de una interfaz de usuario. En general, estas plataformas también proporcionan acceso a la CLI o API para crear los mismos recursos, pero con una API podemos aprovisionarlos rápidamente.
|
||||
|
||||
Infrastructure as Code allows us to hook into those APIs to deploy our resources in the desired state.
|
||||
Infraestructura como Código nos permite conectarnos a esas APIs para implementar nuestros recursos en el estado deseado.
|
||||
|
||||
Other tools but not exclusive or exhaustive below. If you have other tools then please share via a PR.
|
||||
Otras herramientas, aunque no exclusivas ni exhaustivas, se enumeran a continuación. Si tienes otras herramientas, por favor compártelas mediante una PR.
|
||||
|
||||
| Cloud Specific | Cloud Agnostic |
|
||||
| ------------------------------- | -------------- |
|
||||
| AWS CloudFormation | Terraform |
|
||||
| Azure Resource Manager | Pulumi |
|
||||
| Google Cloud Deployment Manager | |
|
||||
| Específicas de la nube | Agnósticas de la nube |
|
||||
| ------------------------------- | --------------------- |
|
||||
| AWS CloudFormation | Terraform |
|
||||
| Azure Resource Manager | Pulumi |
|
||||
| Google Cloud Deployment Manager | |
|
||||
|
||||
This is another reason why we are using Terraform, we want to be agnostic to the clouds and platforms that we wish to use for our demos but also in general.
|
||||
Esta es otra razón por la cual utilizamos Terraform, queremos ser agnósticos a las nubes y plataformas que deseamos utilizar para nuestras demos y en general.
|
||||
|
||||
## Terraform Overview
|
||||
## Descripción general de Terraform
|
||||
|
||||
Terraform is a provisioning-focused tool, Terraform is a CLI that gives the capabilities of being able to provision complex infrastructure environments. With Terraform we can define complex infrastructure requirements that exist locally or remote (cloud) Terraform not only enables us to build things initially but also to maintain and update those resources for their lifetime.
|
||||
Terraform es una herramienta centrada en el aprovisionamiento. Terraform es una CLI que proporciona capacidades para poder aprovisionar entornos de infraestructura complejos. Con Terraform, podemos definir requisitos de infraestructura complejos que existen localmente o de forma remota (en la nube). Terraform no solo nos permite construir cosas inicialmente, sino también mantener y actualizar esos recursos durante su ciclo de vida.
|
||||
|
||||
We are going to cover the high level here but for more details and loads of resources, you can head to [terraform. io](https://www.terraform.io/)
|
||||
Aquí vamos a cubrir los aspectos principales, pero para obtener más detalles y muchos recursos, puedes dirigirte a [terraform.io](https://www.terraform.io/).
|
||||
|
||||
### Write
|
||||
### Escribir
|
||||
|
||||
Terraform allows us to create declarative configuration files that will build our environments. The files are written using the HashiCorp Configuration Language (HCL) which allows for concise descriptions of resources using blocks, arguments, and expressions. We will of course be looking into these in detail in deploying VMs, Containers and within Kubernetes.
|
||||
Terraform nos permite crear archivos de configuración declarativos que construirán nuestros entornos. Los archivos se escriben utilizando el lenguaje de configuración de HashiCorp (HCL), que permite descripciones concisas de recursos utilizando bloques, argumentos y expresiones. Por supuesto, estudiaremos estos en detalle al implementar máquinas virtuales (VMs), contenedores y en Kubernetes.
|
||||
|
||||
### Plan
|
||||
### Planificar
|
||||
|
||||
The ability to check that the above configuration files are going to deploy what we want to see using specific functions of the terraform cli to be able to test that plan before deploying anything or changing anything. Remember Terraform is a continued tool for your infrastructure if you would like to change aspects of your infrastructure you should do that via terraform so that it is captured all in code.
|
||||
La capacidad de verificar que los archivos de configuración mencionados anteriormente desplegarán lo que queremos ver, utilizando funciones específicas de la CLI de Terraform para probar ese plan antes de desplegar o cambiar cualquier cosa. Recuerda que Terraform es una herramienta continua para tu infraestructura. Si deseas cambiar aspectos de tu infraestructura, debes hacerlo a través de Terraform para que quede registrado todo en el código.
|
||||
|
||||
### Apply
|
||||
|
||||
Once you are happy you can go ahead and apply this configuration to the many providers that are available within Terraform. You can see a large number of providers available [here](https://registry.terraform.io/browse/providers)
|
||||
### Aplicar
|
||||
|
||||
Another thing to mention is that there are also modules available, and this is similar to container images in that these modules have been created and shared in public so you do not have to create them again and again just reuse the best practice of deploying a specific infrastructure resource the same way everywhere. You can find the modules available [here](https://registry.terraform.io/browse/modules)
|
||||
Una vez que estés satisfecho, puedes continuar y aplicar esta configuración a los numerosos proveedores disponibles en Terraform. Puedes ver una gran cantidad de proveedores disponibles [aquí](https://registry.terraform.io/browse/providers).
|
||||
|
||||
The Terraform workflow looks like this: (_taken from the terraform site_)
|
||||
Otra cosa que mencionar es que también hay módulos disponibles, y esto es similar a las imágenes de contenedores en el sentido de que estos módulos han sido creados y compartidos públicamente, por lo que no tienes que crearlos una y otra vez, solo puedes reutilizar las mejores prácticas para implementar un recurso de infraestructura específico de la misma manera en todas partes. Puedes encontrar los módulos disponibles [aquí](https://registry.terraform.io/browse/modules).
|
||||
|
||||
El flujo de trabajo de Terraform se ve así: (_tomado del sitio de Terraform_)
|
||||
|
||||

|
||||
|
||||
### Terraform vs Vagrant
|
||||
|
||||
During this challenge, we have used Vagrant which happens to be another Hashicorp open source tool which concentrates on the development environments.
|
||||
Durante este desafío, hemos utilizado Vagrant, que resulta ser otra herramienta de código abierto de HashiCorp que se centra en los entornos de desarrollo.
|
||||
|
||||
- Vagrant is a tool focused on managing development environments
|
||||
- Vagrant es una herramienta enfocada en la gestión de entornos de desarrollo.
|
||||
|
||||
- Terraform is a tool for building infrastructure.
|
||||
- Terraform es una herramienta para construir infraestructura.
|
||||
|
||||
A great comparison of the two tools can be found here on the official [Hashicorp site](https://www.vagrantup.com/intro/vs/terraform)
|
||||
Se puede encontrar una excelente comparación de las dos herramientas aquí en el [sitio oficial de HashiCorp](https://www.vagrantup.com/intro/vs/terraform).
|
||||
|
||||
## Terraform Installation
|
||||
## Instalación de Terraform
|
||||
|
||||
There is not much to the installation of Terraform.
|
||||
La instalación de Terraform no tiene mucho misterio.
|
||||
|
||||
Terraform is cross-platform and you can see below on my Linux machine we have several options to download and install the CLI
|
||||
Terraform es multiplataforma y puedes ver a continuación que en mi máquina Linux tenemos varias opciones para descargar e instalar la CLI.
|
||||
|
||||

|
||||
|
||||
Using `arkade` to install Terraform, arkade is a handy little tool for getting your required tools, apps and clis onto your system. A simple `arkade get terraform` will allow for an update of terraform if available or this same command will also install the Terraform CLI
|
||||
Usando `arkade` para instalar Terraform, arkade es una práctica herramienta que te permite obtener las herramientas, aplicaciones y clis que necesitas en tu sistema. Un simple `arkade get terraform` permitirá actualizar Terraform si está disponible, o este mismo comando también instalará la CLI de Terraform.
|
||||
|
||||

|
||||
|
||||
We are going to get into more around HCL and then also start using Terraform to create some infrastructure resources in various platforms.
|
||||
Vamos a profundizar más en HCL y luego comenzaremos a utilizar Terraform para crear algunos recursos de infraestructura en diversas plataformas.
|
||||
|
||||
## Resources
|
||||
## Recursos
|
||||
|
||||
I have listed a lot of resources down below and I think this topic has been covered so many times out there, If you have additional resources be sure to raise a PR with your resources and I will be happy to review and add them to the list.
|
||||
He enumerado muchos recursos a continuación y creo que este tema ha sido cubierto tantas veces en otros lugares. Si tienes recursos adicionales, asegúrate de enviar una solicitud de extracción (PR) con tus recursos y estaré encantado de revisarlos y agregarlos a la lista.
|
||||
|
||||
- [What is Infrastructure as Code? Difference of Infrastructure as Code Tools](https://www.youtube.com/watch?v=POPP2WTJ8es)
|
||||
- [Terraform Tutorial | Terraform Course Overview 2021](https://www.youtube.com/watch?v=m3cKkYXl-8o)
|
||||
@ -84,5 +85,6 @@ I have listed a lot of resources down below and I think this topic has been cove
|
||||
- [Terraform Simple Projects](https://terraform.joshuajebaraj.com/)
|
||||
- [Terraform Tutorial - The Best Project Ideas](https://www.youtube.com/watch?v=oA-pPa0vfks)
|
||||
- [Awesome Terraform](https://github.com/shuaibiyy/awesome-terraform)
|
||||
- [Herramientas para Terraform](https://vergaracarmona.es/herramientas-para-terraform/)
|
||||
|
||||
See you on [Day 58](day58.md)
|
||||
Nos vemos en el [Día 58](day58.md)
|
||||
|
@ -1,22 +1,23 @@
|
||||
## HashiCorp Configuration Language (HCL)
|
||||
|
||||
Before we start making stuff with Terraform we have to dive a little into HashiCorp Configuration Language (HCL). So far during our challenge, we have looked at a few different scripting and programming languages and here is another one. We touched on the [Go programming language](day07.md) then [bash scripts](day19.md) we even touched on a little python when it came to [network automation](day27.md)
|
||||
Antes de empezar a hacer cosas con Terraform, tenemos que adentrarnos un poco en el lenguaje de configuración de HashiCorp (HCL). Hasta ahora, durante nuestro desafío, hemos visto varios lenguajes de scripting y programación, y aquí tenemos otro. Hemos mencionado el [lenguaje de programación Go](day07.md), luego los [scripts bash](day19.md) e incluso un poco de Python cuando se trata de [automatización de redes](day27.md).
|
||||
|
||||
Now we must cover HashiCorp Configuration Language (HCL) if this is the first time you are seeing the language it might look a little daunting but it's quite simple and very powerful.
|
||||
Ahora debemos cubrir el lenguaje de configuración de HashiCorp (HCL). Si esta es la primera vez que ves este lenguaje, puede parecer un poco intimidante, pero es bastante simple y muy potente.
|
||||
|
||||
As we move through this section, we are going to be using examples that we can run locally on our system regardless of what OS you are using, we will be using VirtualBox, albeit not the infrastructure platform you would usually be using with Terraform. However running this locally, is free and will allow us to achieve what we are looking for in this post. We could also extend this post's concept to docker or Kubernetes as well.
|
||||
A medida que avanzamos en esta sección, vamos a utilizar ejemplos que podemos ejecutar localmente en nuestro sistema, independientemente del sistema operativo que estés usando. Vamos a utilizar VirtualBox, aunque no sea la plataforma de infraestructura que normalmente se usa con Terraform. Sin embargo, ejecutar esto localmente es gratuito y nos permitirá lograr lo que buscamos en esta publicación. También podríamos extender este concepto a Docker o Kubernetes.
|
||||
|
||||
In general, though, you would or should be using Terraform to deploy your infrastructure in the public cloud (AWS, Google, Microsoft Azure) but then also in your virtualisation environments such as (VMware, Microsoft Hyper-V, Nutanix AHV). In the public cloud Terraform allows for us to do a lot more than just Virtual Machine automated deployment, we can create all the required infrastructure such as PaaS workloads and all of the networking required assets such as VPCs and Security Groups.
|
||||
En general, sin embargo, deberías usar Terraform para implementar tu infraestructura en la nube pública (AWS, Google, Microsoft Azure), pero también en tus entornos de virtualización, como VMware, Microsoft Hyper-V, Nutanix AHV. En la nube pública, Terraform nos permite hacer mucho más que simplemente implementar máquinas virtuales. Podemos crear toda la infraestructura necesaria, como cargas de trabajo de PaaS y todos los activos de red requeridos, como VPC y grupos de seguridad.
|
||||
|
||||
There are two important aspects to Terraform, we have the code which we are going to get into in this post and then we also have the state. Both of these together could be called the Terraform core. We then have the environment we wish to speak to and deploy into, which is executed using Terraform providers, briefly mentioned in the last session, but we have an AWS provider, we have Azure providers etc. There are hundreds.
|
||||
Hay dos aspectos importantes en Terraform: el código, que vamos a explorar en esta publicación, y el estado. Ambos juntos podrían denominarse el núcleo de Terraform. Luego tenemos el entorno con el que deseamos interactuar e implementar, que se ejecuta mediante proveedores de Terraform, mencionados brevemente en la última sesión. Pero hay muchos proveedores disponibles, como AWS, Azure, etc. Hay cientos.
|
||||
|
||||
### Basic Terraform Usage
|
||||
### Uso básico de Terraform
|
||||
|
||||
Let's take a look at a Terraform `.tf` file to see how they are made up. The first example we will walk through will be code to deploy resources to AWS, this would then also require the AWS CLI to be installed on your system and configured for your account.
|
||||
Echemos un vistazo a un archivo `.tf` de Terraform para ver cómo se componen. El primer ejemplo que veremos será código para implementar recursos en AWS, lo que también requeriría tener la CLI de AWS instalada en tu sistema y configurada para tu cuenta.
|
||||
|
||||
### Providers
|
||||
### Proveedores
|
||||
|
||||
En la parte superior de nuestra estructura de archivo `.tf`, generalmente llamada `main.tf`, al menos hasta que las cosas se vuelvan más complejas, vamos a definir los proveedores que mencionamos anteriormente. Nuestra fuente del proveedor de AWS, como puedes ver, es `hashicorp/aws`, lo que significa que el proveedor es mantenido o ha sido publicado por HashiCorp ellos mismos. Por defecto, haremos referencia a proveedores disponibles en el [Terraform Registry](https://registry.terraform.io/). También puedes escribir tus propios proveedores y utilizarlos localmente, o publicarlos en el Terraform Registry.
|
||||
|
||||
At the top of our `.tf` file structure, generally called `main.tf` at least until we make things more complex. Here we will define the providers that we have mentioned before. Our source of the AWS provider as you can see is `hashicorp/aws` this means the provider is maintained or has been published by hashicorp themselves. By default you will reference providers that are available from the [Terraform Registry](https://registry.terraform.io/), you also can write your providers, and use these locally, or self-publish to the Terraform Registry.
|
||||
|
||||
```
|
||||
terraform {
|
||||
@ -68,9 +69,10 @@ resource "aws_instance" "90daysofdevops" {
|
||||
}
|
||||
```
|
||||
|
||||
You can see from the above we are also running a `yum` update and installing `httpd` into our ec2 instance.
|
||||
Puedes ver que también estamos ejecutando una actualización de `yum` e instalando `httpd` en nuestra instancia de EC2.
|
||||
|
||||
Si ahora observamos el archivo main.tf completo, podría lucir algo así.
|
||||
|
||||
If we now look at the complete main.tf file it might look something like this.
|
||||
|
||||
```
|
||||
terraform {
|
||||
@ -113,9 +115,9 @@ resource "aws_instance" "90daysofdevops" {
|
||||
}
|
||||
```
|
||||
|
||||
The above code will go and deploy a very simple web server as an ec2 instance in AWS, the great thing about this and any other configuration like this is that we can repeat this and we will get the same output every single time. Other than the chance that I have messed up the code there is no human interaction with the above.
|
||||
El código anterior desplegará un servidor web muy sencillo como una instancia EC2 en AWS. Lo genial de esto y de cualquier otra configuración similar es que podemos repetirlo y obtener la misma salida cada vez. Aparte de la posibilidad de que haya cometido un error en el código, no hay interacción humana con lo anterior.
|
||||
|
||||
We can take a look at a super simple example, one that you will likely never use but let's humour it anyway. Like with all good scripting and programming language we should start with a hello-world scenario.
|
||||
Podemos echar un vistazo a un ejemplo super sencillo, uno que probablemente nunca usarás, pero vamos a hacerle honor de todos modos. Como en todos los buenos lenguajes de scripting y programación, deberíamos comenzar con un escenario de "Hola mundo".
|
||||
|
||||
```
|
||||
terraform {
|
||||
@ -131,64 +133,65 @@ output "hello_world" {
|
||||
}
|
||||
```
|
||||
|
||||
You will find this file in the IAC folder under hello-world, but out of the box, this is not going to simply work there are some commands we need to run to use our terraform code.
|
||||
Encontrarás este archivo en la carpeta IAC dentro de hello-world, pero de entrada, esto no funcionará simplemente, hay algunos comandos que debemos ejecutar para usar nuestro código de Terraform.
|
||||
|
||||
In your terminal navigate to your folder where the main.tf has been created, this could be from this repository or you could create a new one using the code above.
|
||||
En tu terminal, navega hasta la carpeta donde se haya creado el archivo main.tf, esto puede ser desde este repositorio o puedes crear uno nuevo usando el código anterior.
|
||||
|
||||
When in that folder we are going to run `terraform init`
|
||||
Cuando estés en esa carpeta, ejecutaremos `terraform init`.
|
||||
|
||||
We need to perform this on any directory where we have or before we run any terraform code. Initialising a configuration directory downloads and installs the providers defined in the configuration, in this case, we have no providers but in the example above this would download the AWS provider for this configuration.
|
||||
Necesitamos realizar esto en cualquier directorio donde tengamos, o antes de ejecutar cualquier código de Terraform. La inicialización de un directorio de configuración descarga e instala los proveedores definidos en la configuración. En este caso, no tenemos proveedores, pero en el ejemplo anterior, esto descargaría el proveedor de AWS para esta configuración.
|
||||
|
||||

|
||||

|
||||
|
||||
The next command will be `terraform plan`
|
||||
El siguiente comando será `terraform plan`.
|
||||
|
||||
The `terraform plan` command creates an execution plan, which lets you preview the changes that Terraform plans to make to your infrastructure.
|
||||
El comando `terraform plan` crea un plan de ejecución que te permite previsualizar los cambios que Terraform planea realizar en tu infraestructura.
|
||||
|
||||
You can simply see below that with our hello-world example we are going to see output if this was an AWS ec2 instance we would see all the steps that we will be creating.
|
||||
Puedes ver simplemente a continuación que con nuestro ejemplo de hello-world veremos la salida. Si esto fuera una instancia EC2 de AWS, veríamos todos los pasos que se crearán.
|
||||
|
||||

|
||||

|
||||
|
||||
At this point, we have initialised our repository and we have our providers downloaded where required, we have run a test walkthrough to make sure this is what we want to see so now we can run and deploy our code.
|
||||
En este punto, hemos inicializado nuestro repositorio y hemos descargado los proveedores donde sea necesario. Hemos realizado una prueba para asegurarnos de que esto es lo que queremos ver, así que ahora podemos ejecutar y desplegar nuestro código.
|
||||
|
||||
`terraform apply` allows us to do this there is a built-in safety measure to this command and this will again give you a plan view on what is going to happen which warrants a response from you to say yes to continue.
|
||||
`terraform apply` nos permite hacer esto. Hay una medida de seguridad incorporada en este comando, y nuevamente te mostrará un plan de lo que va a suceder, lo cual requiere una respuesta de tu parte para decir que sí, para continuar.
|
||||
|
||||

|
||||

|
||||
|
||||
When we type in yes to enter a value, our code is deployed. Not that exciting but you can see we have the output that we defined in our code.
|
||||
Cuando escribimos "yes" para ingresar un valor, nuestro código se despliega. No es muy emocionante, pero puedes ver que tenemos la salida que definimos en nuestro código.
|
||||
|
||||

|
||||

|
||||
|
||||
Now we have not deployed anything, we have not added, changed or destroyed anything but if we did then we would see that indicated also in the above. If however we had deployed something and we wanted to get rid of everything we deployed we can use the `terraform destroy` command. Again this has that safety where you have to type yes although you can use `--auto-approve` on the end of your `apply` and `destroy` commands to bypass that manual intervention. But I would advise only using this shortcut when learning and testing as everything will disappear sometimes faster than it was built.
|
||||
Ahora, no hemos desplegado nada, no hemos agregado, cambiado o destruido nada, pero si lo hiciéramos, también lo veríamos indicado en lo anterior. Sin embargo, si hubiéramos desplegado algo y quisiéramos eliminar todo lo que hemos creado, podemos usar el comando `terraform destroy`. Nuevamente, este tiene esa medida de seguridad donde tienes que escribir "yes". Aunque puedes usar `--auto-approve` al final de tus comandos `apply` y `destroy` para evitar esa intervención manual. Pero te aconsejaría que solo uses este atajo cuando estés aprendiendo y probando, ya que todo desaparecerá a veces más rápido de lo que se construyó.
|
||||
|
||||
From this, there are 4 commands we have covered from the Terraform CLI.
|
||||
A partir de esto, hemos cubierto 4 comandos de la CLI de Terraform.
|
||||
|
||||
- `terraform init` = get your project folder ready with providers
|
||||
- `terraform plan` = show what is going to be created, and changed during the next command based on our code.
|
||||
- `terraform apply` = will go and deploy the resources defined in our code.
|
||||
- `terraform destroy` = will destroy the resources we have created in our project
|
||||
- `terraform init` = prepara la carpeta del proyecto con los proveedores.
|
||||
- `terraform plan` = muestra lo que se va a crear y cambiar durante el próximo comando, según nuestro código.
|
||||
- `terraform apply` = desplegará los recursos definidos en nuestro código.
|
||||
- `terraform destroy` = destruirá los recursos que hemos creado en nuestro proyecto.
|
||||
|
||||
We also covered two important aspects of our code files.
|
||||
También hemos cubierto dos aspectos importantes de nuestros archivos de código.
|
||||
|
||||
- providers = how does terraform speak to the end platform via APIs
|
||||
- resources = what it is we want to deploy with code
|
||||
- Proveedores = cómo Terraform se comunica con la plataforma final a través de APIs.
|
||||
- Recursos = lo que queremos desplegar con código.
|
||||
|
||||
Another thing to note when running `terraform init` take a look at the tree on the folder before and after to see what happens and where we store providers and modules.
|
||||
Otra cosa a tener en cuenta al ejecutar `terraform init` es observar el árbol de la carpeta antes y después para ver qué sucede y dónde almacenamos los proveedores y los módulos.
|
||||
|
||||
### Terraform state
|
||||
### Estado de Terraform
|
||||
|
||||
We also need to be aware of the state file that is created also inside our directory and for this hello world example our state file is simple. This is a JSON file which is the representation of the world according to Terraform. The state will happily show off your sensitive data so be careful and as a best practice put your `.tfstate` files in your `.gitignore` folder before uploading to GitHub.
|
||||
También debemos tener en cuenta el archivo de estado que se crea dentro de nuestro directorio. Para este ejemplo de hello world, nuestro archivo de estado es simple. Se trata de un archivo JSON que representa el estado del mundo según Terraform. El estado mostrará felizmente tus datos confidenciales, así que ten cuidado y, como buena práctica, agrega tus archivos `.tfstate` a tu archivo `.gitignore` antes de subirlos a GitHub.
|
||||
|
||||
By default, the state file as you can see lives inside the same directory as your project code, but it can also be stored remotely as an option. In a production environment, this is likely going to be a shared location such as an S3 bucket.
|
||||
Por defecto, el archivo de estado, como puedes ver, se encuentra dentro del mismo directorio que tu código de proyecto, pero también se puede almacenar de forma remota como opción. En un entorno de producción, es probable que esto se almacene en un lugar compartido, como un bucket de S3.
|
||||
|
||||
Another option could be Terraform Cloud, this is a paid-for-managed service. (Free up to 5 users)
|
||||
Otra opción podría ser Terraform Cloud, que es un servicio gestionado de pago (gratuito hasta 5 usuarios).
|
||||
|
||||
The pros for storing state in a remote location are that we get:
|
||||
Las ventajas de almacenar el estado en un lugar remoto son:
|
||||
|
||||
- Sensitive data encrypted
|
||||
- Collaboration
|
||||
- Automation
|
||||
- However, it could bring increase the complexity
|
||||
- Datos confidenciales encriptados.
|
||||
- Colaboración.
|
||||
- Automatización.
|
||||
|
||||
Sin embargo, esto podría aumentar la complejidad.
|
||||
|
||||
```JSON
|
||||
{
|
||||
@ -206,9 +209,9 @@ The pros for storing state in a remote location are that we get:
|
||||
}
|
||||
```
|
||||
|
||||
## Resources
|
||||
## Recursos
|
||||
|
||||
I have listed a lot of resources down below and I think this topic has been covered so many times out there, If you have additional resources be sure to raise a PR with your resources and I will be happy to review and add them to the list.
|
||||
A continuación, he enumerado muchos recursos y creo que este tema se ha cubierto muchas veces en otros lugares. Si tienes recursos adicionales, asegúrate de enviar una solicitud de extracción (PR) con tus recursos y estaré encantado de revisarlos y agregarlos a la lista.
|
||||
|
||||
- [What is Infrastructure as Code? Difference of Infrastructure as Code Tools](https://www.youtube.com/watch?v=POPP2WTJ8es)
|
||||
- [Terraform Tutorial | Terraform Course Overview 2021](https://www.youtube.com/watch?v=m3cKkYXl-8o)
|
||||
@ -220,5 +223,6 @@ I have listed a lot of resources down below and I think this topic has been cove
|
||||
- [Terraform Simple Projects](https://terraform.joshuajebaraj.com/)
|
||||
- [Terraform Tutorial - The Best Project Ideas](https://www.youtube.com/watch?v=oA-pPa0vfks)
|
||||
- [Awesome Terraform](https://github.com/shuaibiyy/awesome-terraform)
|
||||
- [Herramientas para Terraform](https://vergaracarmona.es/herramientas-para-terraform/)
|
||||
|
||||
See you on [Day 59](day59.md)
|
||||
Nos vemos en el [Día 59](day59.md)
|
||||
|
@ -82,7 +82,7 @@ id: 1048700
|
||||
|
||||
1. 개발 팀과 운영 팀을 통합합니다.
|
||||
2. 빌드 및 운영 팀을 만들고 모든 개발 및 운영 관련 문제를 전체 DevOps 팀에서 논의합니다.
|
||||
3. 스프린트에 대한 접근 방식을 변경하고 우선순위를 지정하여 개발 작업과 동일한 가치를 지닌 DevOps 작업을 제공하세요. 개발 팀과 운영 팀이 다른 팀의 워크플로와 발생 가능한 문제에 대해 의견을 교환하도록 장려하세요.
|
||||
3. 스프린트에 대한 접근 방식을 변경하고 우선순위를 지정하여 개발 작업과 동일한 가치를 지닌 DevOps 작업을 제공하세요. 개발 팀과 운영 팀이 다른 팀의 workflow와 발생 가능한 문제에 대해 의견을 교환하도록 장려하세요.
|
||||
4. 모든 개발 단계에 QA를 포함하세요.
|
||||
5. 올바른 도구를 선택하세요.
|
||||
6. 가능한 모든 것을 자동화하세요.
|
||||
|
@ -28,7 +28,7 @@ Kasten K10이나 Terraform, HCL과 같은 데브옵스 도구와 상호 작용
|
||||
|
||||
## 제가 방금 프로그래밍 언어를 배우지 말라고 설득한 건가요?
|
||||
|
||||
많은 경우, 데브옵스 엔지니어의 주된 책임은 엔지니어링 팀과 협력하여 데브옵스 관행을 워크플로우에 통합하는 것입니다. 여기에는 애플리케이션에 대한 광범위한 테스트와 워크플로우가 앞서 설명한 데브옵스 원칙을 준수하는지 확인하는 작업인 경우가 많습니다. 그러나 작업의 상당 부분에는 애플리케이션 성능 또는 기타 기술적 결함과 관련된 문제 해결도 포함될 수 있습니다. 따라서 작업 중인 애플리케이션에서 사용하는 프로그래밍 언어에 대한 전문 지식을 갖추는 것이 중요합니다. 예를 들어, 애플리케이션이 Node.js로 작성된 경우 Go나 Python을 알아도 별 도움이 되지 않습니다.
|
||||
많은 경우, 데브옵스 엔지니어의 주된 책임은 엔지니어링 팀과 협력하여 데브옵스 관행을 workflow에 통합하는 것입니다. 여기에는 애플리케이션에 대한 광범위한 테스트와 workflow가 앞서 설명한 데브옵스 원칙을 준수하는지 확인하는 작업인 경우가 많습니다. 그러나 작업의 상당 부분에는 애플리케이션 성능 또는 기타 기술적 결함과 관련된 문제 해결도 포함될 수 있습니다. 따라서 작업 중인 애플리케이션에서 사용하는 프로그래밍 언어에 대한 전문 지식을 갖추는 것이 중요합니다. 예를 들어, 애플리케이션이 Node.js로 작성된 경우 Go나 Python을 알아도 별 도움이 되지 않습니다.
|
||||
|
||||
## 왜 Go인가요?
|
||||
|
||||
|
@ -114,7 +114,7 @@ Windows 클라이언트에서 Powershell을 사용하여 키를 생성했지만,
|
||||
|
||||
위에서 설명한 SSH와는 별개로, 이번에는 웹 서버를 구축하는 방법을 다루고자 합니다. 처음에는 조금 어려워 보일 수 있지만, 실제로는 그렇지 않습니다.
|
||||
|
||||
리눅스 가상 머신을 이미 구축해 두었다고 가정하고, 이 가상 머신에 아파치 웹 서버를 추가하여 내부 네트워크에서 접근할 수 있는 간단한 웹 사이트를 호스팅하려고 합니다. 인터넷에서 접근할 수 있는 웹 사이트는 아니며, 그에 대한 내용은 여기서 다루지 않습니다.
|
||||
리눅스 가상 머신을 이미 구축해 두었다고 가정하고, 이 가상 머신에 apache 웹 서버를 추가하여 내부 네트워크에서 접근할 수 있는 간단한 웹 사이트를 호스팅하려고 합니다. 인터넷에서 접근할 수 있는 웹 사이트는 아니며, 그에 대한 내용은 여기서 다루지 않습니다.
|
||||
|
||||
이 과정은 LAMP 스택이라고도 불립니다.
|
||||
|
||||
@ -197,7 +197,7 @@ LAMP 스택에 워드프레스를 설치하기 위해 [How to install WordPress
|
||||
|
||||
위 링크의 Step 4에 도달했습니다. 워드프레스 디렉토리에 대한 모든 권한이 올바르게 설정되어 있는지 확인해야 합니다.
|
||||
|
||||
내부 네트워크 전용이므로 이 단계에서 "generate security keys"를 할 필요가 없습니다. 아파치 구성을 워드프레스로 변경하는 Step 5로 이동합니다.
|
||||
내부 네트워크 전용이므로 이 단계에서 "generate security keys"를 할 필요가 없습니다. apache 구성을 워드프레스로 변경하는 Step 5로 이동합니다.
|
||||
|
||||
모든 설정이 올바르게 구성되어 있다면, 내부 네트워크 주소를 통해 워드프레스 설치를 진행할 수 있습니다.
|
||||
|
||||
|
@ -34,7 +34,7 @@ id: 1048805
|
||||
|
||||
작업을 식별하고 네트워크 변경 요청에 대한 검색을 수행하여 솔루션을 자동화할 가장 일반적인 이슈와 문제를 파악해야 합니다.
|
||||
|
||||
- 현재 수동으로 처리하고 있는 모든 변경 요청과 워크플로우의 목록을 작성합니다.
|
||||
- 현재 수동으로 처리하고 있는 모든 변경 요청과 workflow의 목록을 작성합니다.
|
||||
- 가장 일반적이고 시간이 오래 걸리며 오류가 발생하기 쉬운 활동을 파악하세요.
|
||||
- 비즈니스 중심 접근 방식을 취하여 요청의 우선순위를 정하세요.
|
||||
- 이는 자동화 프로세스를 구축하기 위한 프레임워크이며, 자동화해야 하는 작업과 자동화하지 않아야 하는 작업을 구분합니다.
|
||||
|
@ -100,7 +100,7 @@ Azure Functions - 서버리스 코드를 제공합니다. 퍼블릭 클라우드
|
||||
|
||||
Azure Event Grid를 사용하면 서비스 및 이벤트에서 로직을 트리거할 수 있습니다.
|
||||
|
||||
Azure Logic App은 그래픽 기반 워크플로 및 통합을 제공합니다.
|
||||
Azure Logic App은 그래픽 기반 workflow 및 통합을 제공합니다.
|
||||
|
||||
또한 일관된 관리 및 예약을 통해 Windows 및 Linux 노드 모두에서 대규모 작업을 실행할 수 있는 Azure Batch도 살펴볼 수 있습니다.
|
||||
|
||||
|
@ -88,7 +88,7 @@ Microsoft Azure에는 두 가지 로드 밸런싱 솔루션이 있습니다. (
|
||||
|
||||
### Azure 포털
|
||||
|
||||
Microsoft Azure Portal은 커맨드라인 도구의 대안을 제공하는 웹 기반 콘솔입니다. Azure 포털에서 구독을 관리할 수 있습니다. 간단한 웹 앱부터 복잡한 클라우드 배포까지 모든 것을 빌드, 관리 및 모니터링할 수 있습니다. 포털 내에서 찾을 수 있는 또 다른 것은 이러한 이동 경로이며, 앞서 언급했듯이 JSON은 모든 Azure 리소스의 기반이며, 포털에서 시작하여 기능, 서비스 및 기능을 이해한 다음 나중에 자동화된 워크플로우에 통합하기 위해 그 아래에 있는 JSON을 이해할 수 있습니다.
|
||||
Microsoft Azure Portal은 커맨드라인 도구의 대안을 제공하는 웹 기반 콘솔입니다. Azure 포털에서 구독을 관리할 수 있습니다. 간단한 웹 앱부터 복잡한 클라우드 배포까지 모든 것을 빌드, 관리 및 모니터링할 수 있습니다. 포털 내에서 찾을 수 있는 또 다른 것은 이러한 이동 경로이며, 앞서 언급했듯이 JSON은 모든 Azure 리소스의 기반이며, 포털에서 시작하여 기능, 서비스 및 기능을 이해한 다음 나중에 자동화된 workflow에 통합하기 위해 그 아래에 있는 JSON을 이해할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
|
@ -12,7 +12,7 @@ id: 1048707
|
||||
|
||||
제목과 글 전체에 끔찍한 말장난이 들어가서 죄송합니다. Git을 아재 개그로 바꾼 사람이 제가 처음은 아닐 겁니다!
|
||||
|
||||
지난 두 번의 포스팅에서 버전 관리 시스템과 버전 관리 시스템으로서의 Git의 기본적인 워크플로우에 대해 배웠고, [Day 35](day35.md)에서는 시스템에 Git을 설치하고 업데이트와 구성을 했습니다. 또한 클라이언트-서버 버전 관리 시스템과 분산 버전 관리 시스템인 Git [Day 36](day36.md) 사이의 이론에 대해 조금 더 자세히 알아보았습니다.
|
||||
지난 두 번의 포스팅에서 버전 관리 시스템과 버전 관리 시스템으로서의 Git의 기본적인 workflow에 대해 배웠고, [Day 35](day35.md)에서는 시스템에 Git을 설치하고 업데이트와 구성을 했습니다. 또한 클라이언트-서버 버전 관리 시스템과 분산 버전 관리 시스템인 Git [Day 36](day36.md) 사이의 이론에 대해 조금 더 자세히 알아보았습니다.
|
||||
|
||||
이제 Git에서 흔히 볼 수 있는 몇 가지 명령어와 사용 사례를 살펴보겠습니다.
|
||||
|
||||
|
@ -70,7 +70,7 @@ Nano가 열리면 설명을 추가한 다음 파일을 저장할 수 있습니
|
||||
|
||||
프로젝트에서 파일을 제거하는 것은 어떨까요? 디렉토리에 커밋했지만 이제 프로젝트에 더 이상 필요하지 않거나 사용하지 않는 다른 파일이 있는 경우, 파일을 제거해야 합니다.
|
||||
|
||||
디렉토리에서 파일을 제거해도 git은 여전히 이 파일을 인식하므로 리포지토리에서도 파일을 제거해야 합니다. 아래에서 이를 위한 워크플로우를 확인할 수 있습니다.
|
||||
디렉토리에서 파일을 제거해도 git은 여전히 이 파일을 인식하므로 리포지토리에서도 파일을 제거해야 합니다. 아래에서 이를 위한 workflow를 확인할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
|
@ -196,7 +196,7 @@ git rebase main
|
||||
|
||||
rebase의 가장 큰 장점은 프로젝트 히스토리가 훨씬 깔끔해진다는 것입니다. 또한 불필요한 merge commit을 제거하며, 마지막 두 이미지를 비교하면 훨씬 더 깔끔한 선형 프로젝트 히스토리를 따라갈 수 있습니다.
|
||||
|
||||
아직 확실한 결론은 아니지만, 더 깔끔한 히스토리를 선택하는 것도 장단점이 있는데, [rebase의 황금률](https://www.atlassian.com/git/tutorials/merging-vs-rebasing#the-golden-rule-of-rebasing)을 따르지 않는다면 프로젝트 히스토리를 다시 작성하는 것은 협업 워크플로에 치명적일 수 있습니다. 그리고 더 중요한 것은 rebase를 하면 merge commit이 제공하는 컨텍스트가 사라져 업스트림 변경 사항이 언제 feature에 통합되었는지 알 수 없다는 것입니다.
|
||||
아직 확실한 결론은 아니지만, 더 깔끔한 히스토리를 선택하는 것도 장단점이 있는데, [rebase의 황금률](https://www.atlassian.com/git/tutorials/merging-vs-rebasing#the-golden-rule-of-rebasing)을 따르지 않는다면 프로젝트 히스토리를 다시 작성하는 것은 협업 workflow에 치명적일 수 있습니다. 그리고 더 중요한 것은 rebase를 하면 merge commit이 제공하는 컨텍스트가 사라져 업스트림 변경 사항이 언제 feature에 통합되었는지 알 수 없다는 것입니다.
|
||||
|
||||
## 자료
|
||||
|
||||
|
@ -185,7 +185,7 @@ Insight 탭은 리포지토리의 활동량부터 commit 및 issues에 이르기
|
||||
|
||||
이 단계에서는 이 작업이 완료되고 우리만 새로운 변경 사항을 사용할 것이므로 변경 사항에 만족할 수도 있지만, 버그 변경일 수도 있으며 이 경우, pull requests를 통해 기여하여 원래 리포지토리 관리자에게 변경 사항을 알리고 변경 사항을 수락하는지 확인하고 싶을 것입니다.
|
||||
|
||||
아래 강조 표시된 기여 버튼을 사용하여 이 작업을 수행할 수 있습니다. 내일 오픈소스 워크플로우를 살펴보면서 이에 대해 더 자세히 다루겠습니다.
|
||||
아래 강조 표시된 기여 버튼을 사용하여 이 작업을 수행할 수 있습니다. 내일 오픈소스 workflow를 살펴보면서 이에 대해 더 자세히 다루겠습니다.
|
||||
|
||||

|
||||
|
||||
|
@ -8,7 +8,7 @@ canonical_url: null
|
||||
id: 1048806
|
||||
---
|
||||
|
||||
## 오픈 소스 워크플로
|
||||
## 오픈 소스 workflow
|
||||
|
||||
지난 7회에 걸친 Git 섹션을 통해 Git이 무엇인지, 그리고 GitHub와 같은 Git 기반 서비스가 어떻게 소스 코드 저장소를 제공할 뿐만 아니라 더 많은 커뮤니티가 함께 코드와 프로젝트를 협업할 수 있는 방법을 제공하는지 더 잘 이해하셨기를 바랍니다.
|
||||
|
||||
|
@ -44,7 +44,7 @@ Windows에서는 WSL2와 Microsoft Hyper-V도 활용할 수 있습니다. WSL2
|
||||
|
||||
Docker Compose는 여러 컨테이너에서 더 복잡한 앱을 실행할 수 있는 도구입니다. 단일 파일과 명령을 사용하여 애플리케이션을 스핀업할 수 있다는 이점이 있습니다.
|
||||
|
||||
### Docker Hub
|
||||
### DockerHub
|
||||
|
||||
docker와 그 구성 요소로 작업하기 위한 중앙 집중식 리소스입니다. 가장 일반적으로는 docker 이미지를 호스팅하는 레지스트리로 알려져 있습니다. 그러나 여기에는 부분적으로 자동화와 함께 사용하거나 보안 검사뿐만 아니라 GitHub에 통합할 수 있는 많은 추가 서비스가 있습니다.
|
||||
|
||||
|
@ -14,11 +14,11 @@ id: 1048708
|
||||
|
||||
이 글에서는 몇 가지 이미지를 우리 환경에 배포하는 작업을 시작하겠습니다. Docker 이미지에 대한 요약 - Docker 이미지는 Docker 컨테이너에서 코드를 실행하는 데 사용되는 파일입니다. Docker 이미지는 템플릿처럼 Docker 컨테이너를 빌드하기 위한 일련의 지침 역할을 합니다. 또한 Docker 이미지는 Docker를 사용할 때 시작점 역할을 하기도 합니다.
|
||||
|
||||
지금 바로 [Docker Hub](https://hub.docker.com/)에서 계정을 생성하세요.
|
||||
지금 바로 [DockerHub](https://hub.docker.com/)에서 계정을 생성하세요.
|
||||
|
||||

|
||||
|
||||
Docker Hub는 Docker 및 그 구성 요소로 작업하기 위한 중앙 집중식 리소스입니다. 가장 일반적으로는 docker 이미지를 호스팅하는 레지스트리로 알려져 있습니다. 그러나 여기에는 부분적으로 자동화와 함께 사용하거나 보안 검사뿐만 아니라 GitHub에 통합할 수 있는 많은 추가 서비스가 있습니다.
|
||||
DockerHub는 Docker 및 그 구성 요소로 작업하기 위한 중앙 집중식 리소스입니다. 가장 일반적으로는 docker 이미지를 호스팅하는 레지스트리로 알려져 있습니다. 그러나 여기에는 부분적으로 자동화와 함께 사용하거나 보안 검사뿐만 아니라 GitHub에 통합할 수 있는 많은 추가 서비스가 있습니다.
|
||||
|
||||
로그인한 후 아래로 스크롤하면 컨테이너 이미지 목록이 표시되며, MySQL, hello-world 등의 데이터베이스 이미지가 표시될 수 있습니다. 데이터베이스 이미지가 필요하거나 직접 만들 필요가 없는 경우 공식 이미지를 사용하는 것이 가장 좋습니다.
|
||||
|
||||
@ -46,11 +46,11 @@ Docker Hub는 Docker 및 그 구성 요소로 작업하기 위한 중앙 집중
|
||||
|
||||

|
||||
|
||||
원격 리포지토리 아래에서 Docker Hub에 저장한 컨테이너 이미지를 찾을 수 있습니다. 아래에서 볼 수 있듯이 이미지가 없습니다.
|
||||
원격 리포지토리 아래에서 DockerHub에 저장한 컨테이너 이미지를 찾을 수 있습니다. 아래에서 볼 수 있듯이 이미지가 없습니다.
|
||||
|
||||

|
||||
|
||||
Docker Hub 사이트에서도 리포지토리가 없음을 확인할 수 있습니다.
|
||||
DockerHub 사이트에서도 리포지토리가 없음을 확인할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
@ -87,7 +87,7 @@ Containers/Apps 탭으로 돌아가서 실행 중인 컨테이너를 클릭합
|
||||
이 컨테이너에는 컨테이너와 이미지에 대한 자세한 내용도 있습니다.
|
||||
|
||||

|
||||
이제 첫 번째 컨테이너를 실행했습니다. 아직은 쉽습니다. 컨테이너 이미지 중 하나를 Docker Hub에서 가져오고 싶다면 어떻게 해야 할까요? 아마도 우리가 사용할 수 있는 `hello world` docker 컨테이너가 있을 것입니다.
|
||||
이제 첫 번째 컨테이너를 실행했습니다. 아직은 쉽습니다. 컨테이너 이미지 중 하나를 DockerHub에서 가져오고 싶다면 어떻게 해야 할까요? 아마도 우리가 사용할 수 있는 `hello world` docker 컨테이너가 있을 것입니다.
|
||||
|
||||
시작 컨테이너는 리소스를 많이 차지하기 때문이 아니라 몇 가지 단계를 더 진행하면서 깔끔하게 정리하기 위해 중단했습니다.
|
||||
|
||||
@ -111,7 +111,7 @@ Containers/Apps 탭으로 돌아가서 실행 중인 컨테이너를 클릭합
|
||||
|
||||

|
||||
|
||||
터미널에서 `docker run -it ubuntu bash`를 실행할 때 우리는 운영 체제의 전체 복사본이 아닌 우분투의 컨테이너화된 버전을 실행할 것입니다. 이 특정 이미지에 대한 자세한 내용은 [Docker Hub](https://hub.docker.com/_/ubuntu)에서 확인할 수 있습니다.
|
||||
터미널에서 `docker run -it ubuntu bash`를 실행할 때 우리는 운영 체제의 전체 복사본이 아닌 우분투의 컨테이너화된 버전을 실행할 것입니다. 이 특정 이미지에 대한 자세한 내용은 [DockerHub](https://hub.docker.com/_/ubuntu)에서 확인할 수 있습니다.
|
||||
|
||||
아래 명령어를 실행하면 대화형 프롬프트(`-it`)가 나타나고 컨테이너에 bash 셸이 생성되는 것을 볼 수 있습니다.
|
||||
|
||||
@ -129,7 +129,7 @@ bash 셸이 있지만 그 이상은 없기 때문에 이 컨테이너 이미지
|
||||
|
||||

|
||||
|
||||
이 글에서는 사용 사례를 통해 Docker Desktop과 컨테이너의 세계에 대한 개요를 간단하고 접근하기 쉬운 방식으로 제공하고자 합니다. 그러나 컨테이너 이미지를 다운로드하고 사용하는 것 외에도 네트워킹, 보안 및 기타 사용 가능한 옵션에 대해서도 다뤄야 합니다. 이 섹션의 궁극적인 목표는 무언가를 만들어서 Docker Hub 리포지토리에 업로드하고 배포하는 것입니다.
|
||||
이 글에서는 사용 사례를 통해 Docker Desktop과 컨테이너의 세계에 대한 개요를 간단하고 접근하기 쉬운 방식으로 제공하고자 합니다. 그러나 컨테이너 이미지를 다운로드하고 사용하는 것 외에도 네트워킹, 보안 및 기타 사용 가능한 옵션에 대해서도 다뤄야 합니다. 이 섹션의 궁극적인 목표는 무언가를 만들어서 DockerHub 리포지토리에 업로드하고 배포하는 것입니다.
|
||||
|
||||
## 자료
|
||||
|
||||
|
@ -10,7 +10,7 @@ id: 1048777
|
||||
|
||||
## Docker 이미지의 구조
|
||||
|
||||
지난 세션에서는 Docker Hub와 결합된 Docker Desktop을 사용하여 몇 가지 검증된 이미지를 배포하고 실행하는 방법에 대한 몇 가지 기본 사항을 다루었습니다. 이미지가 무엇인지에 대한 요약을 계속 언급하면 잊어버리지 않을 것입니다.
|
||||
지난 세션에서는 DockerHub와 결합된 Docker Desktop을 사용하여 몇 가지 검증된 이미지를 배포하고 실행하는 방법에 대한 몇 가지 기본 사항을 다루었습니다. 이미지가 무엇인지에 대한 요약을 계속 언급하면 잊어버리지 않을 것입니다.
|
||||
|
||||
Docker 이미지는 Docker 플랫폼에서 실행할 수 있는 컨테이너를 만들기 위한 일련의 지침이 포함된 읽기 전용 템플릿입니다. 애플리케이션과 사전 구성된 서버 환경을 패키징하여 개인적으로 사용하거나 다른 Docker 사용자와 공개적으로 공유할 수 있는 편리한 방법을 제공합니다. 또한 Docker 이미지는 Docker를 처음 사용하는 모든 사용자에게 시작점이 됩니다.
|
||||
|
||||
@ -30,7 +30,7 @@ docker가 이미지로부터 컨테이너를 실행할 때마다 (어제 실행
|
||||
|
||||

|
||||
|
||||
위의 예제에서 우분투 이미지뿐만 아니라 Docker Hub 및 기타 서드파티 리포지토리에서 사용할 수 있는 다른 많은 기성 컨테이너 이미지도 마찬가지입니다. 이러한 이미지를 일반적으로 부모 이미지라고 합니다. 이 이미지는 다른 모든 레이어가 구축되는 기반이 되며 컨테이너 환경의 기본 구성 요소를 제공합니다.
|
||||
위의 예제에서 우분투 이미지뿐만 아니라 DockerHub 및 기타 서드파티 리포지토리에서 사용할 수 있는 다른 많은 기성 컨테이너 이미지도 마찬가지입니다. 이러한 이미지를 일반적으로 부모 이미지라고 합니다. 이 이미지는 다른 모든 레이어가 구축되는 기반이 되며 컨테이너 환경의 기본 구성 요소를 제공합니다.
|
||||
|
||||
개별 레이어 파일 세트와 함께 Docker 이미지에는 manifest라는 추가 파일도 포함됩니다. 이 파일은 기본적으로 이미지에 대한 JSON 형식의 설명이며 이미지 태그, 전자 서명, 다양한 유형의 호스트 플랫폼에 맞게 컨테이너를 구성하는 방법에 대한 세부 정보와 같은 정보로 구성됩니다.
|
||||
|
||||
@ -103,7 +103,7 @@ pull 옵션이 있지만, 이 이미지는 어디에도 호스팅되지 않기
|
||||
|
||||

|
||||
|
||||
이제 Docker Hub 리포지토리로 이동하여 살펴보면 방금 새 이미지를 push한 것을 확인할 수 있습니다. 이제 Docker Desktop에서 해당 pull 탭을 사용할 수 있습니다.
|
||||
이제 DockerHub 리포지토리로 이동하여 살펴보면 방금 새 이미지를 push한 것을 확인할 수 있습니다. 이제 Docker Desktop에서 해당 pull 탭을 사용할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
|
@ -146,7 +146,7 @@ Docker Desktop에서 볼륨이 여전히 존재한다는 것을 확인할 수
|
||||
|
||||

|
||||
|
||||
이제 `docker-compose up -d`를 다시 사용하면 시작하지만, 이미지는 여전히 우리 시스템의 로컬에 있으므로 Docker Hub 리포지토리에서 다시 가져올 필요가 없습니다.
|
||||
이제 `docker-compose up -d`를 다시 사용하면 시작하지만, 이미지는 여전히 우리 시스템의 로컬에 있으므로 DockerHub 리포지토리에서 다시 가져올 필요가 없습니다.
|
||||
|
||||
docker-compose와 그 기능에 대해 알아보기 시작했을 때 이것이 Kubernetes와 같은 컨테이너 오케스트레이션 도구와 어디에 위치하는지 혼란스러웠는데, 이 짧은 데모에서 우리가 한 모든 작업은 로컬 데스크톱 머신에서 실행 중인 WordPress와 DB가 있는 호스트 하나에 초점을 맞추고 있습니다. 여러 가상 머신이나 여러 물리적 머신이 없으며 애플리케이션의 요구 사항을 쉽게 확장 및 축소할 수도 없습니다.
|
||||
|
||||
|
@ -114,13 +114,13 @@ USER basicuser
|
||||
|
||||
조직에서 컨테이너 이미지의 비공개 레지스트리를 설정하면 원하는 곳에서 호스팅할 수 있거나 이를 위한 관리형 서비스도 있지만, 대체로 사용자와 팀이 사용할 수 있는 이미지를 완벽하게 제어할 수 있습니다.
|
||||
|
||||
Docker Hub는 기준선을 제시하는 데는 훌륭하지만, 이미지 게시자를 많이 신뢰해야 하는 기본적인 서비스만 제공합니다.
|
||||
DockerHub는 기준선을 제시하는 데는 훌륭하지만, 이미지 게시자를 많이 신뢰해야 하는 기본적인 서비스만 제공합니다.
|
||||
|
||||
### 린 & 클린
|
||||
|
||||
보안과 관련되지는 않았지만, 전체적으로 언급했습니다. 그러나 애플리케이션에서 사용하지 않는 리소스가 컨테이너에 필요하지 않은 경우 컨테이너의 크기는 공격 표면 측면에서 보안에 영향을 미칠 수 있습니다.
|
||||
|
||||
또한 `latest` 이미지를 가져올 때 이미지에 많은 부풀림을 가져올 수 있기 때문에 이것이 저의 주요 관심사입니다. Docker Hub는 리포지토리에 있는 각 이미지의 압축 크기를 표시합니다.
|
||||
또한 `latest` 이미지를 가져올 때 이미지에 많은 부풀림을 가져올 수 있기 때문에 이것이 저의 주요 관심사입니다. DockerHub는 리포지토리에 있는 각 이미지의 압축 크기를 표시합니다.
|
||||
|
||||
`docker image`를 확인하면 이미지의 크기를 확인할 수 있는 좋은 명령어입니다.
|
||||
|
||||
|
@ -112,7 +112,7 @@ YAML 파일 위치로 이동한 다음 `kubectl create -f nginx-stateless-demo.y
|
||||
|
||||
위 그림에서 replicaset가 있는 것을 볼 수 있는데, 배포에서 배포할 이미지의 레플리카 개수를 정의합니다. 처음에는 1로 설정되었지만, 애플리케이션을 빠르게 확장하려면 여러 가지 방법으로 확장할 수 있습니다.
|
||||
|
||||
터미널 내에서 텍스트 편집기를 열고 배포를 수정할 수 있는 `kubectl edit deployment nginx-deployment -n nginx`를 사용하여 파일을 편집할 수 있다.
|
||||
터미널 내에서 텍스트 편집기를 열고 배포를 수정할 수 있는 `kubectl edit deployment nginx-deployment -n nginx`를 사용하여 파일을 편집할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
|
@ -77,12 +77,12 @@ pod 라이프사이클에 의존하지 않는 스토리지 계층이 필요합
|
||||
- 볼륨이 pod에 마운트됨
|
||||
- pod는 여러 가지 볼륨 유형(ConfigMaps, Secrets, PVC)을 사용
|
||||
|
||||
PV와 PVC를 생각하는 또 다른 방법은 다음과 같다.
|
||||
PV와 PVC를 생각하는 또 다른 방법은 다음과 같습니다.
|
||||
|
||||
PV는 Kubernetes 어드민에 의해 생성된다.
|
||||
PVC는 사용자 또는 애플리케이션 개발자가 생성한다.
|
||||
PV는 Kubernetes 어드민에 의해 생성됩니다.
|
||||
PVC는 사용자 또는 애플리케이션 개발자가 생성합니다.
|
||||
|
||||
또한 자세히 설명하지는 않겠지만 언급할 가치가 있는 두 가지 다른 유형의 볼륨이 있다:
|
||||
또한 자세히 설명하지는 않겠지만 언급할 가치가 있는 두 가지 다른 유형의 볼륨이 있습니다:
|
||||
|
||||
### ConfigMaps | Secrets
|
||||
|
||||
@ -150,7 +150,7 @@ PVC는 사용자 또는 애플리케이션 개발자가 생성한다.
|
||||
|
||||
앞서 언급한 바와 같이 상태 비저장 애플리케이션에서 Minikube를 사용하고 있기 때문에 애플리케이션에 액세스하는 데 있어 몇 가지 장애물이 있지만, 클러스터 내에서 Ingress 또는 로드 밸런서에 액세스하여 외부에서 액세스하기 위해 자동으로 IP를 받도록 설정되어 있습니다. (위의 Pacman 네임스페이스의 모든 구성 요소 이미지에서 이를 확인할 수 있습니다).
|
||||
|
||||
이 데모에서는 포트 포워드 방법을 사용하여 애플리케이션에 액세스하겠습니다. 새 터미널을 열고 다음 `kubectl port-forward svc/pacman 9090:80 -n pacman` 명령을 실행하고 브라우저를 열면 이제 애플리케이션에 액세스할 수 있다. AWS 또는 특정 위치에서 실행하는 경우, 위의 스크린샷에서 이 pod 이름을 다시 한번 확인하면 클라우드와 영역은 물론 Kubernetes 내의 pod와 동일한 호스트에 대해서도 보고됩니다.
|
||||
이 데모에서는 포트 포워드 방법을 사용하여 애플리케이션에 액세스하겠습니다. 새 터미널을 열고 다음 `kubectl port-forward svc/pacman 9090:80 -n pacman` 명령을 실행하고 브라우저를 열면 이제 애플리케이션에 액세스할 수 있습니다. AWS 또는 특정 위치에서 실행하는 경우, 위의 스크린샷에서 이 pod 이름을 다시 한번 확인하면 클라우드와 영역은 물론 Kubernetes 내의 pod와 동일한 호스트에 대해서도 보고됩니다.
|
||||
|
||||

|
||||
|
||||
@ -188,7 +188,7 @@ Ingress의 경우, 애플리케이션의 내부 서비스에 대한 포워드
|
||||
|
||||
클라우드 제공자를 사용하는 경우, 관리형 Kubernetes 제품에는 클러스터에 대한 Ingress 옵션이 있거나 로드 밸런서 옵션이 제공될 가능성이 높습니다. 이를 직접 구현할 필요가 없다는 것이 관리형 Kubernetes의 장점 중 하나입니다.
|
||||
|
||||
클러스터를 실행하는 경우 엔트리포인트를 구성해야 한다.
|
||||
클러스터를 실행하는 경우 엔트리포인트를 구성해야 합니다.
|
||||
|
||||
### Minikube에서 Ingress 구성하기
|
||||
|
||||
|
133
2022/ko/Days/day56.md
Normal file
133
2022/ko/Days/day56.md
Normal file
@ -0,0 +1,133 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - The Big Picture: IaC - Day 56'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - The Big Picture IaC
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048709
|
||||
---
|
||||
|
||||
## 큰 그림: IaC
|
||||
|
||||
인간은 실수를 합니다! 자동화를 도입해야 합니다!
|
||||
|
||||
현재 시스템을 어떻게 구축하고 계신가요?
|
||||
|
||||
오늘 물리 머신, 가상 머신, 클라우드 VM, 클라우드 PaaS 등 모든 것을 잃게 된다면 어떤 계획을 세우시겠습니까?
|
||||
|
||||
모든 것을 교체하는 데 얼마나 걸리나요?
|
||||
|
||||
IaC는 이를 테스트할 수 있는 동시에 이를 수행할 수 있는 솔루션을 제공하며, 이를 백업 및 복구와 혼동해서는 안 되지만 인프라와 환경, 플랫폼 측면에서 이를 스핀업하여 가축과 반려동물로 취급할 수 있어야 합니다.
|
||||
|
||||
결론은 코드를 사용하여 전체 환경을 재구축할 수 있다는 것입니다.
|
||||
|
||||
처음부터 데브옵스에 대해 일반적으로 장벽을 허물어 시스템을 안전하고 신속하게 프로덕션에 배포하는 방법이라고 말씀드린 것을 기억하세요.
|
||||
|
||||
IaC는 시스템을 제공하는 데 도움이 되며, 우리는 많은 프로세스와 도구에 대해 이야기했습니다. IaC는 프로세스의 이 부분을 구현하기 위해 익숙한 더 많은 도구를 제공합니다.
|
||||
|
||||
이 섹션에서는 IaC에 대해 집중적으로 살펴보겠습니다. 이를 코드의 인프라 또는 코드로서의 구성이라고도 합니다. 가장 잘 알려진 용어는 아마도 IaC가 아닐까 생각합니다.
|
||||
|
||||
### 반려동물 대 가축
|
||||
|
||||
데브옵스 이전을 살펴보면, 새로운 애플리케이션을 빌드해야 하는 경우 대부분의 경우 서버를 수동으로 준비해야 합니다.
|
||||
|
||||
- 가상 머신 배포 | 물리적 서버 및 운영 체제 설치
|
||||
- 네트워킹 구성
|
||||
- 라우팅 테이블 생성
|
||||
- 소프트웨어 및 업데이트 설치
|
||||
- 소프트웨어 구성
|
||||
- 데이터베이스 설치
|
||||
|
||||
이는 시스템 관리자가 수동으로 수행하는 프로세스입니다. 애플리케이션의 규모가 클수록 더 많은 리소스와 서버가 필요하며, 이러한 시스템을 가동하는 데 더 많은 수작업이 필요합니다. 이 작업에는 엄청난 인력과 시간이 소요될 뿐만 아니라 기업 입장에서도 이러한 환경을 구축하기 위해 리소스에 대한 비용을 지불해야 합니다. "인간은 실수를 합니다! 자동화를 도입해야 합니다!"로 섹션을 시작한 이유입니다.
|
||||
|
||||
위의 초기 설정 단계에 이어서 이러한 서버를 유지 관리해야 합니다.
|
||||
|
||||
- 버전 업데이트
|
||||
- 새 릴리스 배포
|
||||
- 데이터 관리
|
||||
- 애플리케이션 복구
|
||||
- 서버 추가, 제거 및 확장
|
||||
- 네트워크 구성
|
||||
|
||||
여러 테스트 및 개발 환경의 복잡성을 추가하세요.
|
||||
|
||||
위에서 언급한 서버를 마치 반려동물처럼 돌보던 시절에는 서버에 애칭을 붙이거나 적어도 한동안 '가족'의 일원이 되기를 바라며 이름을 지어주기도 했습니다.
|
||||
|
||||
IaC를 사용하면 이러한 모든 작업을 처음부터 끝까지 자동화할 수 있습니다. IaC는 인프라를 자동으로 프로비저닝하는 개념으로, 일부 툴은 서버에 문제가 발생하면 서버를 폐기하고 새 서버를 스핀업하는 작업을 수행합니다. 이 프로세스는 자동화되어 있으며 서버는 코드에 정의된 대로 정확하게 작동합니다. 이 시점에서는 장애가 발생하거나 애플리케이션의 일부 또는 전부를 업데이트하여 더 이상 현장에 존재하지 않고 이를 대체할 다른 서버가 있을 때까지는 서버의 명칭이 무엇이든 상관없습니다.
|
||||
|
||||
이는 거의 모든 플랫폼, 가상화, 클라우드 기반 워크로드, 그리고 Kubernetes 및 컨테이너와 같은 클라우드 네이티브 인프라에서 사용할 수 있습니다.
|
||||
|
||||
### 인프라 프로비저닝
|
||||
|
||||
이 섹션에서 사용할 도구는 아래의 처음 두 가지 영역만 다루고 있습니다. Terraform은 우리가 다룰 도구이며, 이를 통해 무에서 시작하여 인프라의 모양을 코드로 정의한 다음 배포할 수 있으며, 인프라를 관리하고 애플리케이션을 처음 배포할 수도 있지만 그 시점에서는 애플리케이션을 추적할 수 없게 되므로 다음 섹션에서 구성 관리 도구로서 Ansible과 같은 것이 이 부분에서 더 잘 작동할 수 있습니다.
|
||||
|
||||
너무 앞서 나가지 않고 초기 애플리케이션 설정을 처리한 다음 해당 애플리케이션과 그 구성을 관리하는 데는 chef, puppet 및 ansible과 같은 도구가 가장 적합합니다.
|
||||
|
||||
소프트웨어의 초기 설치 및 구성
|
||||
|
||||
- 새 서버 스핀업
|
||||
- 네트워크 구성
|
||||
- 로드 밸런서 생성
|
||||
- 인프라 수준에서 구성
|
||||
|
||||
### 프로비저닝된 인프라 구성
|
||||
|
||||
- 서버에 애플리케이션 설치
|
||||
- 애플리케이션을 배포할 서버를 준비합니다.
|
||||
|
||||
### 애플리케이션 배포
|
||||
|
||||
- 애플리케이션 배포 및 관리
|
||||
- 유지 관리 단계
|
||||
- 소프트웨어 업데이트
|
||||
- 재구성
|
||||
|
||||
### IaC 도구의 차이점
|
||||
|
||||
선언적 방식과 절차적 방식
|
||||
|
||||
절차적
|
||||
|
||||
- 단계별 지침
|
||||
- 서버 생성 > 서버 추가 > 이 변경하기
|
||||
|
||||
선언적
|
||||
|
||||
- 결과 선언
|
||||
- 서버 2개
|
||||
|
||||
변경 가능(반려동물) vs 변경 불가(가축)
|
||||
|
||||
변경 가능
|
||||
|
||||
- 대체 대신 변경
|
||||
- 일반적으로 수명이 길다
|
||||
|
||||
변경 불가
|
||||
|
||||
- 변경 대신 교체
|
||||
- 수명이 짧을 수 있음
|
||||
|
||||
이것이 바로 IaC를 위한 다양한 옵션이 있는 이유입니다. 모든 것을 지배하는 하나의 도구가 없기 때문입니다.
|
||||
|
||||
저희는 주로 Terraform을 사용하며 직접 실습해볼 예정인데, 이것이 IaC가 실제로 작동할 때 그 이점을 확인할 수 있는 가장 좋은 방법이기 때문입니다. 실습은 코드 작성에 필요한 기술을 익힐 수 있는 가장 좋은 방법이기도 합니다.
|
||||
|
||||
다음에는 직접 사용해 보기 전에 101을 통해 Terraform에 대해 살펴보겠습니다.
|
||||
|
||||
## 자료
|
||||
|
||||
아래에 많은 리소스를 나열했으며 이 주제는 이미 여러 번 다루어졌다고 생각합니다. 추가 리소스가 있는 경우 리소스와 함께 PR을 올리면 기꺼이 검토하여 목록에 추가해 드리겠습니다.
|
||||
|
||||
- [What is Infrastructure as Code? Difference of Infrastructure as Code Tools](https://www.youtube.com/watch?v=POPP2WTJ8es)
|
||||
- [Terraform Tutorial | Terraform Course Overview 2021](https://www.youtube.com/watch?v=m3cKkYXl-8o)
|
||||
- [Terraform explained in 15 mins | Terraform Tutorial for Beginners](https://www.youtube.com/watch?v=l5k1ai_GBDE)
|
||||
- [Terraform Course - From BEGINNER to PRO!](https://www.youtube.com/watch?v=7xngnjfIlK4&list=WL&index=141&t=16s)
|
||||
- [HashiCorp Terraform Associate Certification Course](https://www.youtube.com/watch?v=V4waklkBC38&list=WL&index=55&t=111s)
|
||||
- [Terraform Full Course for Beginners](https://www.youtube.com/watch?v=EJ3N-hhiWv0&list=WL&index=39&t=27s)
|
||||
- [KodeKloud - Terraform for DevOps Beginners + Labs: Complete Step by Step Guide!](https://www.youtube.com/watch?v=YcJ9IeukJL8&list=WL&index=16&t=11s)
|
||||
- [Terraform Simple Projects](https://terraform.joshuajebaraj.com/)
|
||||
- [Terraform Tutorial - The Best Project Ideas](https://www.youtube.com/watch?v=oA-pPa0vfks)
|
||||
- [Awesome Terraform](https://github.com/shuaibiyy/awesome-terraform)
|
||||
|
||||
[Day 57](day57.md)에서 봐요!
|
98
2022/ko/Days/day57.md
Normal file
98
2022/ko/Days/day57.md
Normal file
@ -0,0 +1,98 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - An intro to Terraform - Day 57'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - An intro to Terraform
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048710
|
||||
---
|
||||
|
||||
## Terraform 소개
|
||||
|
||||
"Terraform은 인프라를 안전하고 효율적으로 구축, 변경, 버전 관리할 수 있는 도구입니다."
|
||||
|
||||
위의 인용문은 Terraform의 개발사인 HashiCorp에서 인용한 것입니다.
|
||||
|
||||
"Terraform은 수백 개의 클라우드 서비스를 관리하기 위한 일관된 CLI workflow를 제공하는 코드 소프트웨어 도구로서 오픈 소스 인프라입니다. Terraform은 클라우드 API를 선언적 구성 파일로 코드화합니다."
|
||||
|
||||
해시코프는 [HashiCorp 배우기](https://learn.hashicorp.com/terraform?utm_source=terraform_io&utm_content=terraform_io_hero)에서 모든 제품을 다루는 훌륭한 리소스를 제공하고 있으며, IaC로 무언가를 달성하려고 할 때 유용한 데모를 제공합니다.
|
||||
|
||||
모든 클라우드 제공업체와 온프레미스 플랫폼은 일반적으로 UI를 통해 리소스를 생성할 수 있는 관리 콘솔에 대한 액세스를 제공하며, 일반적으로 이러한 플랫폼은 동일한 리소스를 생성할 수 있는 CLI 또는 API 액세스도 제공하지만, API를 사용하면 빠르게 프로비저닝할 수 있습니다.형
|
||||
|
||||
IaC를 사용하면 이러한 API에 연결하여 원하는 상태로 리소스를 배포할 수 있습니다.
|
||||
|
||||
아래에 배타적이거나 완전한 도구가 아닌 다른 도구가 있습니다. 다른 도구가 있다면 PR을 통해 공유해 주세요.
|
||||
|
||||
| Cloud Specific | Cloud Agnostic |
|
||||
| ------------------------------- | -------------- |
|
||||
| AWS CloudFormation | Terraform |
|
||||
| Azure Resource Manager | Pulumi |
|
||||
| Google Cloud Deployment Manager | |
|
||||
|
||||
데모뿐만 아니라 일반적으로 사용하고자 하는 클라우드와 플랫폼에 구애받지 않으려는 것이 바로 우리가 Terraform을 사용하는 또 다른 이유입니다.
|
||||
|
||||
## Terraform 개요
|
||||
|
||||
Terraform은 프로비저닝에 중점을 둔 도구로, 복잡한 인프라 환경을 프로비저닝할 수 있는 기능을 제공하는 CLI입니다. 로컬 또는 원격(클라우드)에 존재하는 복잡한 인프라 요구 사항을 정의할 수 있습니다. Terraform을 사용하면 처음에 구축할 수 있을 뿐만 아니라 해당 리소스의 수명 기간 동안 유지 관리 및 업데이트할 수 있습니다.
|
||||
|
||||
여기서는 개략적인 내용만 다루겠지만, 더 자세한 내용과 다양한 리소스를 보려면 [terraform.io](https://www.terraform.io/)를 방문하세요.
|
||||
|
||||
### 쓰기
|
||||
|
||||
Terraform을 사용하면 환경을 구축할 선언적 구성 파일을 만들 수 있습니다. 이 파일은 블록, 인수, 표현식을 사용하여 리소스를 간결하게 설명할 수 있는 해시코프 구성 언어(HCL)를 사용하여 작성됩니다. 물론 가상 머신, 컨테이너를 배포할 때와 쿠버네티스 내에서 이를 자세히 살펴볼 것입니다.
|
||||
|
||||
### 계획
|
||||
|
||||
위의 구성 파일들이 우리가 보고자 하는 것을 배포할 것인지 확인하기 위해 Terraform cli의 특정 기능을 사용하여 배포하거나 변경하기 전에 해당 계획을 테스트할 수 있는 기능입니다. Terraform은 인프라를 위한 지속적인 도구이므로 인프라의 측면을 변경하려면 코드에서 모두 캡처되도록 Terraform을 통해 변경해야 한다는 점을 기억하세요.
|
||||
|
||||
### 적용
|
||||
|
||||
만족스러우면 계속해서 이 구성을 Terraform 내에서 사용할 수 있는 많은 제공업체에 적용할 수 있습니다. [여기](https://registry.terraform.io/browse/providers)에서 사용 가능한 수많은 제공자를 확인할 수 있습니다.
|
||||
|
||||
또 한 가지 언급할 것은 사용 가능한 모듈도 있다는 것인데, 이러한 모듈은 공개적으로 생성 및 공유되어 있으므로 특정 인프라 리소스를 모든 곳에 동일한 방식으로 배포하는 모범 사례를 반복해서 생성할 필요가 없다는 점에서 컨테이너 이미지와 유사합니다. 사용 가능한 모듈은 [여기](https://registry.terraform.io/browse/modules)에서 찾을 수 있습니다.
|
||||
|
||||
Terraform workflow는 다음과 같습니다. (_Terraform 사이트에서 가져옴_)
|
||||
|
||||

|
||||
|
||||
### Terraform vs Vagrant
|
||||
|
||||
이번 챌린지에서는 개발 환경에 집중하는 또 다른 해시코프 오픈소스 도구인 Vagrant를 사용했습니다.
|
||||
|
||||
- Vagrant는 개발 환경 관리에 중점을 둔 도구입니다.
|
||||
|
||||
- Terraform은 인프라 구축을 위한 도구입니다.
|
||||
|
||||
두 도구에 대한 자세한 비교는 공식 [HashiCorp 사이트](https://www.vagrantup.com/intro/vs/terraform)에서 확인할 수 있습니다.
|
||||
|
||||
## Terraform 설치
|
||||
|
||||
Terraform을 설치하는 데에는 많은 것이 필요하지 않습니다.
|
||||
|
||||
Terraform은 크로스 플랫폼이며, 제 리눅스 머신에서 아래에서 CLI를 다운로드하고 설치하는 몇 가지 옵션을 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
`arkade`를 사용하여 Terraform을 설치하면, 아케이드는 필요한 도구, 앱, 클리스를 시스템에 설치할 수 있는 편리한 작은 도구입니다. 간단한 `arkade get terraform`으로 Terraform을 업데이트할 수 있으며, Terraform이 있다면 같은 명령으로 Terraform CLI도 설치할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
앞으로 HCL에 대해 좀 더 자세히 살펴본 다음 다양한 플랫폼에서 인프라 리소스를 생성하는 데 Terraform을 사용해 보도록 하겠습니다.
|
||||
|
||||
## 자료
|
||||
|
||||
아래에 많은 리소스를 나열했으며 이 주제는 이미 여러 번 다루어졌다고 생각합니다. 추가 리소스가 있는 경우 리소스와 함께 PR을 올리면 기꺼이 검토하여 목록에 추가해 드리겠습니다.
|
||||
|
||||
- [What is Infrastructure as Code? Difference of Infrastructure as Code Tools](https://www.youtube.com/watch?v=POPP2WTJ8es)
|
||||
- [Terraform Tutorial | Terraform Course Overview 2021](https://www.youtube.com/watch?v=m3cKkYXl-8o)
|
||||
- [Terraform explained in 15 mins | Terraform Tutorial for Beginners](https://www.youtube.com/watch?v=l5k1ai_GBDE)
|
||||
- [Terraform Course - From BEGINNER to PRO!](https://www.youtube.com/watch?v=7xngnjfIlK4&list=WL&index=141&t=16s)
|
||||
- [HashiCorp Terraform Associate Certification Course](https://www.youtube.com/watch?v=V4waklkBC38&list=WL&index=55&t=111s)
|
||||
- [Terraform Full Course for Beginners](https://www.youtube.com/watch?v=EJ3N-hhiWv0&list=WL&index=39&t=27s)
|
||||
- [KodeKloud - Terraform for DevOps Beginners + Labs: Complete Step by Step Guide!](https://www.youtube.com/watch?v=YcJ9IeukJL8&list=WL&index=16&t=11s)
|
||||
- [Terraform Simple Projects](https://terraform.joshuajebaraj.com/)
|
||||
- [Terraform Tutorial - The Best Project Ideas](https://www.youtube.com/watch?v=oA-pPa0vfks)
|
||||
- [Awesome Terraform](https://github.com/shuaibiyy/awesome-terraform)
|
||||
|
||||
[Day 58](day58.md)에서 봐요!
|
234
2022/ko/Days/day58.md
Normal file
234
2022/ko/Days/day58.md
Normal file
@ -0,0 +1,234 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - HashiCorp Configuration Language (HCL) - Day 58'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - HashiCorp Configuration Language (HCL)
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048741
|
||||
---
|
||||
|
||||
## HashiCorp 구성 언어(HCL)
|
||||
|
||||
Terraform으로 무언가를 만들기 시작하기 전에 HashiCorp 구성 언어(HCL)에 대해 조금 알아볼 필요가 있습니다. 지금까지 챌린지를 진행하면서 몇 가지 다른 스크립팅 및 프로그래밍 언어를 살펴봤는데, 여기에 또 다른 언어가 있습니다. [Go 프로그래밍 언어](day07.md)에 이어 [bash 스크립트](day19.md)를 다루었고, [네트워크 자동화](day27.md)와 관련해서는 파이썬도 조금 다뤄봤습니다.
|
||||
|
||||
이제 HashiCorp 구성 언어(HCL)를 다뤄야 하는데, 이 언어를 처음 접하는 분들에게는 다소 어렵게 느껴질 수 있지만 매우 간단하고 강력한 언어입니다.
|
||||
|
||||
이 섹션을 진행하면서 어떤 OS를 사용하든 시스템에서 로컬로 실행할 수 있는 예제를 사용할 것이며, 일반적으로 Terraform에서 사용하는 인프라 플랫폼은 아니지만 VirtualBox를 사용할 것입니다. 그러나 로컬에서 실행하는 것은 무료이며 이 게시물에서 원하는 것을 달성할 수 있습니다. 이 포스팅의 개념을 도커나 쿠버네티스로 확장할 수도 있습니다.
|
||||
|
||||
하지만 일반적으로는 퍼블릭 클라우드(AWS, Google, Microsoft Azure)뿐만 아니라 가상화 환경(VMware, Microsoft Hyper-V, Nutanix AHV)에도 인프라를 배포하는 데 Terraform을 사용하거나 사용해야 합니다. 퍼블릭 클라우드에서 Terraform을 사용하면 가상 머신 자동 배포뿐 아니라 PaaS 워크로드와 같은 모든 필수 인프라와 VPC 및 보안 그룹과 같은 모든 네트워킹 필수 자산을 생성할 수 있습니다.
|
||||
|
||||
Terraform에는 두 가지 중요한 측면이 있는데, 이 포스팅에서 다룰 code와 state입니다. 이 두 가지를 함께 Terraform의 핵심이라고 부를 수 있습니다. 그런 다음 우리가 대화하고 배포하고자 하는 환경이 있는데, 이는 지난 세션에서 간략히 언급했지만, AWS 공급자, Azure 공급자 등을 사용하여 실행되는 Terraform 공급자를 사용하여 실행됩니다. 수백 개가 있습니다.
|
||||
|
||||
### 기본 Terraform 사용법
|
||||
|
||||
Terraform `.tf` 파일이 어떻게 구성되는지 살펴보겠습니다. 첫 번째로 살펴볼 예제는 AWS에 리소스를 배포하는 코드이며, 이를 위해서는 시스템에 AWS CLI를 설치하고 계정에 맞게 구성해야 합니다.
|
||||
|
||||
### 공급자
|
||||
|
||||
더 복잡하게 만들 때까지는 일반적으로 `main.tf`라고 부르는 `.tf` 파일 구조의 맨 위에 있습니다. 여기서는 앞서 언급했던 공급자를 정의합니다. 보시다시피 AWS 공급자의 소스는 `hashicorp/aws`이며, 이는 공급자가 HashiCorp에서 직접 유지 관리하거나 게시했음을 의미합니다. 기본적으로 [Terraform 레지스트리](https://registry.terraform.io/)에서 사용할 수 있는 제공자를 참조하게 되며, 제공자를 작성하여 로컬에서 사용하거나 Terraform 레지스트리에 자체 게시할 수도 있습니다.
|
||||
|
||||
```
|
||||
terraform {
|
||||
required_providers {
|
||||
aws = {
|
||||
source = "hashicorp/aws"
|
||||
version = "~> 3.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
프로비저닝할 AWS 리전을 결정하기 위해 여기에 리전을 추가할 수도 있는데, 이를 위해 다음을 추가할 수 있습니다:
|
||||
|
||||
```
|
||||
provider "aws" {
|
||||
region = "ap-southeast-1" //리소스를 배포해야 하는 지역
|
||||
}
|
||||
```
|
||||
|
||||
### Terraform 리소스
|
||||
|
||||
- EC2, 로드 밸런서, VPC 등과 같은 하나 이상의 인프라 개체를 설명하는 Terraform 구성 파일의 또 다른 중요한 구성 요소입니다.
|
||||
|
||||
- 리소스 블록은 지정된 유형("aws_instance")의 리소스를 지정된 로컬 이름("90daysofdevops")으로 선언합니다.
|
||||
|
||||
- 리소스 유형과 이름은 함께 지정된 리소스의 식별자 역할을 합니다.
|
||||
|
||||
```
|
||||
resource "aws_instance" "90daysofdevops" {
|
||||
ami = data.aws_ami.instance_id.id
|
||||
instance_type = "t2.micro"
|
||||
availability_zone = "us-west-2a"
|
||||
security_groups = [aws_security_group.allow_web.name]
|
||||
user_data = <<-EOF
|
||||
#! /bin/bash
|
||||
sudo yum update
|
||||
sudo yum install -y httpd
|
||||
sudo systemctl start httpd
|
||||
sudo systemctl enable httpd
|
||||
echo "
|
||||
<h1>Deployed via Terraform</h1>
|
||||
|
||||
" | sudo tee /var/www/html/index.html
|
||||
EOF
|
||||
tags = {
|
||||
Name = "Created by Terraform"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
위에서 `yum` 업데이트를 실행하고 ec2 인스턴스에 `httpd`를 설치하는 것을 볼 수 있습니다.
|
||||
|
||||
이제 전체 main.tf 파일을 보면 다음과 같이 보일 수 있습니다.
|
||||
|
||||
```
|
||||
terraform {
|
||||
required_providers {
|
||||
aws = {
|
||||
source = "hashicorp/aws"
|
||||
version = "~> 3.27"
|
||||
}
|
||||
}
|
||||
|
||||
required_version = ">= 0.14.9"
|
||||
}
|
||||
|
||||
provider "aws" {
|
||||
profile = "default"
|
||||
region = "us-west-2"
|
||||
}
|
||||
|
||||
resource "aws_instance" "90daysofdevops" {
|
||||
ami = "ami-830c94e3"
|
||||
instance_type = "t2.micro"
|
||||
availability_zone = "us-west-2a"
|
||||
user_data = <<-EOF
|
||||
#! /bin/bash
|
||||
sudo yum update
|
||||
sudo yum install -y httpd
|
||||
sudo systemctl start httpd
|
||||
sudo systemctl enable httpd
|
||||
echo "
|
||||
<h1>Deployed via Terraform</h1>
|
||||
|
||||
" | sudo tee /var/www/html/index.html
|
||||
EOF
|
||||
tags = {
|
||||
Name = "Created by Terraform"
|
||||
|
||||
tags = {
|
||||
Name = "ExampleAppServerInstance"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
위의 코드는 AWS에서 매우 간단한 웹 서버를 ec2 인스턴스로 배포합니다. 이 코드와 이와 같은 다른 구성의 가장 큰 장점은 이 작업을 반복할 수 있고 매번 동일한 출력을 얻을 수 있다는 것입니다. 제가 코드를 엉망으로 만들었을 가능성을 제외하고는 위와 같이 사람이 개입할 여지가 없습니다.
|
||||
|
||||
한 번도 사용하지 않을 것 같은 아주 간단한 예제를 살펴볼 수 있지만, 어쨌든 유머러스하게 만들어 보겠습니다. 모든 훌륭한 스크립팅 및 프로그래밍 언어가 그렇듯, Hello World부터 시작해야 합니다.
|
||||
|
||||
```
|
||||
terraform {
|
||||
# 이 모듈은 현재 Terraform 0.13.x에서만 테스트 중입니다. 그러나 더 쉽게 업그레이드할 수 있도록 다음과 같이 설정하고 있습니다.
|
||||
# 0.12.26을 최소 버전으로 설정했는데, 이 버전은 소스 URL이 있는 required_providers에 대한 지원이 추가되었기 때문입니다.
|
||||
# 0.13.x 코드와 호환됩니다.
|
||||
required_version = ">= 0.12.26"
|
||||
}
|
||||
|
||||
# website::tag::1:: 가장 간단한 Terraform 모듈: "Hello, World!"를 출력하기만 하면 됩니다.
|
||||
output "hello_world" {
|
||||
value = "Hello, 90DaysOfDevOps from Terraform"
|
||||
}
|
||||
```
|
||||
|
||||
이 파일은 IaC 폴더 안의 Hello-world 폴더에서 찾을 수 있지만, Terraform 코드를 사용하기 위해 실행해야 하는 몇 가지 명령이 있기 때문에 바로 작동하지는 않습니다.
|
||||
|
||||
터미널에서 main.tf가 생성된 폴더로 이동합니다. 이 저장소에서 가져올 수도 있고 위의 코드를 사용하여 새 저장소를 생성할 수도 있습니다.
|
||||
|
||||
해당 폴더에서 `terraform init`을 실행합니다.
|
||||
|
||||
Terraform 코드가 있는 모든 디렉토리에서 또는 Terraform 코드를 실행하기 전에 이 작업을 수행해야 합니다. 구성 디렉터리를 초기화하면 구성에 정의된 공급자를 다운로드하여 설치합니다. 이 경우에는 공급자가 없지만 위의 예제에서는 이 구성에 대한 AWS 공급자를 다운로드합니다.
|
||||
|
||||

|
||||
|
||||
다음 명령은 `terraform plan`입니다.
|
||||
|
||||
`terraform plan` 명령은 실행 계획을 생성하여 Terraform이 인프라에 적용하려는 변경 사항을 미리 볼 수 있게 해줍니다.
|
||||
|
||||
hello-world 예제를 통해 아래에서 간단히 볼 수 있듯이, 이것이 AWS ec2 인스턴스였다면 생성할 모든 단계가 출력되는 것을 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
이 시점에서 리포지토리를 초기화했고 필요한 경우 제공자를 다운로드했으며, 테스트 워크스루를 실행하여 원하는 대로 표시되는지 확인했으므로 이제 코드를 실행하고 배포할 수 있습니다.
|
||||
|
||||
`terraform apply`를 사용하면 이 작업을 수행할 수 있으며, 이 명령에는 안전 조치가 내장되어 있어 앞으로 일어날 일에 대한 계획 보기가 다시 제공되므로 계속할 것인지에 대한 응답을 보장합니다.
|
||||
|
||||

|
||||
|
||||
값을 입력하기 위해 yes를 입력하면 코드가 배포됩니다. 그다지 흥미롭지는 않지만, 코드에서 정의한 출력이 나오는 것을 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
이제 우리는 아무것도 배포하지 않았고, 아무것도 추가, 변경 또는 삭제하지 않았지만, 만약 배포했다면 위와 같이 표시된 것을 볼 수 있을 것입니다. 그러나 무언가를 배포한 후 배포한 모든 것을 제거하려면 `terraform destroy` 명령을 사용할 수 있습니다. 이 경우에도 `apply` 및 `delete` 명령 끝에 `--auto-approve`을 사용하여 수동 개입을 우회할 수 있지만 예라고 입력해야 하는 안전성이 있습니다. 하지만 이 단축키는 학습 및 테스트 시에만 사용하는 것이 좋으며, 때로는 모든 것이 빌드된 것보다 빨리 사라질 수 있습니다.
|
||||
|
||||
지금까지 Terraform CLI에서 다룬 명령어는 총 4가지입니다.
|
||||
|
||||
- `terraform init` = 프로바이더로 프로젝트 폴더 준비하기
|
||||
- `terraform plan` = 코드를 기반으로 다음 명령 중에 생성 및 변경될 내용을 표시합니다.
|
||||
- `terraform apply`= 코드에 정의된 리소스를 배포합니다.
|
||||
- `terraform destroy` = 프로젝트에서 생성한 리소스를 파괴합니다.
|
||||
|
||||
코드 파일에서 두 가지 중요한 측면도 다루었습니다.
|
||||
|
||||
- providers = API를 통해 Terraform이 최종 플랫폼과 대화하는 방법
|
||||
- resources = 우리가 코드로 배포하고자 하는 것
|
||||
|
||||
또 한 가지 주의해야 할 점은 `terraform init`을 실행할 때 폴더의 트리를 전후로 살펴보고 어떤 일이 발생하고 제공자와 모듈을 어디에 저장하는지 확인하는 것입니다.
|
||||
|
||||
### Terraform state
|
||||
|
||||
또한 디렉터리 내부에 생성되는 state 파일도 알아야 하는데, 이 hello-world 예제에서 state 파일은 간단합니다. 이것은 Terraform에 따라 세계를 표현하는 JSON 파일입니다. 상태는 민감한 데이터를 기꺼이 보여줄 수 있으므로 주의해야 하며, 모범 사례로 GitHub에 업로드하기 전에 `.tfstate` 파일을 `.gitignore` 폴더에 넣는 것이 좋습니다.
|
||||
|
||||
기본적으로 상태 파일은 프로젝트 코드와 같은 디렉터리에 있지만 옵션으로 원격으로 저장할 수도 있습니다. 프로덕션 환경에서는 S3 버킷과 같은 공유 위치가 될 가능성이 높습니다.
|
||||
|
||||
또 다른 옵션으로는 유료 관리형 서비스인 Terraform Cloud가 있습니다. (최대 5명의 사용자까지 무료)
|
||||
|
||||
원격 위치에 상태를 저장할 때 얻을 수 있는 장점은 다음과 같습니다:
|
||||
|
||||
- 민감한 데이터 암호화
|
||||
- 협업
|
||||
- 자동화
|
||||
- 그러나 복잡성이 증가할 수 있습니다.
|
||||
|
||||
```JSON
|
||||
{
|
||||
"version": 4,
|
||||
"terraform_version": "1.1.6",
|
||||
"serial": 1,
|
||||
"lineage": "a74296e7-670d-0cbb-a048-f332696ca850",
|
||||
"outputs": {
|
||||
"hello_world": {
|
||||
"value": "Hello, 90DaysOfDevOps from Terraform",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"resources": []
|
||||
}
|
||||
```
|
||||
|
||||
## 자료
|
||||
|
||||
아래에 많은 리소스를 나열했으며 이 주제는 이미 여러 번 다루어졌다고 생각합니다. 추가 리소스가 있는 경우 리소스와 함께 PR을 올리면 기꺼이 검토하여 목록에 추가해 드리겠습니다.
|
||||
|
||||
- [What is Infrastructure as Code? Difference of Infrastructure as Code Tools](https://www.youtube.com/watch?v=POPP2WTJ8es)
|
||||
- [Terraform Tutorial | Terraform Course Overview 2021](https://www.youtube.com/watch?v=m3cKkYXl-8o)
|
||||
- [Terraform explained in 15 mins | Terraform Tutorial for Beginners](https://www.youtube.com/watch?v=l5k1ai_GBDE)
|
||||
- [Terraform Course - From BEGINNER to PRO!](https://www.youtube.com/watch?v=7xngnjfIlK4&list=WL&index=141&t=16s)
|
||||
- [HashiCorp Terraform Associate Certification Course](https://www.youtube.com/watch?v=V4waklkBC38&list=WL&index=55&t=111s)
|
||||
- [Terraform Full Course for Beginners](https://www.youtube.com/watch?v=EJ3N-hhiWv0&list=WL&index=39&t=27s)
|
||||
- [KodeKloud - Terraform for DevOps Beginners + Labs: Complete Step by Step Guide!](https://www.youtube.com/watch?v=YcJ9IeukJL8&list=WL&index=16&t=11s)
|
||||
- [Terraform Simple Projects](https://terraform.joshuajebaraj.com/)
|
||||
- [Terraform Tutorial - The Best Project Ideas](https://www.youtube.com/watch?v=oA-pPa0vfks)
|
||||
- [Awesome Terraform](https://github.com/shuaibiyy/awesome-terraform)
|
||||
|
||||
[Day 59](day59.md)에서 봐요!
|
130
2022/ko/Days/day59.md
Normal file
130
2022/ko/Days/day59.md
Normal file
@ -0,0 +1,130 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - Create a VM with Terraform & Variables - Day 59'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - Create a VM with Terraform & Variables
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1049051
|
||||
---
|
||||
|
||||
## Terraform 및 변수를 사용하여 VM 생성하기
|
||||
|
||||
이 세션에서는 VirtualBox 내에서 Terraform을 사용하여 VM을 한두 개 생성해 보겠습니다. VirtualBox는 워크스테이션 가상화 옵션이므로 Terraform의 사용 사례는 아니지만, 저는 현재 36,000피트 상공에 있으며 이 정도 높이의 클라우드에 퍼블릭 클라우드 리소스를 배포한 만큼 노트북에서 로컬로 이 작업을 수행하는 것이 훨씬 더 빠릅니다.
|
||||
|
||||
순전히 데모 목적이지만 개념은 동일합니다. 원하는 상태 구성 코드를 만든 다음 VirtualBox 공급자에 대해 실행할 것입니다. 과거에는 여기서는 vagrant를 사용했으며 이 섹션의 시작 부분에서 vagrant와 Terraform의 차이점에 대해 다루었습니다.
|
||||
|
||||
### VirtualBox에서 가상 머신 생성하기
|
||||
|
||||
가장 먼저 할 일은 VirtualBox라는 새 폴더를 생성한 다음 VirtualBox.tf 파일을 생성하고 여기에서 리소스를 정의하는 것입니다. VirtualBox 폴더에서 VirtualBox.tf로 찾을 수 있는 아래 코드는 Virtualbox에 2개의 VM을 생성합니다.
|
||||
|
||||
커뮤니티 VirtualBox 제공업체에 대한 자세한 내용은 [여기](https://registry.terraform.io/providers/terra-farm/virtualbox/latest/docs/resources/vm)에서 확인할 수 있습니다.
|
||||
|
||||
```
|
||||
terraform {
|
||||
required_providers {
|
||||
virtualbox = {
|
||||
source = "terra-farm/virtualbox"
|
||||
version = "0.2.2-alpha.1"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# 현재 공급자 자체에 대한 구성 옵션이 없습니다.
|
||||
|
||||
resource "virtualbox_vm" "node" {
|
||||
count = 2
|
||||
name = format("node-%02d", count.index + 1)
|
||||
image = "https://app.vagrantup.com/ubuntu/boxes/bionic64/versions/20180903.0.0/providers/virtualbox.box"
|
||||
cpus = 2
|
||||
memory = "512 mib"
|
||||
|
||||
network_adapter {
|
||||
type = "hostonly"
|
||||
host_interface = "vboxnet1"
|
||||
}
|
||||
}
|
||||
|
||||
output "IPAddr" {
|
||||
value = element(virtualbox_vm.node.*.network_adapter.0.ipv4_address, 1)
|
||||
}
|
||||
|
||||
output "IPAddr_2" {
|
||||
value = element(virtualbox_vm.node.*.network_adapter.0.ipv4_address, 2)
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
이제 코드가 정의되었으므로 이제 폴더에서 `terraform init`을 수행하여 Virtualbox용 공급자를 다운로드할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
또한 시스템에도 VirtualBox가 설치되어 있어야 합니다. 그런 다음 `terraform plan`을 실행하여 코드가 무엇을 생성하는지 확인할 수 있습니다. 이어서 `terraform apply`를 실행하면 아래 이미지에 완성된 프로세스가 표시됩니다.
|
||||
|
||||

|
||||
|
||||
이제 Virtualbox에서 2개의 가상 머신을 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
### 구성 변경
|
||||
|
||||
배포에 다른 노드를 추가해 보겠습니다. 카운트 라인을 변경하여 원하는 새로운 노드 수를 표시하면 됩니다. `terraform apply`를 실행하면 아래와 같이 표시됩니다.
|
||||
|
||||

|
||||
|
||||
VirtualBox에서 완료되면 이제 3개의 노드가 실행되고 있는 것을 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
완료되면 `terraform destroy`를 사용하여 이를 지우면 머신이 제거됩니다.
|
||||
|
||||

|
||||
|
||||
### 변수 및 출력
|
||||
|
||||
지난 세션에서 hello-world 예제를 실행할 때 출력을 언급했습니다. 여기서 더 자세히 살펴볼 수 있습니다.
|
||||
|
||||
하지만 여기에도 사용할 수 있는 다른 많은 변수가 있으며, 변수를 정의하는 몇 가지 다른 방법도 있습니다.
|
||||
|
||||
- `terraform plan` 또는 `terraform apply` 명령을 사용하여 변수를 수동으로 입력할 수 있습니다.
|
||||
|
||||
- 블록 내의 .tf 파일에 변수를 정의할 수 있습니다.
|
||||
|
||||
- `TF_VAR_NAME` 형식을 사용하여 시스템 내에서 환경 변수를 사용할 수 있습니다.
|
||||
|
||||
- 저는 프로젝트 폴더에 terraform.tfvars 파일을 사용하는 것을 선호합니다.
|
||||
|
||||
- \*auto.tfvars 파일 옵션이 있습니다.
|
||||
|
||||
- 또는 `-var` 또는 `-var-file`을 사용하여 `terraform plan` 또는 `terraform apply`을 실행할 때를 정의할 수 있습니다.
|
||||
|
||||
아래에서 위로 올라가는 것이 변수를 정의하는 순서입니다.
|
||||
|
||||
또한 상태 파일에 민감한 정보가 포함될 것이라고 언급했습니다. 민감한 정보를 변수로 정의하고 이를 민감한 정보로 정의할 수 있습니다.
|
||||
|
||||
```
|
||||
variable "some resource" {
|
||||
description = "something important"
|
||||
type= string
|
||||
sensitive = true
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
## 자료
|
||||
|
||||
아래에 많은 리소스를 나열했으며 이 주제는 이미 여러 번 다루어졌다고 생각합니다. 추가 리소스가 있는 경우 리소스와 함께 PR을 올리면 기꺼이 검토하여 목록에 추가해 드리겠습니다.
|
||||
|
||||
- [What is Infrastructure as Code? Difference of Infrastructure as Code Tools](https://www.youtube.com/watch?v=POPP2WTJ8es)
|
||||
- [Terraform Tutorial | Terraform Course Overview 2021](https://www.youtube.com/watch?v=m3cKkYXl-8o)
|
||||
- [Terraform explained in 15 mins | Terraform Tutorial for Beginners](https://www.youtube.com/watch?v=l5k1ai_GBDE)
|
||||
- [Terraform Course - From BEGINNER to PRO!](https://www.youtube.com/watch?v=7xngnjfIlK4&list=WL&index=141&t=16s)
|
||||
- [HashiCorp Terraform Associate Certification Course](https://www.youtube.com/watch?v=V4waklkBC38&list=WL&index=55&t=111s)
|
||||
- [Terraform Full Course for Beginners](https://www.youtube.com/watch?v=EJ3N-hhiWv0&list=WL&index=39&t=27s)
|
||||
- [KodeKloud - Terraform for DevOps Beginners + Labs: Complete Step by Step Guide!](https://www.youtube.com/watch?v=YcJ9IeukJL8&list=WL&index=16&t=11s)
|
||||
- [Terraform Simple Projects](https://terraform.joshuajebaraj.com/)
|
||||
- [Terraform Tutorial - The Best Project Ideas](https://www.youtube.com/watch?v=oA-pPa0vfks)
|
||||
- [Awesome Terraform](https://github.com/shuaibiyy/awesome-terraform)
|
||||
|
||||
[Day 60](day60.md)에서 봐요!
|
194
2022/ko/Days/day60.md
Normal file
194
2022/ko/Days/day60.md
Normal file
@ -0,0 +1,194 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - Docker Containers, Provisioners & Modules - Day 60'
|
||||
published: false
|
||||
description: '90DaysOfDevOps - Docker Containers, Provisioners & Modules'
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1049052
|
||||
---
|
||||
|
||||
## Docker 컨테이너, Provisioners 및 모듈
|
||||
|
||||
[Day 59](day59.md)에는 Terraform을 사용하여 로컬 무료 VirtualBox 환경에 가상 머신을 프로비저닝했습니다. 이 섹션에서는 몇 가지 구성이 포함된 Docker 컨테이너를 로컬 Docker 환경에 배포해 보겠습니다.
|
||||
|
||||
### Docker 데모
|
||||
|
||||
먼저 아래 코드 블록을 사용하여 간단한 웹 앱을 Docker에 배포하고 이를 게시하여 네트워크에서 사용할 수 있도록 하겠습니다. nginx를 사용할 것이며 로컬 호스트와 포트 8000을 통해 노트북에서 외부에서 사용할 수 있도록 할 것입니다. 커뮤니티에서 제공하는 Docker 공급자를 사용하고 있으며 구성에서도 사용 중인 Docker 이미지를 확인할 수 있습니다.
|
||||
|
||||
```
|
||||
terraform {
|
||||
required_providers {
|
||||
docker = {
|
||||
source = "kreuzwerker/docker"
|
||||
version = "2.16.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
provider "docker" {}
|
||||
|
||||
resource "docker_image" "nginx" {
|
||||
name = "nginx:latest"
|
||||
keep_locally = false
|
||||
}
|
||||
|
||||
resource "docker_container" "nginx" {
|
||||
image = docker_image.nginx.latest
|
||||
name = "tutorial"
|
||||
ports {
|
||||
internal = 80
|
||||
external = 8000
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
첫 번째 작업은 `terraform init` 명령을 사용하여 로컬 머신에 프로바이더를 다운로드하는 것입니다.
|
||||
|
||||

|
||||
|
||||
그런 다음 `terraform apply`를 실행한 다음 `docker ps`를 실행하면 컨테이너가 실행되는 것을 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
이제 브라우저를 열어 `http://localhost:8000/`으로 이동하면 NGINX 컨테이너에 액세스할 수 있는 것을 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
자세한 내용은 [Docker Provider](https://registry.terraform.io/providers/kreuzwerker/docker/latest/docs/resources/container)에서 확인할 수 있습니다.
|
||||
|
||||
위는 Terraform과 Docker로 무엇을 할 수 있는지, 그리고 Terraform 상태에서 어떻게 관리할 수 있는지에 대한 아주 간단한 데모입니다. 컨테이너 섹션에서 docker-compose에 대해 다뤘고, 이것과 IaC, 그리고 Kubernetes 사이에는 약간의 교차점이 있습니다.
|
||||
|
||||
이를 보여드리고 Terraform이 어떻게 좀 더 복잡한 것을 처리할 수 있는지 보여드리기 위해, 우리가 docker-compose로 만든 워드프레스와 MySQL용 docker-compose 파일을 가져와서 이것을 Terraform에 넣도록 하겠습니다. [docker-wordpress.tf](2022/Days/IaC/Docker-WordPress/docker-WordPress.tf)를 찾을 수 있습니다.
|
||||
|
||||
```
|
||||
terraform {
|
||||
required_providers {
|
||||
docker = {
|
||||
source = "kreuzwerker/docker"
|
||||
version = "2.16.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
provider "docker" {}
|
||||
|
||||
variable wordpress_port {
|
||||
default = "8080"
|
||||
}
|
||||
|
||||
resource "docker_volume" "db_data" {
|
||||
name = "db_data"
|
||||
}
|
||||
|
||||
resource "docker_network" "wordpress_net" {
|
||||
name = "wordpress_net"
|
||||
}
|
||||
|
||||
resource "docker_container" "db" {
|
||||
name = "db"
|
||||
image = "mysql:5.7"
|
||||
restart = "always"
|
||||
network_mode = "wordpress_net"
|
||||
env = [
|
||||
"MYSQL_ROOT_PASSWORD=wordpress",
|
||||
"MYSQL_PASSWORD=wordpress",
|
||||
"MYSQL_USER=wordpress",
|
||||
"MYSQL_DATABASE=wordpress"
|
||||
]
|
||||
mounts {
|
||||
type = "volume"
|
||||
target = "/var/lib/mysql"
|
||||
source = "db_data"
|
||||
}
|
||||
}
|
||||
|
||||
resource "docker_container" "wordpress" {
|
||||
name = "wordpress"
|
||||
image = "wordpress:latest"
|
||||
restart = "always"
|
||||
network_mode = "wordpress_net"
|
||||
env = [
|
||||
"WORDPRESS_DB_HOST=db:3306",
|
||||
"WORDPRESS_DB_USER=wordpress",
|
||||
"WORDPRESS_DB_NAME=wordpress",
|
||||
"WORDPRESS_DB_PASSWORD=wordpress"
|
||||
]
|
||||
ports {
|
||||
internal = "80"
|
||||
external = "${var.wordpress_port}"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
이 파일을 다시 새 폴더에 넣은 다음 `terraform init` 명령을 실행하여 필요한 Provisioners를 내려놓습니다.
|
||||
|
||||

|
||||
|
||||
그런 다음 `terraform apply` 명령을 실행한 다음 `docker ps` 출력을 살펴보면 새로 생성된 컨테이너를 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
이제 WordPress 프론트엔드로 이동할 수도 있습니다. 컨테이너 섹션에서 docker-compose로 이 과정을 거쳤을 때와 마찬가지로 이제 설정을 실행할 수 있으며 WordPress 게시물이 MySQL 데이터베이스에 저장됩니다.
|
||||
|
||||

|
||||
|
||||
이제 컨테이너와 Kubernetes에 대해 자세히 살펴봤는데요, 테스트용으로는 괜찮지만, 실제 웹사이트를 운영할 계획이라면 컨테이너만으로는 이 작업을 수행하지 않고 Kubernetes를 사용하여 이를 달성할 것입니다. 다음에는 Terraform과 Kubernetes를 사용하여 살펴보도록 하겠습니다.
|
||||
|
||||
### Provisioners
|
||||
|
||||
Provisioners는 어떤 것이 선언적일 수 없는 경우 이를 배포에 파싱할 수 있는 방법을 제공하기 위해 존재합니다.
|
||||
|
||||
다른 대안이 없고 코드에 이러한 복잡성을 추가해야 하는 경우 다음 코드 블록과 유사한 것을 실행하여 이를 수행할 수 있습니다.
|
||||
|
||||
```
|
||||
resource "docker_container" "db" {
|
||||
# ...
|
||||
|
||||
provisioner "local-exec" {
|
||||
command = "echo The server's IP address is ${self.private_ip}"
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
원격 실행 Provisioners는 원격 리소스가 생성된 후 원격 리소스에서 스크립트를 호출합니다. 이 스크립트는 OS에 따라 다르거나 구성 관리 도구에서 래핑하는 데 사용될 수 있습니다. 이 중 일부는 Provisioners에서 다루고 있습니다.
|
||||
|
||||
[Provisioners에 대한 자세한 내용](https://www.terraform.io/language/resources/provisioners/syntax)
|
||||
|
||||
- file
|
||||
- local-exec
|
||||
- remote-exec
|
||||
- vendor
|
||||
- ansible
|
||||
- chef
|
||||
- puppet
|
||||
|
||||
### 모듈
|
||||
|
||||
모듈은 함께 사용되는 여러 리소스를 위한 컨테이너입니다. 모듈은 동일한 디렉터리에 있는 .tf 파일 모음으로 구성됩니다.
|
||||
|
||||
모듈은 인프라 리소스를 분리할 수 있는 좋은 방법일 뿐만 아니라 이미 만들어진 타사 모듈을 가져올 수 있으므로 처음부터 다시 만들 필요가 없습니다.
|
||||
|
||||
예를 들어, 동일한 프로젝트를 사용하여 일부 VM, VPC, 보안 그룹을 구축한 다음 Kubernetes 클러스터도 구축하려는 경우 리소스를 모듈로 분할하여 리소스와 그룹화 위치를 더 잘 정의하고 싶을 것입니다.
|
||||
|
||||
모듈의 또 다른 장점은 이러한 모듈을 가져와 다른 프로젝트에 사용하거나 커뮤니티를 돕기 위해 공개적으로 공유할 수 있다는 것입니다.
|
||||
|
||||
저희는 인프라를 구성 요소로 나누고 있으며, 여기서 구성 요소는 모듈로 알려져 있습니다.
|
||||
|
||||
## 자료
|
||||
|
||||
아래에 많은 리소스를 나열했으며 이 주제는 이미 여러 번 다루어졌다고 생각합니다. 추가 리소스가 있는 경우 리소스와 함께 PR을 올리면 기꺼이 검토하여 목록에 추가해 드리겠습니다.
|
||||
|
||||
- [What is Infrastructure as Code? Difference of Infrastructure as Code Tools](https://www.youtube.com/watch?v=POPP2WTJ8es)
|
||||
- [Terraform Tutorial | Terraform Course Overview 2021](https://www.youtube.com/watch?v=m3cKkYXl-8o)
|
||||
- [Terraform explained in 15 mins | Terraform Tutorial for Beginners](https://www.youtube.com/watch?v=l5k1ai_GBDE)
|
||||
- [Terraform Course - From BEGINNER to PRO!](https://www.youtube.com/watch?v=7xngnjfIlK4&list=WL&index=141&t=16s)
|
||||
- [HashiCorp Terraform Associate Certification Course](https://www.youtube.com/watch?v=V4waklkBC38&list=WL&index=55&t=111s)
|
||||
- [Terraform Full Course for Beginners](https://www.youtube.com/watch?v=EJ3N-hhiWv0&list=WL&index=39&t=27s)
|
||||
- [KodeKloud - Terraform for DevOps Beginners + Labs: Complete Step by Step Guide!](https://www.youtube.com/watch?v=YcJ9IeukJL8&list=WL&index=16&t=11s)
|
||||
- [Terraform Simple Projects](https://terraform.joshuajebaraj.com/)
|
||||
- [Terraform Tutorial - The Best Project Ideas](https://www.youtube.com/watch?v=oA-pPa0vfks)
|
||||
- [Awesome Terraform](https://github.com/shuaibiyy/awesome-terraform)
|
||||
|
||||
[Day 61](day61.md)에서 봐요!
|
172
2022/ko/Days/day61.md
Normal file
172
2022/ko/Days/day61.md
Normal file
@ -0,0 +1,172 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - Kubernetes & Multiple Environments - Day 61'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - Kubernetes & Multiple Environments
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048743
|
||||
---
|
||||
|
||||
## Kubernetes 및 다중 환경
|
||||
|
||||
지금까지 IaC에 대한 이 섹션에서는 가상 머신을 배포하는 방법을 살펴보았지만, 가상 머신의 모양을 코드에서 정의한 다음 배포한다는 전제는 실제로 동일합니다. Docker 컨테이너도 마찬가지이며, 이 세션에서는 Terraform을 사용하여 Kubernetes에서 지원하는 리소스와 상호 작용하는 방법을 살펴보겠습니다.
|
||||
|
||||
저는 데모 목적으로 3개의 주요 클라우드 제공업체에 Terraform을 사용하여 Kubernetes 클러스터를 배포해 왔으며, 리포지토리 [tf_k8deploy](https://github.com/MichaelCade/tf_k8deploy)를 찾을 수 있습니다.
|
||||
|
||||
그러나 Terraform을 사용하여 Kubernetes 클러스터 내의 객체와 상호 작용할 수도 있는데, 이는 [Kubernetes 공급자](https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs)를 사용하거나 [Helm 공급자](https://registry.terraform.io/providers/hashicorp/helm/latest)를 사용하여 차트 배포를 관리할 수 있습니다.
|
||||
|
||||
이제 이전 섹션에서 살펴본 것처럼 `kubectl`을 사용할 수 있습니다. 하지만 Kubernetes 환경에서 Terraform을 사용하면 몇 가지 이점이 있습니다.
|
||||
|
||||
- 통합 workflow - 클러스터 배포에 Terraform을 사용했다면, 동일한 workflow와 도구를 사용하여 Kubernetes 클러스터 내에 배포할 수 있습니다.
|
||||
|
||||
- 라이프사이클 관리 - Terraform은 단순한 프로비저닝 도구가 아니라 변경, 업데이트, 삭제를 가능하게 합니다.
|
||||
|
||||
### 간단한 Kubernetes 데모
|
||||
|
||||
지난 세션에서 만든 데모와 마찬가지로 이제 Kubernetes 클러스터에 nginx를 배포할 수 있습니다. 여기서는 데모 목적으로 Minikube를 다시 사용하겠습니다. Kubernetes.tf 파일을 생성하고 [여기](2022/Days/IaC/Kubernetes/Kubernetes.tf)에서 이 파일을 찾을 수 있습니다.
|
||||
|
||||
이 파일에서 Kubernetes 공급자를 정의하고, kubeconfig 파일을 가리키고, nginx라는 네임스페이스를 생성한 다음, 2개의 복제본과 마지막으로 서비스를 포함하는 배포를 생성하겠습니다.
|
||||
|
||||
```
|
||||
terraform {
|
||||
required_providers {
|
||||
kubernetes = {
|
||||
source = "hashicorp/kubernetes"
|
||||
version = ">= 2.0.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
provider "kubernetes" {
|
||||
config_path = "~/.kube/config"
|
||||
}
|
||||
resource "kubernetes_namespace" "test" {
|
||||
metadata {
|
||||
name = "nginx"
|
||||
}
|
||||
}
|
||||
resource "kubernetes_deployment" "test" {
|
||||
metadata {
|
||||
name = "nginx"
|
||||
namespace = kubernetes_namespace.test.metadata.0.name
|
||||
}
|
||||
spec {
|
||||
replicas = 2
|
||||
selector {
|
||||
match_labels = {
|
||||
app = "MyTestApp"
|
||||
}
|
||||
}
|
||||
template {
|
||||
metadata {
|
||||
labels = {
|
||||
app = "MyTestApp"
|
||||
}
|
||||
}
|
||||
spec {
|
||||
container {
|
||||
image = "nginx"
|
||||
name = "nginx-container"
|
||||
port {
|
||||
container_port = 80
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
resource "kubernetes_service" "test" {
|
||||
metadata {
|
||||
name = "nginx"
|
||||
namespace = kubernetes_namespace.test.metadata.0.name
|
||||
}
|
||||
spec {
|
||||
selector = {
|
||||
app = kubernetes_deployment.test.spec.0.template.0.metadata.0.labels.app
|
||||
}
|
||||
type = "NodePort"
|
||||
port {
|
||||
node_port = 30201
|
||||
port = 80
|
||||
target_port = 80
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
새 프로젝트 폴더에서 가장 먼저 해야 할 일은 `terraform init` 명령을 실행하는 것입니다.
|
||||
|
||||

|
||||
|
||||
그리고 `terraform apply` 명령을 실행하기 전에 네임스페이스가 없다는 것을 보여드리겠습니다.
|
||||
|
||||

|
||||
|
||||
apply 명령을 실행하면 Kubernetes 클러스터 내에 3개의 새로운 리소스, 네임스페이스, 배포 및 서비스가 생성됩니다.
|
||||
|
||||

|
||||
|
||||
이제 클러스터 내에 배포된 리소스를 살펴볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
이전 섹션에서 보셨듯이 Minikube를 사용하고 있기 때문에 도커 네트워킹으로 인그레스를 시도할 때 한계가 있습니다. 하지만 `kubectl port-forward -n nginx svc/nginx 30201:80` 명령을 실행하고 `http://localhost:30201/`으로 브라우저를 열면 NGINX 페이지를 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
Terraform과 Kubernetes에 대해 더 자세한 데모를 해보고 싶으시다면 [HashiCorp 학습 사이트](https://learn.hashicorp.com/tutorials/terraform/kubernetes-provider)를 방문해 보시기 바랍니다.
|
||||
|
||||
### 여러 환경
|
||||
|
||||
우리가 실행한 데모를 이제 특정 프로덕션, 스테이징 및 개발 환경이 동일하게 보이고 이 코드를 활용하기를 원한다면 Terraform을 사용하여 이를 달성하는 두 가지 접근 방식이 있습니다.
|
||||
|
||||
- `terraform workspaces` - 단일 백엔드 내의 여러 개의 명명된 섹션
|
||||
|
||||
- 파일 구조 - 디렉토리 레이아웃은 분리를 제공하고, 모듈은 재사용을 제공합니다.
|
||||
|
||||
하지만 위의 각 방법에는 장단점이 있습니다.
|
||||
|
||||
### Terraform workspaces
|
||||
|
||||
장점
|
||||
|
||||
- 쉬운 시작
|
||||
- 편리한 terraform.workspace 표현식
|
||||
- 코드 중복 최소화
|
||||
|
||||
단점
|
||||
|
||||
- 인적 오류가 발생하기 쉬움(TF를 사용하여 이를 제거하려고 노력 중임)
|
||||
- 동일한 백엔드 내에 저장된 상태
|
||||
- 코드베이스가 배포 구성을 명확하게 보여주지 않음.
|
||||
|
||||
### 파일 구조
|
||||
|
||||
장점
|
||||
|
||||
- 백엔드 격리
|
||||
- 보안 향상
|
||||
- 인적 오류 가능성 감소
|
||||
- 배포된 상태를 완벽하게 나타내는 코드베이스
|
||||
|
||||
단점
|
||||
|
||||
- 프로비저닝 환경에 여러 Terraform 적용 필요
|
||||
- 코드 중복이 더 많지만, 모듈을 사용하여 최소화할 수 있습니다.
|
||||
|
||||
## 자료
|
||||
|
||||
아래에 많은 리소스를 나열했으며 이 주제는 이미 여러 번 다루어졌다고 생각합니다. 추가 리소스가 있는 경우 리소스와 함께 PR을 올리면 기꺼이 검토하여 목록에 추가해 드리겠습니다.
|
||||
|
||||
- [What is Infrastructure as Code? Difference of Infrastructure as Code Tools](https://www.youtube.com/watch?v=POPP2WTJ8es)
|
||||
- [Terraform Tutorial | Terraform Course Overview 2021](https://www.youtube.com/watch?v=m3cKkYXl-8o)
|
||||
- [Terraform explained in 15 mins | Terraform Tutorial for Beginners](https://www.youtube.com/watch?v=l5k1ai_GBDE)
|
||||
- [Terraform Course - From BEGINNER to PRO!](https://www.youtube.com/watch?v=7xngnjfIlK4&list=WL&index=141&t=16s)
|
||||
- [HashiCorp Terraform Associate Certification Course](https://www.youtube.com/watch?v=V4waklkBC38&list=WL&index=55&t=111s)
|
||||
- [Terraform Full Course for Beginners](https://www.youtube.com/watch?v=EJ3N-hhiWv0&list=WL&index=39&t=27s)
|
||||
- [KodeKloud - Terraform for DevOps Beginners + Labs: Complete Step by Step Guide!](https://www.youtube.com/watch?v=YcJ9IeukJL8&list=WL&index=16&t=11s)
|
||||
- [Terraform Simple Projects](https://terraform.joshuajebaraj.com/)
|
||||
- [Terraform Tutorial - The Best Project Ideas](https://www.youtube.com/watch?v=oA-pPa0vfks)
|
||||
- [Awesome Terraform](https://github.com/shuaibiyy/awesome-terraform)
|
||||
|
||||
[Day 62](day62.md)에서 봐요!
|
135
2022/ko/Days/day62.md
Normal file
135
2022/ko/Days/day62.md
Normal file
@ -0,0 +1,135 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - Testing, Tools & Alternatives - Day 62'
|
||||
published: false
|
||||
description: '90DaysOfDevOps - Testing, Tools & Alternatives'
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1049053
|
||||
---
|
||||
|
||||
## 테스트, 도구 및 대안
|
||||
|
||||
IaC에 대한 이 섹션을 마무리하면서 코드 테스트, 사용 가능한 다양한 도구, 그리고 이를 달성하기 위한 Terraform의 몇 가지 대안에 대해 언급하지 않을 수 없습니다. 이 섹션의 시작 부분에서 말씀드렸듯이 제가 Terraform에 초점을 맞춘 이유는 첫째로 무료이며 오픈 소스이고 둘째로 크로스 플랫폼이며 환경에 구애받지 않기 때문입니다. 하지만 고려해야 할 다른 대안도 있지만, 전반적인 목표는 이것이 인프라를 배포하는 방법이라는 것을 사람들에게 알리는 것입니다.
|
||||
|
||||
### Code Rot
|
||||
|
||||
이 세션에서 다루고자 하는 첫 번째 영역은 Code Rot으로, 애플리케이션 코드와 달리 코드로서의 인프라는 한 번 사용되었다가 오랫동안 사용하지 않을 수도 있습니다. Terraform을 사용하여 AWS에 VM 환경을 배포하려고 하는데, 처음에 완벽하게 작동하고 환경이 갖춰졌지만, 이 환경이 자주 변경되지 않아 코드가 중앙 위치에 저장되기를 바라지만 코드가 변경되지 않는 상태를 그대로 유지한다고 가정해 보겠습니다.
|
||||
|
||||
인프라에 변화가 생기면 어떻게 될까요? 하지만 대역 외에서 수행되거나 다른 환경이 변경되는 경우가 있습니다.
|
||||
|
||||
- 대역 외 변경 사항
|
||||
- 고정되지 않은 버전
|
||||
- 더 이상 사용되지 않는 종속성
|
||||
- 적용되지 않은 변경 사항
|
||||
|
||||
### 테스트
|
||||
|
||||
코드 썩음과 일반적으로 뒤따르는 또 다른 큰 영역은 IaC를 테스트하고 모든 영역이 정상적으로 작동하는지 확인하는 기능입니다.
|
||||
|
||||
먼저 살펴볼 수 있는 몇 가지 기본 제공 테스트 명령어가 있습니다:
|
||||
|
||||
| Command | Description |
|
||||
| -------------------- | ------------------------------------------------------------------------ |
|
||||
| `terraform fmt` | Terraform 구성 파일을 표준 형식과 스타일로 다시 작성합니다. |
|
||||
| `terraform validate` | 디렉터리에 있는 구성 파일의 유효성을 검사하여 구성만 참조합니다. |
|
||||
| `terraform plan` | 실행 계획을 생성하여 Terraform이 계획한 변경 사항을 미리 볼 수 있습니다. |
|
||||
| Custom validation | 입력 변수가 예상과 일치하는지 확인하기 위한 입력 변수 유효성 검사 |
|
||||
|
||||
Terraform 외부에서 사용할 수 있는 몇 가지 테스트 도구도 있습니다:
|
||||
|
||||
- [tflint](https://github.com/terraform-linters/tflint)
|
||||
|
||||
- 가능한 오류를 찾습니다.
|
||||
- 더 이상 사용되지 않는 구문과 사용되지 않는 선언에 대해 경고합니다.
|
||||
- 모범 사례와 명명 규칙을 적용합니다.
|
||||
|
||||
검사 도구
|
||||
|
||||
- [checkov](https://www.checkov.io/) - 클라우드 인프라 구성을 스캔하여 배포하기 전에 잘못된 구성을 찾습니다.
|
||||
- [tfsec](https://aquasecurity.github.io/tfsec/v1.4.2/) - Terraform 코드에 대한 정적 분석 보안 스캐너입니다.
|
||||
- [terrascan](https://github.com/accurics/terrascan) - IaC를 위한 정적 코드 분석기입니다.
|
||||
- [terraform-compliance](https://terraform-compliance.com/) - IaC에 대한 네거티브 테스트 기능을 지원하는 Terraform에 대한 경량의 보안 및 규정 준수 중심 테스트 프레임워크입니다.
|
||||
- [snyk](https://docs.snyk.io/products/snyk-infrastructure-as-code/scan-terraform-files/scan-and-fix-security-issues-in-terraform-files) - Terraform 코드에서 잘못된 구성과 보안 문제를 스캔합니다.
|
||||
|
||||
관리형 클라우드 제품
|
||||
|
||||
- [Terraform Sentinel](https://www.terraform.io/cloud-docs/sentinel) - HashCorp 엔터프라이즈 제품과 통합된 임베디드 정책 기반 프레임워크로 세분화된 로직 기반 정책 결정을 가능하게 하며, 외부 소스의 정보를 사용하도록 확장할 수 있습니다.
|
||||
|
||||
### 자동화된 테스트
|
||||
|
||||
- [Terratest](https://terratest.gruntwork.io/) - Terratest는 인프라 테스트를 위한 패턴과 도우미 함수를 제공하는 Go 라이브러리입니다.
|
||||
- Terratest는 인프라 코드에 대한 자동화된 테스트 작성을 용이하게 합니다. 일반적인 인프라 테스트를 위한 다양한 도우미 함수와 패턴을 제공합니다.
|
||||
- 코드는 2022/Days/IaC/Terratest에서 찾을 수 있습니다.
|
||||
- 이 애플리케이션을 실행하려면
|
||||
- git clone #repo_url# <br />
|
||||
- cd test <br />
|
||||
- go mod init "<MODULE_NAME>" <br />
|
||||
**MODULE_NAME은 github.com/<YOUR_USERNAME>/<YOUR_REPO_NAME>이 됩니다.** <br />
|
||||
- go mod init github.com/<FOLDER-PATH> <br/>
|
||||
- go run
|
||||
|
||||
---
|
||||
|
||||
go mod init "<MODULE_NAME>"은 테스트 폴더에 go.mod 파일을 생성합니다. <br />
|
||||
|
||||
- go.mod 파일은 GoLang에서 의존성 관리의 기초입니다.
|
||||
- 프로젝트에서 필요하거나 사용할 모든 모듈이 go.mod 파일에 유지됩니다.
|
||||
- 프로젝트에서 사용하거나 가져올 모든 패키지의 항목을 생성합니다.
|
||||
- 수동으로 각 종속성을 가져오는 노력을 줄입니다.
|
||||
|
||||
처음 **go test**를 실행하면 go.sum 파일이 생성됩니다. <br />
|
||||
|
||||
- **go test** 또는 **go build**가 처음 실행될 때 go.sum 파일이 생성됩니다.
|
||||
- 특정 버전(최신)으로 모든 패키지를 설치합니다.
|
||||
- 우린 파일을 편집하거나 수정할 필요가 없습니다.
|
||||
|
||||
추가로 언급할 만한 것들
|
||||
|
||||
- [Terraform 클라우드](https://cloud.hashicorp.com/products/terraform) - Terraform 클라우드는 HashCorp의 관리형 서비스 제품입니다. 실무자, 팀 및 조직이 프로덕션에서 Terraform을 사용하기 위해 불필요한 도구와 문서가 필요하지 않습니다.
|
||||
|
||||
- [Terragrunt](https://terragrunt.gruntwork.io/) - Terragrunt는 구성을 건조하게 유지하고, 여러 Terraform 모듈로 작업하고, 원격 상태를 관리하기 위한 추가 도구를 제공하는 얇은 래퍼입니다.
|
||||
|
||||
- [Atlantis](https://www.runatlantis.io/) - Terraform 풀 리퀘스트 자동화
|
||||
|
||||
### 대안
|
||||
|
||||
이 섹션을 시작할 때 57일째에 몇 가지 대안이 있다고 언급했으며, 이번 챌린지에서도 이에 대해 계속 살펴볼 계획입니다.
|
||||
|
||||
| Cloud Specific | Cloud Agnostic |
|
||||
| ------------------------------- | -------------- |
|
||||
| AWS CloudFormation | Terraform |
|
||||
| Azure Resource Manager | Pulumi |
|
||||
| Google Cloud Deployment Manager | |
|
||||
|
||||
저는 위의 목록 중 AWS CloudFormation을 가장 많이 사용했으며 AWS에서 기본으로 제공하지만, Terraform 이외의 다른 제품은 사용해 본 적이 없습니다. 클라우드별 버전은 특정 클라우드에서는 매우 훌륭하지만, 여러 클라우드 환경이 있는 경우 이러한 구성을 마이그레이션하는 데 어려움을 겪거나 IaC 작업을 위해 여러 관리 플레인을 사용해야 할 것입니다.
|
||||
|
||||
흥미로운 다음 단계는 시간을 내서 [Pulumi](https://www.pulumi.com/)에 대해 자세히 알아보는 것입니다.
|
||||
|
||||
Pulumi 사이트의 비교 부분에서
|
||||
|
||||
> "Terraform과 Pulumi 모두 코드가 원하는 인프라 상태를 나타내는 코드 모델로 원하는 상태 인프라를 제공하며, 배포 엔진은 이 원하는 상태를 스택의 현재 상태와 비교하여 어떤 리소스를 생성, 업데이트 또는 삭제해야 하는지를 결정합니다."
|
||||
|
||||
제가 볼 수 있는 가장 큰 차이점은 HCL(HashCorp 구성 언어)과 달리 Pulumi는 Python, TypeScript, JavaScript, Go, .NET과 같은 범용 언어를 허용한다는 점입니다.
|
||||
|
||||
간략한 개요 [Pulumi 소개: 코드형 최신 인프라](https://www.youtube.com/watch?v=QfJTJs24-JM) 저는 선택의 폭이 넓다는 점이 마음에 들어서 좀 더 자세히 알아보고 싶었습니다.
|
||||
|
||||
이것으로 IaC 섹션을 마무리하고, 다음에는 구성 관리와 약간 겹치는 부분, 특히 일부 작업 및 데모에 Ansible을 사용할 구성 관리의 큰 그림을 살펴볼 것입니다.
|
||||
|
||||
## 리소스
|
||||
|
||||
아래에 많은 리소스를 나열했으며 이 주제는 이미 여러 번 다루어졌다고 생각합니다. 추가 리소스가 있는 경우 리소스와 함께 PR을 올리면 기꺼이 검토하여 목록에 추가해 드리겠습니다.
|
||||
|
||||
- [What is Infrastructure as Code? Difference of Infrastructure as Code Tools](https://www.youtube.com/watch?v=POPP2WTJ8es)
|
||||
- [Terraform Tutorial | Terraform Course Overview 2021](https://www.youtube.com/watch?v=m3cKkYXl-8o)
|
||||
- [Terraform explained in 15 mins | Terraform Tutorial for Beginners](https://www.youtube.com/watch?v=l5k1ai_GBDE)
|
||||
- [Terraform Course - From BEGINNER to PRO!](https://www.youtube.com/watch?v=7xngnjfIlK4&list=WL&index=141&t=16s)
|
||||
- [HashiCorp Terraform Associate Certification Course](https://www.youtube.com/watch?v=V4waklkBC38&list=WL&index=55&t=111s)
|
||||
- [Terraform Full Course for Beginners](https://www.youtube.com/watch?v=EJ3N-hhiWv0&list=WL&index=39&t=27s)
|
||||
- [KodeKloud - Terraform for DevOps Beginners + Labs: Complete Step by Step Guide!](https://www.youtube.com/watch?v=YcJ9IeukJL8&list=WL&index=16&t=11s)
|
||||
- [Terraform Simple Projects](https://terraform.joshuajebaraj.com/)
|
||||
- [Terraform Tutorial - The Best Project Ideas](https://www.youtube.com/watch?v=oA-pPa0vfks)
|
||||
- [Awesome Terraform](https://github.com/shuaibiyy/awesome-terraform)
|
||||
- [Pulumi - IaC in your favorite programming language!](https://www.youtube.com/watch?v=vIjeiDcsR3Q&t=51s)
|
||||
|
||||
[Day 63](day63.md)에서 봐요!
|
101
2022/ko/Days/day63.md
Normal file
101
2022/ko/Days/day63.md
Normal file
@ -0,0 +1,101 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - The Big Picture: Configuration Management - Day 63'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - The Big Picture Configuration Management
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048711
|
||||
---
|
||||
|
||||
## 큰 그림: 구성 관리
|
||||
|
||||
IaC를 다루는 섹션의 뒷부분에서 바로 이어서 구성 관리 또는 애플리케이션 구성 관리에 대해 이야기할 때 약간의 교차점이 있을 것입니다.
|
||||
|
||||
구성 관리는 애플리케이션, 시스템, 서버를 원하는 상태로 유지하는 프로세스입니다. 인프라스트럭처와 겹치는 부분은 IaC가 인프라가 원하는 상태에 있는지 확인하지만, 그 이후에는 특히 Terraform이 OS 설정이나 애플리케이션의 원하는 상태를 관리하지 않기 때문에 구성 관리 도구가 필요하다는 점입니다. Deane에서 변경 사항이 발생할 때 시스템과 애플리케이션이 예상대로 작동하는지 확인합니다.
|
||||
|
||||
구성 관리는 문서화되지 않은 크고 작은 변경을 방지합니다.
|
||||
|
||||
### 시나리오: 구성 관리를 사용하려는 이유
|
||||
|
||||
구성 관리를 사용하고자 하는 시나리오나 이유를 알기 위해 철수를 만나보세요. 철수는 우리의 시스템 관리자이며, 환경 내의 모든 시스템에서 열심히 일하며 만족하는 사람입니다.
|
||||
|
||||
시스템에 장애가 발생하거나 화재가 발생하거나 서버가 다운되면 어떻게 될까요? 철수는 화재가 발생하면 어떻게 해야 하는지 정확히 알고 있기 때문에 쉽게 해결할 수 있지만, 특히 대규모로 확장하는 환경에서 여러 서버가 장애를 일으키기 시작하면 철수에게 구성 관리 도구가 필요한 이유가 바로 여기에 있습니다. 구성 관리 도구는 철수가 각 서버를 빠르고 효과적으로 대규모로 설정하는 방법에 대한 지침을 푸시할 수 있는 올바른 코드를 구성하기만 하면 되는 록스타처럼 보이도록 도와줄 수 있습니다.
|
||||
|
||||
### 구성 관리 도구
|
||||
|
||||
다양한 구성 관리 도구를 사용할 수 있으며, 각 도구에는 특정 상황에 더 적합한 특정 기능이 있습니다.
|
||||
|
||||

|
||||
|
||||
이 단계에서는 위 그림의 옵션을 간략히 살펴본 후 어떤 도구를 사용할지, 왜 사용할지 결정하겠습니다.
|
||||
|
||||
- **Chef**
|
||||
- Chef는 인프라 자동화를 통해 모든 환경, 모든 규모에서 구성이 일관되게 적용되도록 보장합니다.
|
||||
- Chef는 Ruby와 Erlang으로 작성된 OpsCode에서 개발한 오픈 소스 도구입니다.
|
||||
- Chef는 이기종 인프라를 보유하고 있으며 성숙한 솔루션을 찾고 있는 조직에 가장 적합합니다.
|
||||
- Recipes와 Cookbooks은 시스템의 구성 코드를 결정합니다.
|
||||
- 프로 - 방대한 Recipes 컬렉션을 사용할 수 있습니다.
|
||||
- 장점 - 강력한 버전 제어를 제공하는 Git과 잘 통합됩니다.
|
||||
- 단점 - 학습 곡선이 가파르며 상당한 시간이 필요합니다
|
||||
- 단점 - 메인 서버에서 제어할 수 있는 권한이 많지 않습니다.
|
||||
- 아키텍처 - 서버/클라이언트
|
||||
- 설정 용이성 - 보통
|
||||
- 언어 - 절차적 - 작업 수행 방법 지정
|
||||
- **Puppet**
|
||||
- Puppet은 자동 배포를 지원하는 구성 관리 도구입니다.
|
||||
- Puppet은 Ruby로 빌드되며 매니페스트 작성에 DSL을 사용합니다.
|
||||
- Puppet은 확장성에 중점을 둔 이기종 인프라에서도 잘 작동합니다.
|
||||
- 장점 - 지원을 위한 대규모 커뮤니티가 있습니다.
|
||||
- 장점 - 잘 발달된 보고 메커니즘입니다.
|
||||
- 단점 - 고급 작업을 수행하려면 Ruby 언어에 대한 지식이 필요합니다.
|
||||
- 단점 - 메인 서버에 대한 제어 권한이 많지 않습니다.
|
||||
- 아키텍처 - 서버/클라이언트
|
||||
- 설정 용이성 - 보통
|
||||
- 언어 - 선언적 - 수행할 작업만 지정 가능
|
||||
- **Ansible**
|
||||
- Ansible은 구성 관리, 클라우드 프로비저닝, 배포 및 오케스트레이션을 자동화하는 IT 자동화 도구입니다.
|
||||
- Ansible Playbook의 핵심은 YAML로 작성되어 있습니다. (몇 번 본 적이 있으므로 YAML에 대한 섹션을 만들어야 합니다.)
|
||||
- Ansible은 빠르게 시작하고 실행하는 데 중점을 두는 환경이 있을 때 잘 작동합니다.
|
||||
- 서버에 지침을 제공하는 Playbook에서 작동합니다.
|
||||
- 장점 - 원격 노드에 에이전트가 필요하지 않습니다.
|
||||
- 장점 - YAML은 배우기 쉽습니다.
|
||||
- 단점 - 성능 속도가 다른 도구보다 느린 경우가 많습니다.(철수가 직접 수동으로 수행하는 것보다 빠름)
|
||||
- 단점 - YAML은 Ruby만큼 강력하지는 않지만 학습 곡선이 적습니다.
|
||||
- 아키텍처 - 클라이언트 전용
|
||||
- 설정 용이성 - 매우 쉬움
|
||||
- 언어 - 절차적 - 작업 수행 방법 지정
|
||||
- **SaltStack**
|
||||
- SaltStack은 구성 관리와 원격 실행을 자동화하는 CLI 기반 도구입니다.
|
||||
- SaltStack은 Python 기반이며, 명령어는 YAML 또는 해당 DSL로 작성됩니다.
|
||||
- 확장성과 복원력을 최우선으로 고려하는 환경에 적합합니다.
|
||||
- 장점 - 가동 및 실행 시 사용이 간편합니다.
|
||||
- 장점 - 우수한 보고 메커니즘입니다.
|
||||
- 단점 - 설정 단계가 까다롭습니다.
|
||||
- 단점 - 다른 서비스보다 훨씬 덜 개발된 새로운 웹 UI가 있습니다.
|
||||
- 아키텍처 - 서버/클라이언트
|
||||
- 설정 용이성 - 보통
|
||||
- 언어 - 선언적 - 수행할 작업만 지정함
|
||||
|
||||
### Ansible과 Terraform 비교
|
||||
|
||||
이 섹션에서 사용할 도구는 Ansible입니다. (사용하기 쉽고 언어에 지식이 약간만 필요합니다.)
|
||||
|
||||
도구를 좀 더 자세히 살펴보기 전에 Ansible과 Terraform의 몇 가지 차이점을 살펴보는 것이 중요하다고 생각합니다.
|
||||
|
||||
| | Ansible | Terraform |
|
||||
| ----------------- | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
|
||||
| 유형 | Ansible은 구성 관리 도구입니다. | Terraform은 오케스트레이션 도구입니다. |
|
||||
| 인프라 | Ansible은 변경 가능한 인프라를 지원하며, Terraform은 변경 불가능한 인프라를 지원합니다. |
|
||||
| 언어 | Ansible은 절차적 언어를 따르고, Terraform은 선언적 언어를 따릅니다. |
|
||||
| 프로비저닝 | 부분 프로비저닝(VM, 네트워크, 스토리지) 제공합니다. | Terraform은 광범위한 프로비저닝(VM, 네트워크, 스토리지) 제공합니다. |
|
||||
| 패키징 | 패키징 및 템플릿에 대한 완벽한 지원 제공합니다. | 패키징 및 템플릿에 대한 부분 지원 제공합니다. |
|
||||
| 라이프사이클 관리 | Ansible에는 라이프사이클 관리 기능이 없습니다. | Terraform은 라이프사이클 및 상태 관리에 크게 의존합니다. |
|
||||
|
||||
## 자료
|
||||
|
||||
- [What is Ansible](https://www.youtube.com/watch?v=1id6ERvfozo)
|
||||
- [Ansible 101 - Episode 1 - Introduction to Ansible](https://www.youtube.com/watch?v=goclfp6a2IQ)
|
||||
- [NetworkChuck - You need to learn Ansible right now!](https://www.youtube.com/watch?v=5hycyr-8EKs&t=955s)
|
||||
|
||||
[Day 64](day64.md)에서 봐요!
|
87
2022/ko/Days/day64.md
Normal file
87
2022/ko/Days/day64.md
Normal file
@ -0,0 +1,87 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - Ansible: Getting Started - Day 64'
|
||||
published: false
|
||||
description: '90DaysOfDevOps - Ansible: Getting Started'
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048765
|
||||
---
|
||||
|
||||
## Ansible: 시작하기
|
||||
|
||||
어제 [Day 63](day63.md)에서 Ansible이 무엇인지에 대해 조금 다루었지만 여기서는 이에 대해 조금 더 자세히 알아보겠습니다. 먼저 Ansible은 RedHat에서 제공합니다. 둘째, 에이전트가 없으며 SSH를 통해 연결하고 명령을 실행합니다. 셋째, 크로스 플랫폼(Linux 및 macOS, WSL2) 및 오픈 소스(엔터프라이즈용 유료 옵션도 있음)이며 다른 모델에 비해 Ansible은 구성을 push합니다.
|
||||
|
||||
### Ansible 설치
|
||||
|
||||
여러분이 상상할 수 있듯이, RedHat과 Ansible 팀은 Ansible을 문서화하는 데 환상적인 작업을 해왔습니다. 이는 일반적으로 [여기](https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html)에서 찾을 수 있는 설치 단계부터 시작됩니다. Ansible은 에이전트가 없는 자동화 도구이며, 이 도구는 "Control Node"라고 하는 시스템에 배포되고 이 Control Node에서 SSH를 통해 머신 및 기타 장치(네트워크일 수 있음)를 관리한다고 말씀드린 것을 기억하세요.
|
||||
|
||||
위에 링크된 문서에는 Windows OS를 Control Node로 사용할 수 없다고 명시되어 있습니다.
|
||||
|
||||
Control Node 및 적어도 이 데모에서는 [Linux 섹션](day20.md)에서 만든 Linux VM을 Control Node로 사용하겠습니다.
|
||||
|
||||
이 시스템은 우분투를 실행 중이며 설치 단계는 다음 명령만 있으면 됩니다.
|
||||
|
||||
```Shell
|
||||
sudo apt update
|
||||
sudo apt install software-properties-common
|
||||
sudo add-apt-repository --yes --update ppa:ansible/ansible
|
||||
sudo apt install ansible
|
||||
```
|
||||
|
||||
이제 Control Node에 ansible이 설치되어 있어야 하며, `ansible --version`을 실행하여 확인할 수 있으며 아래와 비슷한 내용이 표시됩니다.
|
||||
|
||||

|
||||
|
||||
이제 환경의 다른 Node를 제어하는 방법을 살펴보기 전에 로컬 머신에 대해 `ansible localhost -m ping` 명령을 실행하여 ansible의 기능을 확인할 수도 있습니다. 이 명령은 [Ansible 모듈](https://docs.ansible.com/ansible/2.9/user_guide/modules_intro.html)을 사용하며, 여러 시스템에서 하나의 작업을 빠르게 수행할 수 있는 방법이기도 합니다. 로컬 호스트만으로는 그다지 재미있지 않지만, 무언가를 얻거나 모든 시스템이 가동 중이고 1000개 이상의 서버와 디바이스가 있다고 상상해 보세요.
|
||||
|
||||

|
||||
|
||||
또는 실제 모듈의 실제 사용법은 `ansible webservers -m service -a "name=httpd state=started"`와 같이 모든 웹서버에 httpd 서비스가 실행 중인지 여부를 알려주는 것일 수 있습니다. 이 명령에 사용된 웹서버 용어에 대해 간략히 설명했습니다.
|
||||
|
||||
### 호스트
|
||||
|
||||
위에서 localhost를 사용하여 시스템에 대한 간단한 핑 모듈을 실행하는 방법으로는 네트워크에 다른 컴퓨터를 지정할 수 없습니다. 예를 들어 VirtualBox가 실행 중인 Windows 호스트에는 IP 10.0.0.1의 네트워크 어댑터가 있지만 아래에서 볼 수 있듯이 핑으로 연결할 수 있지만 ansible을 사용하여 해당 작업을 수행할 수 없습니다.
|
||||
|
||||

|
||||
|
||||
이러한 작업으로 자동화할 호스트 또는 Node를 지정하려면 이를 정의해야 합니다. 시스템의 /etc/ansible 디렉토리로 이동하여 정의할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
편집하려는 파일은 호스트 파일이며, 텍스트 편집기를 사용하여 호스트를 정의할 수 있습니다. 호스트 파일에는 파일을 사용하고 수정하는 방법에 대한 많은 훌륭한 지침이 포함되어 있습니다. 아래로 스크롤하여 [windows]라는 새 그룹을 만들고 해당 호스트에 대한 `10.0.0.1` IP 주소를 추가하겠습니다. 파일을 저장합니다.
|
||||
|
||||

|
||||
|
||||
그러나 Ansible이 시스템에 연결하려면 SSH를 사용할 수 있어야 한다고 말씀드린 것을 기억하세요. 아래에서 볼 수 있듯이 `ansible windows -m ping`을 실행하면 SSH를 통한 연결에 실패하여 연결할 수 없다는 메시지가 표시됩니다.
|
||||
|
||||

|
||||
|
||||
이제 인벤토리에 호스트를 추가하기 시작했는데, 모든 장치를 정의하는 곳이기 때문에 이 파일의 다른 이름인 네트워크 장치, 스위치 및 라우터도 여기에 추가하고 그룹화할 수 있습니다. 하지만 호스트 파일에는 Linux 시스템 그룹에 액세스하기 위한 자격 증명도 추가했습니다.
|
||||
|
||||

|
||||
|
||||
이제 `ansible Linux -m ping`을 실행하면 아래와 같이 성공합니다.
|
||||
|
||||

|
||||
|
||||
이제 구성을 자동화하려는 대상 시스템인 Node 요구 사항이 있습니다. 이 시스템에는 Ansible을 위한 어떤 것도 설치하지 않습니다(소프트웨어를 설치할 수는 있지만 필요한 Ansible의 클라이언트는 없습니다). Ansible은 SSH를 통해 연결하고 SFTP를 통해 모든 것을 전송합니다. (원하는 경우 SSH를 구성한 경우 SCP 대 SFTP를 사용할 수 있습니다.)
|
||||
|
||||
### Ansible 명령
|
||||
|
||||
리눅스 머신에 대해 `ansible Linux -m ping`을 실행하고 응답을 얻을 수 있는 것을 보셨겠지만, 기본적으로 Ansible을 사용하면 많은 adhoc 명령을 실행할 수 있습니다. 하지만 이 명령을 시스템 그룹에 대해 실행하여 해당 정보를 다시 가져올 수 있습니다. [adhoc 명령](https://docs.ansible.com/ansible/latest/user_guide/intro_adhoc.html)
|
||||
|
||||
명령을 반복하거나 이러한 명령을 실행하기 위해 개별 시스템에 로그인해야 하는 경우 Ansible이 도움이 될 수 있습니다. 예를 들어, 아래의 간단한 명령은 Linux 그룹에 추가하는 모든 시스템에 대한 모든 운영 체제 세부 정보를 출력합니다.
|
||||
`ansible linux -a "cat /etc/os-release"`
|
||||
|
||||
다른 사용 사례로는 시스템 재부팅, 파일 복사, 패커 및 사용자 관리 등이 있습니다. adhoc 명령과 Ansible 모듈을 결합할 수도 있습니다.
|
||||
|
||||
adhoc 명령은 선언적 모델을 사용하여 지정된 최종 상태에 도달하는 데 필요한 작업을 계산하고 실행합니다. adhoc 명령은 시작하기 전에 현재 상태를 확인하고 현재 상태가 지정된 최종 상태와 다르지 않으면 아무 작업도 수행하지 않음으로써 일종의 무임승차를 하는 셈입니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [What is Ansible](https://www.youtube.com/watch?v=1id6ERvfozo)
|
||||
- [Ansible 101 - Episode 1 - Introduction to Ansible](https://www.youtube.com/watch?v=goclfp6a2IQ)
|
||||
- [NetworkChuck - You need to learn Ansible right now!](https://www.youtube.com/watch?v=5hycyr-8EKs&t=955s)
|
||||
|
||||
[Day 65](day65.md)에서 봐요!
|
278
2022/ko/Days/day65.md
Normal file
278
2022/ko/Days/day65.md
Normal file
@ -0,0 +1,278 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - Ansible Playbooks - Day 65'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - Ansible Playbooks
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1049054
|
||||
---
|
||||
|
||||
### Ansible Playbook
|
||||
|
||||
이 섹션에서는 적어도 Ansible의 경우 하나의 명령으로 여러 서버를 실행하여 긴 서버 목록을 재부팅하는 것과 같은 간단한 명령을 수행하고 각 서버에 개별적으로 연결해야 하는 번거로움을 줄일 수 있다는 점이 가장 큰 장점이라고 할 수 있습니다.
|
||||
|
||||
하지만 실제로 베어 운영 체제를 가져와서 해당 시스템에서 실행할 소프트웨어와 서비스를 선언하고 모두 원하는 상태로 실행되도록 하는 것은 어떨까요?
|
||||
|
||||
이것이 바로 Ansible Playbook이 필요한 이유입니다. Playbook을 사용하면 서버 그룹을 가져와서 해당 그룹에 대해 구성 및 설치 작업을 수행할 수 있습니다.
|
||||
|
||||
### Playbook 형식
|
||||
|
||||
Playbook > Play > Task
|
||||
|
||||
스포츠에 관심이 있는 분이라면 Playbook이라는 용어를 들어보셨을 텐데요, Playbook은 다양한 Play와 Task로 구성된 Play 방법을 팀에게 알려주는 것으로, Play를 스포츠나 게임의 세트 피스라고 생각하면 각 Play에 Task가 연관되어 있고, Play를 구성하는 여러 Task가 있을 수 있으며, Playbook에는 여러 가지 다른 Play가 있을 수 있습니다.
|
||||
|
||||
이러한 Playbook은 YAML(YAML은 마크업 언어가 아님)로 작성되어 있으며, 지금까지 다룬 많은 섹션, 특히 컨테이너와 Kubernetes에서 YAML 형식의 구성 파일을 찾을 수 있습니다.
|
||||
|
||||
playbook.yml이라는 간단한 Playbook을 살펴보겠습니다.
|
||||
|
||||
```Yaml
|
||||
- name: Simple Play
|
||||
hosts: localhost
|
||||
connection: local
|
||||
tasks:
|
||||
- name: Ping me
|
||||
ping:
|
||||
- name: print os
|
||||
debug:
|
||||
msg: "{{ ansible_os_family }}"
|
||||
```
|
||||
|
||||
위의 파일 [simple_play](/2022/Days/Configmgmt/simple_play.yml)을 찾을 수 있습니다. 그런 다음 `ansible-playbook simple_play.yml` 명령을 사용하면 다음 단계를 수행합니다.
|
||||
|
||||

|
||||
|
||||
'gathering facts'라는 첫 번째 Task가 발생한 것을 볼 수 있지만, 우리가 트리거하거나 요청하지 않았나요? 이 모듈은 원격 호스트에 대한 유용한 변수를 수집하기 위해 Playbook에서 자동으로 호출됩니다. [ansible.builtin.setup](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/setup_module.html)
|
||||
|
||||
두 번째 Task는 Ping을 설정하는 것이었는데, 이것은 ICMP Ping이 아니라 원격 또는 로컬 호스트에 대한 연결 성공 시 `pong`을 반환하는 파이썬 스크립트입니다. [ansible.builtin.ping](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/ping_module.html)
|
||||
|
||||
그런 다음 첫 번째 Task로 정의한 세 번째 또는 두 번째 Task는 OS를 알려주는 메시지 인쇄를 비활성화하지 않는 한 실행됩니다. 이 Task에서는 조건문을 사용하고 있으므로 모든 유형의 운영 체제에 대해 이 Playbook을 실행할 수 있으며, 그러면 OS 이름이 반환됩니다. 편의상 이 출력은 단순히 메시지를 출력하고 있지만 다음과 같이 말하는 Task를 추가할 수 있습니다:
|
||||
|
||||
```Yaml
|
||||
tasks:
|
||||
- name: "shut down Debian flavoured systems"
|
||||
command: /sbin/shutdown -t now
|
||||
when: ansible_os_family == "Debian"
|
||||
```
|
||||
|
||||
### Vagrant로 환경 설정하기
|
||||
|
||||
Vagrant를 사용하여 Node 환경을 설정할 것입니다. 저는 이것을 합리적인 4 Node로 유지하려고 하지만 300 Node 또는 3000 Node가 될 수 있으며 이것이 서버를 구성할 수 있는 Ansible 및 기타 구성 관리 도구의 힘이라는 것을 알 수 있기를 바랍니다.
|
||||
|
||||
이 파일은 [여기](/2022/Days/Configmgmt/Vagrantfile)에서 찾을 수 있습니다.
|
||||
|
||||
```Vagrant
|
||||
Vagrant.configure("2") do |config|
|
||||
servers=[
|
||||
{
|
||||
:hostname => "db01",
|
||||
:box => "bento/ubuntu-21.10",
|
||||
:ip => "192.168.169.130",
|
||||
:ssh_port => '2210'
|
||||
},
|
||||
{
|
||||
:hostname => "web01",
|
||||
:box => "bento/ubuntu-21.10",
|
||||
:ip => "192.168.169.131",
|
||||
:ssh_port => '2211'
|
||||
},
|
||||
{
|
||||
:hostname => "web02",
|
||||
:box => "bento/ubuntu-21.10",
|
||||
:ip => "192.168.169.132",
|
||||
:ssh_port => '2212'
|
||||
},
|
||||
{
|
||||
:hostname => "loadbalancer",
|
||||
:box => "bento/ubuntu-21.10",
|
||||
:ip => "192.168.169.134",
|
||||
:ssh_port => '2213'
|
||||
}
|
||||
|
||||
]
|
||||
|
||||
config.vm.base_address = 600
|
||||
|
||||
servers.each do |machine|
|
||||
|
||||
config.vm.define machine[:hostname] do |node|
|
||||
node.vm.box = machine[:box]
|
||||
node.vm.hostname = machine[:hostname]
|
||||
|
||||
node.vm.network :public_network, bridge: "Intel(R) Ethernet Connection (7) I219-V", ip: machine[:ip]
|
||||
node.vm.network "forwarded_port", guest: 22, host: machine[:ssh_port], id: "ssh"
|
||||
|
||||
node.vm.provider :virtualbox do |v|
|
||||
v.customize ["modifyvm", :id, "--memory", 2048]
|
||||
v.customize ["modifyvm", :id, "--name", machine[:hostname]]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
```
|
||||
|
||||
`vagrant up` 명령을 사용하여 VirtualBox에서 이러한 머신을 스핀업하면 메모리를 더 추가할 수 있고 각 머신에 대해 다른 private_network 주소를 정의할 수도 있지만 제 환경에서는 이 방법이 작동합니다. 컨트롤 박스는 리눅스 섹션에서 배포한 우분투 데스크톱이라는 점을 기억하세요.
|
||||
|
||||
리소스가 제한되어 있는 경우 `vagrant up web01 web02`를 실행하여 여기서 사용 중인 웹서버만 불러올 수도 있습니다.
|
||||
|
||||
### Ansible 호스트 구성
|
||||
|
||||
이제 환경이 준비되었으므로 Ansible을 확인할 수 있으며, 이를 위해 우분투 데스크톱(이 데스크톱을 사용할 수도 있지만 아래 네트워크에 액세스하는 네트워크에 있는 모든 Linux 기반 머신을 동일하게 사용할 수 있음)을 컨트롤로 사용하고, ansible 호스트 파일에서 새 Node를 그룹에 추가해 보겠습니다, 이 파일을 인벤토리로 생각할 수 있으며, 이에 대한 대안으로 `-i filename`을 사용하여 ansible 명령의 일부로 호출되는 또 다른 인벤토리 파일을 사용할 수 있습니다. 이는 프로덕션, 테스트 및 스테이징 환경마다 다른 파일을 가질 수 있으므로 호스트 파일을 사용하는 것보다 유용할 수 있습니다. 기본 호스트 파일을 사용하고 있으므로 이 파일을 기본으로 사용하므로 지정할 필요가 없습니다.
|
||||
|
||||
기본 호스트 파일에 다음을 추가했습니다.
|
||||
|
||||
```Text
|
||||
[control]
|
||||
ansible-control
|
||||
|
||||
[proxy]
|
||||
loadbalancer
|
||||
|
||||
[webservers]
|
||||
web01
|
||||
web02
|
||||
|
||||
[database]
|
||||
db01
|
||||
|
||||
```
|
||||
|
||||

|
||||
|
||||
계속 진행하기 전에 Node에 대해 명령을 실행할 수 있는지 확인하기 위해 `ansible nodes -m command -a hostname`을 실행해 보겠습니다. 이 간단한 명령은 연결이 있는지 테스트하고 호스트 이름을 다시 보고합니다.
|
||||
|
||||
또한, 연결을 보장하기 위해 /etc/hosts 파일 내의 Ubuntu 제어 Node에 이러한 Node와 IP를 추가했습니다. 우분투 상자에서 각 Node에 대해 SSH 구성을 수행해야 할 수도 있습니다.
|
||||
|
||||
```Text
|
||||
192.168.169.140 ansible-control
|
||||
192.168.169.130 db01
|
||||
192.168.169.131 web01
|
||||
192.168.169.132 web02
|
||||
192.168.169.133 loadbalancer
|
||||
```
|
||||
|
||||

|
||||
|
||||
이 단계에서는 제어 Node와 서버 Node 사이에 SSH 키를 설정하는 과정을 진행하겠습니다. 다음 단계에서는 호스트의 파일에 변수를 추가하여 사용자 이름과 비밀번호를 제공하는 방법을 사용할 수 있습니다. 이 방법은 결코 모범 사례가 될 수 없으므로 권장하지 않습니다.
|
||||
|
||||
SSH를 설정하고 Node 간에 공유하려면 아래 단계를 따르세요. 비밀번호(`vagrant`)를 묻는 메시지가 표시되면 `y`를 몇 번 눌러야 수락할 수 있습니다.
|
||||
|
||||
`ssh-keygen`
|
||||
|
||||

|
||||
|
||||
`ssh-copy-id localhost`
|
||||
|
||||

|
||||
|
||||
이제 모든 VM이 켜져 있다면 `ssh-copy-id web01 && ssh-copy-id web02 && ssh-copy-id loadbalancer && ssh-copy-id db01`을 실행하면 비밀번호를 입력하라는 메시지가 표시됩니다(이 경우 비밀번호는 `vagrant`입니다).
|
||||
|
||||
모든 VM을 실행하지 않고 웹서버만 실행하고 있으므로 `ssh-copy-id web01 && ssh-copy-id web02`를 발급했습니다.
|
||||
|
||||

|
||||
|
||||
Playbook을 실행하기 전에 그룹과 간단하게 연결되었는지 확인하고 싶어서 `ansible webservers -m ping`을 실행하여 연결을 테스트했습니다.
|
||||
|
||||

|
||||
|
||||
### 첫 번째 "진짜" Ansible Playbook
|
||||
|
||||
첫 번째 Ansible Playbook은 웹 서버를 구성하는 것으로, 호스트 파일에서 [webservers] 그룹 아래에 웹 서버를 그룹화했습니다.
|
||||
|
||||
Playbook을 실행하기 전에 web01과 web02에 apache가 설치되어 있지 않은 것을 확인할 수 있습니다. 아래 스크린샷 상단은 이 Playbook을 실행하기 위해 ansible 컨트롤 내에서 생성한 폴더 및 파일 레이아웃을 보여줍니다. `playbook1.yml`이 있고, template 폴더에는 `index.html.j2`와 `ports.conf.j2` 파일이 있습니다. 이 파일은 위에 나열된 리포지토리 폴더에서 찾을 수 있습니다.
|
||||
|
||||
그런 다음 web01에 SSH로 접속하여 apache가 설치되어 있는지 확인합니다.
|
||||
|
||||

|
||||
|
||||
위에서 web01에 apache가 설치되어 있지 않다는 것을 알 수 있으므로 아래 Playbook을 실행하여 이 문제를 해결할 수 있습니다.
|
||||
|
||||
```Yaml
|
||||
- hosts: webservers
|
||||
become: yes
|
||||
vars:
|
||||
http_port: 8000
|
||||
https_port: 4443
|
||||
html_welcome_msg: "Hello 90DaysOfDevOps"
|
||||
tasks:
|
||||
- name: ensure apache is at the latest version
|
||||
apt:
|
||||
name: apache2
|
||||
state: latest
|
||||
|
||||
- name: write the apache2 ports.conf config file
|
||||
template:
|
||||
src: templates/ports.conf.j2
|
||||
dest: /etc/apache2/ports.conf
|
||||
notify:
|
||||
- restart apache
|
||||
|
||||
- name: write a basic index.html file
|
||||
template:
|
||||
src: templates/index.html.j2
|
||||
dest: /var/www/html/index.html
|
||||
notify:
|
||||
- restart apache
|
||||
|
||||
- name: ensure apache is running
|
||||
service:
|
||||
name: apache2
|
||||
state: started
|
||||
|
||||
handlers:
|
||||
- name: restart apache
|
||||
service:
|
||||
name: apache2
|
||||
state: restarted
|
||||
```
|
||||
|
||||
위의 Playbook을 분석합니다:
|
||||
|
||||
- `host: webserver`는 이 Playbook을 실행할 그룹이 웹서버라는 그룹이라는 것을 의미합니다.
|
||||
- `become: yes`는 Playbook을 실행하는 사용자가 원격 시스템에서 루트가 된다는 의미입니다. 루트 비밀번호를 입력하라는 메시지가 표시됩니다.
|
||||
- 그런 다음 `vars`가 있는데, 이는 웹서버 전체에서 원하는 몇 가지 환경 변수를 정의합니다.
|
||||
|
||||
그런 다음 Task를 시작합니다,
|
||||
|
||||
- Task 1은 apache가 최신 버전을 실행 중인지 확인하는 것입니다.
|
||||
- Task 2는 template 폴더에 있는 소스에서 ports.conf 파일을 작성하는 것입니다.
|
||||
- Task 3은 기본 index.html 파일을 생성하는 것입니다.
|
||||
- Task 4는 apache가 실행 중인지 확인하는 것입니다.
|
||||
|
||||
마지막으로 Handler 섹션인 [Handler: 변경에 대한 Task 실행](https://docs.ansible.com/ansible/latest/user_guide/playbooks_handlers.html)이 있습니다.
|
||||
|
||||
"때로는 컴퓨터에서 변경이 이루어질 때만 Task가 실행되기를 원할 때가 있습니다. 예를 들어, 태스크가 해당 서비스의 구성을 업데이트하지만, 구성이 변경되지 않은 경우 서비스를 다시 시작하고 싶을 수 있습니다. Ansible은 이 사용 사례를 해결하기 위해 Handler를 사용합니다. Handler는 알림을 받을 때만 실행되는 태스크입니다. 각 Handler는 전 세계적으로 고유한 이름을 가져야 합니다."
|
||||
|
||||
이 단계에서는 5개의 VM을 배포했다고 생각할 수 있습니다(Ansible 컨트롤 역할을 하는 Ubuntu 데스크톱 머신 포함). 다른 시스템은 이 섹션의 나머지 부분에서 다루게 될 것입니다.
|
||||
|
||||
### Playbook 실행
|
||||
|
||||
이제 Node에 대해 Playbook을 실행할 준비가 되었습니다. Playbook을 실행하려면 `ansible-playbook playbook1.yml`을 사용하면 됩니다. Playbook 내에서 Playbook이 실행될 호스트를 정의했으며, 정의한 Task를 안내합니다.
|
||||
|
||||
명령이 완료되면 Play와 Task를 보여주는 출력이 표시되며, 아래 이미지에서 원하는 상태를 설치하는 데 시간이 걸리는 것을 확인할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
그런 다음 Node로 이동하여 Node에 소프트웨어가 설치되었는지 확인하여 이를 다시 확인할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
위와 같이 두 개의 독립형 웹서버를 배포했으므로 이제 정의한 각각의 IP로 이동하여 새 웹 사이트를 가져올 수 있습니다.
|
||||
|
||||

|
||||
|
||||
이 섹션의 나머지 부분을 진행하면서 이 Playbook을 기반으로 구축할 것입니다. 또한 Ubuntu 데스크톱을 가져와서 Ansible을 사용하여 애플리케이션과 구성을 부트스트랩할 수 있는지 살펴보고 싶어서 이 부분도 다뤄볼 수 있을 것 같습니다. 예를 들어 명령에서 로컬 호스트를 사용하여 로컬 호스트에 대해 Playbook을 실행할 수 있다는 것을 보셨습니다.
|
||||
|
||||
여기에 추가해야 할 또 다른 사항은 우리는 실제로 Ubuntu VM으로만 작업하고 있지만 Ansible은 대상 시스템에 구애받지 않는다는 것입니다. 시스템을 관리하기 위해 이전에 언급했던 대안은 서버별로 서버를 관리할 수 있습니다(서버 수가 많을 경우 확장성이 떨어지고 Node가 3개일 때도 문제가 있음) Linux 섹션에서 다시 다룬 셸 스크립팅을 사용할 수도 있지만 이러한 Node는 잠재적으로 다를 수 있으므로 가능하지만 누군가 스크립트를 유지 및 관리해야 합니다. Ansible은 무료이며 전문화된 스크립트가 필요 없는 대신 간편한 버튼을 누릅니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [What is Ansible](https://www.youtube.com/watch?v=1id6ERvfozo)
|
||||
- [Ansible 101 - Episode 1 - Introduction to Ansible](https://www.youtube.com/watch?v=goclfp6a2IQ)
|
||||
- [NetworkChuck - You need to learn Ansible right now!](https://www.youtube.com/watch?v=5hycyr-8EKs&t=955s)
|
||||
- [Your complete guide to Ansible](https://www.youtube.com/playlist?list=PLnFWJCugpwfzTlIJ-JtuATD2MBBD7_m3u)
|
||||
|
||||
위에 나열된 마지막 재생 목록은 이 섹션의 많은 코드와 아이디어가 나온 곳이며, 동영상 형식의 훌륭한 리소스이자 워크스루입니다.
|
||||
|
||||
[Day 66](day66.md)에서 봐요!
|
130
2022/ko/Days/day66.md
Normal file
130
2022/ko/Days/day66.md
Normal file
@ -0,0 +1,130 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - Ansible Playbooks Continued... - Day 66'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - Ansible Playbooks Continued...
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048712
|
||||
---
|
||||
|
||||
## Ansible Playbook (계속)
|
||||
|
||||
지난 섹션에서는 vagrant 파일을 사용하여 4대의 머신을 배포하는 작은 실험실을 만드는 것으로 시작했고, 이 섹션에서 만든 Linux 머신을 Ansible 제어 시스템으로 사용했습니다.
|
||||
|
||||
또한 Playbook의 몇 가지 시나리오를 실행했고 마지막에는 web01과 web02를 개별 웹 서버로 만드는 Playbook을 만들었습니다.
|
||||
|
||||

|
||||
|
||||
### 깔끔하게 정리하기
|
||||
|
||||
추가 자동화 및 배포를 시작하기 전에 Playbook을 간결하고 깔끔하게 유지하는 기능과 작업과 Handler를 하위 폴더로 분리하는 방법에 대해 다뤄야 합니다.
|
||||
|
||||
작업을 폴더 내의 해당 파일에 복사하겠습니다.
|
||||
|
||||
```Yaml
|
||||
- name: ensure apache is at the latest version
|
||||
apt: name=apache2 state=latest
|
||||
|
||||
- name: write the apache2 ports.conf config file
|
||||
template:
|
||||
src=templates/ports.conf.j2
|
||||
dest=/etc/apache2/ports.conf
|
||||
notify: restart apache
|
||||
|
||||
- name: write a basic index.html file
|
||||
template:
|
||||
src: templates/index.html.j2
|
||||
dest: /var/www/html/index.html
|
||||
notify:
|
||||
- restart apache
|
||||
|
||||
- name: ensure apache is running
|
||||
service:
|
||||
name: apache2
|
||||
state: started
|
||||
```
|
||||
|
||||
Handler도 마찬가지입니다.
|
||||
|
||||
```Yaml
|
||||
- name: restart apache
|
||||
service:
|
||||
name: apache2
|
||||
state: restarted
|
||||
```
|
||||
|
||||
Playbook의 이름을 `playbook2.yml`로 지정한 다음, 이 파일을 가리킵니다. 이 모든 파일은 [ansible-scenario2](/2022/Days/Configmgmt/ansible-scenario2/)에서 찾을 수 있습니다.
|
||||
|
||||
제어 머신에서 테스트할 수 있습니다. 리포지토리에서 파일을 복사한 경우 "write a basic index.html file"에서 변경된 사항을 발견했을 것입니다.
|
||||
|
||||

|
||||
|
||||
`curl web01:8000`을 사용하여 어떤 간단한 변경이 있었는지 알아봅시다.
|
||||
|
||||

|
||||
|
||||
방금 Playbook을 정리하고 규모에 따라 Playbook을 매우 압도적으로 만들 수 있는 영역을 분리하기 시작했습니다.
|
||||
|
||||
### Role과 Ansible Galaxy
|
||||
|
||||
현재 4개의 VM을 배포했으며 이 중 2개의 VM을 웹 서버로 구성했지만 데이터베이스 서버와 로드 밸런서 또는 프록시 등 좀 더 구체적인 기능이 있습니다. 이 작업을 수행하고 리포지토리를 정리하기 위해 Ansible 내에서 Role을 사용할 수 있습니다.
|
||||
|
||||
이를 위해 공유 리포지토리에서 Ansible Role을 관리하기 위해 존재하는 `ansible-galaxy` 명령을 사용합니다.
|
||||
|
||||

|
||||
|
||||
우리는 `ansible-galaxy`를 사용하여 웹서버에 대한 세부 정보를 넣을 apache2의 Role을 생성할 것입니다.
|
||||
|
||||

|
||||
|
||||
위의 명령 `ansible-galaxy init roles/apache2`는 위에 표시된 폴더 구조를 생성합니다. 다음 단계는 기존 작업과 template을 새 구조의 관련 폴더로 이동하는 것입니다.
|
||||
|
||||

|
||||
|
||||
복사하여 붙여넣으면 파일을 쉽게 옮길 수 있지만, tasks/main.yml을 변경하여 이 파일이 apache2_install.yml을 가리키도록 해야 합니다.
|
||||
|
||||
또한 새로운 Role을 참조하도록 Playbook을 변경해야 합니다. playbook1.yml과 playbook2.yml에서 작업과 Handler를 두 버전 간에 변경하면서 다른 방식으로 결정합니다. 아래와 같이 이 Role을 사용하도록 Playbook을 변경해야 합니다:
|
||||
|
||||
```Yaml
|
||||
- hosts: webservers
|
||||
become: yes
|
||||
vars:
|
||||
http_port: 8000
|
||||
https_port: 4443
|
||||
html_welcome_msg: "Hello 90DaysOfDevOps - Welcome to Day 66!"
|
||||
roles:
|
||||
- apache2
|
||||
```
|
||||
|
||||

|
||||
|
||||
이제 새 Playbook 이름인 `ansible-playbook playbook3.yml`로 Playbook을 다시 실행하면 deprecated가 발생한 것을 확인할 수 있으며, 다음에 수정할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
Playbook이 실행되었지만, deprecated가 발생했으므로 이제 방법을 수정해야 합니다. 이를 위해 tasks/main.yml의 include 옵션을 아래와 같이 import_tasks로 변경했습니다.
|
||||
|
||||

|
||||
|
||||
이 파일은 [ansible-scenario3](/2022/Days/Configmgmt/ansible-scenario3)에서 찾을 수 있습니다.
|
||||
|
||||
또한 우리가 만들 `ansible-galaxy`를 사용하면서 몇 가지 Role을 더 만들 것입니다:
|
||||
|
||||
- common = 모든 서버용(`ansible-galaxy init roles/common`)
|
||||
- nginx = 로드밸런서용(`ansible-galaxy init roles/nginx`)
|
||||
|
||||

|
||||
|
||||
여기서는 여기까지만 하고 다음 세션에서는 배포했지만, 아직 아무것도 하지 않은 다른 Node에 대한 작업을 시작하겠습니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [What is Ansible](https://www.youtube.com/watch?v=1id6ERvfozo)
|
||||
- [Ansible 101 - Episode 1 - Introduction to Ansible](https://www.youtube.com/watch?v=goclfp6a2IQ)
|
||||
- [NetworkChuck - You need to learn Ansible right now!](https://www.youtube.com/watch?v=5hycyr-8EKs&t=955s)
|
||||
- [Your complete guide to Ansible](https://www.youtube.com/playlist?list=PLnFWJCugpwfzTlIJ-JtuATD2MBBD7_m3u)
|
||||
|
||||
위에 나열된 마지막 재생 목록은 이 섹션의 많은 코드와 아이디어가 나온 곳이며, 동영상 형식의 훌륭한 리소스이자 워크스루입니다.
|
||||
|
||||
[Day 67](day67.md)에서 봐요!
|
122
2022/ko/Days/day67.md
Normal file
122
2022/ko/Days/day67.md
Normal file
@ -0,0 +1,122 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - Using Roles & Deploying a Loadbalancer - Day 67'
|
||||
published: false
|
||||
description: '90DaysOfDevOps - Using Roles & Deploying a Loadbalancer'
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048713
|
||||
---
|
||||
|
||||
## Role 사용 및 로드밸런서 배포하기
|
||||
|
||||
지난 세션에서는 Role에 대해 다루고 `ansible-galaxy` 명령을 사용하여 앞으로 사용할 몇 가지 Role에 대한 폴더 구조를 만들었습니다. 모든 것이 Role 폴더에 숨겨져 있기 때문에 구성 코드의 작업 저장소가 훨씬 더 깔끔해졌습니다.
|
||||
|
||||
하지만 지금까지는 apache2 Role만 사용했고 웹서버를 처리하기 위해 작동하는 playbook3.yaml이 있습니다.
|
||||
|
||||
이 시점에서 `vagrant up web01 web02`만 사용했다면 이제 `vagrant up loadbalancer`를 실행하면 로드 밸런서/프록시로 사용할 다른 Ubuntu 시스템이 나타납니다.
|
||||
|
||||
호스트 파일에 이 새 시스템을 이미 정의했지만, 사용할 수 있을 때까지 ssh 키가 구성되지 않았으므로 시스템이 가동되고 준비되면 `ssh-copy-id loadbalancer`도 실행해야 합니다.
|
||||
|
||||
### Common Role
|
||||
|
||||
어제 세션 마지막에 `common` Role을 만들었는데, Common은 모든 서버에서 사용되는 반면 다른 Role은 사용 사례에 따라 다르지만 이제 설치하려는 애플리케이션은 가짜처럼 일반적이며 이것이 왜 그런지 많은 이유를 알 수는 없지만 그 목적을 보여줍니다. Common Role 폴더 구조에서 작업 폴더로 이동하면 main.yml이 있습니다. 이 YAML에서 이 파일을 install_tools.yml 파일로 가리켜야 하며, `- import_tasks: install_tools.yml` 줄을 추가하여 이를 수행합니다. 이전에는 `include`였으나 곧 사용되지 않을 예정이므로 import_tasks를 사용합니다.
|
||||
|
||||
```Yaml
|
||||
- name: "Install Common packages"
|
||||
apt: name={{ item }} state=latest
|
||||
with_items:
|
||||
- neofetch
|
||||
- tree
|
||||
- figlet
|
||||
```
|
||||
|
||||
그런 다음 playbook에서 각 호스트 블록에 대한 Common Role을 추가합니다.
|
||||
|
||||
```Yaml
|
||||
- hosts: webservers
|
||||
become: yes
|
||||
vars:
|
||||
http_port: 8000
|
||||
https_port: 4443
|
||||
html_welcome_msg: "Hello 90DaysOfDevOps - Welcome to Day 66!"
|
||||
roles:
|
||||
- common
|
||||
- apache2
|
||||
```
|
||||
|
||||
### Nginx
|
||||
|
||||
다음 단계는 로드밸런서 VM에 nginx를 설치하고 구성하는 것입니다. 일반적인 폴더 구조와 마찬가지로, 마지막 세션을 기반으로 nginx를 구성합니다.
|
||||
|
||||
먼저 playbook에 호스트 블록을 추가하겠습니다. 이 블록에는 Common Role과 새로운 nginx Role이 포함됩니다.
|
||||
|
||||
playbook은 여기에서 찾을 수 있습니다. [playbook4.yml](/2022/Days/Configmgmt/ansible-scenario4/playbook4.yml)
|
||||
|
||||
```Yaml
|
||||
- hosts: webservers
|
||||
become: yes
|
||||
vars:
|
||||
http_port: 8000
|
||||
https_port: 4443
|
||||
html_welcome_msg: "Hello 90DaysOfDevOps - Welcome to Day 66!"
|
||||
roles:
|
||||
- common
|
||||
- apache2
|
||||
|
||||
- hosts: proxy
|
||||
become: yes
|
||||
roles:
|
||||
- common
|
||||
- nginx
|
||||
```
|
||||
|
||||
이것이 의미가 있으려면 실행할 작업을 정의해야 하며, 같은 방식으로 이번에는 설치용 파일과 구성용 파일 두 개를 가리키도록 작업의 main.yml을 수정하겠습니다.
|
||||
|
||||
원하는 결과에 따라 수정한 다른 파일이 몇 개 더 있는데, [ansible-scenario4](/2022/Days/Configmgmt/ansible-scenario4) 폴더에서 변경된 모든 파일을 살펴보세요. nginx 폴더의 작업, Handler 및 template 폴더를 확인하면 추가 변경 사항과 파일을 찾을 수 있습니다.
|
||||
|
||||
### 업데이트된 playbook 실행
|
||||
|
||||
어제부터 시스템에 일부 패키지를 설치하는 Common Role을 추가한 데 이어 설치 및 구성을 포함하는 nginx Role도 추가했습니다.
|
||||
|
||||
`anible-playbook playbook4.yml`을 사용하여 playbook4.yml을 실행해 보겠습니다.
|
||||
|
||||

|
||||
|
||||
이제 웹 서버와 로드밸런서가 구성되었으므로 이제 로드밸런서의 IP 주소인 http://192.168.169.134/ 로 이동할 수 있어야 합니다.
|
||||
|
||||

|
||||
|
||||
이 과정을 따르고 있는데도 이 상태가 나타나지 않는다면 사용 중인 환경의 서버 IP 주소 때문일 수 있습니다. 이 파일은 `templates\mysite.j2`에서 찾을 수 있으며 아래와 유사하게 보입니다: 웹 서버 IP 주소로 업데이트해야 합니다.
|
||||
|
||||
```J2
|
||||
upstream webservers {
|
||||
server 192.168.169.131:8000;
|
||||
server 192.168.169.132:8000;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
|
||||
location / {
|
||||
proxy_pass http://webservers;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
우리가 설치한 것이 모두 정상이라고 확신하지만, ansible을 사용하여 임시 명령을 사용하여 이러한 일반적인 도구 설치를 확인해 보겠습니다.
|
||||
|
||||
`ansible loadbalancer -m command -a neofetch`
|
||||
|
||||

|
||||
|
||||
## 자료
|
||||
|
||||
- [What is Ansible](https://www.youtube.com/watch?v=1id6ERvfozo)
|
||||
- [Ansible 101 - Episode 1 - Introduction to Ansible](https://www.youtube.com/watch?v=goclfp6a2IQ)
|
||||
- [NetworkChuck - You need to learn Ansible right now!](https://www.youtube.com/watch?v=5hycyr-8EKs&t=955s)
|
||||
- [Your complete guide to Ansible](https://www.youtube.com/playlist?list=PLnFWJCugpwfzTlIJ-JtuATD2MBBD7_m3u)
|
||||
|
||||
위에 나열된 마지막 재생 목록은 이 섹션의 많은 코드와 아이디어가 나온 곳이며, 동영상 형식의 훌륭한 리소스이자 워크스루입니다.
|
||||
|
||||
[Day 68](day68.md)에서 봐요!
|
353
2022/ko/Days/day68.md
Normal file
353
2022/ko/Days/day68.md
Normal file
@ -0,0 +1,353 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - Tags, Variables, Inventory & Database Server config - Day 68'
|
||||
published: false
|
||||
description: '90DaysOfDevOps - Tags, Variables, Inventory & Database Server config'
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048780
|
||||
---
|
||||
|
||||
## Tag, Variable, Inventory 및 Database 서버 구성
|
||||
|
||||
### Tag
|
||||
|
||||
어제 세션에 playbook을 남겨두었으므로 모든 작업을 실행하고 해당 playbook 내에서 play해야 합니다. 즉, 웹서버와 로드밸런서 play 및 작업을 모두 실행해야 완료할 수 있습니다.
|
||||
|
||||
하지만 Tag를 사용하면 원하는 경우 이러한 작업을 분리할 수 있습니다. 이는 환경에 매우 크고 긴 playbook이 있는 경우 효율적인 방법이 될 수 있습니다.
|
||||
|
||||
이 경우 playbook 파일에서는 [ansible-scenario5](/2022/Days/Configmgmt/ansible-scenario5/playbook5.yml)를 사용하고 있습니다.
|
||||
|
||||
```Yaml
|
||||
- hosts: webservers
|
||||
become: yes
|
||||
vars:
|
||||
http_port: 8000
|
||||
https_port: 4443
|
||||
html_welcome_msg: "Hello 90DaysOfDevOps - Welcome to Day 66!"
|
||||
roles:
|
||||
- common
|
||||
- apache2
|
||||
tags: web
|
||||
|
||||
- hosts: proxy
|
||||
become: yes
|
||||
roles:
|
||||
- common
|
||||
- nginx
|
||||
tags: proxy
|
||||
```
|
||||
|
||||
그런 다음 `ansible-playbook playbook5.yml --list-tags`를 사용하여 이를 확인할 수 있으며, list Tag는 우리가 playbook에서 정의한 Tag의 윤곽을 나타냅니다.
|
||||
|
||||

|
||||
|
||||
이제 프록시만 타깃팅하려면 `ansible-playbook playbook5.yml --tags proxy`를 실행하면 아래에서 볼 수 있듯이 프록시에 대해서만 playbook을 실행할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
Tag는 작업 수준에서도 추가할 수 있으므로 원하는 위치와 작업을 세분화할 수 있습니다. 예를 들어 애플리케이션 중심 Tag가 될 수도 있고, 작업을 살펴보고 설치, 구성 또는 제거에 따라 작업에 Tag를 지정할 수도 있습니다. 사용할 수 있는 또 다른 매우 유용한 Tag는 다음과 같습니다.
|
||||
|
||||
`tag: always` 이것은 명령에 어떤 --tags를 사용하든 상관없이 항상 값으로 Tag가 지정된 항목이 있으면 ansible-playbook 명령을 실행할 때 항상 실행되도록 보장합니다.
|
||||
|
||||
Tag를 사용하여 여러 Tag를 함께 묶을 수도 있으며, `ansible-playbook playbook5.yml --tags proxy,web`을 실행하도록 선택하면 해당 Tag가 있는 모든 항목이 실행됩니다. 물론 이 예제에서는 playbook을 실행하는 것과 같은 의미이지만, 다른 play가 여러 개 있는 경우에는 이 방법이 의미가 있을 것입니다.
|
||||
|
||||
둘 이상의 Tag를 정의할 수도 있습니다.
|
||||
|
||||
### Variable
|
||||
|
||||
Ansible에는 크게 두 가지 유형의 Variable이 있습니다.
|
||||
|
||||
- User created
|
||||
- Ansible Facts
|
||||
|
||||
### Ansible Facts
|
||||
|
||||
playbook을 실행할 때마다 "Gathering facts"라는 정의되지 않은 작업이 있었는데, 이러한 Variable 또는 fact를 사용하여 자동화 작업을 수행할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
다음 `ansible proxy -m setup` 명령을 실행하면 JSON 형식의 많은 출력을 볼 수 있습니다. 이를 사용하려면 터미널에 많은 정보가 있어야 하므로 `ansible proxy -m setup >> facts.json`을 사용하여 파일로 출력하고 싶습니다. [여기](/2022/Days/Configmgmt/ansible-scenario5/facts.json)에서 이 파일을 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
이 파일을 열면 명령에 대한 모든 종류의 정보를 볼 수 있습니다. IP 주소, 아키텍처, 바이오스 버전을 확인할 수 있습니다. 이 정보를 활용하여 playbook에 사용하려는 경우 유용한 정보가 많이 있습니다.
|
||||
|
||||
한 가지 아이디어는 웹서버의 IP 주소를 하드코딩한 nginx template mysite.j2 내에서 이러한 Variable 중 하나를 잠재적으로 사용하는 것입니다. mysite.j2에 for 루프를 생성하면 [webservers] 그룹을 순환하여 2개 이상의 웹서버를 자동으로 동적으로 생성하거나 이 로드 밸런서 구성에 추가할 수 있습니다.
|
||||
|
||||
```
|
||||
#Dynamic Config for server {{ ansible_facts['nodename'] }}
|
||||
upstream webservers {
|
||||
{% for host in groups['webservers'] %}
|
||||
server {{ hostvars[host]['ansible_facts']['nodename'] }}:8000;
|
||||
{% endfor %}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
|
||||
location / {
|
||||
proxy_pass http://webservers;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
위의 결과는 지금과 동일하게 보이지만 웹 서버를 더 추가하거나 제거하면 프록시 구성이 동적으로 변경됩니다. 이 기능을 사용하려면 이름 확인을 구성해야 합니다.
|
||||
|
||||
### User created
|
||||
|
||||
User created Variable은 우리가 직접 만든 Variable입니다. playbook을 살펴보면 `vars:`가 있고 거기에 3개의 Variable 목록이 있는 것을 볼 수 있습니다.
|
||||
|
||||
```Yaml
|
||||
- hosts: webservers
|
||||
become: yes
|
||||
vars:
|
||||
http_port: 8000
|
||||
https_port: 4443
|
||||
html_welcome_msg: "Hello 90DaysOfDevOps - Welcome to Day 68!"
|
||||
roles:
|
||||
- common
|
||||
- apache2
|
||||
tags: web
|
||||
|
||||
- hosts: proxy
|
||||
become: yes
|
||||
roles:
|
||||
- common
|
||||
- nginx
|
||||
tags: proxy
|
||||
```
|
||||
|
||||
그러나 Variable을 해당 파일로 이동하여 playbook에 Variable이 없도록 할 수 있습니다. 이 작업을 수행하되, [ansible-scenario6](/2022/Days/Configmgmt/ansible-scenario6) 폴더로 이동하겠습니다. 해당 폴더의 루트에 group_vars 폴더를 만들겠습니다. 그런 다음 all이라는 또 다른 폴더를 만듭니다(모든 그룹이 이 Variable을 가져옵니다). 이 폴더에 `common_variables.yml`이라는 파일을 만들고 playbook의 Variable을 이 파일에 복사합니다. Variable과 함께 playbook에서 Variable을 제거합니다.
|
||||
|
||||
```Yaml
|
||||
http_port: 8000
|
||||
https_port: 4443
|
||||
html_welcome_msg: "Hello 90DaysOfDevOps - Welcome to Day 68!"
|
||||
```
|
||||
|
||||
이 Variable을 전역 Variable로 연결하기 때문에 여기에 NTP 및 DNS 서버도 추가할 수 있습니다. Variable은 우리가 만든 폴더 구조에서 설정됩니다. 이제 playbook이 얼마나 깔끔해졌는지 아래에서 확인할 수 있습니다.
|
||||
|
||||
```Yaml
|
||||
- hosts: webservers
|
||||
become: yes
|
||||
roles:
|
||||
- common
|
||||
- apache2
|
||||
tags: web
|
||||
|
||||
- hosts: proxy
|
||||
become: yes
|
||||
roles:
|
||||
- common
|
||||
- nginx
|
||||
tags: proxy
|
||||
```
|
||||
|
||||
그 Variable 중 하나는 http_port로, 아래와 같이 mysite.j2 내의 for 루프에서 이 Variable을 다시 사용할 수 있습니다:
|
||||
|
||||
```J2
|
||||
#Dynamic Config for server {{ ansible_facts['nodename'] }}
|
||||
upstream webservers {
|
||||
{% for host in groups['webservers'] %}
|
||||
server {{ hostvars[host]['ansible_facts']['nodename'] }}:{{ http_port }};
|
||||
{% endfor %}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
|
||||
location / {
|
||||
proxy_pass http://webservers;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
또한, 어떤 웹서버를 사용하고 있는지 파악할 수 있도록 roles/apache2/templates/index.HTML.j2 파일에 분석 가능한 사실을 정의할 수도 있습니다.
|
||||
|
||||
```J2
|
||||
<html>
|
||||
|
||||
<h1>{{ html_welcome_msg }}! I'm webserver {{ ansible_facts['nodename'] }} </h1>
|
||||
|
||||
</html>
|
||||
```
|
||||
|
||||
Variable을 변경하여 `ansible-playbook playbook6.yml` 명령을 실행한 결과, 로드밸런서에 도달하면 그룹에 있는 웹서버 중 하나에 도달한 것을 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
또한 host_vars라는 폴더를 추가하고 web01.yml을 생성하여 원하는 경우 특정 메시지를 표시하거나 호스트별로 표시되는 내용을 변경할 수 있습니다.
|
||||
|
||||
### Inventory 파일
|
||||
|
||||
지금까지 호스트를 결정하기 위해 /etc/ansible 폴더에 있는 기본 호스트 파일을 사용했습니다. 그러나 프로덕션 및 스테이징과 같이 환경마다 다른 파일을 사용할 수 있습니다. 더 많은 환경을 만들지는 않겠습니다. 하지만 호스트 파일은 만들 수 있습니다.
|
||||
|
||||
서버와 노드의 다양한 Inventory에 대해 여러 개의 파일을 만들 수 있습니다. 우리는 `ansible-playbook -i dev playbook.yml`을 사용하여 이를 호출합니다. 호스트 파일 내에 Variable을 정의한 다음 이를 출력하거나 playbook의 다른 곳에서 해당 Variable을 활용할 수도 있습니다. 예를 들어 아래 예제 및 교육 과정에서는 호스트 파일에서 생성된 환경 Variable을 로드밸런서 웹 페이지 template에 추가하여 웹 페이지 메시지의 일부로 환경을 표시했습니다.
|
||||
|
||||
### Database 서버 배포
|
||||
|
||||
아직 전원을 켜고 구성하지 않은 머신이 하나 더 있습니다. vagrant 파일이 있는 곳에서 `vagrant up db01`을 사용하여 이 작업을 수행할 수 있습니다. 전원이 켜지고 액세스할 수 있게 되면 `ssh-copy-id db01`을 사용하여 SSH 키를 복사하여 액세스할 수 있도록 해야 합니다.
|
||||
|
||||
여기서는 [ansible-scenario7](/2022/Days/Configmgmt/ansible-scenario7) 폴더에서 작업할 것입니다.
|
||||
|
||||
그런 다음 `ansible-galaxy init roles/mysql`을 사용하여 "MySQL"이라는 새 Role에 대한 새 폴더 구조를 만들어 보겠습니다.
|
||||
|
||||
playbook에서 Database 구성을 위한 새로운 play 블록을 추가하겠습니다. /etc/ansible/hosts 파일에 그룹 Database가 정의되어 있습니다. 그런 다음 Database 그룹에 공통 Role과 이전 단계에서 생성한 MySQL이라는 새 Role을 갖도록 지시합니다. 또한 Database 그룹에 Database Tag를 지정하고 있는데, 이는 앞서 설명한 것처럼 원하는 경우 이러한 Tag에 대해서만 실행하도록 선택할 수 있음을 의미합니다.
|
||||
|
||||
```Yaml
|
||||
- hosts: webservers
|
||||
become: yes
|
||||
roles:
|
||||
- common
|
||||
- apache2
|
||||
tags:
|
||||
web
|
||||
|
||||
- hosts: proxy
|
||||
become: yes
|
||||
roles:
|
||||
- common
|
||||
- nginx
|
||||
tags:
|
||||
proxy
|
||||
|
||||
- hosts: database
|
||||
become: yes
|
||||
roles:
|
||||
- common
|
||||
- mysql
|
||||
tags: database
|
||||
```
|
||||
|
||||
이제 Role 폴더 구조 내에서 트리가 자동으로 생성되었으므로 다음을 채워야 합니다:
|
||||
|
||||
Handlers - main.yml
|
||||
|
||||
```Yaml
|
||||
# handlers file for roles/mysql
|
||||
- name: restart mysql
|
||||
service:
|
||||
name: mysql
|
||||
state: restarted
|
||||
```
|
||||
|
||||
Tasks - install_mysql.yml, main.yml & setup_mysql.yml
|
||||
|
||||
install_mysql.yml - 이 작업은 MySQL을 설치하고 서비스가 실행 중인지 확인하기 위해 수행됩니다.
|
||||
|
||||
```Yaml
|
||||
- name: "Install Common packages"
|
||||
apt: name={{ item }} state=latest
|
||||
with_items:
|
||||
- python3-pip
|
||||
- mysql-client
|
||||
- python3-mysqldb
|
||||
- libmysqlclient-dev
|
||||
|
||||
- name: Ensure mysql-server is installed latest version
|
||||
apt: name=mysql-server state=latest
|
||||
|
||||
- name: Installing python module MySQL-python
|
||||
pip:
|
||||
name: PyMySQL
|
||||
|
||||
- name: Ensure mysql-server is running
|
||||
service:
|
||||
name: mysql
|
||||
state: started
|
||||
```
|
||||
|
||||
main.yml은 이러한 파일에서 작업을 가져오도록 제안하는 포인터 파일입니다.
|
||||
|
||||
```Yaml
|
||||
# tasks file for roles/mysql
|
||||
- import_tasks: install_mysql.yml
|
||||
- import_tasks: setup_mysql.yml
|
||||
```
|
||||
|
||||
setup_mysql.yml - 이 작업은 Database와 Database 사용자를 생성합니다.
|
||||
|
||||
```Yaml
|
||||
- name: Create my.cnf configuration file
|
||||
template: src=templates/my.cnf.j2 dest=/etc/mysql/conf.d/mysql.cnf
|
||||
notify: restart mysql
|
||||
|
||||
- name: Create database user with name 'devops' and password 'DevOps90' with all database privileges
|
||||
community.mysql.mysql_user:
|
||||
login_unix_socket: /var/run/mysqld/mysqld.sock
|
||||
login_user: "{{ mysql_user_name }}"
|
||||
login_password: "{{ mysql_user_password }}"
|
||||
name: "{{db_user}}"
|
||||
password: "{{db_pass}}"
|
||||
priv: '*.*:ALL'
|
||||
host: '%'
|
||||
state: present
|
||||
|
||||
- name: Create a new database with name '90daysofdevops'
|
||||
mysql_db:
|
||||
login_user: "{{ mysql_user_name }}"
|
||||
login_password: "{{ mysql_user_password }}"
|
||||
name: "{{ db_name }}"
|
||||
state: present
|
||||
```
|
||||
|
||||
위에서 비밀번호, 사용자 이름 및 Database와 같은 일부 구성을 결정하기 위해 몇 가지 Variable을 사용하고 있음을 알 수 있으며, 이 Variable은 모두 group_vars/all/common_variables.yml 파일에 저장되어 있습니다.
|
||||
|
||||
```Yaml
|
||||
http_port: 8000
|
||||
https_port: 4443
|
||||
html_welcome_msg: "Hello 90DaysOfDevOps - Welcome to Day 68!"
|
||||
|
||||
mysql_user_name: root
|
||||
mysql_user_password: "vagrant"
|
||||
db_user: devops
|
||||
db_pass: DevOps90
|
||||
db_name: 90DaysOfDevOps
|
||||
```
|
||||
|
||||
또한 template 폴더에 아래와 같은 my.cnf.j2 파일이 있습니다:
|
||||
|
||||
```J2
|
||||
[mysql]
|
||||
bind-address = 0.0.0.0
|
||||
```
|
||||
|
||||
### playbook 실행
|
||||
|
||||
이제 VM이 실행 중이고 구성 파일이 준비되었으므로 이제 playbook을 실행할 준비가 되었습니다. 다음 `ansible-playbook playbook7.yml`을 실행하면 이전에 수행한 모든 작업이 포함된 playbook을 실행할 수 있고, `ansible-playbook playbook7.yml --tags database` 명령으로 Database 그룹에 배포하여 새 구성 파일만 실행하도록 선택할 수도 있습니다.
|
||||
|
||||
Database Tag에 대해서만 실행했지만, 오류가 발생했습니다. 이 오류는 pip3(파이썬)가 설치되어 있지 않다는 것을 알려줍니다. 이 오류는 일반 작업에 추가하여 해결할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
위의 문제를 수정하고 playbook을 다시 실행했더니 성공적으로 변경되었습니다.
|
||||
|
||||

|
||||
|
||||
이제 새로 구성한 db01 서버에서 모든 것이 우리가 원하는 대로 작동하는지 확인해야 합니다. Control Node에서 `ssh db01` 명령을 사용하여 이 작업을 수행할 수 있습니다.
|
||||
|
||||
MySQL에 연결하기 위해 `sudo /usr/bin/mysql -u root -p`를 사용하고 프롬프트에서 root에 대한 vagrant 암호를 제공했습니다.
|
||||
|
||||
연결이 완료되면 먼저 DevOps라는 사용자가 생성되었는지 확인합니다. `select user, host from mysql.user;`
|
||||
|
||||

|
||||
|
||||
이제 `SHOW DATABASES;` 명령을 실행하여 생성된 새 Database를 확인할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
루트를 사용하여 연결했지만 이제 `sudo /usr/bin/MySQL -u devops -p`를 사용하여 동일한 방법으로 DevOps 계정으로 로그인할 수도 있지만 여기서 암호는 DevOps90입니다.
|
||||
|
||||
제가 발견한 한 가지는 `setup_mysql.yml`에 `login_unix_socket: /var/run/mysqld/mysqld.sock` 줄을 추가해야 db01 MySQL 인스턴스에 성공적으로 연결할 수 있었고 이제 이 작업을 실행할 때마다 사용자를 만들 때 변경 사항을 보고하므로 어떤 제안이라도 대단히 감사하겠습니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [What is Ansible](https://www.youtube.com/watch?v=1id6ERvfozo)
|
||||
- [Ansible 101 - Episode 1 - Introduction to Ansible](https://www.youtube.com/watch?v=goclfp6a2IQ)
|
||||
- [NetworkChuck - You need to learn Ansible right now!](https://www.youtube.com/watch?v=5hycyr-8EKs&t=955s)
|
||||
- [Your complete guide to Ansible](https://www.youtube.com/playlist?list=PLnFWJCugpwfzTlIJ-JtuATD2MBBD7_m3u)
|
||||
|
||||
위에 나열된 마지막 재생 목록은 이 섹션의 많은 코드와 아이디어가 나온 곳이며, 동영상 형식의 훌륭한 리소스이자 워크스루입니다.
|
||||
|
||||
[Day 69](day69.md)에서 봐요!
|
143
2022/ko/Days/day69.md
Normal file
143
2022/ko/Days/day69.md
Normal file
@ -0,0 +1,143 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - All other things Ansible - Automation Controller (Tower), AWX, Vault - Day 69'
|
||||
published: false
|
||||
description: '90DaysOfDevOps - All other things Ansible - Automation Controller (Tower), AWX, Vault'
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048714
|
||||
---
|
||||
|
||||
## 기타 모든 Ansible - 자동화 컨트롤러(타워), AWX, Vault
|
||||
|
||||
구성 관리에 대한 섹션을 마무리하면서 Ansible을 다룰 때 접할 수 있는 다른 영역에 대해 살펴보고 싶었습니다.
|
||||
|
||||
Ansible 자동화 플랫폼을 구성하는 많은 제품이 있습니다.
|
||||
|
||||
Red Hat Ansible Automation Platform은 조직 전반에서 자동화를 구축하고 운영하기 위한 기반입니다. 이 플랫폼에는 전사적인 자동화를 구현하는 데 필요한 모든 도구가 포함되어 있습니다.
|
||||
|
||||

|
||||
|
||||
이 글에서는 이 중 일부를 다루려고 합니다. 하지만 더 자세한 내용은 공식 Red Hat Ansible 사이트에서 더 많은 정보를 확인할 수 있습니다. [Ansible.com](https://www.ansible.com/?hsLang=en-us)
|
||||
|
||||
### Ansible 자동화 컨트롤러 | AWX
|
||||
|
||||
자동화 컨트롤러와 AWX는 제공하는 기능이 매우 유사하기 때문에 이 두 가지를 함께 묶었습니다.
|
||||
|
||||
AWX 프로젝트 또는 줄여서 AWX는 Red Hat이 후원하는 오픈 소스 커뮤니티 프로젝트로, 사용자 환경 내에서 Ansible 프로젝트를 더 잘 제어할 수 있도록 지원합니다. AWX는 자동화 컨트롤러 구성 요소가 파생된 업스트림 프로젝트입니다.
|
||||
|
||||
엔터프라이즈 솔루션을 찾고 계신다면 자동화 컨트롤러를 찾으시거나 이전에 Ansible Tower라고 들어보셨을 것입니다. Ansible 자동화 컨트롤러는 Ansible 자동화 플랫폼의 컨트롤 플레인입니다.
|
||||
|
||||
AWX와 자동화 컨트롤러는 지금까지 이 섹션에서 다룬 다른 모든 기능 위에 다음과 같은 기능을 제공합니다.
|
||||
|
||||
- 사용자 인터페이스
|
||||
- 역할 기반 액세스 제어
|
||||
- workflow
|
||||
- CI/CD 통합
|
||||
|
||||
자동화 컨트롤러는 지원 비용을 지불하는 엔터프라이즈 제품입니다.
|
||||
|
||||
Minikube kubernetes 환경 내에서 AWX를 배포하는 방법을 살펴보겠습니다.
|
||||
|
||||
### Ansible AWX 배포하기
|
||||
|
||||
AWX를 kubernetes 클러스터에 배포할 필요는 없으며, [github](https://github.com/ansible/awx)에서 AWX에 대한 자세한 내용을 확인할 수 있습니다. 그러나 버전 18.0부터는 AWX 오퍼레이터를 사용하여 AWX를 설치하는 것이 선호됩니다.
|
||||
|
||||
우선 Minikube 클러스터가 필요합니다. kubernetes 섹션에서 `minikube start --cpus=4 --memory=6g --addons=ingress` 명령으로 새 Minikube 클러스터를 생성하는 방법을 따라 했다면 이 작업을 수행할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
공식 [Ansible AWX 오퍼레이터](https://github.com/ansible/awx-operator)는 여기에서 확인할 수 있습니다. 설치 지침에 명시된 대로 이 리포지토리를 복제한 다음 배포를 실행해야 합니다.
|
||||
|
||||
위의 리포지토리를 folk한 다음 `git clone https://github.com/MichaelCade/awx-operator.git`을 실행했는데, 여러분도 똑같이 하시고 제가 만든 리포지토리는 변경되거나 존재하지 않을 수 있으므로 사용하지 않는 것이 좋습니다.
|
||||
|
||||
복제된 리포지토리에서 아래와 같이 `NodePort`를 `ClusterIP`로 변경해야 하는 awx-demo.yml 파일을 찾을 수 있습니다:
|
||||
|
||||
```Yaml
|
||||
---
|
||||
apiVersion: awx.ansible.com/v1beta1
|
||||
kind: AWX
|
||||
metadata:
|
||||
name: awx-demo
|
||||
spec:
|
||||
service_type: ClusterIP
|
||||
```
|
||||
|
||||
다음 단계는 awx 연산자를 배포할 네임스페이스를 정의하는 것으로, `export NAMESPACE=awx` 명령을 사용한 다음 `make deploy`로 배포를 시작합니다.
|
||||
|
||||

|
||||
|
||||
확인을 통해 새 네임스페이스가 있고 네임스페이스에서 awx-operator-controller pod가 실행되고 있음을 확인합니다. `kubectl get pods -n awx`
|
||||
|
||||

|
||||
|
||||
복제된 리포지토리 내에서 awx-demo.yml이라는 파일을 찾을 수 있으며, 이제 이 파일을 Kubernetes 클러스터와 awx 네임스페이스에 배포하려고 합니다. `kubectl create -f awx-demo.yml -n awx`
|
||||
|
||||

|
||||
|
||||
`kubectl get pods -n awx -w`로 진행 상황을 계속 주시할 수 있습니다.
|
||||
|
||||
모든 것이 실행되면 아래와 같은 이미지와 비슷한 것이 보일 것입니다.
|
||||
|
||||

|
||||
|
||||
이제 새 터미널에서 `minikube service awx-demo-service --url -n $NAMESPACE`를 실행하여 Minikube 인그레스를 통해 이를 노출한 후 awx 배포에 액세스할 수 있어야 합니다.
|
||||
|
||||

|
||||
|
||||
그런 다음 해당 주소 []로 브라우저를 열면 사용자 이름과 비밀번호를 입력하라는 메시지가 표시되는 것을 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
기본적으로 사용자 이름은 admin이며, 비밀번호를 얻으려면 다음 명령어를 실행하여 `kubectl get secret awx-demo-admin-password -o jsonpath="{.data.password}" -n awx| base64 --decode`를 얻을 수 있습니다.
|
||||
|
||||

|
||||
|
||||
이렇게 하면 중앙 집중화된 위치에서 playbook 및 구성 관리 작업을 관리할 수 있는 UI가 제공되며, 지금까지 하나의 Ansible 제어 스테이션에서 실행하던 것과 달리 팀원들이 함께 작업할 수 있습니다.
|
||||
|
||||
이 영역은 이 도구의 기능을 살펴보는 데 더 많은 시간을 할애할 수 있는 또 다른 영역 중 하나입니다.
|
||||
|
||||
Ansible AWX 사용에 대해 더 자세히 설명하는 Jeff Geerling의 훌륭한 리소스를 소개해 드리겠습니다. [Ansible 101 - 에피소드 10 - Ansible 타워 및 AWX](https://www.youtube.com/watch?v=iKmY4jEiy_A&t=752s)
|
||||
|
||||
이 비디오에서 그는 자동화 컨트롤러(이전 Ansible Tower)와 Ansible AWX(무료 및 오픈 소스)의 차이점에 대해서도 자세히 설명합니다.
|
||||
|
||||
### Ansible Vault
|
||||
|
||||
`ansible-vault`를 사용하면 Ansible 데이터 파일을 암호화하고 해독할 수 있습니다. 이 섹션에서는 일부 민감한 정보를 건너뛰고 일반 텍스트로 표시했습니다.
|
||||
|
||||
Ansible 바이너리에는 이 민감한 정보를 마스킹할 수 있는 `ansible-vault`가 내장되어 있습니다.
|
||||
|
||||

|
||||
|
||||
비밀 관리는 점차 HashiCorp Vault나 AWS 키 관리 서비스와 같은 도구와 함께 더 많은 시간을 할애해야 하는 또 다른 영역이 되었습니다. 이 부분은 더 자세히 살펴볼 영역으로 표시하겠습니다.
|
||||
|
||||
Jeff Geerling의 훌륭한 리소스와 데모를 다시 한번 링크해드리겠습니다 [Ansible 101 - 에피소드 6 - Ansible Vault와 역할](https://www.youtube.com/watch?v=JFweg2dUvqM).
|
||||
|
||||
### Ansible Galaxy(문서)
|
||||
|
||||
이제 데모 프로젝트의 일부 역할과 파일 구조를 생성하기 위해 이미 `ansible-galaxy`를 사용했습니다. 하지만 [Ansible Galaxy 문서](https://galaxy.ansible.com/docs/)도 있습니다.
|
||||
|
||||
"Galaxy는 Ansible 콘텐츠를 찾고 공유하기 위한 허브입니다."
|
||||
|
||||
### Ansible 테스트
|
||||
|
||||
- [Ansible Molecule](https://molecule.readthedocs.io/en/latest/) - Molecule 프로젝트는 Ansible 역할의 개발 및 테스트를 지원하도록 설계되었습니다.
|
||||
|
||||
- [Ansible Lint](https://ansible-lint.readthedocs.io/en/latest/) - playbook, 역할 및 컬렉션을 Lint하기 위한 CLI 도구입니다.
|
||||
|
||||
### 기타 리소스
|
||||
|
||||
- [Ansible 문서](https://docs.ansible.com/ansible/latest/index.html)
|
||||
|
||||
## 자료
|
||||
|
||||
- [What is Ansible](https://www.youtube.com/watch?v=1id6ERvfozo)
|
||||
- [Ansible 101 - Episode 1 - Introduction to Ansible](https://www.youtube.com/watch?v=goclfp6a2IQ)
|
||||
- [NetworkChuck - You need to learn Ansible right now!](https://www.youtube.com/watch?v=5hycyr-8EKs&t=955s)
|
||||
- [Your complete guide to Ansible](https://www.youtube.com/playlist?list=PLnFWJCugpwfzTlIJ-JtuATD2MBBD7_m3u)
|
||||
|
||||
위에 나열된 마지막 재생 목록은 이 섹션의 많은 코드와 아이디어가 나온 곳이며, 동영상 형식의 훌륭한 리소스이자 연습입니다.
|
||||
|
||||
이 포스팅에서는 구성 관리에 대해 살펴본 내용을 마무리하고, 다음에는 CI/CD 파이프라인과 애플리케이션 개발 및 릴리스에 이러한 workflow를 달성하기 위해 사용할 수 있는 몇 가지 도구 및 프로세스에 대해 살펴봅니다.
|
||||
|
||||
[Day 70](day70.md)에서 봐요!
|
123
2022/ko/Days/day70.md
Normal file
123
2022/ko/Days/day70.md
Normal file
@ -0,0 +1,123 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - The Big Picture: CI/CD Pipelines - Day 70'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - The Big Picture CI/CD Pipelines
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048836
|
||||
---
|
||||
|
||||
## 큰 그림: CI/CD 파이프라인
|
||||
|
||||
CI/CD(지속적 통합/지속적 배포) 파이프라인 구현은 최신 DevOps 환경의 중추입니다.
|
||||
|
||||
파이프라인은 애플리케이션의 빌드, 테스트 및 배포를 자동화하여 개발과 운영 간의 격차를 해소합니다.
|
||||
|
||||
챌린지의 첫 번째 섹션에서 이 중요한 요소에 대해 많이 다루었습니다. 하지만 다시 한번 말씀드리자면:
|
||||
|
||||
지속적 통합(CI)은 점진적인 코드 변경을 더 자주 그리고 안정적으로 수행하는 보다 현대적인 소프트웨어 개발 관행입니다. 지속적 통합에 의해 트리거되는 자동화된 빌드 및 테스트 Workflow Step은 리포지토리에 병합되는 코드 변경 사항을 신뢰할 수 있도록 보장합니다.
|
||||
|
||||
그런 다음 해당 코드/애플리케이션은 지속적 배포 프로세스의 일부로 신속하고 원활하게 제공됩니다.
|
||||
|
||||
### CI/CD의 중요성은?
|
||||
|
||||
- 소프트웨어를 빠르고 효율적으로 배포
|
||||
- 애플리케이션을 최대한 빠르게 시장에 출시하기 위한 효과적인 프로세스를 촉진합니다.
|
||||
- 버전 릴리스를 위해 몇 달 또는 몇 년을 기다릴 필요 없이 버그 수정 및 새로운 기능을 지속적으로 제공할 수 있습니다.
|
||||
|
||||
개발자가 영향력 있는 작은 변경을 정기적으로 수행할 수 있으므로 더 빠른 수정과 더 많은 기능을 더 빨리 얻을 수 있습니다.
|
||||
|
||||
### 자, 이게 무슨 뜻인가요?
|
||||
|
||||
[Day 5](day05.md)에서 데브옵스에 대한 많은 이론을 다뤘으며, 이미 여기에서 CI/CD 파이프라인이 최신 데브옵스 환경의 핵심이라고 언급했듯이, 이 파이프라인은 최신 데브옵스 환경의 기본입니다.
|
||||
|
||||

|
||||
|
||||
이제 데브옵스의 기본을 배우는 여정에 조금 더 들어섰으므로 위 이미지의 몇 가지 핵심 사항을 다시 한번 강조하고 싶습니다.
|
||||
|
||||
소프트웨어 개발 수명 주기(SDLC)를 언급하고 있습니다.
|
||||
|
||||
이 주기는 영원히 반복되는 주기이기 때문에 일반적으로 무한 루프 내에 단계가 기록됩니다.
|
||||
|
||||
개발자가 **코드**를 작성하면 **빌드**되거나 모두 컴파일되고, 버그가 있는지 **테스트**되고, 최종 사용자나 고객이 사용하는 프로덕션에 **배포**되고(**운영**), **모니터링** 및 피드백을 수집하고, 마지막으로 해당 피드백을 중심으로 개선 사항을 **계획**하고 반복하는 것이 이 주기의 단계입니다.
|
||||
|
||||
### CI/CD에 대해 좀 더 자세히 알아봅시다.
|
||||
|
||||
### CI
|
||||
|
||||
CI는 개발자가 하루에 여러 번 공유 리포지토리에 코드를 통합해야 하는 개발 관행입니다.
|
||||
|
||||
코드가 작성되어 Github 또는 GitLab과 같은 리포지토리에 push되면 마법이 시작됩니다.
|
||||
|
||||

|
||||
|
||||
자동화된 빌드를 통해 코드가 검증되므로 팀이나 프로젝트 소유자가 문제를 조기에 발견할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
여기에서 코드를 분석하고 일련의 자동화된 테스트를 수행하는데, 세 가지 예는 다음과 같습니다.
|
||||
|
||||
- 단위 테스트는 소스 코드의 개별 단위를 테스트합니다.
|
||||
- 유효성 검사 테스트는 소프트웨어가 의도된 용도를 충족하거나 적합한지 확인합니다.
|
||||
- 형식 테스트는 구문 및 기타 형식 지정 오류를 확인합니다.
|
||||
|
||||
이러한 테스트는 workflow로 생성된 다음 마스터 브랜치로 push할 때마다 실행되므로 거의 모든 주요 개발팀에는 일종의 CI/CD workflow가 있으며, 개발팀에서는 하루 종일 전 세계의 여러 팀에서 다양한 프로젝트를 진행하는 개발자로부터 새로운 코드가 들어올 수 있으므로 코드가 승인되기 전에 모든 사람이 같은 페이지에 있는지 확인하는 테스트의 자동화된 workflow를 구축하는 것이 더 효율적입니다. 사람이 매번 이 작업을 수행하려면 훨씬 더 오랜 시간이 걸립니다.
|
||||
|
||||

|
||||
|
||||
테스트가 완료되고 성공하면 컴파일하여 리포지토리로 보낼 수 있습니다. 예를 들어, 저는 DockerHub를 사용하고 있지만 파이프라인의 CD 측면에 활용되는 모든 곳이 될 수 있습니다.
|
||||
|
||||

|
||||
|
||||
따라서 이 프로세스는 소프트웨어 개발 프로세스와 매우 유사하며, 애플리케이션을 만들고, 버그를 추가하고, 수정한 다음 소스 제어를 업데이트하고, 테스트하면서 버전도 관리합니다.
|
||||
|
||||
다음 단계로 넘어가면 CD 요소인데, 일반적으로 상용 소프트웨어에서 볼 수 있는 CD 요소는 점점 더 많아지고 있으며, 오라클이나 Microsoft와 같은 공급업체로부터 소프트웨어를 받으면 DockerHub 유형 리포지토리에서 이를 소비한 다음 CD 파이프라인을 사용하여 환경에 배포하는 추세를 보게 될 것이라고 주장하고 싶습니다.
|
||||
|
||||
### CD
|
||||
|
||||
이제 테스트된 버전의 코드를 배포할 준비가 되었습니다. 소프트웨어 공급업체가 이 단계를 진행하겠지만, 저는 이것이 앞으로 우리 모두가 필요한 상용 소프트웨어를 배포하는 방식이 될 것이라고 굳게 믿습니다.
|
||||
|
||||
이제 코드를 환경에 배포할 차례입니다. 여기에는 프로덕션 환경뿐만 아니라 스테이징과 같은 다른 환경도 포함될 것입니다.
|
||||
|
||||

|
||||
|
||||
소프트웨어 배포 1일차에서 다음 단계는 올바른 코드 베이스를 올바른 환경으로 가져오고 있는지 확인하는 것입니다. 소프트웨어 리포지토리(DockerHub)에서 요소를 가져올 수도 있지만, 다른 코드 리포지토리에서 추가 구성, 예를 들어 애플리케이션에 대한 구성을 가져올 수도 있습니다. 아래 다이어그램에서는 DockerHub에서 소프트웨어의 최신 릴리스를 가져온 다음 이를 환경에 릴리스하는 동시에 Git 리포지토리에서 구성을 가져올 수 있습니다. CD 도구가 이 작업을 수행하여 모든 것을 환경에 push합니다.
|
||||
|
||||
이 작업은 동시에 수행되지 않을 가능성이 높습니다. 즉, 구성이 올바른지 확인하기 위해 스테이징 환경으로 이동하여 이 구성에 대해 실행한 후 테스트를 위한 수동 단계일 수도 있고, 이 코드를 프로덕션에 배포하기 전에 다시 자동화할 수도 있습니다(자동화로 가겠습니다).
|
||||
|
||||

|
||||
|
||||
그런 다음 애플리케이션의 v2가 나오면 이번에는 단계를 반복하여 애플리케이션 + 구성이 스테이징에 배포되어 모든 것이 정상인지 확인한 다음 프로덕션에 배포합니다.
|
||||
|
||||
### CI/CD를 사용하는 이유는 무엇인가요?
|
||||
|
||||
이미 여러 번 이점에 대해 설명했지만, 수동으로 수행해야 하는 작업을 자동화하여 작은 문제가 메인 코드 베이스에 들어가기 전에 발견하기 때문입니다. 고객에게 잘못된 코드를 push하면 큰 문제가 발생할 수 있다는 것을 상상할 수 있을 것입니다!
|
||||
|
||||
또한 메인 코드 리포지토리는 시간이 지남에 따라 지속적으로 구축되기 때문에 첫날에 수행한 지름길 수정이 몇 년 후 기하급수적으로 더 많은 비용이 드는 수정이 될 수 있다는 생각인 기술 부채를 방지하는 데 도움이 됩니다.
|
||||
|
||||
### 도구
|
||||
|
||||
다른 섹션과 마찬가지로 CI/CD 파이프라인 프로세스를 달성하는 몇 가지 도구에 대해 실습해 보겠습니다.
|
||||
|
||||
모든 도구가 CI와 CD를 모두 수행해야 하는 것은 아니며, 소프트웨어를 Kubernetes 클러스터에 배포하는 데 있어 CD 요소에 능숙한 ArgoCD를 살펴볼 것입니다. 하지만 Jenkins와 같은 것은 다양한 플랫폼에서 작동할 수도 있습니다.
|
||||
|
||||
저는 다음을 살펴볼 계획입니다:
|
||||
|
||||
- Jenkins
|
||||
- ArgoCD
|
||||
- GitHub Actions
|
||||
|
||||
## 자료
|
||||
|
||||
- [Jenkins is the way to build, test, deploy](https://youtu.be/_MXtbjwsz3A)
|
||||
- [Introduction to Jenkins](https://www.edx.org/course/introduction-to-jenkins)
|
||||
- [Jenkins.io](https://www.jenkins.io/)
|
||||
- [ArgoCD](https://argo-cd.readthedocs.io/en/stable/)
|
||||
- [ArgoCD Tutorial for Beginners](https://www.youtube.com/watch?v=MeU5_k9ssrs)
|
||||
- [What is Jenkins?](https://www.youtube.com/watch?v=LFDrDnKPOTg)
|
||||
- [Complete Jenkins Tutorial](https://www.youtube.com/watch?v=nCKxl7Q_20I&t=3s)
|
||||
- [GitHub Actions](https://www.youtube.com/watch?v=R8_veQiYBjI)
|
||||
- [GitHub Actions CI/CD](https://www.youtube.com/watch?v=mFFXuXjVgkU)
|
||||
|
||||
[Day 71](day71.md)에서 봐요!
|
105
2022/ko/Days/day71.md
Normal file
105
2022/ko/Days/day71.md
Normal file
@ -0,0 +1,105 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - What is Jenkins? - Day 71'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - What is Jenkins?
|
||||
tags: 'DevOps, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048745
|
||||
---
|
||||
|
||||
## Jenkins란 무엇인가요?
|
||||
|
||||
Jenkins는 새로 만든 코드를 지속적으로 개발, 테스트 및 배포할 수 있는 지속적 통합 도구입니다.
|
||||
|
||||
야간 빌드 또는 지속적 개발을 통해 이를 달성할 수 있는 방법에는 두 가지가 있습니다. 첫 번째 옵션은 개발자가 하루 종일 작업을 개발하다가 정해진 하루가 끝나면 변경 사항을 소스 코드 저장소에 push하는 것입니다. 그런 다음 밤에는 단위 테스트를 실행하고 소프트웨어를 빌드합니다. 이것이 모든 코드를 통합하는 오래된 방식이라고 할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
다른 옵션이자 선호되는 방식은 개발자가 소스 코드에 변경 사항을 커밋하고 해당 코드 커밋이 완료되면 빌드 프로세스가 지속적으로 시작되는 방식입니다.
|
||||
|
||||

|
||||
|
||||
위의 방법을 사용하면 전 세계에 분산된 개발자가 있는 경우 매일 정해진 시간에 코드 변경 사항 커밋을 중단할 수 없습니다. 이러한 테스트와 빌드 프로세스를 제어하기 위해 CI 서버 역할을 하는 것이 바로 Jenkins입니다.
|
||||
|
||||

|
||||
|
||||
여기서는 Jenkins에 대해 이야기하고 있지만 나중에 몇 가지를 더 추가하여 Jenkins가 전반적으로 가장 인기 있는 것으로 보이는 이유와 그 이유, 그리고 다른 도구가 Jenkins보다 무엇을 할 수 있는지에 대해 알아보고자 합니다.
|
||||
|
||||
- TravisCI - GitHub에서 호스팅되는 소프트웨어 프로젝트를 빌드하고 테스트하는 데 사용되는 호스팅된 분산형 지속적 통합 서비스입니다.
|
||||
- Bamboo - 빠른 컴파일을 위해 여러 빌드를 병렬로 실행할 수 있으며, 리포지토리와 연결할 수 있는 기능이 내장되어 있고 Ant 및 Maven용 빌드 작업이 있습니다.
|
||||
- Buildbot - 소프트웨어 빌드, 테스트 및 릴리스 프로세스를 자동화하기 위한 오픈 소스 프레임워크입니다. Python으로 작성되었으며 여러 플랫폼에서 작업의 분산 병렬 실행을 지원합니다.
|
||||
- Apache Gump - 매일 밤 Java 프로젝트를 빌드하고 테스트하도록 설계된 Java 프로젝트 전용으로, 모든 프로젝트가 API 및 기능 수준 모두에서 호환되도록 보장합니다.
|
||||
|
||||
이제부터는 Jenkins에 초점을 맞추겠습니다. Jenkins는 위의 모든 도구와 마찬가지로 오픈 소스이며 Java로 작성된 자동화 서버입니다. 지속적인 통합을 통해 소프트웨어 개발 프로세스를 자동화하고 지속적인 배포를 용이하게 하는 데 사용됩니다.
|
||||
|
||||
### Jenkins의 특징
|
||||
|
||||
예상할 수 있듯이 Jenkins는 다양한 영역에 걸쳐 많은 기능을 가지고 있습니다.
|
||||
|
||||
**간편한 설치** - Jenkins는 Windows, macOS 및 Linux 운영 체제용 패키지와 함께 실행할 준비가 된 독립형 자바 기반 프로그램입니다.
|
||||
|
||||
**간편한 구성** - 오류 확인 및 기본 제공 도움말이 포함된 웹 인터페이스를 통해 쉽게 설정 및 구성할 수 있습니다.
|
||||
|
||||
**플러그인** - 업데이트 센터에서 다양한 플러그인을 사용할 수 있으며 CI/CD 툴체인의 여러 도구와 통합됩니다.
|
||||
|
||||
**확장 가능** - 사용 가능한 플러그인 외에도 플러그인 아키텍처를 통해 Jenkins를 확장할 수 있어 거의 무한한 용도로 사용할 수 있는 옵션을 제공합니다.
|
||||
|
||||
**분산** - Jenkins는 여러 머신에 작업을 쉽게 분산하여 여러 플랫폼에서 빌드, 테스트 및 배포 속도를 높일 수 있도록 지원합니다.
|
||||
|
||||
### Jenkins 파이프라인
|
||||
|
||||
이 파이프라인을 보셨겠지만, 훨씬 광범위하게 사용되며 특정 도구에 대해서는 언급하지 않았습니다.
|
||||
|
||||
Jenkins에 코드를 커밋하면 모든 자동화된 테스트를 통해 애플리케이션을 빌드한 다음 각 단계가 완료되면 해당 코드를 릴리스 및 배포합니다. 이 프로세스를 자동화할 수 있는 것이 바로 Jenkins입니다.
|
||||
|
||||

|
||||
|
||||
### Jenkins 아키텍처
|
||||
|
||||
먼저, 바퀴를 재발명하고 싶지 않기 때문에 항상 [Jenkins 문서](https://www.jenkins.io/doc/developer/architecture/)에서 시작하는 것이 가장 좋지만, 여기에도 제가 메모하고 배운 내용을 적어 두려고 합니다.
|
||||
|
||||
Jenkins는 윈도우, 리눅스, 맥OS 등 다양한 운영체제에 설치할 수 있을 뿐만 아니라 Docker 컨테이너로 배포하거나 Kubernetes 내에서 배포할 수 있는 기능도 있습니다. [Jenkins 설치하기](https://www.jenkins.io/doc/book/installing/)
|
||||
|
||||
이번 글에서는 Minikube 클러스터 내에 Jenkins를 설치하여 Kubernetes에 배포하는 과정을 시뮬레이션해 보겠습니다. 하지만 이는 이 섹션의 나머지 부분에서 구성한 시나리오에 따라 달라집니다.
|
||||
|
||||
이제 아래 이미지를 분석해 보겠습니다.
|
||||
|
||||
1단계 - 개발자가 소스 코드 리포지토리에 변경 사항을 커밋합니다.
|
||||
|
||||
2단계 - Jenkins가 정기적으로 리포지토리를 확인하여 새 코드를 가져옵니다.
|
||||
|
||||
3단계 - 빌드 서버가 코드를 실행 파일로 빌드하며, 이 예에서는 잘 알려진 빌드 서버로 maven을 사용하고 있습니다. 다루어야 할 또 다른 영역입니다.
|
||||
|
||||
4단계 - 빌드에 실패하면 개발자에게 피드백이 다시 전송됩니다.
|
||||
|
||||
5단계 - 그런 다음 Jenkins는 빌드된 앱을 테스트 서버에 배포합니다. 이 예에서는 잘 알려진 테스트 서버로 selenium을 사용하고 있습니다. 또 다른 영역입니다.
|
||||
|
||||
6단계 - 테스트가 실패하면 개발자에게 피드백이 전달됩니다.
|
||||
|
||||
7단계 - 테스트가 성공하면 프로덕션에 릴리스할 수 있습니다.
|
||||
|
||||
이 주기는 연속적이기 때문에 애플리케이션을 몇 시간, 며칠, 몇 달, 몇 년이 아닌 몇 분 만에 업데이트할 수 있습니다!
|
||||
|
||||

|
||||
|
||||
필요한 경우 master가 slave Jenkins 환경에 작업을 배포할 수 있는 master-slave 기능이 있는 등 Jenkins의 아키텍처에는 훨씬 더 많은 기능이 있습니다.
|
||||
|
||||
참고로 Jenkins는 오픈 소스이므로 지원을 필요로 하는 많은 기업이 있을 것이며, CloudBees는 유료 엔터프라이즈 고객을 위한 지원 및 기타 기능을 제공하는 엔터프라이즈 버전의 Jenkins입니다.
|
||||
|
||||
고객 중 한 예로 Bosch를 들 수 있는데, Bosch 사례 연구는 [여기](https://assets.ctfassets.net/vtn4rfaw6n2j/case-study-boschpdf/40a0b23c61992ed3ee414ae0a55b6777/case-study-bosch.pdf)에서 확인할 수 있습니다.
|
||||
|
||||
내일은 애플리케이션의 단계별 예시를 통해 Jenkins를 사용하는 방법을 살펴본 다음 다른 도구와 함께 사용할 수 있도록 하겠습니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [Jenkins is the way to build, test, deploy](https://youtu.be/_MXtbjwsz3A)
|
||||
- [Jenkins.io](https://www.jenkins.io/)
|
||||
- [ArgoCD](https://argo-cd.readthedocs.io/en/stable/)
|
||||
- [ArgoCD Tutorial for Beginners](https://www.youtube.com/watch?v=MeU5_k9ssrs)
|
||||
- [What is Jenkins?](https://www.youtube.com/watch?v=LFDrDnKPOTg)
|
||||
- [Complete Jenkins Tutorial](https://www.youtube.com/watch?v=nCKxl7Q_20I&t=3s)
|
||||
- [GitHub Actions](https://www.youtube.com/watch?v=R8_veQiYBjI)
|
||||
- [GitHub Actions CI/CD](https://www.youtube.com/watch?v=mFFXuXjVgkU)
|
||||
|
||||
[Day 72](day72.md)에서 봐요!킨
|
162
2022/ko/Days/day72.md
Normal file
162
2022/ko/Days/day72.md
Normal file
@ -0,0 +1,162 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - Getting hands-on with Jenkins - Day 72'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - Getting hands-on with Jenkins
|
||||
tags: 'DevOps, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048829
|
||||
---
|
||||
|
||||
## Jenkins 실습하기
|
||||
|
||||
오늘 계획은 Jenkins를 직접 사용해 보고 CI 파이프라인의 일부로 사용할 수 있는 몇 가지 예제 코드 베이스를 살펴보면서 무언가를 만들어 보는 것입니다.
|
||||
|
||||
### 파이프라인이란 무엇인가요?
|
||||
|
||||
시작하기 전에 CI와 관련하여 파이프라인이 무엇인지 알아야 하는데, 어제 세션에서 이미 다음 이미지와 함께 이 내용을 다루었습니다.
|
||||
|
||||

|
||||
|
||||
위의 프로세스 또는 단계를 자동화하여 최종적으로 배포된 애플리케이션을 고객, 최종 사용자 등에게 제공할 수 있는 결과물을 얻고자 합니다.
|
||||
|
||||
이 자동화된 프로세스를 통해 사용자와 고객에 대한 버전 관리를 수행할 수 있습니다. 모든 변경 사항, 기능 향상, 버그 수정 등은 이 자동화된 프로세스를 거쳐 코드가 양호한지 확인하기 위해 많은 수동 개입 없이 모든 것이 정상인지 확인합니다.
|
||||
|
||||
이 프로세스에는 안정적이고 반복 가능한 방식으로 소프트웨어를 빌드하고, 여러 단계의 테스트 및 배포를 통해 빌드된 소프트웨어('build'라고 함)를 발전시키는 작업이 포함됩니다.
|
||||
|
||||
Jenkins 파이프라인은 Jenkins파일이라는 텍스트 파일로 작성됩니다. 이 파일은 소스 제어 리포지토리에 커밋되어야 합니다. 이를 코드형 파이프라인이라고도 하며, 몇 주 전에 다룬 IaC에 매우 유사하게 비유할 수도 있습니다.
|
||||
|
||||
[Jenkins 파이프라인 정의](https://www.jenkins.io/doc/book/pipeline/#ji-toolbar)
|
||||
|
||||
### Jenkins 배포하기
|
||||
|
||||
Jenkins 배포를 재미있게 해봤는데요, [문서](https://www.jenkins.io/doc/book/installing/)를 보면 Jenkins를 설치할 수 있는 위치에 대한 옵션이 많다는 것을 알 수 있습니다.
|
||||
|
||||
저는 Minikube를 가지고 있고 이를 여러 번 사용했기 때문에 이 작업에도 Minikube를 사용하고 싶었습니다. (또한 무료입니다!) [Kubernetes 설치](https://www.jenkins.io/doc/book/installing/kubernetes/)에 나와 있는 단계는 벽에 부딪혀서 실행하지 못했지만, 여기에 단계를 문서화하면 두 가지를 비교할 수 있습니다.
|
||||
|
||||
첫 번째 단계는 Minikube 클러스터를 시작하고 실행하는 것으로, `minikube start` 명령으로 간단히 할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
여기에서 찾을 수 있는 모든 YAML 구성과 값이 있는 폴더를 [여기](/2022/Days/CICD/Jenkins) 추가했습니다.이제 클러스터가 생겼으므로 다음을 실행하여 jenkins 네임스페이스를 생성할 수 있습니다. `kubectl create -f jenkins-namespace.yml`
|
||||
|
||||

|
||||
|
||||
클러스터에 Jenkins를 배포하기 위해 Helm을 사용할 것이며, Helm은 Kubernetes 섹션에서 다루었습니다. 먼저 jenkinsci Helm 리포지토리 `helm repo add jenkinsci https://charts.jenkins.io`를 추가한 다음 `helm repo update` chart를 업데이트해야 합니다.
|
||||
|
||||

|
||||
|
||||
Jenkins의 기본 개념은 파이프라인의 상태를 저장하는 것으로, 위의 Helm 설치를 지속성 없이 실행할 수 있지만 해당 pod가 재부팅, 변경 또는 수정되면 생성한 파이프라인이나 구성이 손실됩니다. `kubectl apply -f jenkins-volume.yml` 명령으로 jenkins-volume.yml 파일을 사용하여 지속성을 위한 volume을 생성합니다.
|
||||
|
||||

|
||||
|
||||
또한 이 YAML 파일과 명령어를 사용하여 생성할 수 있는 서비스 계정이 필요합니다. `kubectl apply -f jenkins-sa.yml`
|
||||
|
||||

|
||||
이 단계에서는 Helm chart를 사용하여 배포하는 것이 좋으며, 먼저 `chart=jenkinsci/jenkins`를 사용하여 chart를 정의한 다음, 이 명령을 사용하여 배포할 것이며, 여기에는 이전에 클러스터에 배포한 지속성 및 서비스 계정이 포함된 jenkins-values.yml이 포함됩니다. `helm install jenkins -n jenkins -f jenkins-values.yml $chart`
|
||||
|
||||

|
||||
|
||||
이 단계에서는 pod가 이미지를 가져올 것이지만 pod가 스토리지에 액세스할 수 없으므로 Jenkins를 시작하고 실행하기 위한 구성을 시작할 수 없습니다.
|
||||
|
||||
이 단계에서는 문서가 무슨 일이 일어나야 하는지 이해하는 데 큰 도움이 되지 않았습니다. 하지만 Jenkins 설치를 시작할 수 있는 권한이 없다는 것을 알 수 있습니다.
|
||||
|
||||

|
||||
|
||||
위의 문제를 수정하거나 해결하려면, 우리가 제안한 이 위치에 Jenkins pod가 쓸 수 있도록 액세스 권한 또는 올바른 권한을 제공해야 합니다. 이를 위해 `minikube ssh`를 사용하여 실행 중인 Minikube Docker 컨테이너에 들어간 다음 `sudo chown -R 1000:1000 /data/jenkins-volume`을 사용하여 데이터 volume에 대한 권한이 설정되어 있는지 확인할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
위의 프로세스로 pod가 수정되어야 하지만, 그렇지 않은 경우 `kubectl delete pod jenkins-0 -n jenkins` 명령으로 pod를 강제로 새로 고칠 수 있습니다. 이 시점에서, 2/2의 실행 중인 pod인 jenkins-0이 있어야 합니다.
|
||||
|
||||

|
||||
|
||||
이제 관리자 비밀번호가 필요하며 다음 명령어를 사용하여 비밀번호를 입력할 수 있습니다. `kubectl exec --namespace jenkins -it svc/jenkins -c jenkins -- /bin/cat /run/secrets/chart-admin-password && echo`
|
||||
|
||||

|
||||
|
||||
이제 워크스테이션에서 접근할 수 있도록 `port-forward` 명령을 사용할 것이므로 새 터미널을 엽니다. `kubectl --namespace jenkins port-forward svc/jenkins 8080:8080`
|
||||
|
||||

|
||||
|
||||
이제 브라우저를 열고 `http://localhost:8080`에 로그인하여 이전 단계에서 수집한 username: admin과 password로 인증할 수 있어야 합니다.
|
||||
|
||||

|
||||
|
||||
인증이 완료되면 Jenkins 시작 페이지는 다음과 같이 표시되어야 합니다:
|
||||
|
||||

|
||||
|
||||
여기에서 "Manage Jenkins"로 이동하면 사용 가능한 몇 가지 업데이트가 있는 "Manage Plugins"가 표시됩니다. 해당 플러그인을 모두 선택하고 "Download now and install after restart"를 선택합니다.
|
||||
|
||||

|
||||
|
||||
더 나아가 shell 스크립트를 사용하여 Jenkins 배포를 자동화하고 싶다면 트위터에서 저와 공유한 이 훌륭한 리포지토리를 참고하세요 [mehyedes/nodejs-k8s](https://github.com/mehyedes/nodejs-k8s/blob/main/docs/automated-setup.md).
|
||||
|
||||
### Jenkinsfile
|
||||
|
||||
이제 Kubernetes 클러스터에 Jenkins가 배포되었으므로 이제 돌아가서 이 Jenkinsfile에 대해 생각해 볼 수 있습니다.
|
||||
|
||||
모든 Jenkinsfile은 이렇게 시작될 가능성이 높습니다. 먼저 파이프라인의 단계를 정의하는 곳이며, 이 경우에는 빌드 > 테스트 > 배포가 있습니다. 하지만 여기서는 특정 단계를 호출하기 위해 `echo` 명령을 사용하는 것 외에는 아무것도 하지 않습니다.
|
||||
|
||||
```
|
||||
Jenkinsfile (Declarative Pipeline)
|
||||
|
||||
pipeline {
|
||||
agent any
|
||||
|
||||
stages {
|
||||
stage('Build') {
|
||||
steps {
|
||||
echo 'Building..'
|
||||
}
|
||||
}
|
||||
stage('Test') {
|
||||
steps {
|
||||
echo 'Testing..'
|
||||
}
|
||||
}
|
||||
stage('Deploy') {
|
||||
steps {
|
||||
echo 'Deploying....'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Jenkins 대시보드에서 "New Item"을 선택하고 항목에 이름을 지정합니다. 저는 "echo1"이라고 하고 이것이 파이프라인이라고 해보겠습니다.
|
||||
|
||||

|
||||
|
||||
확인을 누르면 파이프라인에만 관심이 있는 간단한 테스트를 위한 탭(일반, 빌드 트리거, 고급 프로젝트 옵션 및 파이프라인)이 표시됩니다. 파이프라인에서 스크립트를 추가할 수 있으며, 위의 스크립트를 복사하여 상자에 붙여 넣을 수 있습니다.
|
||||
|
||||
위에서 말했듯이 이것은 많은 작업을 수행하지는 않지만 빌드 > 테스트 > 배포의 단계를 보여줍니다.
|
||||
|
||||

|
||||
|
||||
저장을 클릭하면 이제 아래에 강조 표시된 "build now"를 사용하여 빌드를 실행할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
또한 터미널을 열고 `kubectl get pods -n jenkins`를 실행하여 어떤 일이 발생하는지 확인해야 합니다.
|
||||
|
||||

|
||||
|
||||
자, 아주 간단하지만 이제 Jenkins 배포와 설치가 올바르게 작동하고 있으며 여기에서 CI 파이프라인의 구성 요소를 볼 수 있습니다.
|
||||
|
||||
다음 섹션에서는 Jenkins 파이프라인을 구축하겠습니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [Jenkins is the way to build, test, deploy](https://youtu.be/_MXtbjwsz3A)
|
||||
- [Jenkins.io](https://www.jenkins.io/)
|
||||
- [ArgoCD](https://argo-cd.readthedocs.io/en/stable/)
|
||||
- [ArgoCD Tutorial for Beginners](https://www.youtube.com/watch?v=MeU5_k9ssrs)
|
||||
- [What is Jenkins?](https://www.youtube.com/watch?v=LFDrDnKPOTg)
|
||||
- [Complete Jenkins Tutorial](https://www.youtube.com/watch?v=nCKxl7Q_20I&t=3s)
|
||||
- [GitHub Actions](https://www.youtube.com/watch?v=R8_veQiYBjI)
|
||||
- [GitHub Actions CI/CD](https://www.youtube.com/watch?v=mFFXuXjVgkU)
|
||||
|
||||
[Day 73](day73.md)에서 봐요!
|
226
2022/ko/Days/day73.md
Normal file
226
2022/ko/Days/day73.md
Normal file
@ -0,0 +1,226 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - Building a Jenkins Pipeline - Day 73'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - Building a Jenkins Pipeline
|
||||
tags: 'DevOps, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048766
|
||||
---
|
||||
|
||||
## Jenkins 파이프라인 구축하기
|
||||
|
||||
지난 섹션에서는 Minikube 클러스터에 Jenkins를 배포하고 파이프라인의 단계를 echo하는 것 외에는 별다른 기능을 하지 않는 매우 기본적인 Jenkins 파이프라인을 설정했습니다.
|
||||
|
||||
또한 Jenkins Pipeline 생성에서 실행할 수 있는 몇 가지 예제 스크립트가 있다는 것을 보셨을 것입니다.
|
||||
|
||||

|
||||
|
||||
첫 번째 데모 스크립트는 "Declarative (Kubernetes)"이며 아래 단계를 볼 수 있습니다.
|
||||
|
||||
```Yaml
|
||||
// Uses Declarative syntax to run commands inside a container.
|
||||
pipeline {
|
||||
agent {
|
||||
kubernetes {
|
||||
// Rather than inline YAML, in a multibranch Pipeline you could use: yamlFile 'jenkins-pod.yaml'
|
||||
// Or, to avoid YAML:
|
||||
// containerTemplate {
|
||||
// name 'shell'
|
||||
// image 'ubuntu'
|
||||
// command 'sleep'
|
||||
// args 'infinity'
|
||||
// }
|
||||
yaml '''
|
||||
apiVersion: v1
|
||||
kind: Pod
|
||||
spec:
|
||||
containers:
|
||||
- name: shell
|
||||
image: ubuntu
|
||||
command:
|
||||
- sleep
|
||||
args:
|
||||
- infinity
|
||||
'''
|
||||
// Can also wrap individual steps:
|
||||
// container('shell') {
|
||||
// sh 'hostname'
|
||||
// }
|
||||
defaultContainer 'shell'
|
||||
}
|
||||
}
|
||||
stages {
|
||||
stage('Main') {
|
||||
steps {
|
||||
sh 'hostname'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
이 파이프라인을 실행하면 어떤 결과가 발생하는지 아래에서 확인할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
### Job 만들기
|
||||
|
||||
#### 목표
|
||||
|
||||
- 간단한 앱을 만들어 GitHub 공용 리포지토리에 저장 [https://github.com/scriptcamp/kubernetes-kaniko.git](https://github.com/scriptcamp/kubernetes-kaniko.git)
|
||||
|
||||
- Jenkins를 사용하여 Docker 컨테이너 이미지를 빌드하고 DockerHub에 push합니다. (이를 위해 비공개 리포지토리를 사용합니다.)
|
||||
|
||||
Minikube에서 실행 중이거나 Minikube를 사용하는 Kubernetes 클러스터에서 이 작업을 수행하려면 [Kaniko](https://github.com/GoogleContainerTools/kaniko#running-kaniko-in-a-kubernetes-cluster)라는 것을 사용해야 하지만, 실제 Kubernetes 클러스터에서 Jenkins를 사용하거나 서버에서 실행하는 경우 에이전트를 지정하여 Docker 빌드 명령을 수행하고 이를 DockerHub에 업로드할 수 있는 기능을 제공하는 것이 일반적입니다.
|
||||
|
||||
위의 내용을 염두에 두고 GitHub credentials로 Kubernetes에 시크릿을 배포해 보겠습니다.
|
||||
|
||||
```Shell
|
||||
kubectl create secret docker-registry dockercred \
|
||||
--docker-server=https://index.docker.io/v1/ \
|
||||
--docker-username=<dockerhub-username> \
|
||||
--docker-password=<dockerhub-password>\
|
||||
--docker-email=<dockerhub-email>
|
||||
```
|
||||
|
||||
여기서 다룰 내용 대부분을 관통하는 [DevOpsCube.com](https://devopscube.com/build-docker-image-kubernetes-pod/)의 또 다른 훌륭한 리소스를 공유하고자 합니다.
|
||||
|
||||
### Jenkins에 credentials 추가하기
|
||||
|
||||
하지만 저희와 다른 Jenkins 시스템을 사용 중이라면 Jenkins 내에서 credentials를 정의한 다음 파이프라인 및 구성 내에서 여러 번 사용하고 싶을 것입니다. 생성 시 결정한 ID를 사용하여 파이프라인에서 이러한 credentials를 참조할 수 있습니다. 계속해서 단계를 진행하여 DockerHub 및 GitHub에 대한 사용자 항목을 만들었습니다.
|
||||
|
||||
먼저 "Manage Jenkins"를 선택한 다음 "Manage Credentials"를 선택합니다.
|
||||
|
||||

|
||||
|
||||
페이지 중앙에 Jenkins로 범위가 설정된 Stores가 표시되면 여기에서 Jenkins를 클릭합니다.
|
||||
|
||||

|
||||
|
||||
이제 Global Credentials (Unrestricted)를 선택합니다.
|
||||
|
||||

|
||||
|
||||
그런 다음 왼쪽 상단에 Add Credentials가 있습니다.
|
||||
|
||||

|
||||
|
||||
계정에 대한 세부 정보를 입력한 다음 확인을 선택하고, 이 credentials를 호출할 때 참조할 ID를 기억하세요. 여기서도 비밀번호 대신 특정 토큰 액세스를 사용하는 것이 좋습니다.
|
||||
|
||||

|
||||
|
||||
GitHub의 경우 [Personal Access Token](https://vzilla.co.uk/vzilla-blog/creating-updating-your-github-personal-access-token)을 사용해야 합니다.
|
||||
|
||||
저는 이 계정을 생성하는 과정이 직관적이지 않아서 사용하지는 않지만, UI에서 명확하지 않아서 그 과정을 공유하고 싶었습니다.
|
||||
|
||||
### 파이프라인 구축
|
||||
|
||||
Kubernetes 클러스터에 비밀로 배포된 DockerHub credentials를 가지고 있으며, 이 credentials를 파이프라인의 DockerHub 단계에 배포하기 위해 호출할 것입니다.
|
||||
|
||||
파이프라인 스크립트는 아래에서 볼 수 있는 것과 같으며, 파이프라인의 프로젝트 가져오기 단계에서도 볼 수 있는 GitHub 리포지토리에 있는 Jenkinsfile이 될 수 있습니다.
|
||||
|
||||
```Yaml
|
||||
podTemplate(yaml: '''
|
||||
apiVersion: v1
|
||||
kind: Pod
|
||||
spec:
|
||||
containers:
|
||||
- name: maven
|
||||
image: maven
|
||||
command:
|
||||
- sleep
|
||||
args:
|
||||
- 99d
|
||||
- name: kaniko
|
||||
image: gcr.io/kaniko-project/executor:debug
|
||||
command:
|
||||
- sleep
|
||||
args:
|
||||
- 9999999
|
||||
volumeMounts:
|
||||
- name: kaniko-secret
|
||||
mountPath: /kaniko/.docker
|
||||
restartPolicy: Never
|
||||
volumes:
|
||||
- name: kaniko-secret
|
||||
secret:
|
||||
secretName: dockercred
|
||||
items:
|
||||
- key: .dockerconfigjson
|
||||
path: config.json
|
||||
''') {
|
||||
node(POD_LABEL) {
|
||||
stage('Get the project') {
|
||||
git url: 'https://github.com/scriptcamp/kubernetes-kaniko.git', branch: 'main'
|
||||
container('maven') {
|
||||
stage('Test the project') {
|
||||
sh '''
|
||||
echo pwd
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Build & Test the Docker Image') {
|
||||
container('kaniko') {
|
||||
stage('Deploy to DockerHub') {
|
||||
sh '''
|
||||
/kaniko/executor --context `pwd` --destination me1e/helloword
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Jenkins 대시보드에서 항목을 시작하려면 "New Item"을 선택해야 합니다.
|
||||
|
||||

|
||||
|
||||
그런 다음 항목에 이름을 지정하고 파이프라인을 선택한 다음 확인을 누릅니다.
|
||||
|
||||

|
||||
|
||||
일반 트리거나 빌드 트리거는 선택하지 않겠지만 흥미로운 일정과 기타 구성이 있을 수 있으므로 이 트리거를 사용해 보겠습니다.
|
||||
|
||||

|
||||
|
||||
마지막에 있는 Pipeline 탭에만 관심이 있습니다.
|
||||
|
||||

|
||||
|
||||
파이프라인 정의에서 위에 있는 파이프라인 스크립트를 스크립트 섹션에 복사하여 붙여 넣고 저장을 누릅니다.
|
||||
|
||||

|
||||
|
||||
다음으로 페이지 왼쪽에서 "Build Now" 옵션을 선택합니다.
|
||||
|
||||

|
||||
|
||||
이제 1분 미만의 짧은 시간을 기다려야 합니다. Status 아래에 위에서 스크립트에서 정의한 단계가 표시됩니다.
|
||||
|
||||

|
||||
|
||||
더 중요한 것은 이제 DockerHub로 이동하여 새 빌드가 있는지 확인하는 것입니다.
|
||||
|
||||

|
||||
|
||||
전체적으로 파악하는 데 시간이 좀 걸렸지만, Minikube와 GitHub 및 DockerHub에 대한 액세스를 사용하여 누구나 실행할 수 있는 시나리오를 실습하고 작업하기 위해 계속 진행하려고 했습니다.
|
||||
|
||||
이 데모에 사용한 DockerHub 리포지토리는 비공개 리포지토리였습니다. 하지만 다음 섹션에서는 이러한 단계 중 일부를 발전시켜 단순히 `pwd`를 출력하고 몇 가지 테스트 및 빌드 단계를 실행하는 대신 무언가를 수행하도록 하고 싶습니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [Jenkins is the way to build, test, deploy](https://youtu.be/_MXtbjwsz3A)
|
||||
- [Jenkins.io](https://www.jenkins.io/)
|
||||
- [ArgoCD](https://argo-cd.readthedocs.io/en/stable/)
|
||||
- [ArgoCD Tutorial for Beginners](https://www.youtube.com/watch?v=MeU5_k9ssrs)
|
||||
- [What is Jenkins?](https://www.youtube.com/watch?v=LFDrDnKPOTg)
|
||||
- [Complete Jenkins Tutorial](https://www.youtube.com/watch?v=nCKxl7Q_20I&t=3s)
|
||||
- [GitHub Actions](https://www.youtube.com/watch?v=R8_veQiYBjI)
|
||||
- [GitHub Actions CI/CD](https://www.youtube.com/watch?v=mFFXuXjVgkU)
|
||||
|
||||
[Day 74](day74.md)에서 봐요!
|
96
2022/ko/Days/day74.md
Normal file
96
2022/ko/Days/day74.md
Normal file
@ -0,0 +1,96 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - Hello World - Jenkinsfile App Pipeline - Day 74'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - Hello World - Jenkinsfile App Pipeline
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048744
|
||||
---
|
||||
|
||||
## Hello World - Jenkinsfile 앱 파이프라인
|
||||
|
||||
지난 섹션에서는 공개 GitHub 리포지토리에 있는 dockerfile에서 비공개 Dockerhub 리포지토리로 docker 이미지를 push하는 간단한 Jenkins 파이프라인을 구축했습니다.
|
||||
|
||||
이 섹션에서는 한 단계 더 나아가 간단한 애플리케이션을 통해 다음을 달성하고자 합니다.
|
||||
|
||||
### 목표
|
||||
|
||||
- Dockerfile (Hello World)
|
||||
- Jenkinsfile
|
||||
- GitHub 리포지토리가 업데이트될 때 트리거할 Jenkins 파이프라인
|
||||
- GitHub 리포지토리를 소스로 사용
|
||||
- Run - 리포지토리 복제/가져오기, 빌드, 테스트, 배포 단계
|
||||
- 점진적인 버전 번호로 DockerHub에 배포
|
||||
- Kubernetes 클러스터에 배포하는(여기에는 GitHub credentials를 사용하는 다른 job 및 매니페스트 리포지토리가 포함됨) Stretch Goal
|
||||
|
||||
### 1단계
|
||||
|
||||
[GitHub 리포지토리](https://github.com/MichaelCade/Jenkins-HelloWorld)가 있습니다. 여기에는 현재 Dockerfile과 index.html이 있습니다.
|
||||
|
||||

|
||||
|
||||
위에서 파이프라인에서 소스로 사용하던 것을 이제 해당 Jenkins 파이프라인 스크립트를 GitHub 리포지토리에도 추가하려고 합니다.
|
||||
|
||||

|
||||
|
||||
이제 Jenkins 대시보드로 돌아가서 새 파이프라인을 만들되, 스크립트를 붙여 넣는 대신 "Pipeline script from SCM"를 사용하고 아래의 구성 옵션을 사용하겠습니다.
|
||||
|
||||
참고로 리포지토리 URL은 `https://github.com/MichaelCade/Jenkins-HelloWorld.git`을 사용하겠습니다.
|
||||
|
||||

|
||||
|
||||
이 시점에서 저장 및 적용을 누르면 수동으로 파이프라인을 실행하여 DockerHub 리포지토리에 업로드된 새 Docker 이미지를 빌드할 수 있습니다.
|
||||
|
||||
하지만 리포지토리 또는 소스 코드가 변경될 때마다 빌드를 트리거하도록 일정을 설정하고 싶습니다. webhooks를 사용하거나 예약 pull을 사용할 수 있습니다.
|
||||
|
||||
파이프라인을 유지하기 위해 값비싼 클라우드 리소스를 사용하고 있고 코드 저장소에 변경 사항이 많다면 많은 비용이 발생할 수 있으므로 이 점을 크게 고려해야 합니다. 이것이 데모 환경이라는 것을 알고 있기 때문에 "poll scm" 옵션을 사용하고 있습니다. (또한 Minikube를 사용하면 webhooks를 사용할 수 있는 기능이 부족하다고 생각합니다.)
|
||||
|
||||

|
||||
|
||||
어제 세션 이후 변경한 한 가지는 이제 이미지를 공개 저장소(이 경우 michaelcade1\90DaysOfDevOps)에 업로드하고 싶다는 것인데, 제 Jenkinsfile에는 이미 이 변경 사항이 있습니다. 그리고 이전 섹션에서 기존 데모 컨테이너 이미지를 모두 제거했습니다.
|
||||
|
||||

|
||||
|
||||
여기서 거꾸로 돌아가서 파이프라인을 생성한 다음 이전에 표시된 대로 구성을 추가했습니다.
|
||||
|
||||

|
||||
|
||||
이 단계에서는 파이프라인이 실행되지 않았으며 스테이지 뷰는 다음과 같이 표시됩니다.
|
||||
|
||||

|
||||
|
||||
이제 "Build Now" 버튼을 트리거해 보겠습니다. 그러면 스테이지 뷰에 스테이지가 표시됩니다.
|
||||
|
||||

|
||||
|
||||
이제 DockerHub 리포지토리로 이동하면 2개의 새 Docker 이미지가 있어야 합니다. 빌드 ID는 1이고 최신 빌드가 있어야 하는데, 이는 "Upload to DockerHub"를 기반으로 생성하는 모든 빌드에 대해 Jenkins Build_ID 환경 변수를 사용하여 버전을 전송하고 최신 빌드도 발행하기 때문입니다.
|
||||
|
||||

|
||||
|
||||
이제 아래와 같이 깃허브 리포지토리에 index.html 파일을 업데이트해 보겠습니다.
|
||||
|
||||

|
||||
|
||||
Jenkins로 돌아가서 "Build Now"를 다시 선택하면 됩니다. 2번 빌드가 성공했는지 확인해 보겠습니다.
|
||||
|
||||

|
||||
|
||||
그런 다음 DockerHub를 간단히 살펴보면 태그가 버전 2와 최신 태그가 있는 것을 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
여기서 한 가지 주목할 점은, 제가 Kubernetes 클러스터에 액세스 및 인증을 통해 DockerHub로 도커 빌드를 push할 수 있는 시크릿을 추가했다는 것입니다. 이 과정을 따라하는 경우 계정에 대해 이 과정을 반복하고 내 리포지토리 및 계정과 연결된 Jenkins파일도 변경해야 합니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [Jenkins is the way to build, test, deploy](https://youtu.be/_MXtbjwsz3A)
|
||||
- [Jenkins.io](https://www.jenkins.io/)
|
||||
- [ArgoCD](https://argo-cd.readthedocs.io/en/stable/)
|
||||
- [ArgoCD Tutorial for Beginners](https://www.youtube.com/watch?v=MeU5_k9ssrs)
|
||||
- [What is Jenkins?](https://www.youtube.com/watch?v=LFDrDnKPOTg)
|
||||
- [Complete Jenkins Tutorial](https://www.youtube.com/watch?v=nCKxl7Q_20I&t=3s)
|
||||
- [GitHub Actions](https://www.youtube.com/watch?v=R8_veQiYBjI)
|
||||
- [GitHub Actions CI/CD](https://www.youtube.com/watch?v=mFFXuXjVgkU)
|
||||
|
||||
[Day 75](day75.md)에서 봐요!
|
188
2022/ko/Days/day75.md
Normal file
188
2022/ko/Days/day75.md
Normal file
@ -0,0 +1,188 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - GitHub Actions Overview - Day 75'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - GitHub Actions Overview
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1049070
|
||||
---
|
||||
|
||||
## GitHub Actions 개요
|
||||
|
||||
이 섹션에서는 방금 시간을 할애한 것과는 다른 접근 방식을 살펴보고자 합니다. 이 세션에서 집중적으로 다룰 내용은 GitHub Actions입니다.
|
||||
|
||||
GitHub Actions는 파이프라인의 다른 작업들 사이에서 빌드, 테스트 및 배포할 수 있는 CI/CD 플랫폼입니다. 이 플랫폼은 GitHub 리포지토리를 대상으로 빌드하고 테스트하는 Wolkflow의 개념을 가지고 있습니다. 또한 GitHub Actions를 사용하여 리포지토리 내에서 발생하는 Event를 기반으로 다른 Wolkflow를 구동할 수도 있습니다.
|
||||
|
||||
### Wolkflow
|
||||
|
||||
전반적으로 GitHub Actions에서는 작업을 **Wolkflow**라고 부릅니다.
|
||||
|
||||
- **Wolkflow**는 구성 가능한 자동화된 프로세스입니다.
|
||||
- YAML 파일로 정의됩니다.
|
||||
- 하나 이상의 **Job**을 포함하고 실행합니다.
|
||||
- 리포지토리의 **Event**에 의해 트리거될 때 실행되거나 수동으로 실행할 수 있습니다.
|
||||
- 리포지토리당 여러 Wolkflow를 사용할 수 있습니다.
|
||||
- **Wolkflow**에는 **Job**과 해당 **Job**을 달성하기 위한 **Step**이 포함됩니다.
|
||||
- **Wolkflow** 내에는 **Wolkflow**가 실행되는 **Runner**도 있습니다.
|
||||
|
||||
예를 들어 PR을 빌드하고 테스트하는 **Wolkflow**, 릴리스가 만들어질 때마다 애플리케이션을 배포하는 **Wolkflow**, 누군가 새 issue를 열 때마다 레이블을 추가하는 또 다른 **Wolkflow**가 있을 수 있습니다.
|
||||
|
||||
### Event
|
||||
|
||||
Event는 Wolkflow를 실행하도록 트리거하는 리포지토리의 특정 이벤트입니다.
|
||||
|
||||
### Job
|
||||
|
||||
Job은 Runner에서 실행되는 Wolkflow의 Step 집합입니다.
|
||||
|
||||
### Step
|
||||
|
||||
Job 내의 각 Ste은 실행되는 shell 스크립트 또는 Action이 될 수 있습니다. Step은 순서대로 실행되며 서로 종속됩니다.
|
||||
|
||||
### Action
|
||||
|
||||
자주 반복되는 작업에는 반복 가능한 사용자 지정 애플리케이션이 사용됩니다.
|
||||
|
||||
### Runner
|
||||
|
||||
Runner는 Wolkflow를 실행하는 서버로, 각 Runner는 한 번에 하나의 작업을 실행합니다. GitHub Actions는 Ubuntu Linux, Microsoft Windows 및 macOS Runner를 실행할 수 있는 기능을 제공합니다. 특정 OS 또는 하드웨어에서 직접 호스팅할 수도 있습니다.
|
||||
|
||||
아래에서 Wolkflow를 트리거하는 Event > Wolkflow가 두 개의 Job으로 구성 > 작업 내에 단계와 액션이 있는 모습을 볼 수 있습니다.
|
||||
|
||||
아래에서 Wolkflow를 트리거하는 Event가 있고 > Wolkflow가 두 개의 Job으로 구성되어 있으며 > Job 내에 Step가 있고 > Action이 있는 것을 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
### YAML
|
||||
|
||||
실제 사용 사례를 살펴보기 전에 위의 이미지를 예제 YAML 파일 형태로 간단히 살펴봅시다.
|
||||
|
||||
주석을 추가하여 YAML Wolkflow의 구성 요소를 찾을 수 있도록 했습니다.
|
||||
|
||||
```Yaml
|
||||
#Workflow
|
||||
name: 90DaysOfDevOps
|
||||
#Event
|
||||
on: [push]
|
||||
#Jobs
|
||||
jobs:
|
||||
check-bats-version:
|
||||
#Runner
|
||||
runs-on: ubuntu-latest
|
||||
#Steps
|
||||
steps:
|
||||
#Actions
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-node@v2
|
||||
with:
|
||||
node-version: '14'
|
||||
- run: npm install -g bats
|
||||
- run: bats -v
|
||||
```
|
||||
|
||||
### GitHub Actions 실습하기
|
||||
|
||||
코드 빌드, 테스트, 배포 및 그 이후의 지속적인 단계와 관련하여 CI/CD 요구 사항을 충족할 수 있는 GitHub Actions에는 많은 옵션이 있다고 생각합니다.
|
||||
|
||||
GitHub Actions를 사용할 수 있는 많은 옵션과 기타 자동화된 작업을 볼 수 있습니다.
|
||||
|
||||
### 코드 lint에 GitHub 액션 사용하기
|
||||
|
||||
한 가지 옵션은 리포지토리 내에서 코드를 깨끗하고 깔끔하게 정리하는 것입니다. 이것이 첫 번째 예제 데모가 될 것입니다.
|
||||
|
||||
이 섹션의 리소스 중 하나에 링크된 몇 가지 예제 코드를 사용하여 `GitHub/super-linter`를 사용하여 코드를 확인하겠습니다.
|
||||
|
||||
```Yaml
|
||||
name: Super-Linter
|
||||
|
||||
on: push
|
||||
|
||||
jobs:
|
||||
super-lint:
|
||||
name: Lint code base
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Run Super-Linter
|
||||
uses: github/super-linter@v3
|
||||
env:
|
||||
DEFAULT_BRANCH: main
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
```
|
||||
|
||||
**github/super-linter**
|
||||
위에서 단계 중 하나에 GitHub/super-linter라는 Action이 있으며 이는 커뮤니티에서 이미 작성된 Step을 참조하고 있음을 알 수 있습니다. 이에 대한 자세한 내용은 [Super-Linter](https://github.com/github/super-linter)에서 확인할 수 있습니다.
|
||||
|
||||
"이 리포지토리는 super-linter를 실행하기 위한 Github Actions를 위한 저장소입니다. 소스 코드의 유효성을 검사하는 데 도움이 되도록 bash로 작성된 다양한 linter의 간단한 조합입니다."
|
||||
|
||||
또한 위의 코드 스니펫에 GITHUB_TOKEN이 언급되어 있어서 이것이 왜 필요한지, 어떤 용도로 사용되는지 궁금했습니다.
|
||||
|
||||
"참고: Wolkflow에서 환경 변수 `GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}`을 전달하면 GitHub Super-Linter가 PR의 Checks 섹션에 각 linter 실행 상태를 표시합니다. 이 기능이 없으면 전체 실행의 전체 상태만 볼 수 있습니다. **GitHub Secret은 GitHub에서 자동으로 설정하므로 설정할 필요가 없으며, Action으로 전달하기만 하면 됩니다.**"
|
||||
|
||||
굵은 텍스트는 이 단계에서 주목해야 할 중요한 부분입니다. 우리는 이 기능을 사용하지만, 리포지토리 내에서 환경 변수를 설정할 필요는 없습니다.
|
||||
|
||||
테스트할 리포지토리는 Jenkins 데모에서 사용한 리포지토리를 사용하겠습니다. [Jenkins-HelloWorld](https://github.com/MichaelCade/Jenkins-HelloWorld).
|
||||
|
||||
다음은 Jenkins 세션에 남겨둔 저장소입니다.
|
||||
|
||||

|
||||
|
||||
이 기능을 활용하려면 위의 Actions 탭을 사용하여 곧 다룰 마켓플레이스에서 선택하거나 위의 super-linter 코드를 사용하여 파일을 생성할 수 있는데, 직접 생성하려면 리포지토리에 이 위치에 새 파일을 만들어야 합니다. `.github/workflows/workflow_name`은 분명히 여러분이 알아볼 수 있는 유용한 이름이어야 하며, 여기에는 리포지토리에 대해 다양한 작업과 작업을 수행하는 다양한 Wolkflow가 있을 수 있습니다.
|
||||
|
||||
`.github/workflows/super-linter.yml`을 생성하겠습니다.
|
||||
|
||||

|
||||
|
||||
이제 코드를 붙여 넣고 리포지토리에 코드를 커밋한 다음 Actions 탭으로 이동하면 아래와 같은 super-linter Wolkflow가 표시됩니다.
|
||||
|
||||

|
||||
|
||||
코드에서 리포지토리에 무언가를 push할 때 이 Wolkflow가 실행되도록 정의했기 때문에, super-linter.yml을 리포지토리에 push할 때 Wolkflow가 트리거되었습니다.
|
||||
|
||||

|
||||
|
||||
위에서 보시다시피 해킹 능력과 코딩 능력에 따라 몇 가지 오류가 발생했습니다.
|
||||
|
||||
적어도 아직은 제 코드는 아니었지만, 이 코드를 실행하고 오류가 발생했을 때 이 [문제](https://github.com/github/super-linter/issues/2255)를 발견했습니다.
|
||||
|
||||
2번 super-linter의 버전을 버전 3에서 4로 변경하고 작업을 다시 실행했습니다.
|
||||
|
||||

|
||||
|
||||
예상대로 해커 코딩에서 몇 가지 문제가 발생했으며 여기 [Wolkflow](https://github.com/MichaelCade/Jenkins-HelloWorld/runs/5600278515?check_suite_focus=true)에서 확인할 수 있습니다.
|
||||
|
||||
Wolkflow 내에서 무언가가 실패하거나 오류를 보고했을 때 리포지토리에 표시되는 모습을 지금 보여주고 싶었습니다.
|
||||
|
||||

|
||||
|
||||
이제 제 코드에서 문제를 해결하고 변경 사항을 적용하면 Wolkflow가 다시 실행됩니다(이미지에서 'bugs'를 해결하는 데 시간이 걸린 것을 볼 수 있습니다.) 파일을 삭제하는 것은 권장되지 않지만, 문제가 해결되었음을 보여주는 매우 빠른 방법입니다.
|
||||
|
||||

|
||||
|
||||
위에 강조 표시된 new Wolkflow 버튼을 누르면 수많은 작업의 문이 열립니다. 이번 챌린지를 진행하면서 눈치채셨겠지만, 저희는 거인의 어깨 위에 서서 코드, 자동화 및 기술을 널리 공유하여 삶을 더 편하게 만들고자 하는 것이 아닙니다.
|
||||
|
||||

|
||||
|
||||
Wolkflow가 성공했을 때 리포지토리의 녹색 체크 표시를 보여드리지 못했네요.
|
||||
|
||||

|
||||
|
||||
지금까지는 GitHub Actions의 기본적인 관점에 대해 설명했지만, 저와 같은 분이라면 GitHub Actions를 사용하여 많은 작업을 자동화할 수 있는 다른 방법을 알고 계실 것입니다.
|
||||
|
||||
다음에는 CD의 또 다른 영역인 애플리케이션을 환경에 배포하기 위해 ArgoCD를 살펴볼 것입니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [Jenkins is the way to build, test, deploy](https://youtu.be/_MXtbjwsz3A)
|
||||
- [Jenkins.io](https://www.jenkins.io/)
|
||||
- [ArgoCD](https://argo-cd.readthedocs.io/en/stable/)
|
||||
- [ArgoCD Tutorial for Beginners](https://www.youtube.com/watch?v=MeU5_k9ssrs)
|
||||
- [What is Jenkins?](https://www.youtube.com/watch?v=LFDrDnKPOTg)
|
||||
- [Complete Jenkins Tutorial](https://www.youtube.com/watch?v=nCKxl7Q_20I&t=3s)
|
||||
- [GitHub Actions](https://www.youtube.com/watch?v=R8_veQiYBjI)
|
||||
- [GitHub Actions CI/CD](https://www.youtube.com/watch?v=mFFXuXjVgkU)
|
||||
|
||||
[Day 76](day76.md)에서 봐요!
|
83
2022/ko/Days/day76.md
Normal file
83
2022/ko/Days/day76.md
Normal file
@ -0,0 +1,83 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - ArgoCD Overview - Day 76'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - ArgoCD Overview
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048809
|
||||
---
|
||||
|
||||
## ArgoCD 개요
|
||||
|
||||
"Argo CD는 Kubernetes를 위한 선언적 GitOps 지속적 배포 도구입니다."
|
||||
|
||||
버전 제어가 핵심입니다. 환경을 즉석에서 변경했는데 그 변경 사항을 기억하지 못하고 불이 켜져 있고 모든 것이 초록색이기 때문에 계속 진행했던 적이 있으신가요? 변경을 시도했다가 모든 것 또는 일부가 망가진 적이 있나요? 변경한 사실을 알았다면 잘못된 스크립트나 맞춤법 오류를 빠르게 되돌릴 수 있을 것입니다. 하지만 대규모로 변경을 진행하다 보니 본인도 몰랐을 수도 있고, 바로 발견하지 못해 비즈니스가 어려움을 겪고 있을 수도 있습니다. 따라서 버전 관리가 중요합니다. 뿐만 아니라 "애플리케이션 정의, 구성 및 환경은 선언적이어야 하며 버전 관리가 이루어져야 합니다." 이 외에도 "애플리케이션 배포 및 수명 주기 관리는 자동화되고, 감시 가능하며, 이해하기 쉬워야 한다"고 언급합니다.
|
||||
|
||||
운영 배경을 가지고 있지만 IaC로 사용하는 데 많은 경험을 쌓은 저로서는 지속적인 배포/제공 워크플로우를 통해 이 모든 좋은 것들을 처리할 수 있는 다음 단계라고 생각합니다.
|
||||
|
||||
[ArgoCD란](https://argo-cd.readthedocs.io/en/stable/)
|
||||
|
||||
### ArgoCD 배포
|
||||
|
||||
이번 배포에서는 신뢰할 수 있는 Minikube Kubernetes 클러스터를 다시 로컬로 사용할 것입니다.
|
||||
|
||||
```Shell
|
||||
kubectl create namespace argocd
|
||||
kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
|
||||
```
|
||||
|
||||

|
||||
|
||||
`kubectl get pods -n argocd`로 모든 ArgoCD pod가 실행되고 있는지 확인합니다.
|
||||
|
||||

|
||||
|
||||
또한, `kubectl get all -n argocd`로 네임스페이스에 배포한 모든 것을 확인해봅시다.
|
||||
|
||||

|
||||
|
||||
위의 내용이 정상적으로 보이면 포트 포워드를 통해 접근하는 것을 고려해야 합니다. 새 터미널에서 `kubectl port-forward svc/argocd-server -n argocd 8080:443` 명령을 사용합니다.
|
||||
|
||||
그런 다음 새 웹 브라우저를 열고 `https://localhost:8080`로 이동합니다.
|
||||
|
||||

|
||||
|
||||
로그인하려면 관리자 사용자 이름이 필요하며, 생성한 암호를 비밀번호로 사용하려면 `kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d && echo`를 사용합니다.
|
||||
|
||||

|
||||
|
||||
로그인하면 비어있는 CD 캔버스가 표시됩니다.
|
||||
|
||||

|
||||
|
||||
### 애플리케이션 배포
|
||||
|
||||
이제 ArgoCD를 실행하고 실행 중이므로 이제 Helm뿐만 아니라 Git 리포지토리에서 애플리케이션을 배포하는 데 사용할 수 있습니다.
|
||||
|
||||
제가 배포하고자 하는 애플리케이션은 Pac-Man입니다. 네, Pac-Man은 유명한 게임이자 데이터 관리와 관련하여 많은 데모에서 사용하는 게임이며, 우리가 Pac-Man을 보는 것은 이번이 마지막이 아닐 것입니다.
|
||||
|
||||
[Pac-Man](https://github.com/MichaelCade/pacman-tanzu.git)의 리포지토리는 여기에서 찾을 수 있습니다.
|
||||
|
||||
스크린샷을 사용하여 각 단계를 설명하는 대신, 이 특정 애플리케이션 배포를 위해 수행한 단계를 다루는 연습 동영상을 만드는 것이 더 쉬울 것이라고 생각했습니다.
|
||||
|
||||
[ArgoCD 데모 - 90일간의 개발 운영](https://www.youtube.com/watch?v=w6J413_j0hA)
|
||||
|
||||
참고 - 영상 중 앱 상태가 정상인데도 만족스럽지 않은 서비스가 있는데, 이는 Pac-Man 서비스에 대해 설정된 로드밸런서 유형이 보류 중이고, Minikube에는 로드밸런서가 구성되지 않았기 때문입니다. 이 문제를 테스트하고 싶으시다면 서비스에 대한 YAML을 ClusterIP로 변경하고 포트 포워딩을 사용하여 게임을 플레이할 수 있습니다.
|
||||
|
||||
이것으로 CICD 파이프라인 섹션을 마칩니다. 현재 업계에서 이 영역에 많은 관심이 집중되고 있으며, 일반적으로 CICD 내에서 사용되는 방법론과 관련된 GitOps 관련 용어도 듣게 될 것입니다.
|
||||
|
||||
다음 섹션에서는 새로운 개념은 아니지만 환경을 다르게 바라보면서 점점 더 중요해지고 있는 또 다른 개념 또는 영역인 Observability에 대해 살펴봅니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [Jenkins is the way to build, test, deploy](https://youtu.be/_MXtbjwsz3A)
|
||||
- [Jenkins.io](https://www.jenkins.io/)
|
||||
- [ArgoCD](https://argo-cd.readthedocs.io/en/stable/)
|
||||
- [ArgoCD Tutorial for Beginners](https://www.youtube.com/watch?v=MeU5_k9ssrs)
|
||||
- [What is Jenkins?](https://www.youtube.com/watch?v=LFDrDnKPOTg)
|
||||
- [Complete Jenkins Tutorial](https://www.youtube.com/watch?v=nCKxl7Q_20I&t=3s)
|
||||
- [GitHub Actions](https://www.youtube.com/watch?v=R8_veQiYBjI)
|
||||
- [GitHub Actions CI/CD](https://www.youtube.com/watch?v=mFFXuXjVgkU)
|
||||
|
||||
[Day 77](day77.md)에서 봐요!
|
83
2022/ko/Days/day77.md
Normal file
83
2022/ko/Days/day77.md
Normal file
@ -0,0 +1,83 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - The Big Picture: Monitoring - Day 77'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - The Big Picture Monitoring
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048715
|
||||
---
|
||||
|
||||
## 큰 그림: 모니터링
|
||||
|
||||
이 섹션에서는 모니터링이란 무엇이며 왜 필요한지에 대해 설명합니다.
|
||||
|
||||
### 모니터링이란 무엇인가요?
|
||||
|
||||
모니터링은 전체 인프라를 면밀히 주시하는 프로세스입니다.
|
||||
|
||||
### 모니터링이란 무엇이며 왜 필요한가요?1
|
||||
|
||||
애플리케이션 서버, 데이터베이스 서버, 웹 서버와 같은 다양한 특수 서버를 포함하여 수천 대의 서버를 관리한다고 가정해 봅시다. 또한 퍼블릭 클라우드 서비스 및 Kubernetes를 비롯한 추가 서비스와 다양한 플랫폼으로 인해 이 문제는 더욱 복잡해질 수 있습니다.
|
||||
|
||||

|
||||
|
||||
우리는 서버의 모든 서비스, 애플리케이션, 리소스가 정상적으로 실행되고 있는지 확인할 책임이 있습니다.
|
||||
|
||||

|
||||
|
||||
어떻게 하나요? 세 가지 방법이 있습니다:
|
||||
|
||||
- 모든 서버에 수동으로 로그인하여 서비스 프로세스 및 리소스에 대한 모든 데이터를 확인합니다.
|
||||
- 우리를 대신하여 서버에 로그인하고 데이터를 확인하는 스크립트를 작성합니다.
|
||||
|
||||
이 두 가지 옵션 모두 상당한 양의 작업이 필요합니다,
|
||||
|
||||
세 번째 옵션은 더 쉬운 방법으로, 시중에 나와 있는 모니터링 솔루션을 사용할 수 있습니다.
|
||||
|
||||
Nagios와 Zabbix는 쉽게 사용할 수 있는 솔루션으로, 원하는 만큼 서버를 포함하도록 모니터링 인프라를 확장할 수 있습니다.
|
||||
|
||||
### Nagios
|
||||
|
||||
Nagios는 같은 이름의 회사에서 만든 인프라 모니터링 도구입니다. 이 도구의 오픈 소스 버전은 Nagios core라고 하며 상용 버전은 Nagios XI라고 합니다. [Nagios 웹사이트](https://www.nagios.org/)
|
||||
|
||||
이 도구를 사용하면 서버를 모니터링하고 서버가 충분히 활용되고 있는지 또는 해결해야 할 장애 작업이 있는지 확인할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
기본적으로 모니터링을 통해 서버와 서비스의 상태를 확인하고 인프라의 상태를 파악하는 두 가지 목표를 달성할 수 있으며, 전체 인프라에 대한 40,000피트 뷰를 제공하여 서버가 제대로 작동하고 있는지, 애플리케이션이 제대로 작동하는지, 웹 서버에 연결할 수 있는지 여부를 확인할 수 있습니다.
|
||||
|
||||
특정 서버에서 지난 10주 동안 디스크가 10%씩 증가하고 있으며, 향후 4~5일 이내에 완전히 소진될 것이고 곧 응답하지 못할 것임을 알려줍니다. 디스크 또는 서버가 위험한 상태에 있을 때 경고하여 서비스 중단을 피하기 위한 적절한 조치를 취할 수 있도록 알려줍니다.
|
||||
|
||||
이 경우 일부 디스크 공간을 확보하여 서버에 장애가 발생하지 않고 사용자에게 영향을 미치지 않도록 할 수 있습니다.
|
||||
|
||||
대부분의 모니터링 엔지니어에게 어려운 질문은 무엇을 모니터링할 것인가, 또는 무엇을 모니터링하지 않을 것인가입니다.
|
||||
|
||||
모든 시스템에는 여러 리소스가 있는데, 이 중 어떤 리소스를 주시해야 하고 어떤 리소스를 간과할 수 있는지, 예를 들어 CPU 사용량을 모니터링해야 하는지에 대한 대답은 분명히 '예'이지만 그럼에도 불구하고 여전히 결정해야 할 사항은 시스템의 열린 포트 수를 모니터링해야 하는지 여부입니다. 범용 서버인 경우 상황에 따라 필요하지 않을 수도 있지만 웹 서버인 경우 다시 모니터링해야 할 수도 있습니다.
|
||||
|
||||
### 지속적인 모니터링
|
||||
|
||||
모니터링은 새로운 항목이 아니며 지속적인 모니터링도 많은 기업이 수년 동안 채택해 온 이상입니다.
|
||||
|
||||
모니터링과 관련하여 세 가지 주요 영역에 중점을 둡니다.
|
||||
|
||||
- 인프라 모니터링
|
||||
- 애플리케이션 모니터링
|
||||
- 네트워크 모니터링
|
||||
|
||||
이 세션에서 두 가지 일반적인 시스템과 도구에 대해 언급했지만, 사용 가능한 도구는 매우 많다는 점에 유의해야 합니다. 모니터링 솔루션의 진정한 이점은 무엇을 모니터링해야 하고 무엇을 모니터링하지 않아야 하는지에 대한 질문에 답하는 데 시간을 할애했을 때 나타납니다.
|
||||
|
||||
어떤 플랫폼에서든 모니터링 솔루션을 켜면 정보를 수집하기 시작하지만, 그 정보가 너무 많으면 솔루션의 이점을 제대로 활용하기 어렵기 때문에 시간을 들여 구성해야 합니다.
|
||||
|
||||
다음 세션에서는 모니터링 도구를 직접 사용해 보고 무엇을 모니터링할 수 있는지 살펴보겠습니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [The Importance of Monitoring in DevOps](https://www.devopsonline.co.uk/the-importance-of-monitoring-in-devops/)
|
||||
- [Understanding Continuous Monitoring in DevOps?](https://medium.com/devopscurry/understanding-continuous-monitoring-in-devops-f6695b004e3b)
|
||||
- [DevOps Monitoring Tools](https://www.youtube.com/watch?v=Zu53QQuYqJ0)
|
||||
- [Top 5 - DevOps Monitoring Tools](https://www.youtube.com/watch?v=4t71iv_9t_4)
|
||||
- [How Prometheus Monitoring works](https://www.youtube.com/watch?v=h4Sl21AKiDg)
|
||||
- [Introduction to Prometheus monitoring](https://www.youtube.com/watch?v=5o37CGlNLr8)
|
||||
|
||||
[Day 78](day78.md)에서 봐요!
|
98
2022/ko/Days/day78.md
Normal file
98
2022/ko/Days/day78.md
Normal file
@ -0,0 +1,98 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - Hands-On Monitoring Tools - Day 78'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - Hands-On Monitoring Tools
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1049056
|
||||
---
|
||||
|
||||
## 실습용 모니터링 도구
|
||||
|
||||
지난 세션에서 모니터링의 큰 그림에 대해 이야기하면서 Nagios를 살펴본 이유는 두 가지였습니다. 첫 번째는 수년 동안 많이 들어본 소프트웨어이기 때문에 그 기능에 대해 조금 더 알고 싶었기 때문입니다.
|
||||
|
||||
오늘은 Prometheus에 대해 살펴보려고 하는데요, 클라우드 네이티브 환경에서 점점 더 많이 사용되고 있지만 Kubernetes 등 외부에서도 이러한 물리적 리소스를 관리하는 데 사용할 수 있습니다.
|
||||
|
||||
### Prometheus - 거의 모든 것을 모니터링합니다.
|
||||
|
||||
우선, Prometheus는 컨테이너와 마이크로서비스 기반 시스템뿐만 아니라 물리적, 가상 및 기타 서비스를 모니터링하는 데 도움이 되는 오픈 소스입니다. Prometheus 뒤에는 대규모 커뮤니티가 있습니다.
|
||||
|
||||
Prometheus에는 다양한 [통합 및 exporter](https://prometheus.io/docs/instrumenting/exporters/)가 있습니다. 핵심은 기존 메트릭을 Prometheus 메트릭으로 내보내는 것입니다. 또한 여러 프로그래밍 언어도 지원합니다.
|
||||
|
||||
pull 접근 방식 - 수천 개의 마이크로서비스 또는 시스템 및 서비스와 대화하는 경우 push 방식은 일반적으로 서비스가 모니터링 시스템으로 push되는 것을 볼 수 있는 곳입니다. 이 경우 네트워크 과부하, 높은 CPU 사용량, 단일 장애 지점 등의 문제가 발생합니다. pull 방식은 모든 서비스의 메트릭 엔드포인트에서 Prometheus가 끌어오는 훨씬 더 나은 경험을 제공합니다.
|
||||
|
||||
다시 한번 Prometheus의 구성을 위한 YAML을 살펴봅니다.
|
||||
|
||||

|
||||
|
||||
나중에 이것이 Kubernetes에 배포되었을 때 어떻게 보이는지, 특히 작업/exporter로부터 메트릭을 가져오는 **PushGateway**가 있는 것을 보게 될 것입니다.
|
||||
|
||||
알림을 push하는 **AlertManager**가 있으며, 여기에서 이메일, 슬랙 및 기타 도구와 같은 외부 서비스와 통합할 수 있습니다.
|
||||
|
||||
그런 다음 PushGateway에서 이러한 pull 메트릭의 검색을 관리하고 push 알림을 AlertManager로 전송하는 Prometheus Server가 있습니다. Prometheus Server는 또한 로컬 디스크에 데이터를 저장합니다. 원격 스토리지 솔루션을 활용할 수도 있습니다.
|
||||
|
||||
또한 메트릭과 상호 작용하는 데 사용되는 언어인 PromQL도 있는데, 이는 나중에 Prometheus 웹 UI에서 볼 수 있지만, 이 섹션의 뒷부분에서 Grafana와 같은 데이터 시각화 도구에서도 어떻게 사용되는지 볼 수 있습니다.
|
||||
|
||||
### Prometheus 배포 방법
|
||||
|
||||
Prometheus 설치 방법은 [다운로드 섹션](https://prometheus.io/download/) 도커 이미지에서도 다양하게 확인할 수 있습니다.
|
||||
|
||||
`docker run --name prometheus -d -p 127.0.0.1:9090:9090 prom/prometheus`
|
||||
|
||||
하지만 여기서는 Kubernetes에 배포하는 데 집중하겠습니다. 여기에도 몇 가지 옵션이 있습니다.
|
||||
|
||||
- 구성 YAML 파일 생성
|
||||
- 오퍼레이터 사용(모든 Prometheus 구성 요소의 관리자)
|
||||
- Helm 차트를 사용하여 오퍼레이터 배포
|
||||
|
||||
### Kubernetes에 배포하기
|
||||
|
||||
이 빠르고 간단한 설치를 위해 다시 로컬에서 Minikube 클러스터를 사용하겠습니다. Minikube와의 이전 접점과 마찬가지로, Helm을 사용하여 Prometheus Helm 차트를 배포할 것입니다.
|
||||
|
||||
`helm repo add prometheus-community https://prometheus-community.github.io/helm-charts`
|
||||
|
||||

|
||||
|
||||
위에서 볼 수 있듯이 Helm 리포지토리 업데이트도 실행했으므로, 이제 `helm install stable prometheus-community/prometheus` 명령을 사용하여 Minikube 환경에 Prometheus를 배포할 준비가 되었습니다.
|
||||
|
||||

|
||||
|
||||
몇 분 후, 몇 개의 새로운 pod가 나타나는데, 이 데모에서는 기본 네임스페이스에 배포했으며, 일반적으로는 이 pod를 해당 네임스페이스에 push합니다.
|
||||
|
||||

|
||||
|
||||
모든 pod가 실행되고 나면 Prometheus의 배포된 모든 측면도 살펴볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
이제 Prometheus Server UI에 액세스하기 위해 다음 명령어를 사용하여 포팅 포워드할 수 있습니다.
|
||||
|
||||
```Shell
|
||||
export POD_NAME=$(kubectl get pods --namespace default -l "app=prometheus,component=server" -o jsonpath="{.items[0].metadata.name}")
|
||||
kubectl --namespace default port-forward $POD_NAME 9090
|
||||
```
|
||||
|
||||
브라우저를 `http://localhost:9090`으로 처음 열면 다음과 같이 빈 화면이 표시됩니다.
|
||||
|
||||

|
||||
|
||||
Kubernetes 클러스터에 배포했기 때문에 Kubernetes API에서 자동으로 메트릭을 가져올 것이므로 일부 PromQL을 사용하여 최소한 `container_cpu_usage_seconds_total` 메트릭을 캡처하고 있는지 확인할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
앞서 말씀드린 것처럼 메트릭을 확보하는 것도 좋지만 모니터링도 중요하지만, 모니터링 대상과 그 이유, 모니터링하지 않는 대상과 그 이유를 알아야 한다는 점에서 PromQL을 배우고 이를 실제로 적용하는 것은 매우 중요합니다!
|
||||
|
||||
다시 Prometheus로 돌아오고 싶지만, 지금은 로그 관리와 데이터 시각화에 대해 생각해 보고 나중에 다시 Prometheus로 돌아올 수 있도록 해야 할 것 같습니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [The Importance of Monitoring in DevOps](https://www.devopsonline.co.uk/the-importance-of-monitoring-in-devops/)
|
||||
- [Understanding Continuous Monitoring in DevOps?](https://medium.com/devopscurry/understanding-continuous-monitoring-in-devops-f6695b004e3b)
|
||||
- [DevOps Monitoring Tools](https://www.youtube.com/watch?v=Zu53QQuYqJ0)
|
||||
- [Top 5 - DevOps Monitoring Tools](https://www.youtube.com/watch?v=4t71iv_9t_4)
|
||||
- [How Prometheus Monitoring works](https://www.youtube.com/watch?v=h4Sl21AKiDg)
|
||||
- [Introduction to Prometheus monitoring](https://www.youtube.com/watch?v=5o37CGlNLr8)
|
||||
- [Promql cheat sheet with examples](https://www.containiq.com/post/promql-cheat-sheet-with-examples)
|
||||
|
||||
[Day 79](day79.md)에서 봐요!
|
81
2022/ko/Days/day79.md
Normal file
81
2022/ko/Days/day79.md
Normal file
@ -0,0 +1,81 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - The Big Picture: Log Management - Day 79'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - The Big Picture Log Management
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1049057
|
||||
---
|
||||
|
||||
## 큰 그림: 로그 관리
|
||||
|
||||
인프라 모니터링 과제와 솔루션의 연속선상에 있는 로그 관리는 전체 통합 가시성 퍼즐의 또 다른 퍼즐 조각입니다.
|
||||
|
||||
### 로그 관리 및 집계
|
||||
|
||||
두 가지 핵심 개념에 대해 이야기해 보겠습니다. 첫 번째는 로그 집계로, 다양한 서비스에서 애플리케이션 로그를 수집하고 태그를 지정하여 쉽게 검색할 수 있는 단일 대시보드에 저장하는 방법입니다.
|
||||
|
||||
애플리케이션 성능 관리 시스템에서 가장 먼저 구축해야 하는 시스템 중 하나는 로그 집계입니다. 애플리케이션 성능 관리는 애플리케이션이 빌드 및 배포된 후에도 지속적으로 작동하는지 확인하여 리소스가 충분히 할당되고 사용자에게 오류가 표시되지 않도록 해야 하는 데브옵스 라이프사이클의 일부입니다. 대부분의 프로덕션 배포에서 많은 관련 이벤트가 Google의 여러 서비스에서 로그를 생성합니다. 하나의 검색이 사용자에게 반환되기 전에 10개의 다른 서비스에 도달할 수 있으며, 10개의 서비스 중 하나에 논리 문제가 있을 수 있는 예기치 않은 검색 결과가 표시되는 경우 로그 집계는 Google과 같은 회사가 프로덕션에서 문제를 진단하는 데 도움이 되며, 모든 요청을 고유 ID에 매핑할 수 있는 단일 대시보드를 구축하여 검색하면 검색에 고유 ID가 부여되고 검색이 다른 서비스를 통과할 때마다 해당 서비스가 현재 수행 중인 작업과 해당 ID가 연결되도록 합니다.
|
||||
|
||||
이것이 바로 로그를 생성하는 모든 곳에서 로그를 효율적으로 수집하고 장애가 다시 발생할 경우 쉽게 검색할 수 있도록 하는 좋은 로그 수집 플랫폼의 핵심입니다.
|
||||
|
||||
### 예제 앱
|
||||
|
||||
예제 애플리케이션은 웹 앱으로, 일반적인 프론트엔드와 백엔드가 중요한 데이터를 MongoDB 데이터베이스에 저장하고 있습니다.
|
||||
|
||||
사용자가 페이지가 모두 하얗게 변하고 오류 메시지가 인쇄되었다고 말하면 현재 스택의 문제를 진단하기 위해 사용자가 수동으로 오류를 보내야 하고 다른 세 가지 서비스의 관련 로그와 일치시켜야 합니다.
|
||||
|
||||
### Elk
|
||||
|
||||
예제 앱과 동일한 환경에 설치한 경우 세 가지 구성 요소인 Elasticsearch, Logstash, Kibana의 이름을 딴 인기 있는 오픈 소스 로그 집계 스택인 Elk에 대해 살펴보겠습니다.
|
||||
|
||||
웹 애플리케이션은 프론트엔드에 연결되고, 프론트엔드는 백엔드에 연결되며, 백엔드는 Logstash로 로그를 전송하고, 이 세 가지 구성 요소가 작동하는 방식은 다음과 같습니다.
|
||||
|
||||
### Elk의 구성 요소
|
||||
|
||||
Elasticsearch, Logstash, Kibana의 구성 요소는 모든 서비스가 Logstash로 로그를 전송하고, Logstash는 애플리케이션이 방출하는 텍스트인 이 로그를 가져온다는 것입니다. 예를 들어, 웹 애플리케이션에서 사용자가 웹 페이지를 방문할 때 웹 페이지는 이 방문자가 현재 이 페이지에 액세스한 것을 기록할 수 있으며, 이것이 로그 메시지의 예입니다.
|
||||
|
||||
그러면 Logstash는 이 로그 메시지에서 사용자가 **시간**에 **무엇**을 했다는 내용을 추출합니다. 시간을 추출하고 메시지를 추출하고 사용자를 추출하고 그것들을 모두 태그로 포함시켜서 메시지가 태그와 메시지의 객체가 되어 특정 사용자의 모든 요청을 쉽게 검색할 수 있도록 하지만 Logstash는 자체적으로 저장하는 것이 아니라 텍스트 쿼리를 위한 효율적인 데이터베이스인 Elasticsearch에 저장하고 Elasticsearch는 Kibana로 결과를 노출하고 Kibana는 Elasticsearch에 연결하는 웹 서버로서 개발자나 팀의 다른 사람들이 관리자를 허용합니다, 대기 중인 엔지니어가 주요 장애가 발생할 때마다 프로덕션에서 로그를 볼 수 있습니다. 관리자는 Kibana에 연결하고, Kibana는 사용자가 원하는 것과 일치하는 로그를 찾기 위해 Elasticsearch를 쿼리합니다.
|
||||
|
||||
검색 창에 "오류를 찾고 싶어요"라고 말하면, Kibana는 문자열 오류가 포함된 메시지를 찾으라고 말하고, 그러면 Elasticsearch는 Logstash가 채운 결과를 반환합니다. Logstash는 다른 모든 서비스에서 이러한 결과를 전송받았을 것입니다.
|
||||
|
||||
### Elk를 사용해 프로덕션 문제를 진단하는 방법
|
||||
|
||||
한 사용자가 Elk 설정으로 이 작업을 수행하려고 할 때 오류 코드 1234567을 보았다고 말합니다. 검색 창에 1234567을 입력하고 엔터를 누르면 그에 해당하는 로그가 표시되고 로그 중 하나에서 내부 서버 오류가 1234567을 반환한다고 표시될 수 있으며, 그 로그를 생성한 서비스가 로그를 생성한 서비스가 백엔드임을 알 수 있고, 해당 로그가 생성된 시간을 확인할 수 있으므로 해당 로그의 시간으로 이동하여 백엔드에서 그 위와 아래의 메시지를 보면 사용자의 요청에 대해 어떤 일이 발생했는지 더 잘 파악할 수 있으며, 이 과정을 다른 서비스에서도 반복하여 사용자에게 문제가 발생한 원인을 찾을 때까지 반복할 수 있습니다.
|
||||
|
||||
### 보안 및 로그 액세스
|
||||
|
||||
퍼즐의 중요한 조각은 로그가 관리자(또는 액세스 권한이 필요한 사용자 및 그룹)에게만 표시되도록 하는 것입니다. 로그에는 인증된 사용자만 액세스해야 하는 토큰과 같은 민감한 정보가 포함될 수 있으며, 인증 방법 없이 Kibana를 인터넷에 노출하고 싶지 않을 것입니다.
|
||||
|
||||
### 로그 관리 도구의 예
|
||||
|
||||
로그 관리 플랫폼의 예는 다음과 같습니다.
|
||||
|
||||
- Elasticsearch
|
||||
- Logstash
|
||||
- Kibana
|
||||
- Fluentd - 인기 있는 오픈 소스 선택
|
||||
- Datadog - 대기업에서 일반적으로 사용되는 호스팅 제품,
|
||||
- LogDNA - 호스트형 제품
|
||||
- Splunk
|
||||
|
||||
클라우드 제공업체는 AWS CloudWatch Logs, Microsoft Azure Monitor, Google Cloud Logging과 같은 로깅도 제공합니다.
|
||||
|
||||
로그 관리는 프로덕션 환경의 문제를 진단하기 위한 애플리케이션 및 인프라 환경의 전반적인 통합 가시성의 핵심 요소입니다. Elk 또는 CloudWatch와 같은 즌비된 솔루션을 설치하는 것은 비교적 간단하며 프로덕션 환경의 문제를 진단하고 분류하는 것이 훨씬 쉬워집니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [The Importance of Monitoring in DevOps](https://www.devopsonline.co.uk/the-importance-of-monitoring-in-devops/)
|
||||
- [Understanding Continuous Monitoring in DevOps?](https://medium.com/devopscurry/understanding-continuous-monitoring-in-devops-f6695b004e3b)
|
||||
- [DevOps Monitoring Tools](https://www.youtube.com/watch?v=Zu53QQuYqJ0)
|
||||
- [Top 5 - DevOps Monitoring Tools](https://www.youtube.com/watch?v=4t71iv_9t_4)
|
||||
- [How Prometheus Monitoring works](https://www.youtube.com/watch?v=h4Sl21AKiDg)
|
||||
- [Introduction to Prometheus monitoring](https://www.youtube.com/watch?v=5o37CGlNLr8)
|
||||
- [Promql cheat sheet with examples](https://www.containiq.com/post/promql-cheat-sheet-with-examples)
|
||||
- [Log Management for DevOps | Manage application, server, and cloud logs with Site24x7](https://www.youtube.com/watch?v=J0csO_Shsj0)
|
||||
- [Log Management what DevOps need to know](https://devops.com/log-management-what-devops-teams-need-to-know/)
|
||||
- [What is Elk Stack?](https://www.youtube.com/watch?v=4X0WLg05ASw)
|
||||
- [Fluentd simply explained](https://www.youtube.com/watch?v=5ofsNyHZwWE&t=14s)
|
||||
|
||||
[Day 80](day80.md)에서 봐요!
|
106
2022/ko/Days/day80.md
Normal file
106
2022/ko/Days/day80.md
Normal file
@ -0,0 +1,106 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - ELK Stack - Day 80'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - ELK Stack
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048746
|
||||
---
|
||||
|
||||
## ELK 스택
|
||||
|
||||
이 세션에서는 앞서 언급한 몇 가지 옵션에 대해 조금 더 실습해 보겠습니다.
|
||||
|
||||
ELK Stack은 세 가지 개별 도구의 조합입니다:
|
||||
|
||||
- [Elasticsearch](https://www.elastic.co/what-is/elasticsearch)는 텍스트, 숫자, 위치 기반 정보, 정형, 비정형 등 모든 유형의 데이터를 위한 분산형 무료 개방형 검색 및 분석 엔진입니다.
|
||||
|
||||
- [Logstash](https://www.elastic.co/logstash/)는 다양한 소스에서 데이터를 수집하고 변환한 다음 원하는 "stash(저장소)"로 전송하는 무료 개방형 서버 측 데이터 처리 파이프라인입니다.
|
||||
|
||||
- [Kibana](https://www.elastic.co/kibana/)는 무료 개방형 사용자 인터페이스로, Elasticsearch 데이터를 시각화하고 Elastic Stack을 탐색할 수 있게 해줍니다. 쿼리 로드 추적부터 앱에서 요청이 흐르는 방식 이해까지 무엇이든 할 수 있습니다.
|
||||
|
||||
ELK 스택을 사용하면 모든 소스에서 모든 형식의 데이터를 안정적이고 안전하게 가져온 다음 실시간으로 검색, 분석 및 시각화할 수 있습니다.
|
||||
|
||||
위에서 언급한 구성 요소 외에도 스택으로 전달하기 위해 다양한 유형의 데이터를 수집하기 위해 엣지 호스트에 설치되는 경량 에이전트인 Beats도 볼 수 있습니다.
|
||||
|
||||
- Log: 분석해야 하는 서버 로그가 식별됩니다.
|
||||
|
||||
- Logstash: 로그와 이벤트 데이터를 수집합니다. 심지어 데이터를 구문 분석하고 변환합니다.
|
||||
|
||||
- ElasticSearch: Logstash에서 변환된 데이터는 저장, 검색 및 색인됩니다.
|
||||
|
||||
- Kibana는 Elasticsearch DB를 사용해 탐색, 시각화, 공유합니다.
|
||||
|
||||

|
||||
|
||||
[Guru99에서 가져온 사진](https://www.guru99.com/elk-stack-tutorial.html)
|
||||
|
||||
이를 설명하는 좋은 리소스는 [ELK 스택에 대한 완전한 가이드](https://logz.io/learn/complete-guide-elk-stack/)입니다.
|
||||
|
||||
Beats가 추가되면서 ELK Stack은 이제 Elastic Stack이라고도 불립니다.
|
||||
|
||||
실습 시나리오에서는 Elastic Stack을 배포할 수 있는 많은 위치가 있지만, 여기서는 시스템에 로컬로 배포하기 위해 docker-compose를 사용하겠습니다.
|
||||
|
||||
[Docker Compose로 Elastic Stack 시작하기](https://www.elastic.co/guide/en/elastic-stack-get-started/current/get-started-stack-docker.html#get-started-docker-tls)
|
||||
|
||||

|
||||
|
||||
여기에서 제가 사용한 원본 파일과 연습을 찾을 수 있습니다. [deviantony/docker-elk](https://github.com/deviantony/docker-elk)
|
||||
|
||||
이제 `docker-compose up -d`를 실행할 수 있는데, 처음 실행할 때는 이미지를 가져와야 합니다.
|
||||
|
||||

|
||||
|
||||
이 리포지토리 또는 제가 사용한 리포지토리를 팔로우하면 "changeme"의 비밀번호를 갖게 되거나 제 리포지토리에서 "90DaysOfDevOps"의 비밀번호를 갖게 됩니다. 사용자 이름은 "elastic"입니다.
|
||||
|
||||
몇 분 후, Kibana server / Docker 컨테이너인 `http://localhost:5601/`로 이동할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
초기 홈 화면은 다음과 같이 표시될 것입니다.
|
||||
|
||||

|
||||
|
||||
"Get started by adding integrations"라는 제목의 섹션 아래에 "Try sample data"가 있으며, 이를 클릭하면 아래 표시된 것 중 하나를 추가할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
저는 "Sample web logs"를 선택하려고 하는데, 이것은 실제로 ELK 스택에 어떤 데이터 세트를 가져올 수 있는지 살펴보기 위한 것입니다.
|
||||
|
||||
"Add Data"를 선택하면 일부 데이터를 채우는 데 시간이 걸리고 "View Data" 옵션과 드롭다운에 해당 데이터를 볼 수 있는 사용 가능한 방법의 목록이 표시됩니다.
|
||||
|
||||

|
||||
|
||||
대시보드 보기에 명시된 대로:
|
||||
|
||||
**샘플 로그 데이터**
|
||||
|
||||
> 이 대시보드에는 사용해 볼 수 있는 샘플 데이터가 포함되어 있습니다. 이 데이터를 보고, 검색하고, 시각화와 상호 작용할 수 있습니다. Kibana에 대한 자세한 내용은 문서를 참조하세요.
|
||||
|
||||

|
||||
|
||||
이것은 Kibana를 사용하여 Logstash를 통해 ElasticSearch에 추가된 데이터를 시각화하는 것입니다. 이것이 유일한 옵션은 아니지만, 저는 이것을 배포하고 살펴보고 싶었습니다.
|
||||
|
||||
언젠가는 Grafana에 대해서도 다룰 예정이며, 이 둘 사이의 데이터 시각화 유사점을 보게 될 것이고, Prometheus도 보셨을 것입니다.
|
||||
|
||||
제가 Elastic Stack과 Prometheus + Grafana를 비교하면서 느낀 핵심은 Elastic Stack 또는 ELK Stack은 로그에 초점을 맞추고 있고 Prometheus는 메트릭에 초점을 맞추고 있다는 것입니다.
|
||||
|
||||
저는 서로 다른 제품에 대해 더 잘 이해하기 위해 MetricFire의 이 기사 [Prometheus vs. ELK](https://www.metricfire.com/blog/prometheus-vs-elk/)를 읽었습니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [Understanding Logging: Containers & Microservices](https://www.youtube.com/watch?v=MMVdkzeQ848)
|
||||
- [The Importance of Monitoring in DevOps](https://www.devopsonline.co.uk/the-importance-of-monitoring-in-devops/)
|
||||
- [Understanding Continuous Monitoring in DevOps?](https://medium.com/devopscurry/understanding-continuous-monitoring-in-devops-f6695b004e3b)
|
||||
- [DevOps Monitoring Tools](https://www.youtube.com/watch?v=Zu53QQuYqJ0)
|
||||
- [Top 5 - DevOps Monitoring Tools](https://www.youtube.com/watch?v=4t71iv_9t_4)
|
||||
- [How Prometheus Monitoring works](https://www.youtube.com/watch?v=h4Sl21AKiDg)
|
||||
- [Introduction to Prometheus monitoring](https://www.youtube.com/watch?v=5o37CGlNLr8)
|
||||
- [Promql cheat sheet with examples](https://www.containiq.com/post/promql-cheat-sheet-with-examples)
|
||||
- [Log Management for DevOps | Manage application, server, and cloud logs with Site24x7](https://www.youtube.com/watch?v=J0csO_Shsj0)
|
||||
- [Log Management what DevOps need to know](https://devops.com/log-management-what-devops-teams-need-to-know/)
|
||||
- [What is ELK Stack?](https://www.youtube.com/watch?v=4X0WLg05ASw)
|
||||
- [Fluentd simply explained](https://www.youtube.com/watch?v=5ofsNyHZwWE&t=14s)
|
||||
|
||||
[Day 81](day81.md)에서 봐요!
|
166
2022/ko/Days/day81.md
Normal file
166
2022/ko/Days/day81.md
Normal file
@ -0,0 +1,166 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - Fluentd & FluentBit - Day 81'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - Fluentd & FluentBit
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048716
|
||||
---
|
||||
|
||||
## Fluentd & FluentBit
|
||||
|
||||
이 통합 observability 섹션의 일부로 살펴보고 싶었던 또 다른 데이터 수집기는 [Fluentd](https://docs.fluentd.org/)였습니다. 오픈소스 통합 로깅 레이어입니다.
|
||||
|
||||
Fluentd는 깨끗하고 안정적인 로깅 파이프라인을 구축하는 데 적합한 네 가지 주요 기능을 갖추고 있습니다:
|
||||
|
||||
JSON을 사용한 통합 로깅: Fluentd는 가능한 한 데이터를 JSON으로 구조화하려고 노력합니다. 이를 통해 여러 소스와 대상에 걸쳐 로그를 수집, 필터링, 버퍼링, 출력하는 등 로그 데이터 처리의 모든 측면을 통합할 수 있습니다. 엄격한 스키마를 강요하지 않고도 액세스할 수 있는 충분한 구조를 가지고 있기 때문에 JSON을 사용하면 다운스트림 데이터 처리가 훨씬 쉬워집니다.
|
||||
|
||||
플러그 가능한 아키텍처: Fluentd는 커뮤니티가 기능을 확장할 수 있는 유연한 플러그인 시스템을 갖추고 있습니다. 300개 이상의 커뮤니티 기여 플러그인이 수십 개의 데이터 소스를 수십 개의 데이터 출력에 연결하여 필요에 따라 데이터를 조작합니다. 플러그인을 사용하면 로그를 즉시 더 효과적으로 활용할 수 있습니다.
|
||||
|
||||
최소한의 리소스 필요: 데이터 수집기는 바쁜 컴퓨터에서도 편안하게 실행될 수 있도록 가벼워야 합니다. Fluentd는 C와 Ruby의 조합으로 작성되어 최소한의 시스템 리소스를 필요로 합니다. 바닐라 인스턴스는 30~40MB의 메모리에서 실행되며 초당 13,000개의 이벤트를 처리할 수 있습니다.
|
||||
|
||||
내장된 안정성: 데이터 손실은 절대 일어나지 않습니다. Fluentd는 메모리 및 파일 기반 버퍼링을 지원하여 노드 간 데이터 손실을 방지합니다. 또한, 강력한 페일오버를 지원하며 고가용성을 위해 설정할 수 있습니다.
|
||||
|
||||
[Fluentd 설치하기](https://docs.fluentd.org/quickstart#step-1-installing-fluentd)
|
||||
|
||||
### 앱은 데이터를 어떻게 기록하나요?
|
||||
|
||||
- 파일에 기록합니다. `.log` 파일(도구 없이는 대규모로 분석하기 어려움)
|
||||
- 데이터베이스에 직접 기록(각 애플리케이션이 올바른 형식으로 구성되어 있어야 함)
|
||||
- 타사 애플리케이션(NodeJS, NGINX, PostgreSQL)
|
||||
|
||||
이것이 바로 통합 로깅 레이어가 필요한 이유입니다.
|
||||
|
||||
FluentD는 위에 표시된 3가지 로깅 데이터 유형을 허용하고 이를 수집, 처리하여 대상(예: Elastic, MongoDB 또는 Kafka 데이터베이스)으로 로그를 전송할 수 있는 기능을 제공합니다.
|
||||
|
||||
모든 데이터, 모든 데이터 소스를 FluentD로 전송할 수 있으며, 이를 모든 대상으로 전송할 수 있습니다. FluentD는 특정 소스나 대상에 종속되지 않습니다.
|
||||
|
||||
Fluentd를 조사하는 과정에서 또 다른 옵션으로 Fluent bit를 계속 발견하게 되었는데, 서버뿐만 아니라 컨테이너에도 배포할 수 있지만 로깅 도구를 Kubernetes 환경에 배포하려는 경우 FluentBit가 해당 기능을 제공할 수 있을 것 같았습니다.
|
||||
|
||||
[Fluentd & FluentBit](https://docs.fluentbit.io/manual/about/fluentd-and-fluent-bit)
|
||||
|
||||
Fluentd와 FluentBit는 입력 플러그인을 사용하여 데이터를 FluentBit 형식으로 변환한 다음, 출력 플러그인을 사용하여 엘라스틱서치와 같은 출력 대상이 무엇이든 출력할 수 있습니다.
|
||||
|
||||
또한 구성 간에 태그와 일치를 사용할 수도 있습니다.
|
||||
|
||||
일부 아키텍처에서는 함께 사용할 수 있지만, FluentBit를 사용해야 할 좋은 이유를 찾을 수 없으며, FluentBit가 시작하기에 가장 좋은 방법인 것 같습니다.
|
||||
|
||||
### Kubernetes의 FluentBit
|
||||
|
||||
Kubernetes의 FluentBit는 데몬셋으로 배포되며, 이는 클러스터의 각 노드에서 실행된다는 것을 의미합니다. 그러면 각 노드의 각 Fluent Bit pod는 해당 노드의 각 컨테이너를 읽고 사용 가능한 모든 로그를 수집합니다. 또한 Kubernetes API 서버에서 메타데이터를 수집합니다.
|
||||
|
||||
Kubernetes 어노테이션은 애플리케이션의 구성 YAML 내에서 사용할 수 있습니다.
|
||||
|
||||
우선, Fluent Helm 리포지토리에서 배포할 수 있습니다. Helm 리포지토리에서 `helm repo add fluent https://fluent.github.io/helm-charts`를 실행한 다음 `helm install fluent-bit fluent/fluent-bit` 명령어를 사용하여 설치합니다.
|
||||
|
||||

|
||||
|
||||
내 클러스터에서는 (테스트 목적으로) 기본 네임스페이스에서 Prometheus를 실행 중이므로 fluent-bit pod가 실행 중인지 확인해야 합니다. `kubectl get all | grep fluent`를 사용하면 앞서 언급한 실행 중인 pod, 서비스 및 데몬셋을 확인할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
FluentBit이 로그를 어디에서 가져올지 알 수 있도록 구성 파일이 있으며, 이 FluentBit의 Kubernetes 배포에는 구성 파일과 유사한 configmap이 있습니다.
|
||||
|
||||

|
||||
|
||||
이 configmap은 다음과 같이 보일 것입니다:
|
||||
|
||||
```
|
||||
Name: fluent-bit
|
||||
Namespace: default
|
||||
Labels: app.kubernetes.io/instance=fluent-bit
|
||||
app.kubernetes.io/managed-by=Helm
|
||||
app.kubernetes.io/name=fluent-bit
|
||||
app.kubernetes.io/version=1.8.14
|
||||
helm.sh/chart=fluent-bit-0.19.21
|
||||
Annotations: meta.helm.sh/release-name: fluent-bit
|
||||
meta.helm.sh/release-namespace: default
|
||||
|
||||
Data
|
||||
====
|
||||
custom_parsers.conf:
|
||||
----
|
||||
[PARSER]
|
||||
Name docker_no_time
|
||||
Format json
|
||||
Time_Keep Off
|
||||
Time_Key time
|
||||
Time_Format %Y-%m-%dT%H:%M:%S.%L
|
||||
|
||||
fluent-bit.conf:
|
||||
----
|
||||
[SERVICE]
|
||||
Daemon Off
|
||||
Flush 1
|
||||
Log_Level info
|
||||
Parsers_File parsers.conf
|
||||
Parsers_File custom_parsers.conf
|
||||
HTTP_Server On
|
||||
HTTP_Listen 0.0.0.0
|
||||
HTTP_Port 2020
|
||||
Health_Check On
|
||||
|
||||
[INPUT]
|
||||
Name tail
|
||||
Path /var/log/containers/*.log
|
||||
multiline.parser docker, cri
|
||||
Tag kube.*
|
||||
Mem_Buf_Limit 5MB
|
||||
Skip_Long_Lines On
|
||||
|
||||
[INPUT]
|
||||
Name systemd
|
||||
Tag host.*
|
||||
Systemd_Filter _SYSTEMD_UNIT=kubelet.service
|
||||
Read_From_Tail On
|
||||
|
||||
[FILTER]
|
||||
Name Kubernetes
|
||||
Match kube.*
|
||||
Merge_Log On
|
||||
Keep_Log Off
|
||||
K8S-Logging.Parser On
|
||||
K8S-Logging.Exclude On
|
||||
|
||||
[OUTPUT]
|
||||
Name es
|
||||
Match kube.*
|
||||
Host elasticsearch-master
|
||||
Logstash_Format On
|
||||
Retry_Limit False
|
||||
|
||||
[OUTPUT]
|
||||
Name es
|
||||
Match host.*
|
||||
Host elasticsearch-master
|
||||
Logstash_Format On
|
||||
Logstash_Prefix node
|
||||
Retry_Limit False
|
||||
|
||||
Events: <none>
|
||||
```
|
||||
|
||||
이제 pod를 로컬호스트로 포트 포워딩하여 연결성을 확보할 수 있습니다. 먼저 `kubectl get pods | grep fluent`로 pod의 이름을 가져온 다음 `kubectl port-forward fluent-bit-8kvl4 2020:2020`을 사용하여 `http://localhost:2020/`으로 웹 브라우저를 엽니다.
|
||||
|
||||

|
||||
|
||||
[FluentBit](https://medium.com/kubernetes-tutorials/exporting-kubernetes-logs-to-elasticsearch-using-fluent-bit-758e8de606af)에 대한 자세한 내용을 다루는 이 훌륭한 매체 기사도 발견했습니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [Understanding Logging: Containers & Microservices](https://www.youtube.com/watch?v=MMVdkzeQ848)
|
||||
- [The Importance of Monitoring in DevOps](https://www.devopsonline.co.uk/the-importance-of-monitoring-in-devops/)
|
||||
- [Understanding Continuous Monitoring in DevOps?](https://medium.com/devopscurry/understanding-continuous-monitoring-in-devops-f6695b004e3b)
|
||||
- [DevOps Monitoring Tools](https://www.youtube.com/watch?v=Zu53QQuYqJ0)
|
||||
- [Top 5 - DevOps Monitoring Tools](https://www.youtube.com/watch?v=4t71iv_9t_4)
|
||||
- [How Prometheus Monitoring works](https://www.youtube.com/watch?v=h4Sl21AKiDg)
|
||||
- [Introduction to Prometheus monitoring](https://www.youtube.com/watch?v=5o37CGlNLr8)
|
||||
- [Promql cheat sheet with examples](https://www.containiq.com/post/promql-cheat-sheet-with-examples)
|
||||
- [Log Management for DevOps | Manage application, server, and cloud logs with Site24x7](https://www.youtube.com/watch?v=J0csO_Shsj0)
|
||||
- [Log Management what DevOps need to know](https://devops.com/log-management-what-devops-teams-need-to-know/)
|
||||
- [What is ELK Stack?](https://www.youtube.com/watch?v=4X0WLg05ASw)
|
||||
- [Fluentd simply explained](https://www.youtube.com/watch?v=5ofsNyHZwWE&t=14s)
|
||||
- [Fluent Bit explained | Fluent Bit vs Fluentd](https://www.youtube.com/watch?v=B2IS-XS-cc0)
|
||||
|
||||
[Day 82](day82.md)에서 봐요!
|
112
2022/ko/Days/day82.md
Normal file
112
2022/ko/Days/day82.md
Normal file
@ -0,0 +1,112 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - EFK Stack - Day 82'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - EFK Stack
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1049059
|
||||
---
|
||||
|
||||
### EFK 스택
|
||||
|
||||
이전 섹션에서는 스택의 로그 수집기로 Logstash를 사용하는 ELK 스택에 대해 이야기했지만, EFK 스택에서는 이를 FluentD 또는 FluentBit으로 대체합니다.
|
||||
|
||||
이 섹션에서 우리의 임무는 EFK를 사용하여 Kubernetes 로그를 모니터링하는 것입니다.
|
||||
|
||||
### EFK 개요
|
||||
|
||||
우리는 다음을 Kubernetes 클러스터에 배포할 것입니다.
|
||||
|
||||

|
||||
|
||||
EFK 스택은 다음과 같은 3가지 소프트웨어가 함께 번들로 제공되는 모음입니다:
|
||||
|
||||
- Elasticsearch: NoSQL 데이터베이스는 데이터를 저장하는 데 사용되며 검색 및 로그 쿼리를 위한 인터페이스를 제공합니다.
|
||||
|
||||
- Fluentd: Fluentd는 통합 로깅 계층을 위한 오픈 소스 데이터 수집기입니다. Fluentd를 사용하면 데이터 수집과 소비를 통합하여 데이터를 더 잘 사용하고 이해할 수 있습니다.
|
||||
|
||||
- Kibana: 로그 관리 및 통계를 위한 인터페이스. elasticsearch에서 정보를 읽는 역할을 담당합니다.
|
||||
|
||||
### Minikube에 EFK 배포하기
|
||||
|
||||
우리는 신뢰할 수 있는 Minikube 클러스터를 사용해 EFK 스택을 배포할 것입니다. 우리 시스템에서 `minikube start`를 사용하여 클러스터를 시작하겠습니다. WSL2가 활성화된 Windows OS를 사용하고 있습니다.
|
||||
|
||||

|
||||
|
||||
EFK 스택을 클러스터에 배포하는 데 필요한 모든 것을 포함하는 [efk-stack.yaml](/2022/Days/Monitoring/EFK%20Stack/efk-stack.yaml)을 생성했으며, `kubectl create -f efk-stack.yaml` 명령을 사용하여 배포되는 모든 것을 확인할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
시스템에 따라 다르지만, 이미 이 작업을 실행하여 이미지를 가져온 경우 다음 명령으로 진행 상황을 확인할 수 있습니다. `kubectl get pods -n kube-logging -w` 몇 분 정도 걸릴 수 있습니다.
|
||||
|
||||

|
||||
|
||||
위의 명령으로 상황을 계속 주시할 수 있지만, 모든 pod가 이제 실행 중인지 확인하기 위해 다음 `kubectl get pods -n kube-logging` 명령을 실행하여 모든 것이 정상임을 명확히 하고 싶습니다.
|
||||
|
||||

|
||||
|
||||
모든 pod가 실행되고 실행 중이고 이 단계에서는 다음을 볼 수 있어야 합니다.
|
||||
|
||||
- ElasticSearch와 연결된 3개의 pod
|
||||
- Fluentd와 연결된 pod 1개
|
||||
- Kibana와 연결된 pod 1개
|
||||
|
||||
또한 `kubectl get all -n kube-logging`을 사용하여 네임스페이스에 모두 표시할 수 있으며, 앞서 설명한 대로 fluentd는 데몬셋으로 배포되고, kibana는 deployment로, Elasticsearch는 statefulset으로 배포됩니다.
|
||||
|
||||

|
||||
|
||||
이제 모든 pod가 실행되고 실행 중이므로 이제 새 터미널에서 포트 포워드 명령을 실행하여 kibana 대시보드에 액세스할 수 있습니다. pod 이름은 여기에 표시된 명령과 다를 것입니다. `kubectl port-forward kibana-84cf7f59c-v2l8v 5601:5601 -n kube-logging`
|
||||
|
||||

|
||||
|
||||
이제 브라우저를 열고 `http://localhost:5601` 주소로 이동하면 아래와 같은 화면이 표시되거나 실제로 샘플 데이터 화면이 표시되거나 계속 진행하여 직접 구성할 수 있습니다. 어느 쪽이든 이전 세션에서 ELK 스택을 살펴볼 때 다루었던 테스트 데이터를 꼭 살펴보시기 바랍니다.
|
||||
|
||||

|
||||
|
||||
다음으로, 왼쪽 메뉴의 "discover" 탭을 누르고 인덱스 패턴에 "\*"를 추가해야 합니다. "Next step"를 눌러 다음 단계로 계속 진행합니다.
|
||||
|
||||

|
||||
|
||||
2단계 2번에서는 시간별로 데이터를 필터링하기 위해 드롭다운에서 @timestamp 옵션을 사용하겠습니다. 패턴 만들기를 누르면 완료하는 데 몇 초 정도 걸릴 수 있습니다.
|
||||
|
||||

|
||||
|
||||
이제 몇 초 후에 "discover" 탭으로 돌아가면 Kubernetes 클러스터에서 데이터가 들어오는 것을 볼 수 있을 것입니다.
|
||||
|
||||

|
||||
|
||||
이제 EFK 스택이 실행 중이고 Fluentd를 통해 Kubernetes 클러스터에서 로그를 수집하고 있으므로 왼쪽 상단의 Kibana 로고를 눌러 홈 화면으로 이동하면 처음 로그인할 때 보았던 것과 동일한 페이지가 표시됩니다.
|
||||
|
||||
다른 플러그인이나 소스로부터 APM, 로그 데이터, 메트릭 데이터, 보안 이벤트를 추가할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
"Add log data"를 선택하면 아래에서 로그를 가져올 위치에 대한 많은 선택 사항이 있음을 알 수 있으며, ELK 스택의 일부인 Logstash가 언급되어 있는 것을 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
메트릭 데이터 아래에서 Prometheus 및 기타 여러 서비스에 대한 소스를 추가할 수 있음을 알 수 있습니다.
|
||||
|
||||
### APM(Application Performance Monitoring)
|
||||
|
||||
애플리케이션 내부에서 심층적인 성능 메트릭과 오류를 수집하는 APM(Application Performance Monitoring)을 수집하는 옵션도 있습니다. 이를 통해 수천 개의 애플리케이션의 성능을 실시간으로 모니터링할 수 있습니다.
|
||||
|
||||
여기서는 APM에 대해 자세히 설명하지 않겠지만, [Elastic 사이트](https://www.elastic.co/observability/application-performance-monitoring)에서 자세한 내용을 확인할 수 있습니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [Understanding Logging: Containers & Microservices](https://www.youtube.com/watch?v=MMVdkzeQ848)
|
||||
- [The Importance of Monitoring in DevOps](https://www.devopsonline.co.uk/the-importance-of-monitoring-in-devops/)
|
||||
- [Understanding Continuous Monitoring in DevOps?](https://medium.com/devopscurry/understanding-continuous-monitoring-in-devops-f6695b004e3b)
|
||||
- [DevOps Monitoring Tools](https://www.youtube.com/watch?v=Zu53QQuYqJ0)
|
||||
- [Top 5 - DevOps Monitoring Tools](https://www.youtube.com/watch?v=4t71iv_9t_4)
|
||||
- [How Prometheus Monitoring works](https://www.youtube.com/watch?v=h4Sl21AKiDg)
|
||||
- [Introduction to Prometheus monitoring](https://www.youtube.com/watch?v=5o37CGlNLr8)
|
||||
- [Promql cheat sheet with examples](https://www.containiq.com/post/promql-cheat-sheet-with-examples)
|
||||
- [Log Management for DevOps | Manage application, server, and cloud logs with Site24x7](https://www.youtube.com/watch?v=J0csO_Shsj0)
|
||||
- [Log Management what DevOps need to know](https://devops.com/log-management-what-devops-teams-need-to-know/)
|
||||
- [What is ELK Stack?](https://www.youtube.com/watch?v=4X0WLg05ASw)
|
||||
- [Fluentd simply explained](https://www.youtube.com/watch?v=5ofsNyHZwWE&t=14s)
|
||||
|
||||
[Day 83](day83.md)에서 봐요!
|
153
2022/ko/Days/day83.md
Normal file
153
2022/ko/Days/day83.md
Normal file
@ -0,0 +1,153 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - Data Visualisation - Grafana - Day 83'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - Data Visualisation - Grafana
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048767
|
||||
---
|
||||
|
||||
## 데이터 시각화 - Grafana
|
||||
|
||||
이 섹션에서는 통합 observability과 관련하여 많은 Kibana를 살펴봤습니다. 하지만 시간을 내어 Grafana에 대해서도 다뤄야 합니다. 하지만 이 둘은 동일하지도 않고 서로 완전히 경쟁하는 것도 아닙니다.
|
||||
|
||||
Kibana의 핵심 기능은 데이터 쿼리 및 분석입니다. 사용자는 다양한 방법을 사용해 근본 원인 분석과 진단을 위해 데이터 내에서 특정 이벤트나 문자열에 대해 Elasticsearch에서 색인된 데이터를 검색할 수 있습니다. 이러한 쿼리를 기반으로 사용자는 차트, 표, 지리적 지도 및 기타 유형의 시각화를 사용하여 다양한 방식으로 데이터를 시각화할 수 있는 Kibana의 시각화 기능을 사용할 수 있습니다.
|
||||
|
||||
Grafana는 Kibana의 folk로 시작되었으며, 당시 Kibana가 제공하지 않았던 메트릭, 즉 모니터링에 대한 지원을 제공하는 것이 목표였습니다.
|
||||
|
||||
Grafana는 무료 오픈 소스 데이터 시각화 도구입니다. 현장에서는 일반적으로 Prometheus와 Grafana를 함께 사용하는 것을 볼 수 있지만, Elasticsearch 및 Graphite와 함께 사용하는 경우도 있습니다.
|
||||
|
||||
두 도구의 주요 차이점은 로깅과 모니터링입니다. 이 섹션에서는 Nagios로 모니터링을 다루기 시작해 Prometheus를 살펴본 다음 로깅으로 이동해 ELK 및 EFK 스택을 다루었습니다.
|
||||
|
||||
Grafana는 시스템 CPU, 메모리, 디스크 및 I/O 사용률과 같은 메트릭을 분석하고 시각화하는 데 적합합니다. 이 플랫폼은 전체 텍스트 데이터 쿼리를 허용하지 않습니다. Kibana는 Elasticsearch 위에서 실행되며 주로 로그 메시지 분석에 사용됩니다.
|
||||
|
||||
Kibana는 배포가 매우 쉬울 뿐만 아니라 배포 위치를 선택할 수 있다는 것을 이미 확인했듯이, Grafana도 마찬가지입니다.
|
||||
|
||||
둘 다 Linux, Mac, Windows, Docker에 설치하거나 소스에서 빌드하는 것을 지원합니다.
|
||||
|
||||
의심할 여지 없이 다른 도구도 있지만, Grafana는 가상, 클라우드 및 클라우드 네이티브 플랫폼에 걸쳐서 제가 본 도구이므로 이 섹션에서 다루고 싶었습니다.
|
||||
|
||||
### Prometheus Operator + Grafana Deployment
|
||||
|
||||
이 섹션에서 이미 Prometheus에 대해 다루었지만, 이 두 가지를 함께 사용하는 경우가 너무 많아서 최소한 시각화에서 어떤 메트릭을 표시할 수 있는지 확인할 수 있는 환경을 만들어 보고 싶었습니다. 환경을 모니터링하는 것이 중요하다는 것은 알고 있지만, Prometheus나 다른 메트릭 도구에서 이러한 메트릭만 살펴보는 것은 번거롭고 확장성이 떨어집니다. 바로 이 지점에서 Grafana가 등장하여 Prometheus 데이터베이스에 수집 및 저장된 메트릭의 대화형 시각화를 제공합니다.
|
||||
|
||||
이 시각화를 통해 환경에 맞는 사용자 정의 차트, 그래프 및 알림을 만들 수 있습니다. 이 연습에서는 Minikube 클러스터를 사용하겠습니다.
|
||||
|
||||
먼저 이것을 로컬 시스템에 복제하는 것으로 시작하겠습니다. `git clone https://github.com/prometheus-operator/kube-prometheus.git` 및 `cd kube-prometheus`를 입력하세요.
|
||||
|
||||

|
||||
|
||||
첫 번째 작업은 Minikube 클러스터 내에서 네임스페이스를 생성하는 것입니다. `kubectl create -f manifests/setup` 이전 섹션에서 따라하지 않은 경우 `minikube start`를 사용하여 여기에 새 클러스터를 불러올 수 있습니다.
|
||||
|
||||

|
||||
|
||||
다음으로, `kubectl create -f manifests/` 명령을 사용하여 데모에 필요한 모든 것을 배포할 것인데, 보시다시피 클러스터 내에 다양한 리소스가 배포될 것입니다.
|
||||
|
||||

|
||||
|
||||
이제 pod가 실행될 때까지 기다려야 하며, 실행 상태가 되면 `kubectl get pods -n monitoring -w` 명령어를 사용하여 pod를 계속 감시할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
모든 것이 실행 중이면 `kubectl get pods -n monitoring` 명령으로 모든 pod가 실행 중이고 정상 상태인지 확인할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
배포와 함께 데모 후반부에서 사용할 몇 가지 서비스를 배포했으며, `kubectl get svc -n monitoring` 명령으로 확인할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
마지막으로 `kubectl get all -n monitoring` 명령으로 새 모니터링 네임스페이스에 배포된 모든 리소스를 확인해 봅시다.
|
||||
|
||||

|
||||
|
||||
새 터미널을 열면 이제 Grafana 도구에 액세스하여 몇 가지 메트릭을 수집하고 시각화할 준비가 되었으며, 사용할 명령은 `kubectl --namespace monitoring port-forward svc/grafana 3000`입니다.
|
||||
|
||||

|
||||
|
||||
브라우저를 열고 http://localhost:3000 로 이동하면 사용자 이름과 비밀번호를 입력하라는 메시지가 표시됩니다.
|
||||
|
||||

|
||||
액세스하기 위한 기본 사용자 이름과 비밀번호는 다음과 같습니다.
|
||||
|
||||
```
|
||||
Username: admin
|
||||
Password: admin
|
||||
```
|
||||
|
||||
하지만 처음 로그인할 때 새 비밀번호를 입력하라는 메시지가 표시됩니다. 초기 화면 또는 홈페이지에는 탐색할 수 있는 몇 가지 영역과 Grafana와 그 기능을 익히는 데 유용한 몇 가지 리소스가 표시됩니다. 나중에 사용하게 될 "Add your first data source" 및 "create your first dashboard" 위젯을 주목하세요.
|
||||
|
||||

|
||||
|
||||
Grafana 데이터 소스에 이미 prometheus 데이터 소스가 추가되어 있는 것을 볼 수 있지만, Minikube를 사용하고 있기 때문에 로컬 호스트에서 사용할 수 있도록 prometheus도 포팅해야 하므로 새 터미널을 열고 다음 명령을 실행할 수 있습니다. `kubectl --namespace monitoring port-forward svc/prometheus-k8s 9090` 이제 Grafana의 홈페이지에서 "Add your first data source"라는 위젯에 들어가서 여기에서 Prometheus를 선택합니다.
|
||||
|
||||

|
||||
|
||||
새 데이터 소스의 경우 http://localhost:9090 주소를 사용할 수 있으며, 아래에 강조 표시된 대로 드롭다운을 브라우저로 변경해야 합니다.
|
||||
|
||||

|
||||
|
||||
이제 페이지 하단에서 저장 및 테스트를 누르면 됩니다. 그러면 아래와 같이 Prometheus의 포트 포워딩이 작동하는 결과를 확인할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
홈페이지로 돌아가서 "Create your first dashboard" 옵션을 찾아 "Add a new panel"를 선택합니다.
|
||||
|
||||

|
||||
|
||||
아래에서 이미 Grafana 데이터 원본에서 수집하고 있는 것을 볼 수 있지만, Prometheus 데이터 원본에서 메트릭을 수집하려면 데이터 원본 드롭다운을 선택하고 새로 만든 "Prometheus-1"을 선택합니다.
|
||||
|
||||

|
||||
|
||||
그런 다음 메트릭 브라우저를 선택하면 Minikube 클러스터와 관련된 Prometheus에서 수집되는 메트릭의 긴 목록이 표시됩니다.
|
||||
|
||||

|
||||
|
||||
데모에서는 시스템 리소스에 대한 몇 가지 출력을 제공하는 메트릭을 찾아보겠습니다. `cluster:node_cpu:ratio{}`는 클러스터의 노드에 대한 세부 정보를 제공하고 이 통합이 작동하고 있음을 증명합니다.
|
||||
|
||||

|
||||
|
||||
이 시각화가 마음에 들면 오른쪽 상단의 적용 버튼을 누르면 이 그래프를 대시보드에 추가할 수 있습니다. 계속해서 그래프와 다른 차트를 추가하여 필요한 시각화를 제공할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
그러나 이전에 만든 수천 개의 대시보드를 활용할 수 있으므로 새로 만들 필요가 없습니다.
|
||||
|
||||

|
||||
|
||||
Kubernetes를 검색하면 선택할 수 있는 미리 빌드된 대시보드의 긴 목록을 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
Kubernetes API 서버 대시보드를 선택하고 새로 추가된 Prometheus-1 데이터 소스에 맞게 데이터 소스를 변경하면 아래에 표시되는 몇 가지 메트릭을 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
### 알림
|
||||
|
||||
또한 배포한 알림 관리자를 활용하여 슬랙이나 다른 통합으로 알림을 보낼 수도 있는데, 이렇게 하려면 아래 세부 정보를 사용하여 알림 관리자 서비스를 포트로 포워드해야 합니다.
|
||||
|
||||
`kubectl --namespace monitoring port-forward svc/alertmanager-main 9093`
|
||||
`http://localhost:9093`
|
||||
|
||||
이것으로 통합 observability에 대한 모든 것에 대한 섹션을 마쳤습니다. 개인적으로 이 섹션은 이 주제가 얼마나 광범위한 주제인지 강조했지만, 마찬가지로 이것이 우리의 역할에 얼마나 중요한지, 특히 다른 섹션에서 이미 다룬 모든 자동화를 통해 매우 극적으로 변화할 수 있는 경우 메트릭, 로깅 또는 추적이든 앞으로 광범위한 환경에서 무슨 일이 일어나고 있는지 잘 파악해야 한다는 것을 알 수 있었습니다.
|
||||
|
||||
다음 섹션에서는 데이터 관리와 데이터 관리와 관련하여 데브옵스 원칙을 어떻게 고려해야 하는지에 대해 살펴보겠습니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [Understanding Logging: Containers & Microservices](https://www.youtube.com/watch?v=MMVdkzeQ848)
|
||||
- [The Importance of Monitoring in DevOps](https://www.devopsonline.co.uk/the-importance-of-monitoring-in-devops/)
|
||||
- [Understanding Continuous Monitoring in DevOps?](https://medium.com/devopscurry/understanding-continuous-monitoring-in-devops-f6695b004e3b)
|
||||
- [DevOps Monitoring Tools](https://www.youtube.com/watch?v=Zu53QQuYqJ0)
|
||||
- [Top 5 - DevOps Monitoring Tools](https://www.youtube.com/watch?v=4t71iv_9t_4)
|
||||
- [How Prometheus Monitoring works](https://www.youtube.com/watch?v=h4Sl21AKiDg)
|
||||
- [Introduction to Prometheus monitoring](https://www.youtube.com/watch?v=5o37CGlNLr8)
|
||||
- [Promql cheat sheet with examples](https://www.containiq.com/post/promql-cheat-sheet-with-examples)
|
||||
- [Log Management for DevOps | Manage application, server, and cloud logs with Site24x7](https://www.youtube.com/watch?v=J0csO_Shsj0)
|
||||
- [Log Management what DevOps need to know](https://devops.com/log-management-what-devops-teams-need-to-know/)
|
||||
- [What is ELK Stack?](https://www.youtube.com/watch?v=4X0WLg05ASw)
|
||||
- [Fluentd simply explained](https://www.youtube.com/watch?v=5ofsNyHZwWE&t=14s)
|
||||
|
||||
[Day 84](day84.md)에서 봐요!
|
73
2022/ko/Days/day84.md
Normal file
73
2022/ko/Days/day84.md
Normal file
@ -0,0 +1,73 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - The Big Picture: Data Management - Day 84'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - The Big Picture Data Management
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048747
|
||||
---
|
||||
|
||||
## 큰 그림: 데이터 관리
|
||||
|
||||

|
||||
|
||||
데이터가 몇 년 전보다 더 중요해졌다는 것은 알고 있지만, 데이터 관리는 결코 넘어야 할 새로운 벽이 아닙니다. 가치 있고 끊임없이 변화하는 데이터는 자동화와 빈번한 소프트웨어 릴리스의 지속적인 통합, 테스트 및 배포에 대해 이야기할 때 엄청난 악몽이 될 수도 있습니다. 영구 데이터와 기본 데이터 서비스는 종종 문제가 발생할 때 주범이 되기도 합니다.
|
||||
|
||||
하지만 클라우드 네이티브 데이터 관리에 들어가기 전에 한 단계 더 올라가야 합니다. 이번 챌린지를 통해 다양한 플랫폼을 다루었습니다. 물리, 가상, 클라우드 또는 클라우드 네이티브(Kubernetes 포함) 등 어떤 플랫폼이든 데이터 관리에 대한 요구 사항을 충족하지 않는 플랫폼은 없습니다.
|
||||
|
||||
비즈니스에서 가장 미션 크리티컬한 시스템을 위한 것이든, 아니면 적어도 일부 톱니바퀴가 시스템의 일부 수준에 영구 데이터를 저장하고 있든, 환경 어딘가에 숨어 있는 데이터베이스를 찾을 가능성이 높습니다.
|
||||
|
||||
### 데브옵스와 데이터
|
||||
|
||||
데브옵스 원칙에 대해 이야기했던 이 시리즈의 맨 처음과 마찬가지로, 데이터와 관련하여 더 나은 프로세스를 위해서는 적절한 인력을 포함시켜야 합니다. 여기에는 DBA가 포함될 수도 있지만, 마찬가지로 데이터 서비스의 백업에 관심이 있는 사람들도 포함될 것입니다.
|
||||
|
||||
둘째, 데이터와 관련된 다양한 데이터 유형, 도메인 및 경계를 식별해야 합니다. 이렇게 하면 데이터베이스 관리자, 스토리지 엔지니어 또는 백업에 집중하는 엔지니어 사이에서만 사일로 방식으로 처리되는 것이 아닙니다. 이렇게 하면 전체 팀이 더 넓은 비즈니스를 위한 애플리케이션을 개발하고 호스팅하는 데 있어 최선의 조치 경로를 결정하고 데이터 아키텍처에 집중할지, 아니면 나중에 고려할지 결정할 수 있습니다.
|
||||
|
||||
이제 데이터 라이프사이클의 다양한 영역에 걸쳐 데이터 수집에 대해 이야기할 수 있습니다. 서비스나 애플리케이션에 데이터를 어디서 어떻게 수집할 것인가? 서비스, 애플리케이션 또는 사용자는 이 데이터에 어떻게 액세스할까요? 또한 데이터를 어떻게 보호할 것인지, 그리고 그 데이터를 어떻게 보호할 것인지에 대해서도 이해해야 합니다.
|
||||
|
||||
### 데이터 관리 101
|
||||
|
||||
[데이터 관리 지식 체계](https://www.dama.org/cpages/body-of-knowledge)에 따르면 데이터 관리는 "데이터 및 정보 자산의 가치를 제어, 보호, 제공 및 향상시키는 계획, 정책, 프로그램 및 관행을 개발, 실행 및 감독하는 것"입니다.
|
||||
|
||||
- 데이터는 비즈니스의 가장 중요한 측면입니다 - 데이터는 전체 비즈니스의 한 부분일 뿐입니다. "데이터는 비즈니스의 생명선"이라는 표현을 본 적이 있는데, 대부분 사실일 것입니다. 혈액이 신체에 매우 중요하지만, 혈액만으로는 혈액을 액체로 만드는 데 필요한 신체적 측면이 부족하다는 생각이 들었습니다.
|
||||
|
||||
- 데이터 품질은 그 어느 때보다 중요합니다. 데이터를 비즈니스 자산으로 취급해야 하며, 이는 자동화 및 DevOps 원칙에 따라 데이터에 필요한 고려 사항을 제공해야 한다는 것을 의미합니다.
|
||||
|
||||
- 적시에 데이터에 액세스해야 합니다. - 효과적인 의사 결정을 내리기 위해 적시에 적절한 데이터에 액세스하지 못하는 것을 참을 수 있는 사람은 아무도 없습니다. 데이터는 프레젠테이션에 관계없이 간소화된 방식으로 적시에 사용할 수 있어야 합니다.
|
||||
|
||||
- 데이터 관리는 DevOps의 조력자가 되어야 합니다 - 앞서 간소화에 대해 언급했지만, 데이터 관리 요구 사항을 주기에 포함시켜 데이터의 가용성뿐만 아니라 데이터 포인트에 대한 다른 중요한 정책 기반 보호와 함께 완전히 테스트된 복구 모델도 포함시켜야 합니다.
|
||||
|
||||
### 데이터옵스
|
||||
|
||||
데이터옵스와 데브옵스 모두 기술 개발 및 운영의 모범 사례를 적용하여 품질을 개선하고, 속도를 높이고, 보안 위협을 줄이고, 고객을 만족시키고, 숙련된 전문가에게 의미 있고 도전적인 업무를 제공합니다. DevOps와 DataOps는 가능한 한 많은 프로세스 단계를 자동화하여 제품 제공을 가속화한다는 목표를 공유합니다. 데이터옵스의 목표는 탄력적인 데이터 파이프라인과 데이터 분석을 통한 신뢰할 수 있는 인사이트입니다.
|
||||
|
||||
데이터옵스에 중점을 두는 가장 일반적인 상위 영역은 머신 러닝, 빅 데이터, 인공 지능을 포함한 데이터 분석이 될 것입니다.
|
||||
|
||||
### 데이터 관리는 정보 관리입니다.
|
||||
|
||||
이 섹션에서는 머신 러닝이나 인공 지능을 다루지 않고 데이터 보호 관점에서 데이터를 보호하는 데 초점을 맞출 것이며, 이 하위 섹션의 제목은 "데이터 관리는 정보의 관리"이며 정보 = 데이터라고 연관 지을 수 있습니다.
|
||||
|
||||
데이터와 관련된 여정에서 고려해야 할 세 가지 핵심 영역은 다음과 같습니다:
|
||||
|
||||
- 정확성 - 프로덕션 데이터가 정확한지 확인하는 것과 마찬가지로 백업 형태의 데이터도 작동하는지 확인하고 복구에 대해 테스트하여 장애나 사유가 발생할 경우 가능한 한 빨리 다시 가동할 수 있도록 해야 합니다.
|
||||
|
||||
- 일관성 - 데이터 서비스가 여러 위치에 걸쳐 있는 경우 프로덕션의 경우 모든 데이터 위치에서 일관성을 유지하여 정확한 데이터를 얻을 수 있도록 해야 하며, 이는 이러한 데이터 서비스를 보호하는 데 있어서도 마찬가지입니다. 특히 데이터 서비스는 백업, 복제본 등을 위해 해당 데이터의 깨끗한 사본을 생성할 수 있도록 다양한 수준에서 일관성을 보장해야 합니다.
|
||||
|
||||
- 보안 - 액세스 제어와 마찬가지로 일반적으로 데이터를 보관하는 것은 현재 전 세계적으로 화두가 되고 있는 주제입니다. 적절한 사람만 데이터에 액세스할 수 있도록 하는 것이 가장 중요하며, 이는 다시 데이터 보호로 이어져 필요한 사람만 백업에 액세스하고 백업에서 복원할 수 있으며 다른 버전의 비즈니스 데이터를 복제하여 제공할 수 있도록 해야 합니다.
|
||||
|
||||
더 나은 데이터 = 더 나은 의사 결정
|
||||
|
||||
### 데이터 관리의 Days
|
||||
|
||||
앞으로 6회에 걸쳐 데이터베이스, 백업 및 복구, 재해 복구, 애플리케이션 모빌리티에 대해 자세히 살펴보면서 데모와 실습을 병행할 예정입니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [Kubernetes Backup and Restore made easy!](https://www.youtube.com/watch?v=01qcYSck1c4&t=217s)
|
||||
- [Kubernetes Backups, Upgrades, Migrations - with Velero](https://www.youtube.com/watch?v=zybLTQER0yY)
|
||||
- [7 Database Paradigms](https://www.youtube.com/watch?v=W2Z7fbCLSTw&t=520s)
|
||||
- [Disaster Recovery vs. Backup: What's the difference?](https://www.youtube.com/watch?v=07EHsPuKXc0)
|
||||
- [Veeam Portability & Cloud Mobility](https://www.youtube.com/watch?v=hDBlTdzE6Us&t=3s)
|
||||
|
||||
[Day 85](day85.md)에서 봐요!
|
152
2022/ko/Days/day85.md
Normal file
152
2022/ko/Days/day85.md
Normal file
@ -0,0 +1,152 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - Data Services - Day 85'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - Data Services
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048781
|
||||
---
|
||||
|
||||
## 데이터 서비스
|
||||
|
||||
데이터베이스는 우리 환경에서 가장 흔히 접하는 데이터 서비스가 될 것입니다. 이번 세션에서는 다양한 유형의 데이터베이스와 각 데이터베이스의 사용 사례에 대해 살펴보고자 합니다. 이번 챌린지를 통해 우리가 사용하고 본 몇 가지 사례를 살펴보겠습니다.
|
||||
|
||||
애플리케이션 개발 관점에서 올바른 데이터 서비스 또는 데이터베이스를 선택하는 것은 애플리케이션의 성능과 확장성 측면에서 매우 중요한 결정이 될 것입니다.
|
||||
|
||||
https://www.youtube.com/watch?v=W2Z7fbCLSTw
|
||||
|
||||
### Key-value
|
||||
|
||||
Key-value 데이터베이스는 간단한 Key-value 방식을 사용하여 데이터를 저장하는 비관계형 데이터베이스의 한 유형입니다. Key-value 데이터베이스는 키가 고유 식별자 역할을 하는 Key-value 쌍의 모음으로 데이터를 저장합니다. 키와 값은 단순한 객체부터 복잡한 복합 객체에 이르기까지 무엇이든 될 수 있습니다. Key-value 데이터베이스는 고도로 파티셔닝이 가능하며 다른 유형의 데이터베이스에서는 달성할 수 없는 규모로 수평 확장이 가능합니다.
|
||||
|
||||
Key-value 데이터베이스의 예로는 Redis가 있습니다.
|
||||
|
||||
_Redis는 인메모리 데이터 구조 저장소로, 분산형 인메모리 Key-value 데이터베이스, 캐시 및 메시지 브로커로 사용되며 내구성을 옵션으로 선택할 수 있습니다. Redis는 문자열, 목록, 맵, 집합, 정렬된 집합, HyperLogLogs, 비트맵, 스트림, 공간 인덱스 등 다양한 종류의 추상 데이터 구조를 지원합니다._
|
||||
|
||||

|
||||
|
||||
Redis에 대한 설명에서 알 수 있듯이 이것은 데이터베이스가 빠르다는 것을 의미하지만, 그 대가로 공간에 제한이 있다는 것을 의미합니다. 또한 쿼리나 조인이 없으므로 데이터 모델링 옵션이 매우 제한적입니다.
|
||||
|
||||
Best for:
|
||||
|
||||
- 캐싱
|
||||
- Pub/Sub
|
||||
- 리더보드
|
||||
- 쇼핑 카트
|
||||
|
||||
일반적으로 다른 영구 데이터 레이어 위에 캐시로 사용됩니다.
|
||||
|
||||
### Wide-column
|
||||
|
||||
Wide-column 데이터베이스는 데이터 저장소를 여러 서버 또는 데이터베이스 노드에 분산할 수 있는 유연한 컬럼으로 구성하고, 다차원 매핑을 사용하여 컬럼, 행, 타임스탬프로 데이터를 참조하는 NoSQL 데이터베이스입니다.
|
||||
|
||||
_Cassandra는 무료 오픈소스, 분산형, 광역 열 저장소, NoSQL 데이터베이스 관리 시스템으로, 여러 상품 서버에서 대량의 데이터를 처리하도록 설계되어 단일 장애 지점 없이 고가용성을 제공합니다._
|
||||
|
||||

|
||||
|
||||
스키마가 없어 비정형 데이터를 처리할 수 없지만 일부 워크로드에는 이점으로 작용할 수 있습니다.
|
||||
|
||||
Best for:
|
||||
|
||||
- 시계열
|
||||
- 과거 기록
|
||||
- 많은 쓰기, 적은 읽기
|
||||
|
||||
### 문서
|
||||
|
||||
문서 데이터베이스(문서 지향 데이터베이스 또는 문서 저장소라고도 함)는 문서에 정보를 저장하는 데이터베이스입니다.
|
||||
|
||||
_MongoDB는 소스 사용이 가능한 크로스 플랫폼 문서 지향 데이터베이스 프로그램입니다. NoSQL 데이터베이스 프로그램으로 분류되는 MongoDB는 선택적 스키마와 함께 JSON과 유사한 문서를 사용합니다. MongoDB는 MongoDB Inc.에서 개발했으며 서버 사이드 퍼블릭 라이선스에 따라 라이선스가 부여됩니다._
|
||||
|
||||

|
||||
|
||||
NoSQL 문서 데이터베이스를 사용하면 복잡한 SQL 코드를 사용하지 않고도 간단한 데이터를 저장할 수 있습니다. 안정성 저하 없이 빠르게 저장할 수 있습니다.
|
||||
|
||||
Best for:
|
||||
|
||||
- 대부분의 애플리케이션
|
||||
- 게임
|
||||
- 사물 인터넷
|
||||
|
||||
### 관계형
|
||||
|
||||
데이터베이스를 처음 사용하시지만 데이터베이스에 대해 알고 계신다면 관계형 데이터베이스를 접해 보셨을 것입니다.
|
||||
|
||||
관계형 데이터베이스는 1970년 E. F. Codd가 제안한 데이터의 관계형 모델에 기반한 디지털 데이터베이스입니다. 관계형 데이터베이스를 유지 관리하는 데 사용되는 시스템은 관계형 데이터베이스 관리 시스템입니다. 많은 관계형 데이터베이스 시스템에는 데이터베이스를 쿼리하고 유지 관리하기 위해 SQL을 사용할 수 있는 옵션이 있습니다.
|
||||
|
||||
_MySQL은 오픈소스 관계형 데이터베이스 관리 시스템입니다. 이 이름은 공동 창립자 Michael Widenius의 딸 이름인 'My'와 구조화된 쿼리 언어의 약자인 'SQL'을 조합한 것입니다._
|
||||
|
||||
MySQL은 관계형 데이터베이스의 한 예이며 다른 많은 옵션이 있습니다.
|
||||
|
||||

|
||||
|
||||
관계형 데이터베이스를 연구하는 동안 **ACID**라는 용어 또는 약어가 많이 언급되었는데, (원자성, 일관성, 격리성, 내구성)은 오류, 정전 및 기타 사고에도 불구하고 데이터 유효성을 보장하기 위한 데이터베이스 트랜잭션의 일련의 속성입니다. 데이터베이스의 맥락에서 ACID 속성을 충족하는 일련의 데이터베이스 작업(데이터에 대한 단일 논리적 작업으로 인식될 수 있음)을 트랜잭션이라고 합니다. 예를 들어, 한 은행 계좌에서 다른 은행 계좌로 자금을 이체하는 경우, 한 계좌에서 인출하고 다른 계좌에 입금하는 등 여러 가지 변경 사항이 포함되더라도 이는 단일 트랜잭션에 해당합니다.
|
||||
|
||||
Best for:
|
||||
|
||||
- 대부분의 애플리케이션(수년 동안 사용되어 왔지만, 최고라는 의미는 아님)
|
||||
|
||||
비정형 데이터에는 적합하지 않으며, 특정 워크로드에 대해 더 나은 확장 기능을 제공하는 다른 NoSQL이 언급되는 경우 확장 기능이 이상적이지 않습니다.
|
||||
|
||||
### 그래프
|
||||
|
||||
그래프 데이터베이스는 테이블이나 문서 대신 노드와 관계를 저장합니다. 화이트보드에 아이디어를 스케치하는 것처럼 데이터가 저장됩니다. 데이터는 사전 정의된 모델에 제한되지 않고 저장되므로 매우 유연한 방식으로 데이터를 사고하고 사용할 수 있습니다.
|
||||
|
||||
_Neo4j는 Neo4j, Inc.에서 개발한 그래프 데이터베이스 관리 시스템입니다. 개발자는 네이티브 그래프 저장 및 처리 기능을 갖춘 ACID 호환 트랜잭션 데이터베이스라고 설명합니다._
|
||||
|
||||
Best for:
|
||||
|
||||
- 그래프
|
||||
- 지식 그래프
|
||||
- 추천 엔진
|
||||
|
||||
### 검색 엔진
|
||||
|
||||
지난 섹션에서는 Elasticsearch 방식으로 검색 엔진 데이터베이스를 사용했습니다.
|
||||
|
||||
검색 엔진 데이터베이스는 데이터 콘텐츠 검색 전용으로 사용되는 비관계형 데이터베이스의 한 유형입니다. 검색 엔진 데이터베이스는 인덱스를 사용해 데이터 간에 유사한 특성을 분류하고 검색 기능을 용이하게 합니다.
|
||||
|
||||
_Elasticsearch는 Lucene 라이브러리를 기반으로 하는 검색 엔진입니다. HTTP 웹 인터페이스와 스키마가 없는 JSON 문서를 갖춘 분산형 멀티테넌트 지원 전체 텍스트 검색 엔진을 제공합니다._
|
||||
|
||||
Best for:
|
||||
|
||||
- 검색 엔진
|
||||
- Typeahead
|
||||
- 로그 검색
|
||||
|
||||
### Multi-model
|
||||
|
||||
Multi-model 데이터베이스는 단일 통합 백엔드에 대해 여러 데이터 모델을 지원하도록 설계된 데이터베이스 관리 시스템입니다. 반면, 대부분의 데이터베이스 관리 시스템은 데이터를 구성, 저장 및 조작하는 방법을 결정하는 단일 데이터 모델을 중심으로 구성됩니다. 문서, 그래프, 관계형, Key-value 모델은 Multi-model 데이터베이스에서 지원할 수 있는 데이터 모델의 예입니다.
|
||||
|
||||
_Fauna는 네이티브 GraphQL을 통해 안전하고 확장 가능한 클라우드 API로 제공되는 유연하고 개발자 친화적인 트랜잭션 데이터베이스입니다._
|
||||
|
||||
Best for:
|
||||
|
||||
- 데이터 모델 선택에 얽매이지 않는 경우
|
||||
- ACID 준수
|
||||
- 빠름
|
||||
- 프로비저닝 오버헤드 없음
|
||||
- 데이터를 어떻게 소비하고 클라우드에 무거운 작업을 맡기고 싶으신가요?
|
||||
|
||||
어떤 산업에 종사하든 데이터베이스의 한 영역을 접하게 될 것이므로, 이것으로 데이터베이스 개요 세션을 마무리하겠습니다. 그런 다음 이 섹션의 뒷부분에서 몇 가지 예를 들어 데이터 관리, 특히 이러한 데이터 서비스의 보호 및 저장에 대해 살펴볼 것입니다.
|
||||
|
||||
아래에 링크한 수많은 리소스를 통해 모든 데이터베이스 유형과 이에 수반되는 모든 것을 심도 있게 살펴보는 데 90년이 걸릴 수도 있습니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [Redis Crash Course - the What, Why and How to use Redis as your primary database](https://www.youtube.com/watch?v=OqCK95AS-YE)
|
||||
- [Redis: How to setup a cluster - for beginners](https://www.youtube.com/watch?v=GEg7s3i6Jak)
|
||||
- [Redis on Kubernetes for beginners](https://www.youtube.com/watch?v=JmCn7k0PlV4)
|
||||
- [Intro to Cassandra - Cassandra Fundamentals](https://www.youtube.com/watch?v=YjYWsN1vek8)
|
||||
- [MongoDB Crash Course](https://www.youtube.com/watch?v=ofme2o29ngU)
|
||||
- [MongoDB in 100 Seconds](https://www.youtube.com/watch?v=-bt_y4Loofg)
|
||||
- [What is a Relational Database?](https://www.youtube.com/watch?v=OqjJjpjDRLc)
|
||||
- [Learn PostgreSQL Tutorial - Full Course for Beginners](https://www.youtube.com/watch?v=qw--VYLpxG4)
|
||||
- [MySQL Tutorial for Beginners [Full Course]](https://www.youtube.com/watch?v=7S_tz1z_5bA)
|
||||
- [What is a graph database? (in 10 minutes)](https://www.youtube.com/watch?v=REVkXVxvMQE)
|
||||
- [What is Elasticsearch?](https://www.youtube.com/watch?v=ZP0NmfyfsoM)
|
||||
- [FaunaDB Basics - The Database of your Dreams](https://www.youtube.com/watch?v=2CipVwISumA)
|
||||
- [Fauna Crash Course - Covering the Basics](https://www.youtube.com/watch?v=ihaB7CqJju0)
|
||||
|
||||
[Day 86](day86.md)에서 봐요!
|
181
2022/ko/Days/day86.md
Normal file
181
2022/ko/Days/day86.md
Normal file
@ -0,0 +1,181 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - Backup all the platforms - Day 86'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - Backup all the platforms
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1049058
|
||||
---
|
||||
|
||||
## 모든 플랫폼 백업
|
||||
|
||||
이번 챌린지를 진행하는 동안 다양한 플랫폼과 환경에 대해 논의했습니다. 이 모든 플랫폼과 환경의 공통점은 모두 어느 정도의 데이터 보호가 필요하다는 사실입니다!
|
||||
|
||||
데이터 보호는 수년 전부터 존재해 왔지만, 오늘날의 풍부한 데이터와 이러한 데이터가 가져다주는 가치는 여러 노드와 애플리케이션 전반의 고가용성을 통해 인프라 장애에 대한 복원력을 확보해야 할 뿐만 아니라 장애 시나리오가 발생할 경우 안전하고 안전한 위치에 중요한 데이터의 사본이 필요하다는 점을 고려해야 한다는 것을 의미합니다.
|
||||
|
||||
요즘 사이버 범죄와 랜섬웨어에 대한 이야기를 많이 듣는데, 이는 엄청난 위협이며 랜섬웨어의 공격을 받을 수 있다는 사실에 대해 오해하지 마세요. 랜섬웨어는 시기의 문제가 아닙니다. 따라서 그 시기가 닥쳤을 때를 대비해 데이터를 안전하게 보호해야 하는 이유는 더욱 커집니다. 그러나 데이터 손실의 가장 흔한 원인은 랜섬웨어나 사이버 범죄가 아니라 실수로 인한 삭제입니다!
|
||||
|
||||
우리 모두는 실수로 삭제하지 말았어야 할 파일을 삭제하고 순간적으로 후회한 경험이 있을 것입니다.
|
||||
|
||||
챌린지 기간 동안 논의한 모든 기술과 자동화를 통해 상태 저장 데이터 또는 복잡한 stateless 구성을 보호해야 하는 요구 사항은 플랫폼에 관계없이 여전히 존재합니다.
|
||||
|
||||

|
||||
|
||||
하지만 자동화를 염두에 두고 데이터 보호를 수행할 수 있어야 하며 워크플로우에 통합할 수 있어야 합니다.
|
||||
|
||||
백업이 무엇인지 살펴보면
|
||||
|
||||
_정보 기술에서 백업 또는 데이터 백업은 데이터 손실이 발생한 후 원본을 복원하는 데 사용할 수 있도록 컴퓨터 데이터의 복사본을 다른 곳에 저장하는 것입니다. 이러한 과정을 나타내는 동사 형태는 "back up"이고, 명사 및 형용사 형태는 "백업"입니다._
|
||||
|
||||
이를 가장 간단한 형태로 분류하면 백업은 데이터를 복사하여 새 위치에 붙여 넣는 것입니다. 간단히 말해, 지금 당장 C: 드라이브에 있는 파일을 D: 드라이브로 복사하여 백업을 만들면 C: 드라이브에 문제가 발생하거나 파일 내에서 잘못 편집된 부분이 있을 때를 대비해 복사본을 확보할 수 있습니다. D: 드라이브에 있는 사본으로 되돌릴 수 있습니다. 이제 C 드라이브와 D 드라이브가 모두 있는 곳에서 컴퓨터가 죽으면 보호되지 않으므로 시스템 외부의 솔루션이나 집에 있는 NAS 드라이브에 데이터 사본을 저장하는 방법을 고려해야 하나요? 하지만 집에 무슨 일이 생기면 다른 위치의 다른 시스템에 저장하는 것을 고려해야 할 수도 있고, 클라우드가 옵션이 될 수도 있습니다. 장애 위험을 줄이기 위해 중요한 파일의 사본을 여러 위치에 저장할 수 있을까요?
|
||||
|
||||
### 3-2-1 백업 방법론
|
||||
|
||||
이제 3-2-1 규칙 또는 백업 방법론에 대해 이야기하기에 좋은 시기인 것 같습니다. 이 주제를 다룬 [라이트닝 토크](https://www.youtube.com/watch?v=5wRt1bJfKBw)를 진행한 적이 있습니다.
|
||||
|
||||
데이터를 보호해야 하는 이유에 대해서는 이미 몇 가지 극단적인 예를 들었지만, 아래에 몇 가지를 더 말씀드리겠습니다:
|
||||
|
||||

|
||||
|
||||
이제 3-2-1 방법론에 대해 말씀드리겠습니다. 데이터의 첫 번째 복사본 또는 백업은 가능한 한 프로덕션 시스템에 가깝게 저장해야 하는데, 그 이유는 복구 속도를 고려한 것이며, 다시 실수로 삭제하는 경우가 가장 흔한 복구 이유가 될 것이라는 원래의 이야기로 돌아가겠습니다. 하지만 원본 또는 프로덕션 시스템 외부의 적절한 보조 미디어에 저장하고 싶습니다.
|
||||
|
||||
그런 다음 다른 집, 건물, 데이터 센터 또는 퍼블릭 클라우드 등 두 번째 위치로 데이터 사본을 외부 또는 오프사이트로 전송하고 싶습니다.
|
||||
|
||||

|
||||
|
||||
### 백업 책임
|
||||
|
||||
백업을 하지 않아도 된다는 속설에 대해 "모든 것이 stateless 상태"라는 말을 들어보셨을 것입니다. 모든 것이 stateless 상태라면 비즈니스는 무엇일까요? 데이터베이스도 없고, 워드 문서도 없나요? 비즈니스 내의 모든 개인이 데이터를 보호해야 할 책임이 있지만, 미션 크리티컬 애플리케이션과 데이터에 대한 백업 프로세스를 제공하는 것은 대부분 운영 팀에서 담당하게 될 것입니다.
|
||||
|
||||
데이터베이스에 실수를 해서 클러스터의 모든 노드에 복제되거나 화재, 홍수, 피의 시나리오로 인해 클러스터를 더 이상 사용할 수 없게 되어 중요한 데이터가 손실되는 경우를 제외하고는 "고가용성은 내 백업이고, 클러스터에 여러 노드를 구축했으니 절대 다운될 일은 없습니다!"라고 생각하는 것도 좋은 생각일 수 있습니다. 고집을 부리는 것이 아니라 데이터와 서비스를 인식하는 것이 중요하며, 모든 사람이 아키텍처에 고가용성 및 내결함성을 고려해야 하지만 이것이 백업의 필요성을 대체할 수는 없습니다!
|
||||
|
||||
복제는 데이터의 오프사이트 복사본을 제공하는 것처럼 보일 수 있으며, 위에서 언급한 클러스터가 여러 위치에 분산되어 있을 수도 있지만 첫 번째 실수는 여전히 그곳에 복제될 것입니다. 하지만 백업 요구사항은 환경 내에서 애플리케이션 복제 또는 시스템 복제와 함께 고려해야 합니다.
|
||||
|
||||
이제 이 모든 것을 말했듯이 다른 쪽에서도 극단적으로 나아가 너무 많은 위치에 데이터 사본을 전송할 수 있으며, 이는 비용뿐만 아니라 표면 영역이 크게 확장되어 공격받을 위험이 높아집니다.
|
||||
|
||||
어쨌든 백업은 누가 관리하나요? 각 비즈니스마다 다르겠지만 누군가는 백업 요구 사항을 이해해야 합니다. 그리고 복구 계획도 이해해야 합니다!
|
||||
|
||||
### 모두가 신경 쓸 때까지 아무도 신경 쓰지 않습니다.
|
||||
|
||||
백업은 대표적인 예로, 무언가를 복원해야 할 때까지 아무도 백업에 대해 신경 쓰지 않습니다. 데이터를 백업해야 한다는 요구 사항과 함께 복원 방법도 고려해야 합니다!
|
||||
|
||||
텍스트 문서의 예에서는 아주 작은 파일에 대해 이야기하고 있으므로 앞뒤로 복사하는 기능이 쉽고 빠릅니다. 하지만 100GB 이상의 파일에 대해 이야기하는 경우에는 시간이 오래 걸립니다. 또한 가상 머신을 예로 들면 복구해야 하는 수준도 고려해야 합니다.
|
||||
|
||||
전체 가상 머신이 있고 운영 체제, 애플리케이션이 설치되어 있으며 데이터베이스 서버인 경우 일부 데이터베이스 파일도 있습니다. 실수로 데이터베이스에 잘못된 코드 줄을 삽입한 경우 전체 가상 머신을 복원할 필요는 없으며, 복구 대상만 세분화하여 복구하고 싶습니다.
|
||||
|
||||
### 백업 시나리오
|
||||
|
||||
이제 일부 데이터를 보호하는 시나리오를 구축해 보겠습니다. 특히, 로컬 컴퓨터(이 경우에는 Windows이지만 제가 사용할 도구는 무료 오픈 소스일 뿐만 아니라 크로스 플랫폼도 지원합니다)에서 일부 파일을 보호하고 싶습니다. 집에 로컬로 있는 NAS 장치뿐만 아니라 클라우드의 Object Storage 버킷에도 보호되도록 하고 싶습니다.
|
||||
|
||||
이 중요한 데이터를 백업하고 싶은데, 마침 90DaysOfDevOps의 저장소이기도 하고, 지금 이 글을 읽고 있는 GitHub로도 전송되고 있는데, 만약 내 컴퓨터가 죽고 GitHub가 다운되면 어떻게 될까요? 다른 사람이 어떻게 콘텐츠를 읽을 수 있을 뿐만 아니라 해당 데이터를 다른 서비스로 어떻게 복원할 수 있을까요?
|
||||
|
||||

|
||||
|
||||
이를 달성하는 데 도움이 되는 많은 도구가 있지만, 저는 백업을 암호화, 중복 제거 및 압축하는 동시에 여러 위치로 백업을 보낼 수 있는 오픈 소스 백업 도구인 [Kopia](https://kopia.io/)라는 도구를 사용하려고 합니다.
|
||||
|
||||
[여기](https://github.com/kopia/kopia/releases)에서 릴리스를 다운로드할 수 있으며, 이 글을 쓰는 시점에서는 v0.10.6을 사용할 것입니다.
|
||||
|
||||
### Kopia 설치하기
|
||||
|
||||
Kopia CLI와 GUI가 있는데, 여기서는 GUI를 사용하겠지만 GUI를 제공하지 않는 리눅스 서버의 경우 CLI 버전도 사용할 수 있다는 것을 알고 있습니다.
|
||||
|
||||
저는 `KopiaUI-Setup-0.10.6.exe`를 사용하겠습니다.
|
||||
|
||||
다음번 설치는 매우 빠르게 진행되며, 애플리케이션을 열면 백업 저장소로 사용할 스토리지 유형을 선택할 수 있는 선택 항목이 표시됩니다.
|
||||
|
||||

|
||||
|
||||
### 리포지토리 설정하기
|
||||
|
||||
먼저 로컬 NAS 장치를 사용하여 리포지토리를 설정하고 SMB를 사용하여 이 작업을 수행하려고 하지만 NFS를 사용할 수도 있습니다.
|
||||
|
||||

|
||||
|
||||
다음 화면에서는 비밀번호를 정의할 것이며, 이 비밀번호는 리포지토리 콘텐츠를 암호화하는 데 사용됩니다.
|
||||
|
||||

|
||||
|
||||
이제 리포지토리가 구성되었으므로 임시 스냅샷을 트리거하여 리포지토리에 데이터 쓰기를 시작할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
먼저 스냅샷할 대상의 경로를 입력해야 하며, 여기서는 `90DaysOfDevOps` 폴더의 복사본을 만들고자 합니다. 곧 스케줄링 측면으로 돌아가겠습니다.
|
||||
|
||||

|
||||
|
||||
스냅샷 보존을 정의할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
제외하려는 파일이나 파일 형식이 있을 수 있습니다.
|
||||
|
||||

|
||||
|
||||
일정을 정의하려면 이다음 화면에서 할 수 있으며, 이 스냅샷을 처음 생성할 때 이 페이지가 정의할 첫 페이지입니다.
|
||||
|
||||

|
||||
|
||||
그리고 여기에서 처리할 수 있는 몇 가지 다른 설정이 표시됩니다.
|
||||
|
||||

|
||||
|
||||
지금 스냅샷을 선택하면 데이터가 리포지토리에 기록됩니다.
|
||||
|
||||

|
||||
|
||||
### S3로 오프사이트 백업
|
||||
|
||||
Kopia에서는 UI를 통해 한 번에 하나의 리포지토리만 구성할 수 있는 것처럼 보입니다. 그러나 UI를 통해 창의력을 발휘하여 여러 리포지토리 구성 파일을 선택하여 로컬 및 오프사이트에 복사본을 오브젝트 스토리지에 저장하려는 목표를 달성할 수 있습니다.
|
||||
|
||||
제가 데이터를 전송하기 위해 선택한 오브젝트 스토리지는 Google 클라우드 스토리지입니다. 먼저 Google 클라우드 플랫폼 계정에 로그인하고 스토리지 버킷을 생성했습니다. 시스템에 이미 구글 클라우드 SDK가 설치되어 있었지만 `gcloud auth application-default login`을 실행하면 계정으로 인증되었습니다.
|
||||
|
||||

|
||||
|
||||
그런 다음 Kopia의 CLI를 사용하여 이전 단계에서 SMB 리포지토리를 추가한 후 리포지토리의 현재 상태를 표시했습니다. `C:\Program Files\KopiaUI\resources\server\kopia.exe" --config-file=C:\Users\micha\AppData\Roaming\kopia\repository.config repository status` 명령을 사용하여 이 작업을 수행했습니다.
|
||||
|
||||

|
||||
|
||||
이제 데모를 위해 리포지토리에 대한 구성을 교체할 준비가 되었습니다. 이 두 리포지토리에 모두 적용하는 장기적인 솔루션을 원한다면 `smb.config` 파일과 `object.config` 파일을 생성하고 이 두 명령을 실행하여 데이터 사본을 각 위치로 전송할 수 있어야 할 것입니다. 리포지토리를 추가하기 위해 `"C:\Program Files\KopiaUI\resources\server\kopia.exe" --config-file=C:\Users\micha\AppData\Roaming\kopia\repository.config repository create gcs --bucket 90daysofdevops`를 실행합니다.
|
||||
|
||||
위의 명령은 우리가 생성한 구글 클라우드 스토리지 버킷의 이름이 `90daysofdevops`라는 것을 고려합니다.
|
||||
|
||||

|
||||
|
||||
이제 새 리포지토리를 생성했으므로 `"C:\Program Files\KopiaUI\resources\server\kopia.exe" --config-file=C:\Users\micha\AppData\Roaming\kopia\repository.config repository status` 명령을 다시 실행하면 이제 GCS 리포지토리 구성이 표시됩니다.
|
||||
|
||||

|
||||
|
||||
다음으로 해야 할 일은 스냅샷을 생성하여 새로 생성한 리포지토리로 전송하는 것입니다. `"C:\Program Files\KopiaUI\resources\server\kopia.exe" --config-file=C:\Users\micha\AppData\Roaming\kopia\repository.config kopia snapshot create "C:\Users\micha\demo\90DaysOfDevOps"` 명령을 사용하여 이 프로세스를 시작할 수 있습니다. 아래 브라우저에서 이제 Google 클라우드 스토리지 버킷에 백업에 기반한 kopia 파일이 있는 것을 확인할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
위의 프로세스를 통해 중요한 데이터를 두 개의 다른 위치로 전송해야 하는 요구 사항을 해결할 수 있으며, 그중 하나는 Google Cloud Storage의 오프사이트에 있고 물론 다른 미디어 유형에 데이터의 프로덕션 사본이 여전히 있습니다.
|
||||
|
||||
### 복원
|
||||
|
||||
복원은 또 다른 고려 사항이며 매우 중요한 기능으로, Kopia는 기존 위치뿐만 아니라 새로운 위치로도 복원할 수 있는 기능을 제공합니다.
|
||||
|
||||
`"C:\Program Files\KopiaUI\resources\server\kopia.exe" --config-file=C:\Users\micha\AppData\Roaming\kopia\repository.config snapshot list` 명령을 실행하면 현재 구성된 리포지토리(GCS)에 있는 스냅샷이 나열됩니다.
|
||||
|
||||

|
||||
|
||||
그런 다음 `"C:\Program Files\KopiaUI\resources\server\kopia.exe" --config-file=C:\Users\micha\AppData\Roaming\kopia\repository.config mount all Z:` 명령을 사용하여 GCS에서 직접 해당 스냅샷을 마운트할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
또한 `kopia snapshot restore kdbd9dff738996cfe7bcf99b45314e193`을 사용하여 스냅샷 내용을 복원할 수도 있습니다.
|
||||
|
||||
위의 명령어가 매우 긴데, 이는 실습 상단에 설명한 대로 KopiaUI 버전의 kopia.exe를 사용했기 때문이며, kopia.exe를 다운로드하여 경로에 넣으면 `kopia` 명령어만 사용하면 됩니다.
|
||||
|
||||
다음 세션에서는 Kubernetes 내에서 워크로드를 보호하는 데 중점을 두겠습니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [Kubernetes Backup and Restore made easy!](https://www.youtube.com/watch?v=01qcYSck1c4&t=217s)
|
||||
- [Kubernetes Backups, Upgrades, Migrations - with Velero](https://www.youtube.com/watch?v=zybLTQER0yY)
|
||||
- [7 Database Paradigms](https://www.youtube.com/watch?v=W2Z7fbCLSTw&t=520s)
|
||||
- [Disaster Recovery vs. Backup: What's the difference?](https://www.youtube.com/watch?v=07EHsPuKXc0)
|
||||
- [Veeam Portability & Cloud Mobility](https://www.youtube.com/watch?v=hDBlTdzE6Us&t=3s)
|
||||
|
||||
[Day 87](day87.md)에서 봐요!
|
190
2022/ko/Days/day87.md
Normal file
190
2022/ko/Days/day87.md
Normal file
@ -0,0 +1,190 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - Hands-On Backup & Recovery - Day 87'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - Hands-On Backup & Recovery
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048717
|
||||
---
|
||||
|
||||
## 백업 및 복구 실습
|
||||
|
||||
지난 세션에서는 로컬 NAS와 클라우드 기반 오브젝트 스토리지에 중요한 데이터를 백업하는 데 사용한 오픈소스 백업 도구인 [Kopia](https://kopia.io/)에 대해 살펴봤습니다.
|
||||
|
||||
이번 섹션에서는 Kubernetes 백업의 세계로 들어가 보겠습니다. 이 플랫폼은 챌린지 초반에 [큰 그림: Kubernetes](/2022/Days/Days/day49.md)에서 다뤘던 플랫폼입니다.
|
||||
|
||||
이번에도 Minikube 클러스터를 사용하지만, 이번에는 사용 가능한 몇 가지 애드온을 활용하겠습니다.
|
||||
|
||||
### Kubernetes 클러스터 설정
|
||||
|
||||
Minikube 클러스터를 설정하기 위해 `minikube start --addons volumesnapshots,csi-hostpath-driver --apiserver-port=6443 --container-runtime=containerd -p 90daysofdevops --kubernetes-version=1.21.2`를 실행하면 백업을 수행할 때 이를 최대한 활용하기 위해 `volumesnapshots` 및 `csi-hostpath-driver`를 사용하고 있는 것을 알 수 있습니다.
|
||||
|
||||
이 시점에서는 아직 Kasten K10을 배포하지 않았지만, 클러스터가 가동되면 다음 명령을 실행하여 Kasten K10이 이를 사용할 수 있도록 volumesnapshotclass에 주석을 달려고 합니다.
|
||||
|
||||
```Shell
|
||||
kubectl annotate volumesnapshotclass csi-hostpath-snapclass \
|
||||
k10.kasten.io/is-snapshot-class=true
|
||||
```
|
||||
|
||||
또한 다음을 사용하여 기본 저장소 클래스를 표준 기본 저장소 클래스에서 csi-hostpath 저장소 클래스로 변경할 것입니다.
|
||||
|
||||
```Shell
|
||||
kubectl patch storageclass csi-hostpath-sc -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"true"}}}'
|
||||
|
||||
kubectl patch storageclass standard -p '{"metadata": {"annotations":{"storageclass.kubernetes.io/is-default-class":"false"}}}'
|
||||
```
|
||||
|
||||

|
||||
|
||||
### Kasten K10 배포하기
|
||||
|
||||
Kasten Helm 리포지토리를 추가합니다.
|
||||
|
||||
`helm repo add kasten https://charts.kasten.io/`
|
||||
|
||||
여기에서도 `arkade kasten install k10`을 사용할 수 있지만 데모를 위해 다음 단계를 진행하겠습니다. [자세한 내용](https://blog.kasten.io/kasten-k10-goes-to-the-arkade)
|
||||
|
||||
네임스페이스를 생성하고 K10을 배포합니다.(약 5분 정도 소요됨)
|
||||
|
||||
`helm install k10 kasten/k10 --namespace=kasten-io --set auth.tokenAuth.enabled=true --set injectKanisterSidecar.enabled=true --set-string injectKanisterSidecar.namespaceSelector.matchLabels.k10/injectKanisterSidecar=true --create-namespace`
|
||||
|
||||

|
||||
|
||||
다음 명령어를 실행하여 pod가 생성되는 것을 확인할 수 있습니다.
|
||||
|
||||
`kubectl get pods -n kasten-io -w`
|
||||
|
||||

|
||||
|
||||
포트 포워딩을 통해 K10 대시보드에 접속하고, 새 터미널을 열어 아래 명령을 실행합니다.
|
||||
|
||||
`kubectl --namespace kasten-io port-forward service/gateway 8080:8000`
|
||||
|
||||
Kasten 대시보드는 `http://127.0.0.1:8080/k10/#/`에서 사용할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
이제 대시보드로 인증하려면 다음 명령어로 얻을 수 있는 토큰이 필요합니다.
|
||||
|
||||
```Shell
|
||||
TOKEN_NAME=$(kubectl get secret --namespace kasten-io|grep k10-k10-token | cut -d " " -f 1)
|
||||
TOKEN=$(kubectl get secret --namespace kasten-io $TOKEN_NAME -o jsonpath="{.data.token}" | base64 --decode)
|
||||
|
||||
echo "Token value: "
|
||||
echo $TOKEN
|
||||
```
|
||||
|
||||

|
||||
|
||||
이제 이 토큰을 가져와 브라우저에 입력하면 이메일과 회사 이름을 입력하라는 메시지가 표시됩니다.
|
||||
|
||||

|
||||
|
||||
그러면 Kasten K10 대시보드에 액세스할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
### stateful 애플리케이션 배포
|
||||
|
||||
Kubernetes 섹션에서 사용한 stateful 애플리케이션을 사용합니다.
|
||||
|
||||

|
||||
|
||||
이 애플리케이션의 YAML 구성 파일은 여기에서 찾을 수 있습니다. -> [pacman-stateful-demo.yaml](/2022/Days/Kubernetes/pacman-stateful-demo.yaml)
|
||||
|
||||

|
||||
|
||||
`kubectl get all -n pacman`을 사용하여 다가오는 pod를 확인할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
그런 다음 새 터미널에서 pacman 프론트엔드를 포트 포워드할 수 있습니다. `kubectl port-forward svc/pacman 9090:80 -n pacman`을 실행합니다.
|
||||
|
||||
브라우저에서 다른 탭을 열어 http://localhost:9090/ 에접속합니다.
|
||||
|
||||

|
||||
|
||||
시간을 내어 백엔드 MongoDB 데이터베이스에서 높은 점수를 기록하세요.
|
||||
|
||||

|
||||
|
||||
### 높은 점수 보호
|
||||
|
||||
이제 데이터베이스에 미션 크리티컬한 데이터가 있으며 이를 잃고 싶지 않습니다. 이 전체 애플리케이션을 보호하기 위해 Kasten K10을 사용할 수 있습니다.
|
||||
|
||||
Kasten K10 대시보드 탭으로 돌아가면 Kubernetes 클러스터에 pacman 애플리케이션이 추가되어 애플리케이션 수가 1개에서 2개로 늘어난 것을 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
애플리케이션 카드를 클릭하면 클러스터에서 자동으로 검색된 애플리케이션을 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
Kasten K10을 사용하면 스토리지 기반 스냅샷을 활용할 수 있을 뿐만 아니라 사본을 오브젝트 스토리지 옵션으로 내보낼 수도 있습니다.
|
||||
|
||||
데모에서는 클러스터에 수동 스토리지 스냅샷을 생성한 다음, 고득점 데이터에 불량 데이터를 추가하여 실수로 실수하는 상황을 시뮬레이션해 보겠습니다.
|
||||
|
||||
먼저 아래의 수동 스냅샷 옵션을 사용할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
데모에서는 모든 것을 기본값으로 두겠습니다.
|
||||
|
||||

|
||||
|
||||
대시보드로 돌아가면 실행 중인 작업에 대한 상태 보고서가 표시되며, 완료되면 이와 같이 성공적으로 표시됩니다.
|
||||
|
||||

|
||||
|
||||
### 실패 시나리오
|
||||
|
||||
이제 애플리케이션에 규범적인 잘못된 변경을 추가하기만 하면 미션 크리티컬 데이터에 치명적인 변경을 수행할 수 있습니다.
|
||||
|
||||
아래에서 볼 수 있듯이, 프로덕션 미션 크리티컬 데이터베이스에는 원하지 않는 두 가지 입력이 있습니다.
|
||||
|
||||

|
||||
|
||||
### 데이터 복원
|
||||
|
||||
이것은 간단한 데모이며 현실적이지 않은 방식이지만 데이터베이스를 삭제하는 것이 얼마나 쉬운지 보셨나요?
|
||||
|
||||
이제 고득점 목록을 실수하기 전의 상태로 조금 더 깔끔하게 정리해 보겠습니다.
|
||||
|
||||
애플리케이션 카드와 pacman 탭으로 돌아가면 이제 복원할 수 있는 복원 지점이 하나 생겼습니다.
|
||||
|
||||

|
||||
|
||||
복원을 선택하면 해당 애플리케이션에 연결된 모든 스냅샷과 내보내기를 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
복원을 선택하면 사이드 창이 나타나며, 기본 설정을 유지하고 복원을 누릅니다.
|
||||
|
||||

|
||||
|
||||
복원할 것인지 확인합니다.
|
||||
|
||||

|
||||
|
||||
그런 다음 대시보드로 돌아가서 복원 진행 상황을 확인할 수 있습니다. 다음과 같은 화면이 표시됩니다.
|
||||
|
||||

|
||||
|
||||
하지만 더 중요한 것은 미션 크리티컬 애플리케이션에서 고점수 목록이 어떻게 보이는지입니다. 앞서 다룬 대로 pacman으로 포트 포워딩을 다시 시작해야 합니다.
|
||||
|
||||

|
||||
|
||||
매우 간단한 데모이며, 백업과 관련하여 Kasten K10이 달성할 수 있는 것의 표면적인 부분만 다루었습니다. 앞으로 이러한 영역 중 일부에 대해 좀 더 심층적인 비디오 콘텐츠를 제작할 예정입니다. 또한 재해 복구 및 데이터의 이동성과 관련하여 데이터 관리와 관련된 몇 가지 다른 주요 영역을 강조하기 위해 Kasten K10을 사용할 것입니다.
|
||||
|
||||
다음에는 애플리케이션 일관성에 대해 살펴보겠습니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [Kubernetes Backup and Restore made easy!](https://www.youtube.com/watch?v=01qcYSck1c4&t=217s)
|
||||
- [Kubernetes Backups, Upgrades, Migrations - with Velero](https://www.youtube.com/watch?v=zybLTQER0yY)
|
||||
- [7 Database Paradigms](https://www.youtube.com/watch?v=W2Z7fbCLSTw&t=520s)
|
||||
- [Disaster Recovery vs. Backup: What's the difference?](https://www.youtube.com/watch?v=07EHsPuKXc0)
|
||||
- [Veeam Portability & Cloud Mobility](https://www.youtube.com/watch?v=hDBlTdzE6Us&t=3s)
|
||||
|
||||
[Day 88](day88.md)에서 봐요!
|
296
2022/ko/Days/day88.md
Normal file
296
2022/ko/Days/day88.md
Normal file
@ -0,0 +1,296 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - Application Focused Backup - Day 88'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - Application Focused Backups
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048749
|
||||
---
|
||||
|
||||
## 애플리케이션 중심 백업
|
||||
|
||||
데이터 서비스 또는 데이터베이스와 같은 데이터 집약적인 애플리케이션에 대해서는 이미 [day 85](day85.md)에서 설명한 바 있습니다. 이러한 데이터 서비스의 경우 특히 애플리케이션 일관성과 관련하여 일관성을 관리하는 방법을 고려해야 합니다.
|
||||
|
||||
이 글에서는 애플리케이션 데이터를 일관되게 보호하는 것과 관련된 요구 사항을 자세히 살펴보겠습니다.
|
||||
|
||||
이를 위해 우리가 선택한 도구는 [Kanister](https://kanister.io/)입니다.
|
||||
|
||||

|
||||
|
||||
### Kanister 소개
|
||||
|
||||
Kanister는 Kasten이 만든 오픈소스 프로젝트로, Kubernetes에서 애플리케이션 데이터를 관리(백업 및 복원)할 수 있게 해줍니다. Kanister를 Helm 애플리케이션으로 Kubernetes 클러스터에 배포할 수 있습니다.
|
||||
|
||||
Kanister는 Kubernetes 커스텀 리소스를 사용하며, Kanister를 배포할 때 설치되는 주요 커스텀 리소스는 다음과 같습니다.
|
||||
|
||||
- `Profile` - 백업을 저장하고 복구할 대상 위치입니다. 가장 일반적으로는 오브젝트 스토리지입니다.
|
||||
- `Blueprint` - 데이터베이스를 백업 및 복구하기 위해 수행해야 하는 단계가 Blueprint에 유지되어야 합니다.
|
||||
- `ActionSet` - 대상 백업을 Profile로 이동하고 복원 작업을 수행하는 동작입니다.
|
||||
|
||||
### 실행 연습
|
||||
|
||||
실습에 들어가기 전에 Kanister가 애플리케이션 데이터를 보호하기 위해 취하는 워크플로우를 살펴보겠습니다. 먼저 컨트롤러를 Helm을 사용하여 Kubernetes 클러스터에 배포하고, Kanister는 해당 네임스페이스 내에 위치합니다. 커뮤니티에서 지원하는 많은 Blueprint를 사용할 수 있으며, 이에 대해서는 곧 자세히 다루겠습니다. 그런 다음 데이터베이스 워크로드가 있습니다.
|
||||
|
||||

|
||||
|
||||
이제 ActionSet을 생성합니다.
|
||||
|
||||

|
||||
|
||||
ActionSet을 사용하면 특정 데이터 서비스에 대해 Blueprint에 정의된 액션을 실행할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
ActionSet은 차례로 Kanister 함수(KubeExec, KubeTask, 리소스 라이프사이클)를 사용하여 백업을 대상 리포지토리(Profile)로 push합니다.
|
||||
|
||||

|
||||
|
||||
해당 작업이 완료/실패하면 해당 상태가 ActionSet에서 업데이트됩니다.
|
||||
|
||||

|
||||
|
||||
### Kanister 배포
|
||||
|
||||
이번에도 Minikube 클러스터를 사용하여 애플리케이션 백업을 수행합니다. 이전 세션에서 계속 실행 중이라면 이 클러스터를 계속 사용할 수 있습니다.
|
||||
|
||||
이 글을 쓰는 시점에, 우리는 다음 Helm 명령으로 이미지 버전 `0.75.0`을 사용하여 Kubernetes 클러스터에 kanister를 설치합니다.
|
||||
|
||||
`helm install kanister --namespace kanister kanister/kanister-operator --set image.tag=0.75.0 --create-namespace`
|
||||
|
||||

|
||||
|
||||
`kubectl get pods -n kanister`를 사용하여 pod가 실행 중인지 확인한 다음 사용자 정의 리소스 정의가 사용 가능한지 확인할 수 있습니다.(Kanister만 설치한 경우 강조 표시된 3이 표시됩니다.)
|
||||
|
||||

|
||||
|
||||
### 데이터베이스 배포하기
|
||||
|
||||
Helm을 통해 MySQL을 배포합니다:
|
||||
|
||||
```Shell
|
||||
APP_NAME=my-production-app
|
||||
kubectl create ns ${APP_NAME}
|
||||
helm repo add bitnami https://charts.bitnami.com/bitnami
|
||||
helm install mysql-store bitnami/mysql --set primary.persistence.size=1Gi,volumePermissions.enabled=true --namespace=${APP_NAME}
|
||||
kubectl get pods -n ${APP_NAME} -w
|
||||
```
|
||||
|
||||

|
||||
|
||||
초기 데이터로 MySQL 데이터베이스를 채우고 다음을 실행합니다:
|
||||
|
||||
```Shell
|
||||
MYSQL_ROOT_PASSWORD=$(kubectl get secret --namespace ${APP_NAME} mysql-store -o jsonpath="{.data.mysql-root-password}" | base64 --decode)
|
||||
MYSQL_HOST=mysql-store.${APP_NAME}.svc.cluster.local
|
||||
MYSQL_EXEC="mysql -h ${MYSQL_HOST} -u root --password=${MYSQL_ROOT_PASSWORD} -DmyImportantData -t"
|
||||
echo MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
|
||||
```
|
||||
|
||||
### MySQL 클라이언트 생성하기
|
||||
|
||||
클라이언트 역할을 할 다른 컨테이너 이미지를 실행합니다.
|
||||
|
||||
```Shell
|
||||
APP_NAME=my-production-app
|
||||
kubectl run mysql-client --rm --env APP_NS=${APP_NAME} --env MYSQL_EXEC="${MYSQL_EXEC}" --env MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD} --env MYSQL_HOST=${MYSQL_HOST} --namespace ${APP_NAME} --tty -i --restart='Never' --image docker.io/bitnami/mysql:latest --command -- bash
|
||||
```
|
||||
|
||||
```Shell
|
||||
참고: 이미 기존 MySQL 클라이언트 pod가 실행 중인 경우 다음 명령으로 삭제하세요.
|
||||
|
||||
kubectl delete pod -n ${APP_NAME} mysql-client
|
||||
```
|
||||
|
||||
### MySQL에 데이터 추가하기
|
||||
|
||||
```Shell
|
||||
echo "create database myImportantData;" | mysql -h ${MYSQL_HOST} -u root --password=${MYSQL_ROOT_PASSWORD}
|
||||
MYSQL_EXEC="mysql -h ${MYSQL_HOST} -u root --password=${MYSQL_ROOT_PASSWORD} -DmyImportantData -t"
|
||||
echo "drop table Accounts" | ${MYSQL_EXEC}
|
||||
echo "create table if not exists Accounts(name text, balance integer); insert into Accounts values('nick', 0);" | ${MYSQL_EXEC}
|
||||
echo "insert into Accounts values('albert', 112);" | ${MYSQL_EXEC}
|
||||
echo "insert into Accounts values('alfred', 358);" | ${MYSQL_EXEC}
|
||||
echo "insert into Accounts values('beatrice', 1321);" | ${MYSQL_EXEC}
|
||||
echo "insert into Accounts values('bartholomew', 34);" | ${MYSQL_EXEC}
|
||||
echo "insert into Accounts values('edward', 5589);" | ${MYSQL_EXEC}
|
||||
echo "insert into Accounts values('edwin', 144);" | ${MYSQL_EXEC}
|
||||
echo "insert into Accounts values('edwina', 233);" | ${MYSQL_EXEC}
|
||||
echo "insert into Accounts values('rastapopoulos', 377);" | ${MYSQL_EXEC}
|
||||
echo "select * from Accounts;" | ${MYSQL_EXEC}
|
||||
exit
|
||||
```
|
||||
|
||||
아래와 같은 데이터를 볼 수 있을 것입니다.
|
||||
|
||||

|
||||
|
||||
### Kanister Profile 생성
|
||||
|
||||
Kanister는 Blueprint와 이 두 유틸리티를 통해 오브젝트 스토리지 공급자와 상호작용할 수 있는 CLI인 `kanctl`과 또 다른 유틸리티인 `kando`를 제공합니다.
|
||||
|
||||
[CLI 다운로드](https://docs.kanister.io/tooling.html#tooling)
|
||||
|
||||
이제 Profile 대상과 복원 위치로 사용할 AWS S3 버킷을 생성했습니다. 환경 변수를 사용하여 `kanctl`로 실행하는 명령을 계속 보여드릴 수 있도록 환경 변수를 사용하여 kanister Profile을 생성하겠습니다.
|
||||
|
||||
`kanctl create profile s3compliant --access-key $ACCESS_KEY --secret-key $SECRET_KEY --bucket $BUCKET --region eu-west-2 --namespace my-production-app`
|
||||
|
||||

|
||||
|
||||
### Blueprint 시간
|
||||
|
||||
[Kanister 예제](https://github.com/kanisterio/kanister/tree/master/examples)에 나열되어 있지 않은 데이터 서비스가 아니라면 처음부터 만들 필요는 없지만, 커뮤니티 기여를 통해 이 프로젝트의 인지도를 높일 수 있습니다.
|
||||
|
||||
우리가 사용할 Blueprint는 아래와 같습니다.
|
||||
|
||||
```Shell
|
||||
apiVersion: cr.kanister.io/v1alpha1
|
||||
kind: Blueprint
|
||||
metadata:
|
||||
name: mysql-blueprint
|
||||
actions:
|
||||
backup:
|
||||
outputArtifacts:
|
||||
mysqlCloudDump:
|
||||
keyValue:
|
||||
s3path: "{{ .Phases.dumpToObjectStore.Output.s3path }}"
|
||||
phases:
|
||||
- func: KubeTask
|
||||
name: dumpToObjectStore
|
||||
objects:
|
||||
mysqlSecret:
|
||||
kind: Secret
|
||||
name: '{{ index .Object.metadata.labels "app.kubernetes.io/instance" }}'
|
||||
namespace: '{{ .StatefulSet.Namespace }}'
|
||||
args:
|
||||
image: ghcr.io/kanisterio/mysql-sidecar:0.75.0
|
||||
namespace: "{{ .StatefulSet.Namespace }}"
|
||||
command:
|
||||
- bash
|
||||
- -o
|
||||
- errexit
|
||||
- -o
|
||||
- pipefail
|
||||
- -c
|
||||
- |
|
||||
s3_path="/mysql-backups/{{ .StatefulSet.Namespace }}/{{ index .Object.metadata.labels "app.kubernetes.io/instance" }}/{{ toDate "2006-01-02T15:04:05.999999999Z07:00" .Time | date "2006-01-02T15-04-05" }}/dump.sql.gz"
|
||||
root_password="{{ index .Phases.dumpToObjectStore.Secrets.mysqlSecret.Data "mysql-root-password" | toString }}"
|
||||
mysqldump --column-statistics=0 -u root --password=${root_password} -h {{ index .Object.metadata.labels "app.kubernetes.io/instance" }} --single-transaction --all-databases | gzip - | kando location push --profile '{{ toJson .Profile }}' --path ${s3_path} -
|
||||
kando output s3path ${s3_path}
|
||||
restore:
|
||||
inputArtifactNames:
|
||||
- mysqlCloudDump
|
||||
phases:
|
||||
- func: KubeTask
|
||||
name: restoreFromBlobStore
|
||||
objects:
|
||||
mysqlSecret:
|
||||
kind: Secret
|
||||
name: '{{ index .Object.metadata.labels "app.kubernetes.io/instance" }}'
|
||||
namespace: '{{ .StatefulSet.Namespace }}'
|
||||
args:
|
||||
image: ghcr.io/kanisterio/mysql-sidecar:0.75.0
|
||||
namespace: "{{ .StatefulSet.Namespace }}"
|
||||
command:
|
||||
- bash
|
||||
- -o
|
||||
- errexit
|
||||
- -o
|
||||
- pipefail
|
||||
- -c
|
||||
- |
|
||||
s3_path="{{ .ArtifactsIn.mysqlCloudDump.KeyValue.s3path }}"
|
||||
root_password="{{ index .Phases.restoreFromBlobStore.Secrets.mysqlSecret.Data "mysql-root-password" | toString }}"
|
||||
kando location pull --profile '{{ toJson .Profile }}' --path ${s3_path} - | gunzip | mysql -u root --password=${root_password} -h {{ index .Object.metadata.labels "app.kubernetes.io/instance" }}
|
||||
delete:
|
||||
inputArtifactNames:
|
||||
- mysqlCloudDump
|
||||
phases:
|
||||
- func: KubeTask
|
||||
name: deleteFromBlobStore
|
||||
args:
|
||||
image: ghcr.io/kanisterio/mysql-sidecar:0.75.0
|
||||
namespace: "{{ .Namespace.Name }}"
|
||||
command:
|
||||
- bash
|
||||
- -o
|
||||
- errexit
|
||||
- -o
|
||||
- pipefail
|
||||
- -c
|
||||
- |
|
||||
s3_path="{{ .ArtifactsIn.mysqlCloudDump.KeyValue.s3path }}"
|
||||
kando location delete --profile '{{ toJson .Profile }}' --path ${s3_path}
|
||||
```
|
||||
|
||||
이를 추가하기 위해 `kubectl create -f mysql-blueprint.yml -n kanister` 명령을 사용합니다.
|
||||
|
||||

|
||||
|
||||
### ActionSet을 생성하고 애플리케이션 보호하기
|
||||
|
||||
이제 이 애플리케이션에 대한 백업을 정의하는 ActionSet을 사용하여 MySQL 데이터의 백업을 수행하겠습니다. 컨트롤러와 동일한 네임스페이스에 ActionSet을 생성합니다.
|
||||
|
||||
`kubectl get profiles.cr.kanister.io -n my-production-app` 명령은 이전에 생성한 Profile을 표시하며, 여기에 여러 Profile을 구성할 수 있으므로 다른 ActionSet에 특정 Profile을 사용할 수 있습니다.
|
||||
|
||||
그런 다음 `kanctl`을 사용하여 다음 명령으로 ActionSet을 생성합니다.
|
||||
|
||||
`kanctl create actionset --action backup --namespace kanister --blueprint mysql-blueprint --statefulset my-production-app/mysql-store --profile my-production-app/s3-profile-dc5zm --secrets mysql=my-production-app/mysql-store`
|
||||
|
||||
위의 명령에서 네임스페이스에 추가한 Blueprint, `my-production-app` 네임스페이스의 statefulset, 그리고 MySQL 애플리케이션에 들어가기 위한 시크릿을 정의하고 있음을 알 수 있습니다.
|
||||
|
||||

|
||||
|
||||
ActionSet 이름을 가져와서 다음 명령 `kubectl --namespace kanister describe actionset backup-qpnqv`를 사용하여 ActionSet의 상태를 확인합니다.
|
||||
|
||||
마지막으로, 이제 AWS S3 버킷에 데이터가 있는지 확인할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
### 복원
|
||||
|
||||
복원하기 전에 약간의 손상을 입혀야 합니다. 테이블을 drop할 수도 있고, 실수일 수도 있고 그렇지 않을 수도 있습니다.
|
||||
|
||||
MySQL pod에 연결합니다.
|
||||
|
||||
```Shell
|
||||
APP_NAME=my-production-app
|
||||
kubectl run mysql-client --rm --env APP_NS=${APP_NAME} --env MYSQL_EXEC="${MYSQL_EXEC}" --env MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD} --env MYSQL_HOST=${MYSQL_HOST} --namespace ${APP_NAME} --tty -i --restart='Never' --image docker.io/bitnami/mysql:latest --command -- bash
|
||||
```
|
||||
|
||||
중요 데이터 DB는 `echo "SHOW DATABASES;" | ${mysql_exec}`로 확인할 수 있습니다.
|
||||
|
||||
그런 다음 drop하기 위해 `echo "DROP DATABASE myImportantData;" | ${mysql_exec}`를 실행했습니다.
|
||||
|
||||
그리고 데이터베이스를 보여주기 위해 몇 번의 시도를 통해 이것이 사라진 것을 확인했습니다.
|
||||
|
||||

|
||||
|
||||
이제 Kanister를 사용하여 `kubectl get actionset -n kanister`를 사용하여 앞서 가져 온 ActionSet 이름을 찾아 중요한 데이터를 다시 가져올 수 있습니다. 그런 다음 `kanctl create actionset -n kanister --action restore --from "backup-qpnqv"`를 사용하여 데이터를 복원하기 위한 복원 ActionSet을 생성합니다.
|
||||
|
||||

|
||||
|
||||
아래 명령어를 사용하여 데이터베이스에 연결하면 데이터가 복구되었는지 확인할 수 있습니다.
|
||||
|
||||
```Shell
|
||||
APP_NAME=my-production-app
|
||||
kubectl run mysql-client --rm --env APP_NS=${APP_NAME} --env MYSQL_EXEC="${MYSQL_EXEC}" --env MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD} --env MYSQL_HOST=${MYSQL_HOST} --namespace ${APP_NAME} --tty -i --restart='Never' --image docker.io/bitnami/mysql:latest --command -- bash
|
||||
```
|
||||
|
||||
이제 MySQL 클라이언트에 들어가서 `echo "SHOW DATABASES;" | ${MYSQL_EXEC}`를 실행하면 데이터베이스가 다시 돌아온 것을 확인할 수 있습니다. 또한 `"select * from Accounts;" | ${MYSQL_EXEC}`를 실행하여 데이터베이스의 내용을 확인할 수 있으며 중요한 데이터가 복원되었습니다.
|
||||
|
||||

|
||||
|
||||
다음 포스트에서는 Kubernetes 내의 재해 복구에 대해 살펴보겠습니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [Kanister Overview - An extensible open-source framework for app-lvl data management on Kubernetes](https://www.youtube.com/watch?v=wFD42Zpbfts)
|
||||
- [Application Level Data Operations on Kubernetes](https://community.cncf.io/events/details/cncf-cncf-online-programs-presents-cncf-live-webinar-kanister-application-level-data-operations-on-kubernetes/)
|
||||
- [Kubernetes Backup and Restore made easy!](https://www.youtube.com/watch?v=01qcYSck1c4&t=217s)
|
||||
- [Kubernetes Backups, Upgrades, Migrations - with Velero](https://www.youtube.com/watch?v=zybLTQER0yY)
|
||||
- [7 Database Paradigms](https://www.youtube.com/watch?v=W2Z7fbCLSTw&t=520s)
|
||||
- [Disaster Recovery vs. Backup: What's the difference?](https://www.youtube.com/watch?v=07EHsPuKXc0)
|
||||
- [Veeam Portability & Cloud Mobility](https://www.youtube.com/watch?v=hDBlTdzE6Us&t=3s)
|
||||
|
||||
[Day 89](day89.md)에서 봐요!
|
221
2022/ko/Days/day89.md
Normal file
221
2022/ko/Days/day89.md
Normal file
@ -0,0 +1,221 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - Disaster Recovery - Day 89'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - Disaster Recovery
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048718
|
||||
---
|
||||
|
||||
## 재해 복구
|
||||
|
||||
장애 시나리오에 따라 복구 요구 사항이 어떻게 달라지는지 이미 언급했습니다. 화재, 홍수, 피의 시나리오의 경우 대부분 재해 상황으로, 워크로드를 완전히 다른 위치에서 가능한 한 빨리 가동하거나 최소한 복구 시간 목표(RTO)를 거의 0에 가깝게 설정해야 할 수 있습니다.
|
||||
|
||||
이는 전체 애플리케이션 스택을 standby 환경으로 복제하는 작업을 자동화할 때만 대규모로 달성할 수 있습니다.
|
||||
|
||||
이를 통해 클라우드 리전, 클라우드 제공업체 간 또는 온프레미스와 클라우드 인프라 간에 빠른 페일오버를 수행할 수 있습니다.
|
||||
|
||||
지금까지의 주제에 따라 몇 세션 전에 배포하고 구성한 Minikube 클러스터를 사용하여 Kasten K10을 사용하여 이를 달성하는 방법에 대해 집중적으로 살펴보겠습니다.
|
||||
|
||||
그런 다음 이론상 어느 위치에서나 standby 클러스터 역할을 할 수 있는 또 다른 Minikube 클러스터를 Kasten K10을 설치하여 생성할 것입니다.
|
||||
|
||||
Kasten K10은 또한 실행 중인 Kubernetes 클러스터에 문제가 발생할 경우 카탈로그 데이터를 복제하여 새 클러스터에서 사용할 수 있도록 하는 기능을 내장하고 있습니다. [K10 재해 복구](https://docs.kasten.io/latest/operating/dr.html).
|
||||
|
||||
### K10에 오브젝트 스토리지 추가
|
||||
|
||||
가장 먼저 해야 할 일은 백업을 위한 대상 위치로 오브젝트 스토리지 버킷을 추가하는 것입니다. 이것은 오프사이트 위치 역할을 할 뿐만 아니라 복구할 재해 복구 소스 데이터로도 활용할 수 있습니다.
|
||||
|
||||
지난 세션에서 Kanister 데모를 위해 생성한 S3 버킷을 정리했습니다.
|
||||
|
||||

|
||||
|
||||
포트 포워딩을 통해 K10 대시보드에 접속하고 새 터미널을 열어 아래 명령을 실행합니다:
|
||||
|
||||
`kubectl --namespace kasten-io port-forward service/gateway 8080:8000`
|
||||
|
||||
Kasten 대시보드는 `http://127.0.0.1:8080/k10/#/`에서 확인할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
대시보드로 인증하려면 이제 다음 명령으로 얻을 수 있는 토큰이 필요합니다.
|
||||
|
||||
```Shell
|
||||
TOKEN_NAME=$(kubectl get secret --namespace kasten-io|grep k10-k10-token | cut -d " " -f 1)
|
||||
TOKEN=$(kubectl get secret --namespace kasten-io $TOKEN_NAME -o jsonpath="{.data.token}" | base64 --decode)
|
||||
|
||||
echo "Token value: "
|
||||
echo $TOKEN
|
||||
```
|
||||
|
||||

|
||||
|
||||
이제 이 토큰을 가져와 브라우저에 입력하면 이메일과 회사 이름을 입력하라는 메시지가 표시됩니다.
|
||||
|
||||

|
||||
|
||||
그러면 Kasten K10 대시보드에 액세스할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
이제 Kasten K10 대시보드로 돌아왔으므로 location profile을 추가하고 페이지 상단의 "Settings"와 "New Profile"을 선택합니다.
|
||||
|
||||

|
||||
|
||||
아래 이미지에서 이 location profile의 위치를 선택할 수 있는 것을 볼 수 있으며, Amazon S3를 선택하고 민감한 액세스 자격 증명, 지역 및 버킷 이름을 추가할 것입니다.
|
||||
|
||||

|
||||
|
||||
새 프로필 생성 창을 아래로 스크롤하면 S3 Object Lock API를 활용하는 변경 불가능한 백업도 활성화할 수 있다는 것을 알 수 있습니다. 이 데모에서는 이 기능을 사용하지 않겠습니다.
|
||||
|
||||

|
||||
|
||||
"Save Profile"을 누르면 아래와 같이 새로 생성되거나 추가된 location profile을 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
### pacman 앱을 오브젝트 스토리지에 보호하는 정책 만들기
|
||||
|
||||
이전 세션에서는 pacman 애플리케이션의 임시 스냅샷만 만들었으므로 애플리케이션 백업을 새로 생성한 오브젝트 스토리지 위치로 전송하는 백업 정책을 만들어야 합니다.
|
||||
|
||||
대시보드로 돌아가서 정책 카드를 선택하면 아래와 같은 화면이 표시됩니다. "Create New Policy"를 선택합니다.
|
||||
|
||||

|
||||
|
||||
먼저 정책에 유용한 이름과 설명을 지정할 수 있습니다. 또한 on-demand로 사용하는 데모 용도로 백업 빈도를 정의할 수도 있습니다.
|
||||
|
||||

|
||||
|
||||
다음으로 스냅샷 내보내기를 통해 백업을 활성화하여 데이터를 location profile로 내보내려고 합니다. location profile이 여러 개 있는 경우 백업을 전송할 위치를 선택할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
다음으로 이름 또는 레이블로 애플리케이션을 선택하는데, 저는 이름과 모든 리소스를 기준으로 선택하겠습니다.
|
||||
|
||||

|
||||
|
||||
고급 설정에서는 이 중 어떤 것도 사용하지 않을 것이지만, 어제 작성한 [Kanister 사용법](https://github.com/MichaelCade/90DaysOfDevOps/blob/main/Days/day88.md)에 따라 Kasten K10의 일부로 Kanister를 활용하여 데이터의 애플리케이션 일관된 사본을 가져올 수 있습니다.
|
||||
|
||||

|
||||
|
||||
마지막으로 "Create Policy"을 선택하면 이제 정책 창에서 정책을 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
생성된 정책의 맨 아래에는 "Show import details"가 있는데, standby 클러스터로 import하기 위해서는 이 문자열이 필요합니다. 지금은 안전한 곳에 복사하세요.
|
||||
|
||||

|
||||
|
||||
계속 진행하기 전에 "run once"을 선택하여 개체 스토리지 버킷으로 백업을 전송하기만 하면 됩니다.
|
||||
|
||||

|
||||
|
||||
아래 스크린샷은 데이터 백업 및 내보내기가 성공적으로 완료된 것을 보여드리기 위한 것입니다.
|
||||
|
||||

|
||||
|
||||
### 새 MiniKube 클러스터 생성 및 K10 배포
|
||||
|
||||
그런 다음 두 번째 Kubernetes 클러스터를 배포해야 하며, OpenShift를 포함하여 지원되는 모든 버전의 Kubernetes가 될 수 있지만 교육용으로는 다른 이름의 무료 버전의 MiniKube를 사용하겠습니다.
|
||||
|
||||
`minikube start --addons volumesnapshots,csi-hostpath-driver --apiserver-port=6443 --container-runtime=containerd -p standby --kubernetes-version=1.21.2`를 사용하여 새 클러스터를 생성할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
그리고 다음을 사용하여 이 클러스터에 Kasten K10을 배포할 수 있습니다:
|
||||
|
||||
`helm install k10 kasten/k10 --namespace=kasten-io --set auth.tokenAuth.enabled=true --set injectKanisterSidecar.enabled=true --set-string injectKanisterSidecar.namespaceSelector.matchLabels.k10/injectKanisterSidecar=true --create-namespace`
|
||||
|
||||
이 작업에는 시간이 걸리겠지만, 그동안 `kubectl get pods -n kasten-io -w`를 사용하여 pod가 실행 상태가 되는 진행 상황을 확인할 수 있습니다.
|
||||
|
||||
Minikube를 사용하고 있기 때문에 import 정책을 실행할 때 애플리케이션이 실행되며, 이 standby 클러스터에서 스토리지 클래스가 동일하다는 점에 주목할 필요가 있습니다. 그러나 마지막 세션에서 다룰 내용은 이동성과 변환입니다.
|
||||
|
||||
pod가 가동되고 실행되면 다른 클러스터에서 이전 단계에서 수행한 단계를 따를 수 있습니다.
|
||||
|
||||
포트 포워딩을 통해 K10 대시보드에 액세스하고 새 터미널을 열어 아래 명령을 실행합니다.
|
||||
|
||||
`kubectl --namespace kasten-io port-forward service/gateway 8080:8000`
|
||||
|
||||
Kasten 대시보드는 `http://127.0.0.1:8080/k10/#/`에서 확인할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
대시보드로 인증하려면 이제 다음 명령으로 얻을 수 있는 토큰이 필요합니다.
|
||||
|
||||
```Shell
|
||||
TOKEN_NAME=$(kubectl get secret --namespace kasten-io|grep k10-k10-token | cut -d " " -f 1)
|
||||
TOKEN=$(kubectl get secret --namespace kasten-io $TOKEN_NAME -o jsonpath="{.data.token}" | base64 --decode)
|
||||
|
||||
echo "Token value: "
|
||||
echo $TOKEN
|
||||
```
|
||||
|
||||

|
||||
|
||||
이제 이 토큰을 가져와 브라우저에 입력하면 이메일과 회사 이름을 입력하라는 메시지가 표시됩니다.
|
||||
|
||||

|
||||
|
||||
그러면 Kasten K10 대시보드에 액세스할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
### pacman을 새로운 Minikube 클러스터로 import
|
||||
|
||||
이제 해당 standby 클러스터에서 import 정책을 생성하고 개체 스토리지 백업에 연결하여 어떤 모양과 방식으로 가져올지 결정할 수 있습니다.
|
||||
|
||||
먼저, 앞서 다른 클러스터에서 살펴본 location profile을 추가하고, 여기에 다크 모드를 표시하여 프로덕션 시스템과 DR standby location의 차이를 보여줍니다.
|
||||
|
||||

|
||||
|
||||
이제 대시보드로 돌아가서 정책 탭으로 이동하여 새 정책을 생성합니다.
|
||||
|
||||

|
||||
|
||||
아래 이미지에 따라 import 정책을 만듭니다. 완료되면 정책을 만들 수 있습니다. 여기에는 import 후 복원하는 옵션이 있으며, 일부 사용자는 이 옵션을 원할 수 있으며, 이 옵션은 완료되면 standby 클러스터로 복원됩니다. 또한 복원할 때 애플리케이션의 구성을 변경할 수 있으며, 이는 [day 90](day90.md)에 문서화한 내용입니다.
|
||||
|
||||

|
||||
|
||||
on demeand import를 선택했지만 언제 import를 수행할지 일정을 설정할 수 있습니다. 이 때문에 한 번 실행하겠습니다.
|
||||
|
||||

|
||||
|
||||
아래에서 성공적인 import 정책 작업을 확인할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
이제 대시보드로 돌아가서 애플리케이션 카드로 이동하면 아래에 "Removed" 아래에 표시되는 드롭다운을 선택하면 여기에 애플리케이션이 표시됩니다. 복원을 선택합니다.
|
||||
|
||||

|
||||
|
||||
여기에서 사용 가능한 복원 지점을 확인할 수 있습니다. 이것은 기본 클러스터에서 pacman 애플리케이션에 대해 실행한 백업 작업입니다.
|
||||
|
||||

|
||||
|
||||
다음 세션에서 더 자세히 다루고자 하므로 기본값은 변경하지 않겠습니다.
|
||||
|
||||

|
||||
|
||||
"Restore"을 누르면 확인 메시지가 표시됩니다.
|
||||
|
||||

|
||||
|
||||
아래에서 standby 클러스터에 있는 것을 확인할 수 있으며, pod를 확인하면 실행 중인 애플리케이션이 있는 것을 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
이제 포트 포워딩을 할 수 있습니다.(real-life/프로덕션 환경에서는 애플리케이션에 액세스하기 위해 이 단계가 필요하지 않으며, ingress를 사용할 것입니다).
|
||||
|
||||

|
||||
|
||||
다음으로 애플리케이션 이동성 및 변환에 대해 살펴보겠습니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [Kubernetes Backup and Restore made easy!](https://www.youtube.com/watch?v=01qcYSck1c4&t=217s)
|
||||
- [Kubernetes Backups, Upgrades, Migrations - with Velero](https://www.youtube.com/watch?v=zybLTQER0yY)
|
||||
- [7 Database Paradigms](https://www.youtube.com/watch?v=W2Z7fbCLSTw&t=520s)
|
||||
- [Disaster Recovery vs. Backup: What's the difference?](https://www.youtube.com/watch?v=07EHsPuKXc0)
|
||||
- [Veeam Portability & Cloud Mobility](https://www.youtube.com/watch?v=hDBlTdzE6Us&t=3s)
|
||||
|
||||
[Day 90](day90.md)에서 봐요!
|
127
2022/ko/Days/day90.md
Normal file
127
2022/ko/Days/day90.md
Normal file
@ -0,0 +1,127 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - Data & Application Mobility - Day 90'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - Data & Application Mobility
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048748
|
||||
---
|
||||
|
||||
## 데이터 및 애플리케이션 이동성
|
||||
|
||||
90DaysOfDevOps 챌린지 90일 차! 이번 마지막 세션에서는 데이터와 애플리케이션의 이동성에 대해 다뤄보겠습니다. 특히 Kubernetes에 초점을 맞출 예정이지만, 플랫폼 간 및 플랫폼 전반의 요구사항은 계속 증가하는 요구사항이며 현장에서 볼 수 있는 것입니다.
|
||||
|
||||
"워크로드, 애플리케이션 및 데이터를 한 위치에서 다른 위치로 이동하고 싶다"는 사용 사례는 비용, 위험 또는 비즈니스에 더 나은 서비스를 제공하기 위한 것 등 여러 가지 이유가 있을 수 있습니다.
|
||||
|
||||
이 세션에서는 워크로드를 가지고 한 클러스터에서 다른 클러스터로 Kubernetes 워크로드를 이동하는 방법을 살펴보되, 이 과정에서 대상 위치에서 애플리케이션이 있는 방식을 변경할 것입니다.
|
||||
|
||||
여기에는 [재해 복구](day89.md)에서 겪었던 많은 특징이 사용됩니다.
|
||||
|
||||
### **요구 사항**
|
||||
|
||||
현재 Kubernetes 클러스터로는 수요를 감당할 수 없고 비용이 천정부지로 치솟고 있기 때문에 프로덕션 Kubernetes 클러스터를 다른 퍼블릭 클라우드에 위치한 재해 복구 위치로 이전하여 확장 기능을 제공하면서도 더 저렴한 요금으로 운영하고자 하는 비즈니스 결정이 내려졌습니다. 또한 대상 클라우드에서 사용할 수 있는 일부 기본 클라우드 서비스를 활용할 수도 있습니다.
|
||||
|
||||
현재 미션 크리티컬 애플리케이션(Pac-Man)에 데이터베이스(MongoDB)가 있고 느린 스토리지에서 실행되고 있는데, 더 빠른 새로운 스토리지 계층으로 옮기고 싶습니다.
|
||||
|
||||
현재 Pac-Man(NodeJS) 프론트엔드는 확장이 잘되지 않으며, 새로운 위치에서 사용 가능한 pod의 수를 늘리고 싶습니다.
|
||||
|
||||
### IT팀에 문의하기
|
||||
|
||||
간략하게 설명했지만, 실제로는 이미 재해 복구 Kubernetes 클러스터에 임포트한 상태입니다.
|
||||
|
||||
가장 먼저 해야 할 일은 재해 복구 테스트를 위해 89일에 수행한 복원 작업을 제거하는 것입니다.
|
||||
|
||||
"standby" Minikube 클러스터에서 `kubectl delete ns pacman`을 사용하여 이 작업을 수행할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
시작하려면 Kasten K10 대시보드로 이동하여 애플리케이션 카드를 선택합니다. 드롭다운에서 "Removed"을 선택합니다.
|
||||
|
||||

|
||||
|
||||
그러면 사용 가능한 복원 지점 목록이 표시됩니다. 여기에는 미션 크리티컬 데이터가 포함되어 있으므로 사용 가능한 지점을 선택합니다. (이 예에서는 복원 지점이 하나만 있습니다.)
|
||||
|
||||

|
||||
|
||||
재해 복구 프로세스를 작업할 때는 모든 것을 기본값으로 두었습니다. 그러나 애플리케이션을 변환해야 하는 재해 복구 프로세스가 있는 경우 이러한 추가 복원 옵션을 사용할 수 있습니다. 이 경우 스토리지와 복제본 수를 변경해야 합니다.
|
||||
|
||||

|
||||
|
||||
"Apply transforms to restored resources" 옵션을 선택합니다.
|
||||
|
||||

|
||||
|
||||
수행하려는 변환에 대한 두 가지 기본 제공 예제가 요구 사항에 필요한 것입니다.
|
||||
|
||||

|
||||
|
||||
첫 번째 요구 사항은 기본 클러스터에서는 `csi-hostpath-sc`라는 스토리지 클래스를 사용했지만, 새 클러스터에서는 `standard`를 사용하고자 하는 것이므로 여기서 변경을 수행할 수 있습니다.
|
||||
|
||||

|
||||
|
||||
이제 하단의 변형 만들기 버튼을 누르세요.
|
||||
|
||||

|
||||
|
||||
다음 요구 사항은 pacman 프론트엔드 배포를 "5"로 확장하는 것입니다.
|
||||
|
||||

|
||||
|
||||
이 과정을 잘 따라가셨다면 아래와 같이 두 가지 transform을 모두 보실 수 있을 것입니다.
|
||||
|
||||

|
||||
|
||||
이제 아래 이미지에서 아래 나열된 모든 아티팩트를 복원할 것임을 알 수 있으며, 원한다면 복원하려는 대상을 더 세분화할 수도 있습니다. "Restore" 버튼을 누릅니다.
|
||||
|
||||

|
||||
|
||||
다시 한번 작업을 확인하라는 메시지가 표시됩니다.
|
||||
|
||||

|
||||
|
||||
마지막으로 터미널로 돌아가서 클러스터를 살펴보면, 이제 pacman pod에 대해 5개의 pod가 있고 스토리지 클래스가 표준 대 csi-hostpath-sc로 설정된 것을 볼 수 있습니다.
|
||||
|
||||

|
||||
|
||||
변환을 통해 다양한 옵션을 얻을 수 있습니다. 마이그레이션뿐만 아니라 재해 복구, 테스트 및 개발 유형 시나리오 등에도 적용할 수 있습니다.
|
||||
|
||||
### API 및 자동화
|
||||
|
||||
API를 활용하여 이러한 작업 중 일부를 자동화하는 기능에 대해서는 언급하지 않았지만, 이러한 옵션은 존재하며 UI 전체에 걸쳐 일부 이동 경로가 자동화 작업에 API를 활용할 수 있는 명령 집합을 제공합니다.
|
||||
|
||||
Kasten K10에서 주목해야 할 중요한 점은 배포 시 Kubernetes 클러스터 내부에 배포된 다음 Kubernetes API를 통해 호출할 수 있다는 것입니다.
|
||||
|
||||
이것으로 데이터 저장 및 보호에 관한 섹션을 마무리하겠습니다.
|
||||
|
||||
## 자료
|
||||
|
||||
- [쿠버네티스 백업과 복원이 쉬워졌다!](https://www.youtube.com/watch?v=01qcYSck1c4&t=217s)
|
||||
- [Kubernetes 백업, 업그레이드, 마이그레이션 - Velero와 함께](https://www.youtube.com/watch?v=zybLTQER0yY)
|
||||
- [7가지 데이터베이스 패러다임](https://www.youtube.com/watch?v=W2Z7fbCLSTw&t=520s)
|
||||
- [재해 복구와 백업: 차이점은 무엇인가요?](https://www.youtube.com/watch?v=07EHsPuKXc0)
|
||||
- [Veeam 이동성 및 클라우드 이동성](https://www.youtube.com/watch?v=hDBlTdzE6Us&t=3s)
|
||||
|
||||
### **Closing**
|
||||
|
||||
이 챌린지를 마무리하면서, 정보가 항상 관련성이 있는지 확인하기 위해 계속해서 피드백을 요청하고 싶습니다.
|
||||
|
||||
또한 데브옵스 주제와 관련하여 미처 다루지 못했거나 더 깊이 파고들지 못한 많은 주제가 있다는 점에 감사드립니다.
|
||||
|
||||
이는 내년에 이 챌린지를 다시 시도하여 90일 분량의 콘텐츠와 워크스루를 다시 만들 수 있다는 것을 의미합니다.
|
||||
|
||||
### 다음은 무엇인가요?
|
||||
|
||||
우선, 잠시 글쓰기를 쉬면서 2022년 1월 1일에 이 챌린지를 시작해서 2022년 3월 31일 19시 50분(BST)에 마쳤습니다! 슬로건이었죠. 하지만 제가 오랫동안 말하고 말했듯이이 콘텐츠가 한 사람에게 도움이 된다면 항상 공개적으로 배울 가치가 있습니다!
|
||||
|
||||
앞으로 이 콘텐츠를 어디로 가져갈지에 대한 몇 가지 아이디어가 있는데, 이 콘텐츠가 깃허브 저장소 외에 다른 곳에서 활용될 수 있기를 바라며 전자책이나 실제 책으로도 제작하는 것을 검토해 볼 수 있기를 바랍니다.
|
||||
|
||||
그런 일이 일어나기 전에 각 게시물을 다시 살펴보고 모든 것이 문법적으로 올바른지 확인해야 한다는 것도 알고 있습니다. 마크다운을 인쇄물이나 전자책으로 만드는 방법에 대해 알고 계신 분이 있다면 피드백을 주시면 감사하겠습니다.
|
||||
|
||||
언제나 그렇듯이 이슈와 홍보를 계속 보내주시기 바랍니다.
|
||||
|
||||
Thanks!
|
||||
@MichaelCade1
|
||||
|
||||
- [GitHub](https://github.com/MichaelCade)
|
||||
- [Twitter](https://twitter.com/MichaelCade1)
|
@ -1,115 +1,116 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - The Big Picture: CI/CD Pipelines - Day 70'
|
||||
title: '#90DaysOfDevOps - 概览:CI/CD 管道 - 第七十天'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - The Big Picture CI/CD Pipelines
|
||||
tags: "devops, 90daysofdevops, learning"
|
||||
description: 90DaysOfDevOps - 概览:CI/CD 管道
|
||||
tags: 'devops, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048836
|
||||
---
|
||||
## The Big Picture: CI/CD Pipelines
|
||||
|
||||
A CI/CD (Continous Integration/Continous Deployment) Pipeline implementation is the backbone of the modern DevOps environment.
|
||||
## 概览:CI/CD 管道
|
||||
|
||||
It bridges the gap between development and operations by automating the build, test and deployment of applications.
|
||||
CI/CD(持续集成/持续部署)管道实现的是现代DevOps环境的支柱。
|
||||
|
||||
We covered a lot of this Continous mantra in the opening section of the challenge. But to reiterate:
|
||||
它通过自动化应用程序的构建、测试和部署,将开发和运营联系了起来。
|
||||
|
||||
Continous Integration (CI) is a more modern software development practice in which incremental code changes are made more frequently and reliabily. Automated build and test workflow steps triggered by Contininous Integration ensures that code changes being merged into the repository are reliable.
|
||||
我们在挑战的开头部分介绍了很多这种持续不断的“咒语”。但这里要重申:
|
||||
|
||||
That code / Application is then delivered quickly and seamlessly as part of the Continuous Deployment process.
|
||||
持续集成(CI)是一种更现代的软件开发实践活动,其想法是使代码增加、更改得更频繁、更可靠。由持续集成触发的自动化构建和测试工作流步骤确保了合并到仓库中的代码变更是可靠的。
|
||||
|
||||
### The importance of CI/CD?
|
||||
作为持续部署过程的一部分,这些代码/应用程序将快速无缝地交付。
|
||||
|
||||
- Ship software quickly and efficiently
|
||||
- Facilitates an effective process for getting applications to market as fast as possible
|
||||
- A continous flow of bug fixes and new features without waiting months or years for version releases.
|
||||
### CI/CD的重要特点?
|
||||
|
||||
The ability for developers to make small impactful changes regular means we get faster fixes and more features quicker.
|
||||
- 快速高效地推送软件
|
||||
- 是帮助应用程序尽快推向市场的有效流程
|
||||
- 持续不断地进行错误修复和新功能添加,且无需等待数月或数年进行版本发布。
|
||||
|
||||
### Ok, so what does this mean?
|
||||
开发人员能够定期进行有影响力的小变更,这意味着我们可以更快地进行修复和添加更多功能。
|
||||
|
||||
On [Day 5](day5.md) we covered a lot of the theory behind DevOps and as already mentioned here already that the CI/CD Pipeline is the backbone of the modern DevOps environment.
|
||||
### 所以这意味着什么?
|
||||
|
||||

|
||||
在[第五天](day05.md),我们介绍了DevOps背后的许多理论。正如这里已经提到的,CI/CD管道是现代DevOps环境的支柱。
|
||||
|
||||
I want to reiterate some of the key points on this image above, now that we are a little further into our journey of learning the fundamentals of DevOps.
|
||||

|
||||
|
||||
We are referring to the software development life cycle (SDLC).
|
||||
我想重申上图中的一些关键点,现在我们在学习DevOps基础知识的过程中又向前迈进了一步。
|
||||
|
||||
The steps are usually written out within an infinity loop since it's a cycle that repeats forever.
|
||||
我们指的是软件开发生命周期(SDLC)。
|
||||
|
||||
The steps in the cycle are, developers write the **code** then it gets **built** or all compiled together then it's **tested** for bugs then it's **deployed** into production where it's used (**Operated**) by end users or customers then we **monitor** and collect feedback and finally we **plan** improvements around that feedback **rinse and repeat**.
|
||||
这些步骤通常是在无限循环中的,因为这是一个一直重复的循环流程。
|
||||
|
||||
### Let's go a little deeper into CI/CD
|
||||
这个循环中的步骤是,开发人员编写**代码code**,然后将其**构建built**或全部编译在一起,对其中的bugs进行**测试tested**,接着是**部署deployed**到最终用户或客户(**操作/使用operated**)的产品中,然后我们**监控monitor**并收集反馈,最后我们围绕收集到的反馈进行**计划plan**并**重复rinse and repeat**。
|
||||
|
||||
### CI
|
||||
### 更深入了解 CI/CD
|
||||
|
||||
CI is a development practice that requires developers to integrate code into a shared repository several times a day.
|
||||
### CI 持续集成
|
||||
|
||||
When the code is written and pushed to a repository like github or gitlab that's where the magic begins.
|
||||
CI是一种开发实践活动,要求开发人员每天多次将代码集成到共享的仓库中。
|
||||
|
||||

|
||||
当代码被编写并推送(pushed)到Github或GitLab这样的仓库时,魔法就开始了。
|
||||
|
||||
The code is verified by an automated build which allows teams or the project owner to detect any problems early.
|
||||

|
||||
|
||||

|
||||
代码通过一个自动化构建活动进行验证,这个步骤可以使团队或项目所有者尽早发现问题。
|
||||
|
||||
From there the code is analysed and given a series of automated tests three examples are
|
||||

|
||||
|
||||
- Unit testing this tests the individual units of the source code
|
||||
- Validation testing this makes sure that the software satisfies or fits the intended use
|
||||
- Format testing this checks for syntax and other formatting errors
|
||||
提交的代码会被分析,并给出了一系列自动化测试,这里给出三个例子
|
||||
|
||||
These tests are created as a workflow and then are run every time you push to the master branch so pretty much every major development team has some sort of CI/CD workflow and remember on a development team the new code could be coming in from teams all over the world at different times of the day from developers working on all sorts of different projects it's more efficient to build an automated workflow of tests that make sure that everyone is on the same page before the code is accepted. It would take much longer for a human to do this each time.
|
||||
- 单元测试,测试源代码的各个单元
|
||||
- 验证测试,确保软件满足或适合预期用途
|
||||
- 格式测试,检查语法和其他格式错误
|
||||
|
||||

|
||||
这些测试是作为一个工作流被创建,每当你推送到主分支(master branch)时都会运行。所以几乎每个主要的开发团队都有某种CI/CD工作流。请记住,在开发团队中,新代码可能会在一天中的不同时间从世界各地的团队、从事各种不同项目的开发人员那里传入到测试的工作流程中。因此确保在接受代码之前每个人都在同一页面上。人们每次都要花更长的时间才能做到这一点。
|
||||
|
||||
Once we have our tests complete and they are successful then we can compile and send to our repository. For example I am using Docker Hub but this could be anywhere that then gets leveraged for the CD aspect of the pipeline.
|
||||

|
||||
|
||||

|
||||
一旦我们完成了测试并通过,我们就可以编译它们并将其发送到我们的仓库。例如,我正在使用Docker Hub,但这可能是任何可以用于管道的CD(持续部署)的地方。
|
||||
|
||||
So this process is obviously very much down to the software development process, we are creating our application, adding, fixing bugs etc and then updating our source control and versioning that whilst also testing.
|
||||

|
||||
|
||||
Moving onto the next phase is the CD element which in fact more and more is what we generally see from any off the shelf software, I would argue that we will see a trend that if we get our software from a vendor such as Oracle or Microsoft we will consume that from a Docker Hub type repository and then we would use our CD pipelines to deploy that into our environments.
|
||||
因此,这个过程很大程度上取决于软件开发过程,我们会是正在创建我们的应用程序,添加功能,修复bugs等,然后更新我们的源代码控制和版本控制,同时进行测试。
|
||||
|
||||
### CD
|
||||
进入下一阶段是CD,这更多的是我们通常在任何现成的软件中看到的。如果我们需要从Oracle或Microsoft等供应商那里获得软件,我们将看到一种趋势,从Docker Hub这类仓库中获取这些软件,然后使用我们的CD管道将其部署到我们的环境中。
|
||||
|
||||
Now we have our tested version of our code and we are ready to deploy out into the wild and like I say, the Software vendor will run through this stage but I strongly believe this is how we will all deploy the off the shelf software we require in the future.
|
||||
### CD 持续部署
|
||||
|
||||
It is now time to release our code into an environment. This is going to include Production but also likely other environments as well such as staging.
|
||||
现在我们已经有了代码的测试版本,我们已经准备好进行广泛的部署,正如我上文所说,软件供应商将完成这一阶段,但我坚信这就是我们未来部署所需现成软件的方式。
|
||||
|
||||

|
||||
是时候将我们的代码发布到环境中了。这将包括生产环境,但也可能包括其他环境,如暂存staging。
|
||||
|
||||
Our next step at least on Day 1 of v1 of the software deployment is we need to make sure we are pulling the correct code base to the correct environment. This could be pulling elements from the software repository (DockerHub) but it is more than likely that we are also pulling additional configuration from maybe another code repository, the configuration for the application for example. In the diagram below we are pulling the latest release of the software from DockerHub and then we are releasing this to our environments whilst possibly picking up configuration from a Git repository. Our CD tool is performing this and pushing everything to our environment.
|
||||

|
||||
|
||||
It is most likely that this is not done at the same time. i.e we would go to a staging environment run against this with our own configuration make sure things are correct and this could be a manual step for testing or it could again be automated (lets go with automated) before then allowing this code to be deployed into production.
|
||||
至少在软件部署v1的第一天,我们的下一步是需要确保将正确的代码库拉到(pull)正确的环境中。这可能是从软件仓库(DockerHub)中提取元素,也是可能从另一个代码仓库中提取额外的配置,例如应用程序的配置。在下图中,我们从DockerHub获取最新版本的软件,然后将其发布到我们的环境中,同时可能从Git仓库中获取配置。我们的CD工具正在执行此操作,并将所有内容推送到我们的环境中。
|
||||
|
||||

|
||||
这些很可能不是同时进行的。例如,我们将使用我们的配置进入一个针对此运行的暂存环境,以确保事情是正确的,这可能是一个手动测试步骤,也可能之前实现自动化且可以将此代码部署到生产中。
|
||||
|
||||
Then after this when v2 of the application comes out we rinse and repeat the steps this time we ensure our application + configuration is deployed to staging ensure everything is good and then we deploy to production.
|
||||

|
||||
|
||||
### Why use CI/CD?
|
||||
然后,当应用程序的v2版本发布时,我们重复这些步骤,这一次我们确保我们的应用程序+配置被部署到暂存staging,确保一切正常,然后我们部署到生产中。
|
||||
|
||||
I think we have probably covered the benefits a number of time but it is because it automates things that otherwise would have to be done manually it finds small problems before it sneaks into the main codebase, you can probably imagine that if you push bad code out to your customers then you're going to have a bad time!
|
||||
### 为什么使用CI/CD?
|
||||
|
||||
It also helps to prevent something that we call technical debt which is the idea that since the main code repos are constantly being built upon over time then a shortcut fix taken on day one is now an exponentially more expensive fix years later because now that band-aid of a fix would be so deeply intertwined and baked into all the code bases and logic.
|
||||
我觉得我们已经多次介绍了这些好处,但正是因为它将原来需要手动完成的事情进行自动化了,它可以在加入到主代码库之前发现了一些小问题。你可能可以想象,如果你把坏代码推送给你的客户,这会是多么糟糕!
|
||||
|
||||
### Tooling
|
||||
这也有助于防止我们称之为技术债务(technical debt)的事情,即由于主要代码仓库是随着时间推移而不断构建的,那么有一天做的小修复在几年后会变得更加昂贵,因为现在修复的地方将彻底融入到所有的代码仓库和逻辑中。
|
||||
|
||||
Like with other sections we are going to get hands on with some of the tools that achieve the CI/CD pipeline process.
|
||||
### 工具
|
||||
|
||||
I think it is also important to note that not all tools have to do both CI and CD, We will take a look at ArgoCD which you guessed it is great at the CD element of deploying our software to a Kubernetes cluster. But something like Jenkins can work across many different platforms.
|
||||
与其他章节一样,我们将实操一些CI/CD管道流程的工具。
|
||||
|
||||
My plan is to look at the following:
|
||||
我认为同样重要的是要注意,并不是所有的工具都必须有CI和CD的功能。我们将看看ArgoCD,你可能觉得它在部署软件到Kubernetes集群的CD功能方面非常出色。而像Jenkins这类工具则可以在许多不同的平台上工作。
|
||||
|
||||
我计划关注以下内容:
|
||||
- Jenkins
|
||||
- ArgoCD
|
||||
- GitHub Actions
|
||||
|
||||
## Resources
|
||||
## 相关资料
|
||||
|
||||
- [Jenkins is the way to build, test, deploy](https://youtu.be/_MXtbjwsz3A)
|
||||
- [Introduction to Jenkins](https://www.edx.org/course/introduction-to-jenkins)
|
||||
- [Jenkins.io](https://www.jenkins.io/)
|
||||
- [ArgoCD](https://argo-cd.readthedocs.io/en/stable/)
|
||||
- [ArgoCD Tutorial for Beginners](https://www.youtube.com/watch?v=MeU5_k9ssrs)
|
||||
@ -118,4 +119,4 @@ My plan is to look at the following:
|
||||
- [GitHub Actions](https://www.youtube.com/watch?v=R8_veQiYBjI)
|
||||
- [GitHub Actions CI/CD](https://www.youtube.com/watch?v=mFFXuXjVgkU)
|
||||
|
||||
See you on [Day 71](day71.md)
|
||||
[第七十一天](day71.md)见。
|
||||
|
@ -1,99 +1,102 @@
|
||||
---
|
||||
title: '#90DaysOfDevOps - What is Jenkins? - Day 71'
|
||||
title: '#90DaysOfDevOps - 什么是 Jenkins? - 第七十一天'
|
||||
published: false
|
||||
description: 90DaysOfDevOps - What is Jenkins?
|
||||
tags: "devops, 90daysofdevops, learning"
|
||||
description: 90DaysOfDevOps - 什么是 Jenkins?
|
||||
tags: 'DevOps, 90daysofdevops, learning'
|
||||
cover_image: null
|
||||
canonical_url: null
|
||||
id: 1048745
|
||||
---
|
||||
## What is Jenkins?
|
||||
|
||||
Jenkins is a continous integration tool that allows continous development, test and deployment of newly created code.
|
||||
## 什么是 Jenkins?
|
||||
|
||||
There are two ways we can achieve this with either nightly builds or continous development. The first option is that our developers are developing throughout the day on their tasks and come the end of the set day they push their changes to the source code repository. Then during the night we run our unit tests and build of the software. This could be deemed as the old way to integrate all code.
|
||||
Jenkins是一个持续集成工具,允许对新建的代码进行持续开发、测试和部署。
|
||||
|
||||

|
||||
可以通过夜间构建或持续开发两种方法来实现这些。第一种选择是,我们的开发人员全天都在开发他们的任务,并在当天结束时将他们的更改推送(push)到源代码仓库。然后在晚上,我们运行单元测试并构建软件。这可以被认为是集成所有代码的旧方法。
|
||||
|
||||
The other option and the preferred way is that our developers are still committing their changes to source code, then when that code commit has been made there is a build process kicked off continously.
|
||||

|
||||
|
||||

|
||||
另一种选择也是首选的方式是,我们的开发人员仍在提交他们对源代码的更改,然后当代码提交完成后,构建过程就会不断启动。
|
||||
|
||||
The above methods means that with distributed developers across the world we don't have a set time each day where we have to stop committing our code changes. This is where Jenkins comes in to act as that CI server to control those tests and build processes.
|
||||

|
||||
|
||||

|
||||
上述方法意味着,对于分布在世界各地的开发人员来说,我们每天都没有固定的时间来停止提交代码更改。这就是Jenkins作为CI服务器来控制这些测试和构建过程。
|
||||
|
||||
I know we are talking about Jenkins here but I also want to add a few more to maybe look into later on down the line to get an understanding why I am seeing Jenkins as the overall most popular, why is that and what can the others do over Jenkins.
|
||||

|
||||
|
||||
- TravisCI - A hosted, distributed continous integration service used to build and test software projects hosted on GitHub.
|
||||
虽然我们在这里讨论的是Jenkins,但我也想补充一些内容(也许以后会深入研究),了解为什么我会认为Jenkins是最受欢迎的,为什么会得出这样的判断,以及其他人能在Jenkins上做些什么。
|
||||
|
||||
- Bamboo - Can run multiple builds in parallel for faster compilation, built in functionality to connect with repositories and has build tasks for Ant, Maven.
|
||||
- TravisCI,一种托管的分布式持续集成服务,用于构建和测试托管在GitHub上的软件项目。
|
||||
- Bamboo,可以并行运行多个构建以实现更快的编译,内置与仓库连接的功能,并具有Ant和Maven的构建任务功能。
|
||||
- Buildbot,是一个用于自动化软件构建、测试和发布过程的开源框架。它是用Python编写的,支持跨多个平台分布式并行执行作业。
|
||||
- ApacheGump,专门针对Java项目,旨在每晚构建和测试这些Java项目。确保所有项目在API和功能级别都兼容。
|
||||
|
||||
- Buildbot - is an open-source framework for automating software build, test and release processes. It is written in Python and supports distributed, parallel execution of jobs across multiple platforms.
|
||||
因为我们现在将重点关注Jenkins - Jenkins和上述所有工具一样,是开源的,是一个用Java编写的自动化服务器。它用于通过持续集成实现软件开发过程的自动化,并有助于持续交付。
|
||||
|
||||
- Apache Gump - Specific to Java projects, designed with the aim to build and test those Java projects every night. ensures that all projects are compatible at both API and functionality level.
|
||||
### Jenkins的特性
|
||||
|
||||
Because we are now going to focus on Jenkins - Jenkins is again open source like all of the above tools and is an automation server written in Java. It is used to automate the software development process via continous integration adn faciliates continous delivery.
|
||||
正如你所料,Jenkins有很多功能,涵盖了很多领域。
|
||||
|
||||
### Features of Jenkins
|
||||
**易于安装** - Jenkins是一个独立的基于java的程序,可以与Windows、macOS和Linux操作系统上的软件包一起运行。
|
||||
|
||||
As you can probably expect Jenkins has a lot of features spanning a lot of areas.
|
||||
**轻松配置** - 通过内置的web界面进行设置和配置,包括错误检查和内置帮助。
|
||||
|
||||
**Easy Installation** - Jenkins is a self contained java based program ready to run with packages for Windows, macOS and Linux operating systems.
|
||||
**插件** - 更新中心提供了许多插件,并与CI/CD工具链中的许多工具集成。
|
||||
|
||||
**Easy Configuration** - Easy setup and configured via a web interface which includes error checks and built in help.
|
||||
**可扩展** - 除了可用的插件外,Jenkins还可以通过该插件架构进行扩展,该架构为它的用途提供了几乎无限的选项。
|
||||
|
||||
**Plug-ins** - Lots of plugins available in the Update Centre and integrates with many tools in the CI / CD toolchain.
|
||||
**分布式** - Jenkins可以轻松地在多台机器上分配工作,有助于加快跨多个平台的构建、测试和部署。
|
||||
|
||||
**Extensible** - In addition to the Plug-Ins available, Jenkins can be extended by that plugin architecture which provides nearly infinite options for what it can be used for.
|
||||
### Jenkins的管道pipeline
|
||||
|
||||
**Distributed** - Jenkins easily distributes work across multiple machines, helping to speed up builds, tests and deployments across multiple platforms.
|
||||
|
||||
### Jenkins Pipeline
|
||||
你将会了解这个管道流程,但其还有更广的使用范围,而且我们还没有谈到具体的工具。
|
||||
|
||||
You will have seen this pipeline but used in a much broader and we have not spoken about specific tools.
|
||||
您会把代码提交给Jenkins,然后它将构建您的应用程序,并进行所有自动化测试。接着在每个步骤都完成后进行代码的发布和部署。Jenkins是实现这一过程自动化的工具。
|
||||
|
||||
You are going to be committing code to Jenkins, which then will build out your application, with all automated tests, it will then release and deploy that code when each step is completed. Jenkins is what allows for the automation of this process.
|
||||

|
||||
|
||||

|
||||
### Jenkins的架构
|
||||
|
||||
### Jenkins Architecture
|
||||
首先,不要想着重新造轮子,[Jenkins Documentation](https://www.jenkins.io/doc/developer/architecture/)总是一个开始开始学习的地方,但我也会在这里记下我的笔记和学到的东西。
|
||||
|
||||
First up and not wanting to reinvent the wheel, the [Jenkins Documentation](https://www.jenkins.io/doc/developer/architecture/) is always the place to start but I am going to put down my notes and learnings here as well.
|
||||
Jenkins可以被安装在许多不同的操作系统上,包括Windows、Linux和macOS,也可以作为Docker容器或在Kubernetes中进行部署。[安装Jenkins](https://www.jenkins.io/doc/book/installing/)
|
||||
|
||||
Jenkins can be installed on many different operating systems, Windows, Linux and macOS but then also the ability to deploy as a Docker container and within Kubernetes. [Installing Jenkins](https://www.jenkins.io/doc/book/installing/)
|
||||
当我们开始使用它时,我们可能会考虑在一个minikube集群中安装Jenkins,模拟部署到Kubernetes的过程。但这将取决于我们在本节后续部分中所设置的场景。
|
||||
|
||||
As we get into this we will likely take a look at installing Jenkins within a minikube cluster simulating the deployment to Kubernetes. But this will depend on the scenarios we put together throughout the rest of the section.
|
||||
现在让我们对下面的图像进行拆解。
|
||||
|
||||
Let's now break down the image below.
|
||||
步骤1 - 开发人员提交对源代码仓库的更改。
|
||||
|
||||
Step 1 - Developers commit changes to the source code repository.
|
||||
步骤2 - Jenkins定期检查仓库并提取(pull)任何新代码。
|
||||
|
||||
Step 2 - Jenkins checks the repository at regular intervals and pulls any new code.
|
||||
步骤3 - 构建服务器(build server)将代码构建为可执行文件,在本例中,我们使用maven作为构建服务器。
|
||||
|
||||
Step 3 - A build server then builds the code into an executable, in this example we are using maven as a well known build server. Another area to cover.
|
||||
步骤4 - 如果构建失败,则将反馈发送至开发人员。
|
||||
|
||||
Step 4 - If the build fails then feedback is sent back to the developers.
|
||||
步骤5 - Jenkins将构建应用程序部署到测试服务器,在本例中,我们使用selenium作为测试服务器。
|
||||
|
||||
Step 5 - Jenkins then deploys the build app to the test server, in this example we are using selenium as a well known test server. Another area to cover.
|
||||
步骤6 - 如果测试失败,则将反馈发送至开发人员。
|
||||
|
||||
Step 6 - If the test fails then feedback is passed to the developers.
|
||||
步骤7 - 如果测试成功,那么我们可以将它们发布到生产中。
|
||||
|
||||
Step 7 - If the tests are successful then we can release to production.
|
||||
这个周期是连续的,这使得应用程序可以在几分钟内更新,而不是几小时、几天、几个月和几年!
|
||||
|
||||
This cycle is continous, this is what allows applications to be updated in minutes vs hours, days, months, years!
|
||||

|
||||
|
||||

|
||||
Jenkins的架构中还有很多东西,如果你需要的话,它们有主从功能,可以使主机能够将任务分配到从属Jenkins环境。
|
||||
|
||||
There is a lot more to the architecture of Jenkins if you require it, they have a master-slave capability, which enables a master to distribute the tasks to slave jenkins environment.
|
||||
|
||||
For reference with Jenkins being open source, there are going to be lots of enterprises that require support, CloudBees is that enterprise version of Jenkins that brings support and possibly other functionality for the paying enterprise customer.
|
||||
参考开源的Jenkins,将会有很多企业需要支持,CloudBees是Jenkins的企业版本,为付费企业客户提供支持,并可能提供其他功能。
|
||||
|
||||
An example of this in a customer is Bosch, you can find the Bosch case study [here](https://assets.ctfassets.net/vtn4rfaw6n2j/case-study-boschpdf/40a0b23c61992ed3ee414ae0a55b6777/case-study-bosch.pdf)
|
||||
|
||||
I am going to be looking for a step by step example of an application that we can use to walkthrough using Jenkins and then also use this with some other tools.
|
||||
I am going to be looking for a step-by-step example of an application that we can use to walk through using Jenkins and then also use this with some other tools.
|
||||
|
||||
## Resources
|
||||
博世Bosch就是一个例子,您可以在这里找到博世案例研究(https://assets.ctfassets.net/vtn4rfaw6n2j/case-study-boschpdf/40a0b23c61992ed3ee414ae0a55b6777/case-study-bosch.pdf)
|
||||
|
||||
我将通过一个应用程序示例,我们可以一步步地使用Jenkins进行实操,然后也可以将它与其他一些工具一起使用。
|
||||
|
||||
## 相关资料
|
||||
|
||||
- [Jenkins is the way to build, test, deploy](https://youtu.be/_MXtbjwsz3A)
|
||||
- [Jenkins.io](https://www.jenkins.io/)
|
||||
@ -104,4 +107,4 @@ I am going to be looking for a step by step example of an application that we ca
|
||||
- [GitHub Actions](https://www.youtube.com/watch?v=R8_veQiYBjI)
|
||||
- [GitHub Actions CI/CD](https://www.youtube.com/watch?v=mFFXuXjVgkU)
|
||||
|
||||
See you on [Day 72](day72.md)
|
||||
[第七十二天](day72.md)见。
|
||||
|
@ -62,11 +62,11 @@ As Cybersecurity grows in importance with all the big brands getting hit there i
|
||||
|
||||
The above abstract was taken from the top resource listed at the end of the post.
|
||||
|
||||
<span style="color:red">**Red**</span>, <span style="color:blue">**Blue**</span>, <span style="color:yellow">**Yellow**</span> are primary colours, combine them and we start to understand where the other colours or secondary colours come into play, again really great explanation in that first link.
|
||||
<span style="color:red">**Red**</span>, <span style="color:blue">**Blue**</span>, <span style="color:yellow">**Yellow**</span> are primary colours, combine them and we start to understand where the other colours or secondary colours come into play, again a really great explanation in that first link.
|
||||
|
||||
- <span style="color:purple">**Purple Team**</span> - The special team! If the you take <span style="color:blue">**Blue**</span> and <span style="color:red">**Red**</span> you get <span style="color:purple">**Purple**</span>. If you integrate defence with offence and you collaborate and share knowledge between the teams you overall provide a better posture throughout.
|
||||
- <span style="color:purple">**Purple Team**</span> - The special team! If you take <span style="color:blue">**Blue**</span> and <span style="color:red">**Red**</span> you get <span style="color:purple">**Purple**</span>. If you integrate defence with offence and you collaborate and share knowledge between the teams you overall provide a better posture throughout.
|
||||
|
||||
- <span style="color:green">**Green Team**</span> - Feedback loop, the <span style="color:green">**Green**</span> team are going to take insights from the <span style="color:blue">**Blue**</span> team and work closely with the <span style="color:yellow">**Yellow**</span> team to be more effcient. Mix <span style="color:blue">**Blue**</span> and <span style="color:green">**Green**</span> and what do you <span style="color:purple">**get**</span>?
|
||||
- <span style="color:green">**Green Team**</span> - Feedback loop, the <span style="color:green">**Green**</span> team are going to take insights from the <span style="color:blue">**Blue**</span> team and work closely with the <span style="color:yellow">**Yellow**</span> team to be more efficient. Mix <span style="color:blue">**Blue**</span> and <span style="color:green">**Green**</span> and what do you <span style="color:purple">**get**</span>?
|
||||
|
||||
- <span style="color:orange">**Orange Team**</span> - Much like the <span style="color:green">**Green**</span> team working with the <span style="color:blue">**Blue**</span> team for feedback, the <span style="color:orange">**Orange**</span> team works with the <span style="color:red">**Red**</span> team and pass on what they have learnt to the <span style="color:yellow">**Yellow**</span> team to build better security into their code.
|
||||
|
||||
|
@ -6,13 +6,13 @@ The aim of this series of blog posts is to provide an introduction to databases
|
||||
|
||||
Here’s what we’ll be covering: -
|
||||
|
||||
- An introduction to databases
|
||||
- Querying data in databases
|
||||
- Backing up databases
|
||||
- High availability and disaster recovery
|
||||
- Performance tuning
|
||||
- Database security
|
||||
- Monitoring and troubleshooting database issues
|
||||
- [An introduction to databases](./day63.md)
|
||||
- [Querying data in databases](./day64.md)
|
||||
- [Backing up databases](./day65.md)
|
||||
- [High availability and disaster recovery](./day66.md)
|
||||
- [Performance tuning](./day67.md)
|
||||
- [Database security](./day68.md)
|
||||
- [Monitoring and troubleshooting database issues](./day69.md)
|
||||
|
||||
We’ll also be providing examples to accompany the concepts discussed. In order to do so you will need Docker Desktop installed. Docker can be downloaded here (https://www.docker.com/products/docker-desktop/) and is completely free.
|
||||
|
||||
@ -26,10 +26,10 @@ https://www.pgadmin.org/
|
||||
# About Us
|
||||
|
||||
<b>Andrew Pruski</b><br>
|
||||
Andrew is a Field Solutions Architect working for Pure Storage. He is a Microsoft Data Platform MVP, Certified Kubernetes Administrator, and Raspberry Pi tinkerer. You can find him on twitter @dbafromthecold, LinkedIn, and blogging at dbafromthecold.com
|
||||
Andrew is a Field Solutions Architect working for Pure Storage. He is a Microsoft Data Platform MVP, Certified Kubernetes Administrator, and Raspberry Pi tinkerer. You can find him on twitter [@dbafromthecold](https://twitter.com/dbafromthecold), [LinkedIn](https://www.linkedin.com/in/andrewpruski/), and blogging at [dbafromthecold.com](https://dbafromthecold.com/)
|
||||
|
||||
<b>Taylor Riggan</b><br>
|
||||
Taylor is a Sr. Graph Architect on the Amazon Neptune development team at Amazon Web Services. He works with customers of all sizes to help them learn and use purpose-built NoSQL databases via the creation of reference architectures, sample solutions, and delivering hands-on workshops. You can find him on twitter @triggan and LinkedIn.
|
||||
Taylor is a Sr. Graph Architect on the Amazon Neptune development team at Amazon Web Services. He works with customers of all sizes to help them learn and use purpose-built NoSQL databases via the creation of reference architectures, sample solutions, and delivering hands-on workshops. You can find him on twitter [@triggan](https://twitter.com/triggan) and [LinkedIn](https://www.linkedin.com/in/triggan/).
|
||||
|
||||
<br>
|
||||
|
||||
@ -52,36 +52,44 @@ This is where database technologies come into play. Databases give us the abilit
|
||||
|
||||
# Relational databases
|
||||
|
||||
## History & Background
|
||||
|
||||
When it comes to databases, there are two main types...relational and non-relational (or NoSQL) databases.
|
||||
|
||||
SQL Server, Oracle, MySQL, and PostgreSQL are all types of relational databases.
|
||||
|
||||
Relational databases were first described by Edgar Codd in 1970 whilst he was working at IBM in a research paper , “A Relation Model of Data for Large Shared Data Banks”.
|
||||
Relational databases were first described by Edgar Codd in 1970 whilst he was working at IBM in a research paper , [“A Relation Model of Data for Large Shared Data Banks"](https://dl.acm.org/doi/pdf/10.1145/362384.362685).
|
||||
|
||||
This paper led the way for the rise of the various different relational databases that we have today.
|
||||
|
||||
In a relational database, data is organised into tables (containing rows and columns) and these tables have “relationships” with each other.
|
||||
## Data Model
|
||||
|
||||
In a relational database, data is organised into tables (containing rows and columns). Relationships are generated by creating cross-references between rows in different tables.
|
||||
|
||||
For example, a Person table may have an addressID column which points to a row within an Address table, this allows for an end user or application to easily retrieve a record from the Person table and the related record from the Address table.
|
||||
|
||||
The addressID column is a unique “key” in the Address table but is present in the Person table as a “foreign key”.
|
||||

|
||||
|
||||
The design of the tables and the relations between them in a relational database is said to be the database schema. The process of building this schema is called database normalisation.
|
||||
The AddressID column is a unique “key” in the Address table but is present in the Person table as a “foreign key”. We display this relationship in the diagram above. This is a simple example of an [Entity-Relationship](https://en.wikipedia.org/wiki/Entity%E2%80%93relationship_model) diagram that shows the structure of our database.
|
||||
|
||||
Data is selected, updated, or deleted from a relational database via a programming language called SQL (Structured Query Language).
|
||||
The design of the tables and the relations between them in a relational database is said to be the database schema. The process of building this schema is called [database normalisation](https://en.wikipedia.org/wiki/Database_normalization).
|
||||
|
||||
Data is selected, updated, or deleted from a relational database via a programming language called SQL (Structured Query Language). We'll cover some of the basic concepts of SQL in [Day 64](./day64.md).
|
||||
|
||||
## Indexes
|
||||
|
||||
In order to support retrieving data from tables in a relational database, there is the concept of “indexes”. In order to locate one row or a subset of rows from a table, indexes provide a way for queries to quickly identify the rows they are looking for, without having to scan all the rows in the table.
|
||||
|
||||
The analogy often used when describing indexes is an index of a book. The user (or query) uses the index to go directly to the page (or row) they are looking for, without having to “scan” all the way through the book from the start.
|
||||
|
||||
Queries accessing databases can also be referred to as transactions…a logical unit of work that accesses and/or modifies the data. In order to maintain consistency in the database, transactions must have certain properties. These properties are referred to as ACID properties: -
|
||||
Queries accessing databases can also be referred to as transactions…a logical unit of work that accesses and/or modifies the data. In order to maintain consistency in the database, transactions must have certain properties. These properties are referred to as [ACID](https://en.wikipedia.org/wiki/ACID) properties: -
|
||||
|
||||
A - Atomic - all of the transaction completes or none of it does<br>
|
||||
C - Consistency - the data modified must not violate the integrity of the database<br>
|
||||
I - Isolation - multiple transactions take place independently of one another<br>
|
||||
D - Durability - Once a transaction has completed, it will remain in the system, even in the event of a system failure.
|
||||
|
||||
We will go through querying relational databases in the next blog post.
|
||||
We will go through querying relational databases in the [next blog post](./day64.md).
|
||||
|
||||
<br>
|
||||
|
||||
@ -89,27 +97,38 @@ We will go through querying relational databases in the next blog post.
|
||||
|
||||
The downside of relational databases is that the data ingested has to "fit" to the structure of the database schema. But what if we're dealing with large amounts of data that doesn't match that structure?
|
||||
|
||||
This is where non-relational databases come into play. These types of databases are referred to as NoSQL (non-SQL or Not Only SQL) databases and are either schema-free or have a schema that allows for changes in the structure.
|
||||
This is where non-relational databases come into play. These types of databases are referred to as NoSQL (non-SQL or Not Only SQL or NewSQL) databases and are either schema-free or have a schema that allows for changes in the structure.
|
||||
|
||||
Apache Cassandra, MongoDB, and Redis are all types of NoSQL databases.
|
||||
|
||||
Non-relational databases have existed since the 1960s but the term “NoSQL” was used in 1998 by Carlo Strozzi when naming his Strozzi NoSQL database, however that was still a relational database. It wasn’t until 2009 when Johan Oskarsson reintroduced the term when he organised an event to discuss “open-source distributed, non-relational databases”.
|
||||
There are various different types of NoSQL databases, all of which store and retrieve data differently.
|
||||
|
||||
For example: -
|
||||
## Types of Non-Relational Databases
|
||||
|
||||
Apache Cassandra is a wide-column store database. It uses tables, rows, and columns like a relational database but the names and formats of the columns can vary from row to row in the same table. It uses Cassandra Query Language (CSQL) to access the data stored.
|
||||
### Wide-Coluumn or Key-Value Stores
|
||||
|
||||
MongoDB is a document store database. Data is stored as objects (documents) within the database that do not adhere to a defined schema. MongoDB supports a variety of methods to access data, such as range queries and regular expression searches.
|
||||
[Apache Cassandra](https://cassandra.apache.org/_/index.html) is a wide-column store database. It uses tables, rows, and columns like a relational database but the names and formats of the columns can vary from row to row in the same table. It uses Cassandra Query Language (CSQL) to access the data stored. Wide-column databases, or key-value stores, are optimized for storing very large datasets and servicing millions of queries to perform simple look-ups by a "key", or a single value. These are used in place of a Relational Database when there is a requirement to scale-out the underlying infrastructure to multiple machines in order to process so many requests.
|
||||
|
||||
Redis is a distributed in-memory key-value database. Redis supports many different data structures - sets, hashes, lists, etc. - https://redis.com/redis-enterprise/data-structures/
|
||||
The records can be identified using a unique key. Redis supports various different programming languages in order to access the data stored.
|
||||
### Document Stores
|
||||
|
||||
NoSQL databases generally do not comply with ACID properties but there are exceptions.
|
||||
[MongoDB](https://www.mongodb.com/) is a document store database. Data is stored as objects (documents) within the database that do not adhere to a defined schema. MongoDB supports a variety of methods to access data, such as range queries and regular expression searches. Document stores extend the thinking of key-value stores by servicing lots of requests (millions, at-scale) but also allowing a user to write queries on nested attributes. Documents are typically formated as JSON (not Microsoft Office documents ;) ), and the nested structure of JSON provides an easy means to define query filters on JSON document attributes.
|
||||
|
||||
Each has pros and cons when it comes to storing data, which one to use would be decided on the type of data that is being ingested.
|
||||
### In-Memory Databases
|
||||
|
||||
<br>
|
||||
[Redis](https://redis.io/) is a distributed in-memory key-value database. Redis supports many [different data structures](https://redis.com/redis-enterprise/data-structures/) - sets, hashes, lists, etc. The records can be identified using a unique key. Redis supports various different programming languages in order to access the data stored. In-memory stores are used when fast (sub-millisecond) access times are required. They trade-off a higher cost and lack of immediate persistency for fast access. Developers will often use in-memory stores as a cache in front of other databases, or to optimize aggregations. Redis supports a data structure called a sorted-set, which pre-sorts data and will perform better than an `ORDER BY` query in other databases. You might want to use this sort of pattern if you're building a product website and showing your users what are the best-selling products on your site (sorted by number of purchases).
|
||||
|
||||
### Graph Databases
|
||||
|
||||
[Neo4j](https://neo4j.com) is an open-source graph database. Graph databases are designed to store and query highly connected datasets with many relationships. Data is stored as vertices (or nodes) and edges (or relationships) and a number of attributes (called properties) that can describe a vertex or an edge. Graph databases are optimized for querying across the many connections in the dataset, patterns that may require complex `JOIN` patterns in a relational database. The query languages supported by Graph databases allow a user to easily express these types of "traversal" patterns. Allowing for concepts like recursion that are not easily expressed in languages such as SQL.
|
||||
|
||||
<br />
|
||||
|
||||
NoSQL databases typically trade-off the concept of ACID compliant transactions for their ability to scale or service specific types of data access patterns. If you want to understand these concepts better, we suggest you look into [CAP Theorem](https://en.wikipedia.org/wiki/CAP_theorem).
|
||||
|
||||
CAP Theorem is a concept from Computer Science that discusses the tradeoffs between data Consistency, Availability, and Partitioning. Each has pros and cons when it comes to storing data, which ones to use would be decided on the type of data that is being ingested.
|
||||
|
||||
<br />
|
||||
|
||||
# When to use relational vs non-relational databases
|
||||
|
||||
|
BIN
2023/images/day63-2.png
Normal file
BIN
2023/images/day63-2.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 18 KiB |
Loading…
Reference in New Issue
Block a user