Laboratorul 03. Terraform si Ansible

Pentru cea mai recenta versiune a acestui document intrati aici Terraform si Ansible

Ce facem noi astazi

Scenariu

Incercam sa simulam exemplele din IaC vs click-click, respectiv cel din Configuration management vs click-clack folosind:

  • Docker pentru a simula un provider de masini virtuale

  • Terraform pentru a interactiona cu acest provider

  • Ansible, folosind pluginul Docker pentru inventar, pentru a aplica playbook-ul asupra acestor sisteme

Terraform

CLI

Descarcam si instalam utilitarul CLI Terraform:

cd /workspace/student
mkdir terraform
cd terraform
TF_VERSION="1.0.2"
curl -O https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_linux_amd64.zip
unzip terraform_${TF_VERSION}_linux_amd64.zip
chmod +x terraform

Provider

Folosim un provider (neoficial) pentru a interactiona cu un demon docker ce asculta pe sistemul de pe care rulam Terraform.

provider.tf
terraform {
  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = "2.14.0"
    }
  }
}

provider "docker" {
  host = "unix:///var/run/docker.sock"
}

Modul ROOT

Vom declara intr-un fisier cu extensia .tf faptul ca vrem sa cream doua containere; le vom folosi pentru a simula crearea unor masini virtuale.

Un container ce ruleaza Debian, altul cu CentOS.

main.tf
resource "docker_container" "debian" {
  name    = "debian10"
  image   = docker_image.debian.latest
  command = ["/bin/sh", "-c", "while :; do sleep 100; done"]

  labels {
    label = "Group"
    value = "summerschool"
  }

  env = [
    "http_proxy=${var.http_proxy}",
    "https_proxy=${var.http_proxy}"
  ]

  mounts {
    source = "/etc/ssl/certs/ca-certificates.crt"
    target = "/etc/ssl/certs/ca-certificates.crt"
    read_only = true
    type    = "bind"
  }
}

resource "docker_image" "debian" {
  name = "python:3.6-buster"
}

resource "docker_container" "centos" {
  name  = "centos7"
  image = docker_image.centos.latest
  command = ["/bin/sh", "-c", "while :; do sleep 100; done"]

  labels {
    label = "Group"
    value = "summerschool"
  }

  env = [
    "http_proxy=${var.http_proxy}",
    "https_proxy=${var.http_proxy}"
  ]

  mounts {
    source = "/etc/ssl/certs/ca-certificates.crt"
    target = "/etc/pki/tls/cert.pem"
    read_only = true
    type    = "bind"
  }
}

resource "docker_image" "centos" {
  name = "centos:7.9.2009"
}

variable "http_proxy" {
  description = "Proxy http pe care-l vrem pasat in interiorul containerului"
  default     = "http://10.2.8.100:3128"
}
Note
In reteaua corporate in care ne aflam avem cateva constrangeri, intre care faptul ca trebuie sa iesim in Internet printr-un proxy i.e., http_proxy si https_proxy setate ca variabile in planurile de mai sus, respectiv CA-ul de pe host pe care il montam in container i.e., block set-ul mounts, pentru ca cel din urma contine CA-urile de care avem nevoie in cadrul retelei. Teste efectuate in afara VM-urilor de studenti nu ar trebui sa aiba nevoie de aceste modificari; pe de alta parte, e posibil sa aveti nevoie de parte din ele, sau de altele :^)
Rulam init pentru a aduce providerul de interes si pentru a initializa backend-ul
./terraform init

Initializing the backend...

Initializing provider plugins...
- Reusing previous version of kreuzwerker/docker from the dependency lock file
- Using previously-installed kreuzwerker/docker v2.14.0

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
Rulam apply
./terraform apply

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # docker_container.centos will be created
  + resource "docker_container" "centos" {
      + attach           = false
      + bridge           = (known after apply)
      + command          = [
          + "/bin/sh",
          + "-c",
          + "while :; do sleep 100; done",
        ]
      + container_logs   = (known after apply)
      + entrypoint       = (known after apply)
      + env              = (known after apply)
      + exit_code        = (known after apply)
...

State

Stateul il vom tine local, fiecare pe masina lui de lucru.

Ansible

CLI

Instalam ansible
cd /workspace/student
mkdir ansible
cd ansible
ANSIBLE_VERSION="4.2.0"
python3 -m venv /workspace/student/venvs/ansible
. /workspace/student/venvs/ansible/bin/activate
pip install -U pip
pip install ansible==${ANSIBLE_VERSION} docker-py
Note
E posibil ca pe alte distributii, in afara acestui workshop, sa mai fie nevoie de niste pachete pentru ca ansible sa se instaleze corect. Urmati instructiunile pip pentru a instala (folosind package managerul de sistem) pachetele necesare sau instalati ansible din repository-urile oficiale; detalii gasiti si in sectiunea Documentatie.
Configuram inventarul in /workspace/student/ansible/inv.docker.yml
---
plugin: community.docker.docker_containers
docker_host: unix://var/run/docker.sock
connection_type: docker-cli


keyed_groups:                               # Cream grupuri
        - prefix: grup                      # prefixate cu grup_
          key: 'docker_config.Labels.Group' # pe baza label-ului numit Group configurat in resursa declarata in Terraform

Aplicam playbookul din sectiunea Configuration management vs click-clack:

playbook.yml
---
- hosts: "{{ _hosts | default('all') }}"   # executam asupra tuturor sistemelor despre care stim
  become_user: root                        # ne conectam ca si utilizatorul root
  vars:
    utilizatori:
      - user: asterix # Parola este: asterix
        parola: "$6$U9D8CKVFasZBXtfE$jElu7BDrU7bykn2LudE1moTKea3ffK5Tad0P9x2T/U5y0rGm8Q4qcbm/VivSvRy0Yk3b29V0rX3J.KH0UFMEP/"
      - user: obelix
      - user: idefix
    pachete:   # definim o variabila de tip lista pentru stocarea numelor pachetelor
      - lynx
      - tmux
      - vsftpd
      - gcc
    motd: |
      Va rugam politicos sa nu folositi acest sistem daca nu aveti dreptul sa o faceti.  Multumim!

      --- Panoramix si echipa
  tasks:       # executam pasii pe care ni-i dorim
    - name: Instalam grupul
      group:
        name: "admini"

    - name: Instalam utilizatorii
      user:
        name: "{{ item.user }}"
        group: "admini"
        password: "{{ item.parola | default(omit) }}"
        state: present
      loop: "{{ utilizatori }}" # executam modulul `user` pentru fiecare utilizator

    - name: Instalam pachetele
      package:
        name: "{{ pachete }}"
        state: present

    - name: Aplicam bannerul
      copy:
        content: "{{ motd }}"
        dest: "/etc/motd"
        owner: root
        group: root
        mode: "0644"

asupra hosturilor parte din grupul grup_summerschool:

cd /workspace/student/ansible
. /workspace/student/venvs/ansible/bin/activate
ansible-playbook -i inv.docker.yml playbook.yml --extra-vars _hosts=grup_summerschool
Verificam outputul aruncat de ansible
PLAY [grup_summerschool] ************************************************************************

TASK [Gathering Facts] **************************************************************************
ok: [centos7]
ok: [debian10]

TASK [Instalam grupul] **************************************************************************
changed: [debian10]
changed: [centos7]

TASK [Instalam utilizatorii] ********************************************************************
changed: [debian10] => (item={'user': 'asterix', 'parola': '$6$U9D8CKVFasZBXtfE$jElu7BDrU7bykn2LudE1moTKea3ffK5Tad0P9x2T/U5y0rGm8Q4qcbm/VivSvRy0Yk3b29V0rX3J.KH0UFMEP/'})
changed: [centos7] => (item={'user': 'asterix', 'parola': '$6$U9D8CKVFasZBXtfE$jElu7BDrU7bykn2LudE1moTKea3ffK5Tad0P9x2T/U5y0rGm8Q4qcbm/VivSvRy0Yk3b29V0rX3J.KH0UFMEP/'})
changed: [debian10] => (item={'user': 'obelix'})
changed: [centos7] => (item={'user': 'obelix'})
changed: [debian10] => (item={'user': 'idefix'})
changed: [centos7] => (item={'user': 'idefix'})

TASK [Instalam pachetele] ***********************************************************************
changed: [debian10]
changed: [centos7]

TASK [Aplicam bannerul] *************************************************************************
changed: [centos7]
changed: [debian10]

PLAY RECAP **************************************************************************************
centos7   : ok=5    changed=4    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
debian10  : ok=5    changed=4    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Verificari si incheiere

Userul idefix, parte a grupului admini
docker exec -ti debian10 id idefix
uid=1002(idefix) gid=1000(admini) groups=1000(admini)
Autentificare pe sistem, afisare banner
docker exec -ti centos7 login asterix
Password:
Linux 1ecf0b33205b 4.15.0-76-generic #86-Ubuntu SMP Fri Jan 17 17:24:28 UTC 2020 x86_64
Va rugam politicos sa nu folositi acest sistem daca nu aveti dreptul sa o
faceti.  Multumim!

--- Panoramix
$
Existenta pachete pe sistem
docker exec -ti centos7 /bin/sh -c 'rpm -qa | grep vsftpd'
vsftpd-3.0.2-29.el7_9.x86_64
Curatare mediu
cd /workspace/student/terraform
./terraform destroy

Felicitari

######## ######## ##       ####  ######  #### ########    ###    ########  ####
##       ##       ##        ##  ##    ##  ##     ##      ## ##   ##     ##  ##
##       ##       ##        ##  ##        ##     ##     ##   ##  ##     ##  ##
######   ######   ##        ##  ##        ##     ##    ##     ## ########   ##
##       ##       ##        ##  ##        ##     ##    ######### ##   ##    ##
##       ##       ##        ##  ##    ##  ##     ##    ##     ## ##    ##   ##
##       ######## ######## ####  ######  ####    ##    ##     ## ##     ## ####

Asta a fost tot, toate bune!

devops/laboratoare/03.txt ยท Last modified: 2021/07/21 00:13 by sorin.paduraru
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0