Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Using Macros with CloudFormation (Spanish Edition)

Using Macros with CloudFormation (Spanish Edition)

My deck for the Cloud en Espa~nol #12 online meetup. Send me an email (cover page) if you would like the English version.

Luis Colon @ AWS

February 13, 2019
Tweet

More Decks by Luis Colon @ AWS

Other Decks in Technology

Transcript

  1. © 2018, Amazon Web Services, Inc. or its Affiliates. All

    rights reserved. Luis Colon (@luiscolon1) Senior Developer Advocate (Evangelista) AWS CloudFormation Request English version via email [email protected] 13.02.2019 Usando Macros con CloudFormation Febrero 2019
  2. © 2018, Amazon Web Services, Inc. or its Affiliates. All

    rights reserved. • Fundamentos • Opciones de Codificación • Transformaciones y Macros • Pasos • Otros Ejemplos • Enlaces • Comunidad Agenda
  3. © 2018, Amazon Web Services, Inc. or its Affiliates. All

    rights reserved. CloudFormation • Administrar (crear, actualizar, limpiar) recursos en AWS • Provee un lenguaje común para create recursos y describir el estado deseado • Entiende dependencias • Provee estabilización y rollbacks Codifica plantillas en YAML/JSON o usar plantillas de muestra Cargar archivos de plantillas localmente o desde un cubo S3 Crea pilas usando la consola de administración, o API, o CLI Las pilas y los recursos quedan aprovisionados y estabilizados
  4. © 2018, Amazon Web Services, Inc. or its Affiliates. All

    rights reserved. Conceptos Básicos de Plantillas AWSTemplateFormatVersion: "2010-09-09"
 Description: A CodeCommit Repo and Cloud9 Dev Environment
 Resources:
 MyRepo:
 Type: "AWS::CodeCommit::Repository"
 Properties:
 RepositoryName: MyRepo
 RepositoryDescription: Sample Repo for Cloud9 Demo
 MyC9Environment:
 Type: "AWS::Cloud9::EnvironmentEC2"
 Properties:
 Repositories:
 - PathComponent: /cfn
 RepositoryUrl: !GetAtt MyRepo.CloneUrlHttp
 InstanceType: t2.micro • Describe recursos • Nombre logico • Tipo • Propiedades/ Atributos
  5. © 2018, Amazon Web Services, Inc. or its Affiliates. All

    rights reserved. Opciones de Codificación Nivel Alto Nivel Bajo • AWS CDK (ahora en “developer preview"), Pulumi (independiente) • Se mantiene al nivel alto, vs. los “traductores” (DSLs) • El CDK traduce a plantillas de CloudFormation también, mientras Pulumi no Imperativo • Troposphere (Python), SparkleFormation (Ruby), GoFormation (Go) • Aprovecha los controles de flujo de los lenguajes de nivel superior • Generación de plantillas de CloudFormation (en estos casos) Idiomas específicos (DSLs) • CloudFormation (con o sin macros), modulos de Terraform • Declara el estado deseado, el sistema encuentra la ruta para llegar a ese estado • Abstracción y control de flujo son posibles, pero limitados Declarativo • Usando AWS SDKs & CLIs • Paso a paso, instrucciones especificas • Manejo de errores y actualizaciones de estado dejadas al autor Mas manual
  6. © 2018, Amazon Web Services, Inc. or its Affiliates. All

    rights reserved. Macros • Permite escribir código abreviado que expande automáticamente cuando la plantilla se implementa • Crear funciones y utilidades, “loops”, manejar texto, asegurar que sus recursos cumplen con estándares • Facil de reutilizar y compartir en pilas y plantillas • Usuarios de macros se pueden aislar de los detalles del código • Son funciones Lambda, y pueden ser escritos en cualquier lenguaje compatible con Lambda • Macros son transformaciones, similar a SAM (Serverless Application Model)
  7. © 2018, Amazon Web Services, Inc. or its Affiliates. All

    rights reserved. Ejemplo 1: Iterador Transform: - Count Resources: Bucket: Type: AWS::S3::Bucket Count: 3 Transform: - Count Sqs: Type: AWS:::SQS::Queue Count: 2 Resources: Bucket1: Type: AWS::S3::Bucket Bucket2: Type: AWS::S3::Bucket Bucket3: Type: AWS::S3::Bucket Resources: Sqs1: Type: AWS:::SQS::Queue Sqs2: Type: AWS:::SQS::Queue
  8. © 2018, Amazon Web Services, Inc. or its Affiliates. All

    rights reserved. Ejemplo 1: Iterador (Codigo Lambda) import copy def process_template(template): new_template = copy.deepcopy(template) status = 'success' for name, resource in template['Resources'].items(): if 'Count' in resource: count = new_template['Resources'][name].pop('Count') multiplied = multiply(name, new_template['Resources'][name], count) if not set(multiplied.keys()) & set(new_template['Resources'].keys()): new_template['Resources'].update(multiplied) else: status = 'failed' return status, template return status, new_template def multiply(resource_name, resource_structure, count): resources = {} for iteration in range(1, count): resources[resource_name+str(iteration)] = resource_structure return resources def handler(event, context): result = process_template(event['fragment']) return { 'requestId': event['requestId'], 'status': result[0], 'fragment': result[1], }
  9. © 2018, Amazon Web Services, Inc. or its Affiliates. All

    rights reserved. Ejemplo 1: Implementación del Macro AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Resources: Macro: Type: AWS::CloudFormation::Macro Properties: Name: Count FunctionName: !GetAtt CountMacroFunction.Arn CountMacroFunction: Type: AWS::Serverless::Function Properties: CodeUri: src Handler: index.handler Runtime: python3.6 Timeout: 5 https://github.com/awslabs/aws-cloudformation-templates/tree/master/aws/services/CloudFormation/MacrosExamples/Count
  10. © 2018, Amazon Web Services, Inc. or its Affiliates. All

    rights reserved. Ejemplo 2: Variables Globales Transform: Globals Globals: SomeText: some-text ThingTag: Key: Thing Value: This is a thing Resources: Bucket: Type: AWS::S3::Bucket Properties: BucketName: "@SomeText" Tags: - "@ThingTag" - Key: OtherThing Value: Other thing value Resources: Bucket: Type: AWS::S3::Bucket Properties: BucketName: “some-text" Tags: - Key: Thing Value: This is a thing - Key: OtherThing Value: Other thing value
  11. © 2018, Amazon Web Services, Inc. or its Affiliates. All

    rights reserved. Ejemplo 3: Funciones para texto Parameters: InputString: Default: "This is a test input string" Type: String Resources: S3Bucket: Type: "AWS::S3::Bucket" Properties: Tags: - Key: Upper Value: 'Fn::Transform': - Name: 'StringMacro' Parameters: InputString: !Ref InputString Operation: Upper Parameters: InputString: Default: "This is a test input string" Type: String Resources: S3Bucket: Type: "AWS::S3::Bucket" Properties: Tags: - Key: Upper Value: “THIS IS A TEST INPUT STRING”
  12. © 2018, Amazon Web Services, Inc. or its Affiliates. All

    rights reserved. Ejemplo 4: Valores Pre-Determinados (Cubo S3) Transform: Defaults Resources: Bucket1: Type: AWS::S3::Bucket Resources: Bucket1: Type: AWS::S3::Bucket Properties: AccessControl: Private Bucket1Policy: Type: AWS::S3::BucketPolicy Properties: Bucket: Ref: Bucket1 PolicyDocument: Version: "2012-10-17" Statement: - Effect: Deny Principal: "*" Action: "s3:Delete*" Resource: Fn::Sub: "arn:aws:s3:::${Bucket1}/*" Condition: Bool: aws:MultiFactorAuthPresent: "false"
  13. © 2018, Amazon Web Services, Inc. or its Affiliates. All

    rights reserved. • Ejemplos: • https://github.com/awslabs/aws-cloudformation-templates/ tree/master/aws/services/CloudFormation/MacrosExamples • Otros ejemplos: • https://github.com/KablamoOSS/cfn-macros • Comunidad CloudFormation en Slack • awsdevelopers.slack.com • Envie email a @luiscolon1 en Twitter Enlaces
  14. © 2018, Amazon Web Services, Inc. or its Affiliates. All

    rights reserved. :) Gracias! Luis Colon (@luiscolon1) Senior Developer Advocate (Evangelista) AWS CloudFormation [email protected] 13.02.2019