Skip to content
English
On this page

Guía de Configuración de AWS Amplify CLI

1. Requisitos Previos

1.1 Requerimientos Base

bash
# Node.js v14.x o superior
node --version

# npm v6.x o superior
npm --version

# AWS CLI configurado
aws configure list

1.2 Permisos AWS Necesarios

json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "amplify:*",
                "cognito:*",
                "dynamodb:*",
                "iam:*",
                "lambda:*",
                "s3:*",
                "appsync:*",
                "cloudformation:*"
            ],
            "Resource": "*"
        }
    ]
}

2. Instalación

2.1 Instalación Global

bash
# Instalar Amplify CLI
npm install -g @aws-amplify/cli

# Verificar instalación
amplify --version

# Configurar Amplify
amplify configure

2.2 Configuración Inicial del Proyecto

bash
# Crear nuevo proyecto
mkdir mi-proyecto-amplify
cd mi-proyecto-amplify

# Inicializar proyecto
amplify init

# Configurar proyecto existente
amplify pull --appId XXXXX --envName dev

3. Estructura del Proyecto

3.1 Estructura Base

mi-proyecto-amplify/
├── amplify/
│   ├── backend/
│   │   ├── api/
│   │   ├── auth/
│   │   ├── function/
│   │   └── storage/
│   ├── hooks/
│   └── team-provider-info.json
├── src/
│   ├── graphql/
│   ├── models/
│   └── app.js
├── .gitignore
├── amplify.yml
└── package.json

3.2 Configuración de Ambiente

javascript
// src/aws-exports.js
const awsmobile = {
    "aws_project_region": "us-east-1",
    "aws_cognito_region": "us-east-1",
    "aws_user_pools_id": "us-east-1_xxxxx",
    "aws_user_pools_web_client_id": "xxxxx"
};

export default awsmobile;

4. Comandos Principales

4.1 Gestión de Categorías

bash
# Agregar autenticación
amplify add auth

# Agregar API
amplify add api

# Agregar almacenamiento
amplify add storage

# Agregar función Lambda
amplify add function

4.2 Gestión de Entorno

bash
# Crear nuevo entorno
amplify env add

# Listar entornos
amplify env list

# Cambiar entorno
amplify env checkout prod

# Eliminar entorno
amplify env remove dev

5. Configuración de Servicios

5.1 Configuración de API (GraphQL)

graphql
# amplify/backend/api/myapi/schema.graphql
type Todo @model {
  id: ID!
  name: String!
  description: String
  status: TodoStatus!
  createdAt: AWSDateTime!
}

enum TodoStatus {
  NEW
  IN_PROGRESS
  COMPLETED
}

5.2 Configuración de Autenticación

javascript
// amplify/backend/auth/cognitoConfig.json
{
  "identityPoolName": "myapp_identity_pool",
  "allowUnauthenticatedIdentities": false,
  "resourceNameTruncated": "myapp",
  "userPoolName": "myapp_user_pool",
  "autoVerifiedAttributes": ["email"],
  "mfaConfiguration": "OFF",
  "mfaTypes": ["SMS Text Message"],
  "smsAuthenticationMessage": "Your authentication code is {####}",
  "smsVerificationMessage": "Your verification code is {####}",
  "emailVerificationSubject": "Your verification code",
  "emailVerificationMessage": "Your verification code is {####}"
}

6. Desarrollo Local

6.1 Mock API

bash
# Iniciar API local
amplify mock api

# Consultar API local
curl http://localhost:20002/graphql \
  -H "Content-Type: application/json" \
  -d '{"query": "query { listTodos { items { id name status } } }"}'

6.2 Testing Local

javascript
// tests/api.test.js
import { API } from 'aws-amplify';
import * as queries from './graphql/queries';

describe('API Tests', () => {
  it('should fetch todos', async () => {
    const response = await API.graphql({ 
      query: queries.listTodos 
    });
    expect(response.data.listTodos.items).toBeDefined();
  });
});

7. Despliegue y Publicación

7.1 Despliegue de Backend

bash
# Publicar todos los cambios
amplify push

# Publicar con confirmación
amplify push --y

# Publicar categoría específica
amplify push api

7.2 Publicación Frontend

bash
# Publicar frontend
amplify publish

# Publicar con hosting
amplify add hosting
amplify publish

8. Gestión de Datos

8.1 DataStore

javascript
// src/models/schema.js
import { DataStore } from '@aws-amplify/datastore';
import { Todo } from './models';

async function createTodo() {
  try {
    await DataStore.save(
      new Todo({
        name: "Nueva tarea",
        description: "Descripción",
        status: "NEW"
      })
    );
  } catch (error) {
    console.log("Error saving todo", error);
  }
}

8.2 Storage

javascript
// src/storage/upload.js
import { Storage } from 'aws-amplify';

async function uploadFile(file) {
  try {
    await Storage.put(file.name, file, {
      contentType: file.type,
      level: 'private'
    });
  } catch (error) {
    console.log('Error uploading file:', error);
  }
}

9. Seguridad

9.1 Configuración de Autenticación

javascript
// src/config/auth.js
import { Auth } from 'aws-amplify';

async function signUp(username, password, email) {
  try {
    const { user } = await Auth.signUp({
      username,
      password,
      attributes: {
        email
      }
    });
    return user;
  } catch (error) {
    console.log('Error signing up:', error);
    throw error;
  }
}

9.2 Autorización

graphql
# amplify/backend/api/myapi/schema.graphql
type PrivateNote @model 
@auth(rules: [
  { allow: owner },
  { allow: groups, groups: ["Admins"] }
]) {
  id: ID!
  content: String!
  owner: String
}

10. Monitoreo y Análisis

10.1 Analytics

javascript
// src/analytics/tracking.js
import { Analytics } from 'aws-amplify';

async function trackEvent(name, attributes) {
  try {
    await Analytics.record({
      name,
      attributes
    });
  } catch (error) {
    console.log('Error recording event:', error);
  }
}

10.2 Logging

javascript
// src/utils/logger.js
import { Logger } from 'aws-amplify';

const logger = new Logger('MyApp');

logger.info('Evento informativo');
logger.warn('Advertencia');
logger.error('Error crítico');

11. CI/CD

11.1 Configuración de Pipeline

yaml
# amplify.yml
version: 1
backend:
  phases:
    build:
      commands:
        - amplify push --y
frontend:
  phases:
    preBuild:
      commands:
        - npm ci
    build:
      commands:
        - npm run build
  artifacts:
    baseDirectory: build
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*

11.2 Automatización

bash
# Scripts de automatización
amplify add script

# Configurar hooks
amplify add hook

12. Comandos Útiles Adicionales

bash
# Estado del proyecto
amplify status

# Consola web
amplify console

# Generar modelos
amplify codegen models

# Limpiar recursos locales
amplify clean

# Actualizar CLI
npm install -g @aws-amplify/cli@latest

13. Troubleshooting

13.1 Problemas Comunes

bash
# Resetear estado local
amplify clean
amplify pull

# Verificar logs
amplify console api
amplify console auth

# Validar configuración
amplify status

13.2 Debug

bash
# Habilitar logs detallados
export DEBUG=amplify:*

# Verificar credenciales
amplify configure

Esta guía proporciona una base sólida para trabajar con AWS Amplify CLI. Recuerda mantener actualizadas las herramientas y seguir las mejores prácticas de seguridad de AWS.