{"id":153,"date":"2021-04-01T17:40:52","date_gmt":"2021-04-01T16:40:52","guid":{"rendered":"https:\/\/www.netexpertise.eu\/es\/?p=153"},"modified":"2021-08-24T07:08:04","modified_gmt":"2021-08-24T06:08:04","slug":"inventario-dinamico-ansible-de-servidores-ibm-cloud","status":"publish","type":"post","link":"http:\/\/www.netexpertise.eu\/es\/devops\/ansible\/inventario-dinamico-ansible-de-servidores-ibm-cloud.html","title":{"rendered":"Inventario din\u00e1mico Ansible de Servidores IBM Cloud"},"content":{"rendered":"\n<p id=\"tw-target-text\">IBM Cloud se basa en la <a href=\"https:\/\/sldn.softlayer.com\/article\/getting-started\/\">API Softlayer<\/a> &#8211; tambi\u00e9n conocida como IBM Classic Infrastructure &#8211; para automatizar acciones. La API est\u00e1 disponible en diferentes lenguajes como Python, Go, Java o PHP. <br>Voy a generar un inventario din\u00e1mico de los servidores recuperados de mi cuenta de IBM Cloud directamente utilizables por <a href=\"\/en\/category\/devops\/ansible\">Ansible<\/a>.<br><br><\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img src=\"http:\/\/www.netexpertise.eu\/uploads\/duck-meet-ducks-rubber-ducks-3325701.jpg\" alt=\"\"\/><\/figure><\/div>\n\n\n\n<p><br>Generar\u00e9 grupos correspondientes a los datacenters. Tambi\u00e9n le gustar\u00eda agrupar servidores en todo tipo de categor\u00edas como bases de datos, Mysql, Linux, Web, etc&#8230; No se preocupe, tambi\u00e9n podemos hacer esto de una forma muy sencilla.<br>Esto se puede lograr agregando etiquetas a los hosts en <a href=\"http:\/\/cloud.ibm.com\">IBM Cloud portal<\/a> y obviamente, un host puede tener varias etiquetas y pertenecer a los grupos de Ansible correspondientes a estas etiquetas \/ tags.<\/p>\n\n\n\n<p>Una vez que estos grupos han sido declarados en el archivo inventory, puede ejecutar playbooks de Ansible como instalar paquetes de Apache en servidores que pertenecen al grupo \u00abWeb\u00bb por ejemplo.<\/p>\n\n\n\n<p><br>Primero debe agregar su API key en un archivo de shell para ejecutar antes del script. Podr\u00eda ser parte del script, pero permite que cada usuario use su propia clave.<br><br><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"bash\" class=\"language-bash\">export SL_USERNAME=nombre_usuario\nexport SL_API_KEY=a1b2c3[...]3456<\/code><\/pre>\n\n\n\n<p><br>Ejecute <em>. .\/IBM_SL_env.sh<\/em> primero para agregar el nombre de usuario y la clave de API en las variables de entorno que leer\u00e1 el script de Python a continuaci\u00f3n.<br><br><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">#!\/usr\/bin\/env python3 &nbsp;\nimport os\nimport SoftLayer\n \nHOST_VARS_DIR&nbsp; = \"host_vars\"\nINVENTORY_FILE = \"inventory\"\n \nclass Inventory:\n &nbsp; def __init__(self):\n &nbsp; &nbsp; &nbsp;# Variables\n &nbsp; &nbsp; &nbsp;self.categories = {}\n &nbsp; &nbsp; &nbsp;self.datacenter = {}\n &nbsp; &nbsp; &nbsp;self.servers = {}\n \n &nbsp; &nbsp; &nbsp;# Create Softlayer connection\n &nbsp; &nbsp; &nbsp;self.client = SoftLayer.create_client_from_env()\n \n &nbsp; &nbsp; &nbsp;# Init Methods\n &nbsp; &nbsp; &nbsp;self.get_server_list()\n &nbsp; &nbsp; &nbsp;self.write_inventory()\n \n\n &nbsp; def short_host_name(self, host):\n &nbsp; &nbsp; &nbsp;return host['fullyQualifiedDomainName'][:host['fullyQualifiedDomainName'].find('.mydomain.')]\n \n\n &nbsp; def add_host_to_cat(self, host, cat):\n &nbsp; &nbsp; &nbsp;if cat == \"ibm-kubernetes-service\": cat = \"kube\"\n &nbsp; &nbsp; &nbsp;if cat not in self.categories:\n &nbsp; &nbsp; &nbsp; &nbsp; self.categories[cat] = [host]\n &nbsp; &nbsp; &nbsp;else:\n &nbsp; &nbsp; &nbsp; &nbsp; self.categories[cat].append(host)\n \n\n &nbsp; def add_server_to_list(self, host):\n &nbsp; &nbsp; &nbsp;try:\n &nbsp; &nbsp; &nbsp; &nbsp; host[\"primaryBackendIpAddress\"]\n &nbsp; &nbsp; &nbsp;except KeyError:\n &nbsp; &nbsp; &nbsp; &nbsp; pass\n &nbsp; &nbsp; &nbsp;else:\n &nbsp; &nbsp; &nbsp; &nbsp; host[\"ShortHostname\"] = self.short_host_name(host)\n &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\n &nbsp; &nbsp; &nbsp; &nbsp; # Build server Categories list\n &nbsp; &nbsp; &nbsp; &nbsp; if host[\"tagReferences\"] != []:\n &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for tagRef in host[\"tagReferences\"]:\n &nbsp; &nbsp; &nbsp; &nbsp;       self.add_host_to_cat(host[\"ShortHostname\"], tagRef[\"tag\"][\"name\"].strip())\n &nbsp; &nbsp; &nbsp; &nbsp;  &nbsp; &nbsp;\n &nbsp; &nbsp; &nbsp; &nbsp; # Build datacenter lists\n &nbsp; &nbsp; &nbsp; &nbsp; if host[\"datacenter\"][\"name\"] not in self.datacenter:\n &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;self.datacenter[host[\"datacenter\"][\"name\"]] = [host[\"ShortHostname\"]]\n &nbsp; &nbsp; &nbsp; &nbsp; else:\n &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;self.datacenter[host[\"datacenter\"][\"name\"]].append(host[\"ShortHostname\"])\n &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\n &nbsp; &nbsp; &nbsp; &nbsp; # Build server attribute list\n &nbsp; &nbsp; &nbsp; &nbsp; serverAttributes = {}\n &nbsp; &nbsp; &nbsp; &nbsp; serverAttributes['IP'] = host[\"primaryBackendIpAddress\"]\n &nbsp; &nbsp; &nbsp; &nbsp; self.servers[host[\"ShortHostname\"]] = serverAttributes\n &nbsp;&nbsp; &nbsp;\n\n &nbsp; def get_server_list(self):\n &nbsp; &nbsp; &nbsp;object_mask = \"mask[id,fullyQualifiedDomainName,\" \\\n &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\"primaryBackendIpAddress,\" \\\n &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\"tagReferences[tag[name]],\" \\\n &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\"datacenter]\"\n \n &nbsp; &nbsp; &nbsp;# Get virtual server list\n &nbsp; &nbsp; &nbsp;mgr = SoftLayer.VSManager(self.client)\n &nbsp; &nbsp; &nbsp;for vs in mgr.list_instances(mask=object_mask):\n &nbsp; &nbsp; &nbsp; &nbsp; self.add_server_to_list(vs)\n \n &nbsp; &nbsp; &nbsp;# Get bare metal servers\n &nbsp; &nbsp; &nbsp;hsl = SoftLayer.HardwareManager(self.client)\n &nbsp; &nbsp; &nbsp;for hs in hsl.list_hardware(mask=object_mask):\n &nbsp; &nbsp; &nbsp; &nbsp; self.add_server_to_list(hs)\n \n\n &nbsp; def write_inventory(self):\n &nbsp; &nbsp; &nbsp;# host_vars structure\n &nbsp; &nbsp; &nbsp;if not os.path.exists(HOST_VARS_DIR):\n &nbsp; &nbsp; &nbsp; &nbsp; os.makedirs(HOST_VARS_DIR)\n \n &nbsp; &nbsp; &nbsp;inventoryFile = open(INVENTORY_FILE,\"w\")\n \n &nbsp; &nbsp; &nbsp;for cat in self.categories.keys():\n &nbsp; &nbsp; &nbsp; &nbsp; if cat != \"kube\":\n &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;inventoryFile.write(\"[\" + cat + \"]\\n\")\n &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for host in self.categories[cat]:\n &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # write host vars\n &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; inventoryFile.write(host + \"\\n\")\n &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; file = open(HOST_VARS_DIR+\"\/\"+host,\"w\")\n &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; file.write(\"ansible_host: \" + self.servers[host]['IP'] + \"\\n\")\n &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; file.close() &nbsp; &nbsp; &nbsp; &nbsp;\n &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;inventoryFile.write(\"\\n\")\n &nbsp; &nbsp; &nbsp;for dc in self.datacenter.keys():\n &nbsp; &nbsp; &nbsp; &nbsp; inventoryFile.write(\"[\" + dc + \"]\\n\")\n &nbsp; &nbsp; &nbsp; &nbsp; for host in self.datacenter[dc]:\n &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if not host.startswith(\"kube\"):\n &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; inventoryFile.write(host + \"\\n\")\n &nbsp; &nbsp; &nbsp; &nbsp; inventoryFile.write(\"\\n\")\n &nbsp; &nbsp; &nbsp;inventoryFile.close()\n\nif __name__ == \"__main__\":\n &nbsp; exit(Inventory())<\/code><\/pre>\n\n\n\n<p><br>Algunas notas:<\/p>\n\n\n\n<p>Los nodos de Kubernetes administrado son visibles en la infraestructura cl\u00e1sica de IBM Cloud como cualquier VM (VSI en terminolog\u00eda de IBM) pero no puede conectarse a ellos. Por lo tanto, se agregan a la categor\u00eda \u00abKube\u00bb antes de ser ignorados.<\/p>\n\n\n\n<p><br>Se crea un archivo separado en hosts_var para cada servidor, que contiene su direcci\u00f3n IP. Puede agregar otras variables como par\u00e1metros iSCSI, etc&#8230;<\/p>\n\n\n\n<p><br>El script recupera m\u00e1quinas virtuales en el inventario Ansible, as\u00ed como m\u00e1quinas f\u00edsicas (bare metal). Es posible comentar cualquiera de estas secciones si no es necesario, guardando una llamada a IBM.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>IBM Cloud se basa en la API Softlayer &#8211; tambi\u00e9n conocida como IBM Classic Infrastructure &#8211; para automatizar acciones. La API est\u00e1 disponible en diferentes lenguajes como Python, Go, Java o PHP. Voy a generar un inventario din\u00e1mico de los servidores recuperados de mi cuenta de IBM Cloud directamente utilizables por Ansible. Generar\u00e9 grupos correspondientes [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_mi_skip_tracking":false},"categories":[63,65],"tags":[67,69,68,66],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v19.13 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Netexpertise - Inventario din\u00e1mico Ansible de Servidores IBM Cloud<\/title>\n<meta name=\"description\" content=\"Cree un inventario din\u00e1mico Ansible de servidores IBM Cloud en Python con las API de Softlayer\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.netexpertise.eu\/es\/devops\/ansible\/inventario-dinamico-ansible-de-servidores-ibm-cloud.html\" \/>\n<meta property=\"og:locale\" content=\"es_ES\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Netexpertise - Inventario din\u00e1mico Ansible de Servidores IBM Cloud\" \/>\n<meta property=\"og:description\" content=\"Cree un inventario din\u00e1mico Ansible de servidores IBM Cloud en Python con las API de Softlayer\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.netexpertise.eu\/es\/devops\/ansible\/inventario-dinamico-ansible-de-servidores-ibm-cloud.html\" \/>\n<meta property=\"og:site_name\" content=\"Netexpertise\" \/>\n<meta property=\"article:published_time\" content=\"2021-04-01T16:40:52+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2021-08-24T06:08:04+00:00\" \/>\n<meta property=\"og:image\" content=\"http:\/\/www.netexpertise.eu\/uploads\/duck-meet-ducks-rubber-ducks-3325701.jpg\" \/>\n<meta name=\"author\" content=\"dave\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@netexpertise\" \/>\n<meta name=\"twitter:site\" content=\"@netexpertise\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.netexpertise.eu\/es\/devops\/ansible\/inventario-dinamico-ansible-de-servidores-ibm-cloud.html\",\"url\":\"https:\/\/www.netexpertise.eu\/es\/devops\/ansible\/inventario-dinamico-ansible-de-servidores-ibm-cloud.html\",\"name\":\"Netexpertise - Inventario din\u00e1mico Ansible de Servidores IBM Cloud\",\"isPartOf\":{\"@id\":\"https:\/\/www.netexpertise.eu\/es\/#website\"},\"datePublished\":\"2021-04-01T16:40:52+00:00\",\"dateModified\":\"2021-08-24T06:08:04+00:00\",\"author\":{\"@id\":\"https:\/\/www.netexpertise.eu\/es\/#\/schema\/person\/27ec923be6625ac4b4bb86c8f0b12abf\"},\"description\":\"Cree un inventario din\u00e1mico Ansible de servidores IBM Cloud en Python con las API de Softlayer\",\"breadcrumb\":{\"@id\":\"https:\/\/www.netexpertise.eu\/es\/devops\/ansible\/inventario-dinamico-ansible-de-servidores-ibm-cloud.html#breadcrumb\"},\"inLanguage\":\"es\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.netexpertise.eu\/es\/devops\/ansible\/inventario-dinamico-ansible-de-servidores-ibm-cloud.html\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.netexpertise.eu\/es\/devops\/ansible\/inventario-dinamico-ansible-de-servidores-ibm-cloud.html#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Portada\",\"item\":\"https:\/\/www.netexpertise.eu\/es\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Inventario din\u00e1mico Ansible de Servidores IBM Cloud\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.netexpertise.eu\/es\/#website\",\"url\":\"https:\/\/www.netexpertise.eu\/es\/\",\"name\":\"Netexpertise\",\"description\":\"Sistemas \/ Redes \/ DevOps\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.netexpertise.eu\/es\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"es\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.netexpertise.eu\/es\/#\/schema\/person\/27ec923be6625ac4b4bb86c8f0b12abf\",\"name\":\"dave\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"es\",\"@id\":\"https:\/\/www.netexpertise.eu\/es\/#\/schema\/person\/image\/\",\"url\":\"http:\/\/1.gravatar.com\/avatar\/1129916e1f4955bd632f27f836f64e55?s=96&d=mm&r=g\",\"contentUrl\":\"http:\/\/1.gravatar.com\/avatar\/1129916e1f4955bd632f27f836f64e55?s=96&d=mm&r=g\",\"caption\":\"dave\"}}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Netexpertise - Inventario din\u00e1mico Ansible de Servidores IBM Cloud","description":"Cree un inventario din\u00e1mico Ansible de servidores IBM Cloud en Python con las API de Softlayer","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.netexpertise.eu\/es\/devops\/ansible\/inventario-dinamico-ansible-de-servidores-ibm-cloud.html","og_locale":"es_ES","og_type":"article","og_title":"Netexpertise - Inventario din\u00e1mico Ansible de Servidores IBM Cloud","og_description":"Cree un inventario din\u00e1mico Ansible de servidores IBM Cloud en Python con las API de Softlayer","og_url":"https:\/\/www.netexpertise.eu\/es\/devops\/ansible\/inventario-dinamico-ansible-de-servidores-ibm-cloud.html","og_site_name":"Netexpertise","article_published_time":"2021-04-01T16:40:52+00:00","article_modified_time":"2021-08-24T06:08:04+00:00","og_image":[{"url":"http:\/\/www.netexpertise.eu\/uploads\/duck-meet-ducks-rubber-ducks-3325701.jpg"}],"author":"dave","twitter_card":"summary_large_image","twitter_creator":"@netexpertise","twitter_site":"@netexpertise","schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.netexpertise.eu\/es\/devops\/ansible\/inventario-dinamico-ansible-de-servidores-ibm-cloud.html","url":"https:\/\/www.netexpertise.eu\/es\/devops\/ansible\/inventario-dinamico-ansible-de-servidores-ibm-cloud.html","name":"Netexpertise - Inventario din\u00e1mico Ansible de Servidores IBM Cloud","isPartOf":{"@id":"https:\/\/www.netexpertise.eu\/es\/#website"},"datePublished":"2021-04-01T16:40:52+00:00","dateModified":"2021-08-24T06:08:04+00:00","author":{"@id":"https:\/\/www.netexpertise.eu\/es\/#\/schema\/person\/27ec923be6625ac4b4bb86c8f0b12abf"},"description":"Cree un inventario din\u00e1mico Ansible de servidores IBM Cloud en Python con las API de Softlayer","breadcrumb":{"@id":"https:\/\/www.netexpertise.eu\/es\/devops\/ansible\/inventario-dinamico-ansible-de-servidores-ibm-cloud.html#breadcrumb"},"inLanguage":"es","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.netexpertise.eu\/es\/devops\/ansible\/inventario-dinamico-ansible-de-servidores-ibm-cloud.html"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.netexpertise.eu\/es\/devops\/ansible\/inventario-dinamico-ansible-de-servidores-ibm-cloud.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Portada","item":"https:\/\/www.netexpertise.eu\/es"},{"@type":"ListItem","position":2,"name":"Inventario din\u00e1mico Ansible de Servidores IBM Cloud"}]},{"@type":"WebSite","@id":"https:\/\/www.netexpertise.eu\/es\/#website","url":"https:\/\/www.netexpertise.eu\/es\/","name":"Netexpertise","description":"Sistemas \/ Redes \/ DevOps","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.netexpertise.eu\/es\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"es"},{"@type":"Person","@id":"https:\/\/www.netexpertise.eu\/es\/#\/schema\/person\/27ec923be6625ac4b4bb86c8f0b12abf","name":"dave","image":{"@type":"ImageObject","inLanguage":"es","@id":"https:\/\/www.netexpertise.eu\/es\/#\/schema\/person\/image\/","url":"http:\/\/1.gravatar.com\/avatar\/1129916e1f4955bd632f27f836f64e55?s=96&d=mm&r=g","contentUrl":"http:\/\/1.gravatar.com\/avatar\/1129916e1f4955bd632f27f836f64e55?s=96&d=mm&r=g","caption":"dave"}}]}},"_links":{"self":[{"href":"http:\/\/www.netexpertise.eu\/es\/wp-json\/wp\/v2\/posts\/153"}],"collection":[{"href":"http:\/\/www.netexpertise.eu\/es\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.netexpertise.eu\/es\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.netexpertise.eu\/es\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/www.netexpertise.eu\/es\/wp-json\/wp\/v2\/comments?post=153"}],"version-history":[{"count":15,"href":"http:\/\/www.netexpertise.eu\/es\/wp-json\/wp\/v2\/posts\/153\/revisions"}],"predecessor-version":[{"id":365,"href":"http:\/\/www.netexpertise.eu\/es\/wp-json\/wp\/v2\/posts\/153\/revisions\/365"}],"wp:attachment":[{"href":"http:\/\/www.netexpertise.eu\/es\/wp-json\/wp\/v2\/media?parent=153"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.netexpertise.eu\/es\/wp-json\/wp\/v2\/categories?post=153"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.netexpertise.eu\/es\/wp-json\/wp\/v2\/tags?post=153"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}