Kubernetes Programming with Go: Programming Kubernetes Clients and Operators Using Go and the Kubernetes API 1st Edition Philippe Martin All Chapters Instant Download
Kubernetes Programming with Go: Programming Kubernetes Clients and Operators Using Go and the Kubernetes API 1st Edition Philippe Martin All Chapters Instant Download
com
https://ebookmeta.com/product/kubernetes-programming-with-
go-programming-kubernetes-clients-and-operators-using-go-
and-the-kubernetes-api-1st-edition-philippe-martin/
OR CLICK HERE
DOWLOAD NOW
https://ebookmeta.com/product/kubernetes-preparing-for-the-cka-and-
ckad-certifications-martin/
ebookmeta.com
https://ebookmeta.com/product/nonsequential-and-distributed-
programming-with-go-christian-maurer/
ebookmeta.com
https://ebookmeta.com/product/anthology-of-student-verse-at-
pennsylvania-leroy-smith/
ebookmeta.com
NCLEX RN For Dummies with Online Practice Tests 2nd
Edition Patrick R Coonan Rhoda L Sommer
https://ebookmeta.com/product/nclex-rn-for-dummies-with-online-
practice-tests-2nd-edition-patrick-r-coonan-rhoda-l-sommer/
ebookmeta.com
https://ebookmeta.com/product/caste-discrimination-and-exclusion-in-
indian-universities-a-critical-reflection-1st-edition-n-sukumar/
ebookmeta.com
https://ebookmeta.com/product/dk-how-to-be-good-at-math-the-simplest-
ever-visual-guide-ages-7-11-dorling-kindersley-2/
ebookmeta.com
https://ebookmeta.com/product/essential-clinical-procedures-4th-
edition-richard-dehn/
ebookmeta.com
Press and Politics in Pre-Revolutionary France Jack R.
Censer (Editor)
https://ebookmeta.com/product/press-and-politics-in-pre-revolutionary-
france-jack-r-censer-editor/
ebookmeta.com
Kubernetes Programming
with Go
Programming Kubernetes Clients
and Operators Using
Go and the Kubernetes API
Philippe Martin
Kubernetes Programming with Go: Programming Kubernetes Clients and Operators
Using Go and the Kubernetes API
Philippe Martin
Blanquefort, France
Introduction������������������������������������������������������������������������������������������������������������xix
v
Table of Contents
vi
Table of Contents
Toleration������������������������������������������������������������������������������������������������������������������������������� 65
Well-Known Labels���������������������������������������������������������������������������������������������������������������� 66
Writing Kubernetes Resources in Go������������������������������������������������������������������������������������������ 67
Importing the Package���������������������������������������������������������������������������������������������������������� 67
The TypeMeta Fields�������������������������������������������������������������������������������������������������������������� 68
The ObjectMeta Fields����������������������������������������������������������������������������������������������������������� 69
Spec and Status�������������������������������������������������������������������������������������������������������������������� 76
Comparison with Writing YAML Manifests����������������������������������������������������������������������������� 76
A Complete Example������������������������������������������������������������������������������������������������������������������� 78
Conclusion���������������������������������������������������������������������������������������������������������������������������������� 83
vii
Table of Contents
Conversion��������������������������������������������������������������������������������������������������������������������������� 101
Serialization������������������������������������������������������������������������������������������������������������������������� 103
RESTMapper����������������������������������������������������������������������������������������������������������������������������� 105
Kind to Resource����������������������������������������������������������������������������������������������������������������� 106
Resource to Kind����������������������������������������������������������������������������������������������������������������� 107
Finding Resources��������������������������������������������������������������������������������������������������������������� 107
The DefaultRESTMapper Implementation���������������������������������������������������������������������������� 107
Conclusion�������������������������������������������������������������������������������������������������������������������������������� 108
viii
Table of Contents
x
Table of Contents
xi
Table of Contents
Index��������������������������������������������������������������������������������������������������������������������� 309
xii
About the Author
Philippe Martin has been working with Kubernetes for
five years, first by creating an Operator to deploy video
CDNs into the cloud, later helping companies deploy their
applications into Kubernetes, then writing a Client to help
developers work in a Kubernetes environment. Philippe
has passed the CKAD, CKA, and CKS certifications. He has
extensive experience with distributed systems and open-
source software: he started his career 20 years ago creating
thin clients based on the Linux kernel and open-source
components. He is currently working at Red Hat on the
Development Tools team.
Philippe has been active in the development of Kubernetes, especially its
documentation, and participates in the translation of the official documentation into
French, has edited two reference books about the Kubernetes API and kubectl, and is
responsible for the French translation of the Kubernetes Dashboard. He participated in
Google Season of Docs to create the new Kubernetes API Reference section of the official
documentation and is maintaining it.
xiii
About the Technical Reviewers
Bartosz Majsak writes code for fun and profit while proudly
wearing a red fedora (also known as the Red Hat). He has
been long-time open-source contributor and Java developer
turned into Golang aficionado. Bartosz is overly enthusiastic
about coffee, open source, and speaking at conferences,
not necessarily in that order. One thing that perhaps proves
he is not a total geek is his addiction to alpine skiing (and
running).
xv
Acknowledgments
I would like to thank the whole Anevia “CDN” team who started working with me on
Kubernetes back in 2018: David, Ansou, Hossam, Yassine, Étienne, Jason, and Michaël.
Special thanks to Damien Lucas for initiating this project and for having trusted us with
this challenge.
My discovery of Kubernetes has been much easier and pleasant thanks to the TGIK
channel and its numerous episodes, hosted by Joe Beda, Kris Nova, and many others.
Plus, thanks to all the Kubernetes community for such a great ecosystem!
xvii
Introduction
Back in 2017, I was working for a company building video streaming software. At the end
of that year, a small team, including me, got assigned a new job to work on deploying
the Video CDN developed by the company on Kubernetes. We decided to explore the
concept of Custom Resources and Operators to deploy this CDN.
The current Kubernetes release was 1.9, the concept of Custom Resource Definition
had just been released in 1.7, and the sample-controller repository was the only
documentation we knew of to help build an Operator. The Kubernetes ecosystem,
being especially lively, had tools appearing in the following months, specifically the
Kubebuilder SDK. Thus, our project was launched.
From that moment on, I spent numerous days exploring how to build Operators and
other programs interacting with the Kubernetes API. But the damage was done: I had
started to learn Kubernetes programming from specific to general, and it took me a long
time to fully understand the innards of the Kubernetes API.
I have written this book in the hope that it can teach new Kubernetes developers how
to program, from general to specific, with the Kubernetes API in Go.
Chapters at a Glance
The target reader for this book has some experience working with REST APIs, accessing
them either by HTTP or using clients for specific languages; and has some knowledge of
the Kubernetes platform, essentially as a user—for example, some experience deploying
such APIs or frontend applications with the help of YAML manifests.
xix
Introduction
At this point in the book, the reader should be comfortable with building Go
applications working with native resources of the Kubernetes API.
By the end of the book, the reader should be able to start building Kubernetes
operators in Go and have a very good understanding of what happens behind the scenes.
xx
CHAPTER 1
Kubernetes API
Introduction
Kubernetes is a platform to orchestrate containers operating in the declarative mode.
There are one-thousand-and-one ways to describe how the Kubernetes platform is
constructed. This book focuses on programming with the platform.
The entry point of the Kubernetes platform is the API. This chapter explores the
Kubernetes architecture by highlighting the central role of the Kubernetes API. It then
focuses on the HTTP REST nature of the Kubernetes API, and on the extensions added to
organize the many resources managed by it.
Finally, you will learn how to navigate the reference documentation effectively to be
able to extract the maximum quantity of useful information daily.
1. The API server – this is the central point on the control-plane; the
user and the various pieces of the control-plane contact this API to
create, get, delete, update, and watch resources.
1
© Philippe Martin 2023
P. Martin, Kubernetes Programming with Go, https://doi.org/10.1007/978-1-4842-9026-2_1
Chapter 1 Kubernetes API Introduction
2
Chapter 1 Kubernetes API Introduction
etcd
Kubectl
---
Control-plane
cre
at watch
de e set
up lete,
d
Controllers
wa ate
tch
API Server crea
te
te
dele te
a
upd
tch
wa
wa ate
tch
up
d
Kubelet
watch
Scheduler
no Kube-proxy
de
s
O
penAPI Specification
The Kubernetes API is an HTTP REST API. The Kubernetes team provides a specification
for this API in the OpenAPI format, either in v2 format at https://github.com/
kubernetes/kubernetes/tree/master/api/openapi-spec or in Kubernetes v1.24,
in v3 format, at https://github.com/kubernetes/kubernetes/tree/master/api/
openapi-spec/v3.
These specifications also are accessible from the API Server at these paths:
/openapi/v2 and /openapi/v3.
An OpenAPI specification is made up of various parts and, among these, are a list of
paths and a list of definitions. The paths are the URLs you use to request this API, and
for each path, the specification gives the distinct operations such as get, delete, or post.
Then for each operation, the specification indicates what are the parameters and body
format for the request, and what are the possible response codes and associated body
format for the response.
3
Chapter 1 Kubernetes API Introduction
The parameters and bodies for requests and responses can be either simple types
or, more generally, structures containing data. The list of definitions includes data
structures that help build the parameters and bodies for the operations’ requests and
responses.
Figure 1-2 is a simplified view of a specification for a User API. This API can accept
two different paths: /user/{userId} and /user. The first path, /user/{userId}, can accept
two operations, get and delete, respectively, to receive information about a specific user,
given its user ID; and to delete information about a specific user, given its user ID. The
second path, /user, can accept a single operation, post, to add a new user, given its
information.
In this API, a definition of a structure User is given, describing the information for a
user: its ID, first name, and last name. This data structure is used in the response body of
the get operation on the first path, and in the request body of the post operation on the
second path.
4
Chapter 1 Kubernetes API Introduction
SDWKV
XVHU^XVHU,G`
JHW
SDUDPHWHUV
XVHU,GLQWHJHU
UHTXHVW%RG\ HPSW\
UHVSRQVHV
8VHU
GHOHWH
SDUDPHWHUV
XVHU,GLQWHJHU
UHTXHVW%RG\ HPSW\
UHVSRQVHV
HPSW\
XVHU
SRVW
SDUDPHWHUV HPSW\
UHTXHVW%RG\8VHU
UHVSRQVHV
8VHU
GHILQLWLRQV
8VHU
,'LQWHJHU
)LUVW1DPHVWULQJ
/DVW1DPHVWULQJ
V
erbs and Kinds
The Kubernetes API adds two concepts to this specification: the Kubernetes API Verbs
and the Kubernetes Kinds.
5
Chapter 1 Kubernetes API Introduction
The Kubernetes API Verbs are mapped directly to the operations in the OpenAPI
specification. The defined verbs are get, create, update, patch, delete, list, watch, and
deletecollection. The correspondence with the HTTP verbs can be found in Table 1-1.
get GET
create POST
update PUT
patch PATCH
delete DELETE
list GET
watch GET
deletecollection DELETE
The Kubernetes Kinds are a subset of the definitions in the OpenAPI specification.
When requests are made to the Kubernetes API, data structures are exchanged through
the bodies of requests and responses. These structures share common fields, apiVersion
and kind, to help the participants of the request recognize these structures.
If you wanted to make your User API manage this Kind concept, the User structure
would contain two additional fields, apiVersion and kind—for example, with values v1
and User. To determine whether a definition in the Kubernetes OpenAPI specification
is a Kubernetes Kind, you can look at the x-kubernetes-group-version-kind field of the
definition. If this field is defined, the definition is a kind, and it gives you the values of the
apiVersion and kind fields.
Group-Version-Resource
The Kubernetes API is a REST API, and as a result of that it manages Resources, and the
paths to manage these resources follow the REST naming conventions—that is, by using
a plural name to identify a resource and by grouping these resources.
6
Chapter 1 Kubernetes API Introduction
Because the Kubernetes API manages hundreds of resources, they are grouped
together, and because the API evolves, the resources are versioned. For these reasons,
each resource belongs to a given Group and Version, and each resource is uniquely
identified by a Group-Version-Resource, commonly known as GVR.
To find the various resources in the Kubernetes API, you can browse the OpenAPI
specification to extract the distinct paths. Legacy resources (e.g., pods or nodes) will
have been introduced early in the Kubernetes API and all belong to the group core and
the version v1.
The paths to manage legacy resources cluster-wide follow the format /api/
v1/<plural_resource_name>—for example, /api/v1/nodes to manage nodes. Note
that the core group is not represented in the path. To manage resources in a given
namespace, the path format is /api/v1/namespaces/<namespace_name>/<plural_
resource_name>—for example, /api/v1/namespaces/default/pods to manage pods in
the default namespace.
Newer resources are accessible through paths following the format
/apis/<group>/<version>/<plural_resource_name> or /apis/<group>/<version>/
namespaces/<namespace_name>/<plural_resource_name>.
To summarize, the formats of the various paths to access resources are:
or
7
Chapter 1 Kubernetes API Introduction
or
• /apis/<group>/<version>/namespaces/<ns>/<plural_name> – to
access namespaced resources in a specific namespace
Sub-resources
Following the REST API convention, the resources can have sub-resources. A sub-
resource is a resource that belongs to another and can be accessed by specifying its
name after the name of the resource, as follows:
• /api/v1/<plural>/<res-name>/<sub-resource>
Ex: /api/v1/nodes/node1/status
• /api/v1/namespaces/<ns>/<plural>/<res-name>/<sub-resource>
Ex: /api/v1/namespaces/ns1/pods/pod1/status
• /apis/<group>/<version>/<plural>/<res-name>/<sub-resource>
Ex: /apis/storage.k8s.io/v1/volumeattachments/volatt1/status
• /apis/<grp>/<v>/namespaces/<ns>/<plural>/<name>/<sub-res>
Ex: /apis/apps/v1/namespaces/ns1/deployments/dep1/status
Most Kubernetes resources have a status sub-resource. You can see, when writing
operators, that the operator needs to update the status sub-resource to be able to
indicate the state of this resource observed by the operator. The operations that can
be executed in the status sub-resource are get, patch, and update. The Pod has more
sub-resources, including attach, binding, eviction, exec, log, portforward, and proxy.
These sub-resources are useful for getting information about a specific running pod, or
executing some specific operation on a running pod, and so on.
8
Chapter 1 Kubernetes API Introduction
The resources that can Scale (i.e., deployments, replicasets, etc.) have a scale sub-
resource. The operations that can be executed in the scale sub-resource are get, patch,
and update.
Note that these categories are not part of the Kubernetes API definition but are used
in this website to help inexperienced users find their way into the multitude of available
resources.
9
Chapter 1 Kubernetes API Introduction
To be precise, the name displayed is not the resource name in the REST sense, but
the associated principal kind, as shown in Figure 1-4. For example, when managing
Pods, the resource name used in the REST paths is pods (i.e., lowercase and plural), and
the definition used to exchange information about Pods during HTTP requests is named
Pod (i.e., uppercase and singular). Note that other kinds can be associated with the same
resource. In the example in this chapter, the PodList kind (used to exchange information
about Lists of Pods) also exists.
Figure 1-4. The resources for a specific category, with a short description
10
Chapter 1 Kubernetes API Introduction
The apiVersion indicated in the header can help you write a YAML manifest for a
Deployment resource because you need to specify, for each resource in a Kubernetes
manifest, the apiVersion and kind.
In this case, you know the manifest for a deployment will start with the following:
apiVersion: apps/v1
kind: Deployment
The next header line indicates the import to use when writing Go code. In Chapter 3,
you will see how to use this import when describing resources in Go.
After the header, a list of structure definitions is described, also accessible from the
table of contents for the Deployment documentation page in Figure 1-6. The first one is
the principal kind of the resource, optionally followed by structure definitions that are
used in fields of the first kind.
11
Chapter 1 Kubernetes API Introduction
For example, the Deployment kind contains a spec field, of type DeploymentSpec,
which is described later. Note that DeploymentSpec is not a structure directly
exchanged during HTTP requests, and for that, it is not a kind and does not contain kind
or apiVersion fields.
Following the principal kind, and its associated definitions, other kinds associated
with the resource are displayed. In this case, the DeploymentList kind.
Operations Documentation
The next subject in the API Documentation for a resource is the list of possible
operations on this resource or its sub-resources, also accessible from the table of
contents page (see Figure 1-6). By examining the details for the create operation to
Create a Deployment, as shown in Figure 1-7, you can see the HTTP Request verb and
path to use, the parameters to pass during the request, and the possible responses. The
HTTP verb to use for the request is POST and the path is /apis/apps/v1/namespaces/
{namespace}/deployments.
12
Chapter 1 Kubernetes API Introduction
13
Discovering Diverse Content Through
Random Scribd Documents
de una felicidad plena, redonda y definitiva. Sino fuera por el jactancioso
ruido del tren, oiríanse, de seguro, las voces de su canto. No se concebía a
aquel hombre en aquella hora sino cantando.
Reía entre tanto la naturaleza, y cada nimio detalle del paisaje se revestía
de una íntima belleza. En el paisaje aquel, tan simple y sobrio, faltaban los
elementos teatrales y decorativos. Pero había un amable encanto en la
hierba matizada de rocío, en la lechuza que se posaba sobre un poste y abría
sus curiosas y atónitas pupilas circulares, en las ovejas que pastaban, en el
desbande de las aves azoradas, en la cómica expectación de los novillos
ante el paso ruidoso del tren. Y, sobre todo, en la luz purísima que inundaba
la llanura, aquella infinita llanura que se abría delante de la imaginación
como un concepto casi metafísico de la libertad y de lo inconmensurable.
Y yo pensé: ¿Somos más felices los hombres porque amontonemos
mayor número de útiles, de necesidades y de ideas? Aquel rancho[22]
perdido en la llanura, aquellos dos sauces, el fogón encendido, la mujer que
se queda amamantando a su criatura y el hombre que sale a cabalgar serena
y noblemente, ¿no representaban la suma de las cosas y de las emociones
que requiere un hombre para sentirse bien dentro del universo y cara a la
vida? En aquella cabaña se habían reducido las necesidades hasta el
mínimo. Siendo tan pocas las exigencias, el alma, en aquella parquedad de
apetitos, debía pensar que el mundo era aún demasiado pródigo. Era la
antítesis de la gran metrópoli, de la ciudad insaciable y codiciosa, de la urbe
consumida por las pasiones. La ciudad no se satisfacía nunca. Anhelaba
siempre más, nuevas formas de placer y de molicie. Las grandes fábricas
gemían continuamente para producir los útiles, tan caros a la civilización;
los hombres de ciencia alargaban sus vigilias para sorprender una nueva
invención; y corrían los barcos y los trenes, acarreando cosas aptas para la
molicie del hombre, y las calles se llenaban de fiebre, los Bancos
multiplicaban sus negocios, el mundo entero vibraba al conjuro del
universal anhelo. Todo para que unos hombres pudieran usar cosas
agradables, y todo para que la vida se llenase de complicación. Lujo,
vanidad, automóviles, timbres eléctricos, ascensores, teléfonos, bebidas
heladas, salsas, especies, vinos espumantes, vestidos de seda, sombreros
increíbles. Para satisfacer estas necesidades artificiosas, el mundo llenábase
de inquietudes, estallaban las guerras, morían los miserables en los
rincones.
En ese rancho perdido en mitad de la llanura ¿qué faltaba? La vida no
reclamaba sino tres o cuatro casos simples: un pedazo de carne asada, una
infusión de “mate”, y, como lujo, una galleta dura. Quizá un poco de tabaco
para las horas de reposo. Y en los días de fiesta, un trago de ginebra. Para
dormir, el sagrado suelo. Y en las noches tibias, tener como techumbre el
cielo, empavesado de estrellas.
He ahí una razón fundamental: la vida conquistada a bajo precio. Pero la
otra razón, la que se apoya sobre los intereses eternos, colectivos,
universales, arguye que ese plan de vida es ruinoso, y que al simplificar las
necesidades, reduciendo el radio de nuestros deseos, la civilización corre
apuro de malograrse. La civilización es un algo supremo, inasequible,
imponderable como el mismo Dios. Todos venimos a ofrecernos como
servidores de ese fetiche insaciable, y sudamos, padecemos, morimos entre
estertores de codicia, de vanidad o de ambición, a la mayor gloria del
progreso. Se nos dice que es humillante desertar de nuestro puesto. Y
efectivamente cumplimos con nuestro deber.
Por mi parte, yo siento en muchas ocasiones una fuerte intención de
desertar. Siempre que me sitúo enfrente de la naturaleza libre, ingenua y
pictórica, me asalta el mismo prurito de renunciar a mi corteza urbana,
quitarme el uniforme de civilizado, traicionar a la obra del progreso y
convertirme en un hombre sencillo.
He pensado seriamente en llegar a poder vivir así, como aquel paisano
que a lomo de su potro tordillo salía cantando de mañana por lo ancho de la
llanura. Renunciar a los numerosos detalles de la civilización, despreciar la
vestidura del placer, la apariencia sonora de la dicha, a cambio de la
verdadera felicidad. Reconciliarse con la salud, auténtica madre de la
alegría. Ejercitar las funciones corporales con una segura amplitud. Sentir la
plena conciencia de la normalidad del ser. Dormir sin achaques, de un largo
y robusto tirón. Cabalgar, vencer las dificultades que se oponen al músculo,
sudar, beber agua sana a grandes tragos. Respirar el viento sin temor, y
agradecerlo más aún cuanto más frío. Ofrecerse al sol sin veladuras ni
encogimientos. Recibir el golpe de la lluvia como una caricia. Curtirse la
piel, tensa como un pandero. Ver acostarse el sol, sin miedo al mañana.
Levantarse con el alba y agradecer con todas las fuerzas del cándido
espíritu la gracia de poder vivir un nuevo día...
CA P Í T UL O V
El Amor y la Queja
Palomita blanca,
remonta tu vuelo,
y al bien que yo adoro
dile que me muero...
También Martín Fierro colabora en esta propensión a la queja dulce y al
dolor de la ausencia. Azuzado por la justicia, pobre y errante, necesita poner
su memoria en la dama de sus pensamientos y canta:
En la orilla de un arroyo
solitario lo pasaba,
en mil cosas cavilaba,
y a una güelta repentina
se me hacía ver a mi china
o escuchar que me llamaba.
P OR entre los versos del Martín Fierro brilla con frecuencia el cuchillo
de nuestro gaucho errante, y con esa arma compañera se consuman
hazañas increíbles, como el resistir en pleno campo abierto a un pelotón
de soldados policiales.
Viajando una vez por la provincia de Entre Ríos, cuyo paisaje algo seco
y surcado de pelados oteros recuerda bastante al campo de Castilla,
sorprendí un hombre a caballo, verdadera imagen del romancesco tipo del
gaucho. Ya no vestía chiripá, pero en su defecto portaba unos anchísimos
calzones bombachos, y sobre la erguida cabeza llevaba un sombrero
afieltrado, con masculino y coquetón talante. Al girar de espaldas, mostró
en el cinto, por la parte de los riñones, cruzado un largo cuchillo de punta
sutil. Mientras el tren arrancaba con enfática carrera, el hombre del caballo
y del cuchillo se internó serenamente en la llanura, bien tieso en su silla
nacional, impasible y orgulloso, como una página del pasado que se vuelve
y huye...
He nombrado el cuchillo, y la palabra no es justa del todo. El cuchillo o
facón gauchesco era más bien una espada. Sus dimensiones tenían una
prudente medida, y si era demasiado largo para cuchillo, quedaba algo corto
para llegar a espada. El gaucho no podía llevar una espada al cinto, como
un soldado de caballería; su manera violenta y continua de cabalgar, y su
deseo de no separarse nunca del arma fiel, le obligó a cortar la espada del
caballero o del hidalgo. La cruzó en la cintura, la sujetó a su cuerpo, y así
logró convertirla en algo indivisible con su persona.
Al referirme al cuchillo del gaucho hablo en pretérito, porque el arma
nacional de los ríoplatenses va desapareciendo, y sólo es usado tal vez en
las comarcas desviadas. El europeo ha traído el uso del revólver, arma fácil
y expedita que no requiere una maniobra tan complicada como aquel acero
filoso, únicamente eficaz cuando la mano, la vista y el corazón del gaucho
lo esgrimía en los imponentes entreveros[28].
Tampoco podía el europeo desenvolverse en el seno de la Naturaleza,
desafiarla y vencerla como el gaucho. Este hombre primitivo contaba
solamente con su voluntad y sus iniciativas. Situado en mitad del desierto,
se buscaba un camino, se orientaba por las huellas sutiles de la luz o del
color y sabor de las hierbas, y nada quedaba para él sin expresión, desde el
vuelo de las aves hasta el mugido de las bestias errabundas. Poco debía
contar con la justicia ni con los poderes constituidos; en último caso fiaba a
su acero la defensa de su familia y de su prestigio personal. El europeo,
debilitado por la civilización, procura reconciliarse con la Naturaleza, y al
reñir contra ella no marcha de frente, sino que la soslaya, y pone por medio
la mecánica de la industria y la otra mecánica de las leyes colectivas.
Un pueblo entero, libre y robusto, usaba hasta ayer mismo la espada del
caballero o del hidalgo, como hace dos o tres siglos la usaban en Europa las
gentes nobles. No se olvide que la espada significa libertad, aunque las
mentes un poco aturdidas por la democracia tomen esto por una blasfemia.
La espada no ha sido nunca negocio de esclavos, porque implica el sentido
de la mayor independencia personal. La espada hace sagrado el concepto de
la personalidad, y un hombre que la lleva al cinto está significando a todos
los otros hombres que su independencia personal comienza desde la misma
punta de su espada. Los caballeros del siglo XVI, llevando todos el signo
acerado y mortífero de la libertad, por imposición natural interponían entre
ellos la virtud más deseable y democrática: el respeto mutuo.
Así Pizarro, detenido en la isla del Gallo por las suspicacias de algunos
compañeros, cuando quiso arrastrar su gente a la gran aventura de
conquistar el Perú no osó proferir gritos y órdenes de mando, sino que sacó
la espada, rayó la tierra con un brusco ademán y empezó: ¡Señores...!
Aquellos hidalgos trajeron la espada a la llanura ríoplatense, y el gaucho,
pobre y errante como su progenitor, lleno de sus mismos prejuicios, reacio a
la industria, atento al honor y a la libertad más que al ahorro, fué un
testamentario y un continuador en América de la tradición castellana.
Cuando en la tierra originaria no quedaron hidalgos de espada al cinto, en la
Pampa vivía el gaucho una vida hidalguesca, con su caballo y su daga, su
puntillo de honor y su aventura.
No; no era para todos el manejo de la daga gauchesca. Nada tan
complicado como su esgrima, ni nada tan terrible como un hombre de
aquellos cuando enrollaba al brazo el poncho, se quitaba las grandes
espuelas y hacía brillar la hoja del cuchillo. A veces las pendencias duraban
mucho tiempo, y el sudor bañaba los rostros que la ira hacía enrojecer. Los
circunstantes formaban en círculo, y a nadie se le ocurría que podía
intervenir en aquel torneo legal y honroso. Juntos los pies de ambos
luchadores, casi abrazados los dos, hacían largo tiempo culebrear los
aceros, parándose los tajos con el poncho, ladeándose, evitándose como
ágiles reptiles. Un chirle en la cara era golpe muy apreciado, y a veces
bastaba la herida del rostro para lavar una ofensa. Pero los verdaderamente
bravos no se contentaban con tan poco. Martín Fierro era hábil en hundir el
cuchillo hasta la empuñadura.
Yo tenía un facón con S[29]
que era de lima de acero;
le hice un tiro, lo quitó
y vino ciego el moreno.
Y ya me hizo relumbrar
por los ojos el cuchillo,
alcanzando por la punta
a cortarme en un carrillo.
Hazañas y Entreveros
A la llegada metió
el pingo hasta la ramada,
y yo sin decirle nada
me quedé en el mostrador.
Y ya salimos trenzaos,
porque el hombre no era lerdo;
mas como el tino no pierdo
y soy medio ligerón,
le dejé mostrando el sebo
de un revés con el facón.
Pero estas son riñas de uno contra uno, de forma caballeresca popular y
muy semejantes a las riñas de otros países. Donde se prueba el valor del
gaucho y la potencia de su cuchillo y de su esgrima, es en los entreveros de
uno contra muchos, o en la pelea contra un indio armado de boleadoras.
Me encontraba, como digo,
en aquella soledá,
entre tanta oscuridá
echando al viento mis quejas,
cuando el grito del chajá[30]
me hizo parar[31] las orejas.
Al punto me santigüé
y eché de giñebra un taco;
lo mesmito que el mataco[33]
me arrollé con el porrón.
“Si han de darme pa tabaco,
dije, esta es güena ocasión.”
Y ya vide el fogonazo
de un tiro de carabina;
mas quiso la suerte indina
de aquel maula, que me errase,
y ahí no más lo levantase
lo mesmo que una sardina...
El más engolosinao
se me apió con un hachazo;
se lo quité con el brazo,
de no, me mata los piojos;
y antes de que diera un paso
le eché tierra en los dos ojos.
Y mientras se sacudía
refregándose la vista,
yo me le fuí como lista
y ahí no más me le afirmé,
diciéndole: “Dios te asista”,
y de un revés lo voltié...
En fin, la feroz pelea de uno contra tantos acaba, o se precipita al
desenlace, cuando uno de los soldados, el sargento Cruz, se pasa al campo
de Martín Fierro, gritando aquella voz quijotesca:
...¡Cruz no consiente
que se cometa el delito
de matar ansí un valiente!
C AP Í T UL O VI I I
Los Indios