Feat: Adds cognito and memory

This commit is contained in:
2025-10-22 11:24:38 -03:00
parent f71b054dca
commit d37d5132eb
45 changed files with 3983 additions and 0 deletions

13
assistente/Dockerfile Normal file
View File

@@ -0,0 +1,13 @@
FROM public.ecr.aws/lambda/python:3.13
# Copy requirements.txt
COPY requirements.txt ${LAMBDA_TASK_ROOT}
# Install the specified packages
RUN pip install -r requirements.txt
# Copy function code
COPY ./ ${LAMBDA_TASK_ROOT}
# Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile)
CMD ["agent.agent_call"]

93
assistente/README.md Normal file
View File

@@ -0,0 +1,93 @@
# ChatBot
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.shared.cloud.dnxbrasil.com.br/dnx-br/clientes/ifsp/chatbot.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.shared.cloud.dnxbrasil.com.br/dnx-br/clientes/ifsp/chatbot/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.

70
assistente/agent.py Normal file
View File

@@ -0,0 +1,70 @@
import json
import time
from langchain_aws import ChatBedrock
from langchain_aws.retrievers import AmazonKnowledgeBasesRetriever
from langgraph.checkpoint.memory import MemorySaver
from langgraph.prebuilt import create_react_agent
from langfuse import Langfuse
from langfuse.langchain import CallbackHandler
from tools import secrets,dynamo
langfuse = Langfuse(
public_key=json.loads(secrets.get_secret())['api-langfuse-public'],
secret_key=json.loads(secrets.get_secret())['api-langfuse-secret'],
host="http://44.200.69.191:3000/"
)
langfuse_handler = CallbackHandler()
def agent_call(event,context):
llm = ChatBedrock(
model_id="us.anthropic.claude-sonnet-4-20250514-v1:0",
region_name="us-east-1",
#aws_access_key_id=os.environ["AWS_ACCESS_KEY_ID"],
#aws_secret_access_key=os.environ["AWS_SECRET_ACCESS_KEY"],
#aws_session_token=os.environ["AWS_SESSION_TOKEN"],
model_kwargs={"temperature": 0.1, 'max_tokens': 1000,},
provider='anthropic'
)
retriever = AmazonKnowledgeBasesRetriever(
knowledge_base_id="PETAZDUOFZ",
region_name="us-east-1",
retrieval_config={"vectorSearchConfiguration": {"numberOfResults": 4}},
)
username=(event['username'])
if event['chat_history']==[]:
history=dynamo.read_memory('frente')
else:
history=event['chat_history']
memory = MemorySaver()
model = llm
tools = [retriever.as_tool()]
prompt="""<rules>
Act like a human in Portuguese Brasil.
You are a assistant for employees and store owners that wants to know about the COMM.pix product, wich makes it possible to use Pix as a payment method outside of Brasil.
Answer questions based on the documents that you have access using the retriever tool, do not create information.
The chat history will be given, without any documents.
If there are info or context missing ask the user before proceding with the document retrieval.
Also return the title of the source document.
If you don't know the answer or can't find it, say so.
<\rules>
<glossary>
<\glossary>
<chain_of_thought>
<\chain_of_thought>
<general_info>
<\general_info>
Answer the following questions as best you can. You have access to the following tools:
{tools}
Chat History:"""+str(history)
agent_executor = create_react_agent(model, tools, checkpointer=memory, prompt=prompt)
config = {"configurable": {"thread_id": "abc123"},"callbacks": [langfuse_handler]}
input_message = event["message"]
dict=input_message[0]
#input_message=[{"role":"user","content":"aluno superior, nunca recebi auxilio, campus são paulo, Meu pai não é registrado, como faço para ganhar auxilio?"}]
response=""
for step in agent_executor.stream({"messages": input_message}, config, stream_mode="values"):
response={"json":(step["messages"][-1].text())}
response['dynamo_reponse']=dynamo.write_memory(username,int(time.time()),dict['role'],dict['content'])
response['chat_history']=history
return (response)

View File

@@ -0,0 +1,6 @@
langchain_core
langchain
langchain_aws
langgraph
langfuse
boto3

View File

@@ -0,0 +1,40 @@
import boto3
def write_memory(user,timestamp,role,content):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('assistente-produtos-servicos-memoria') # Replace 'YourTableName' with your actual table name
item_data = {
'UserId': user, # Replace with your partition key attribute and value
'Timestamp': timestamp, # Replace with your sort key attribute and value (if applicable)
'role': role,
'content': content
}
try:
response = table.put_item(Item=item_data)
except Exception as e:
print("Error adding item:", e)
def read_memory(userid):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('assistente-produtos-servicos-memoria')
# Query parameters
try:
response = table.query(
KeyConditionExpression=boto3.dynamodb.conditions.Key('UserId').eq(userid),
ScanIndexForward=False, # Descending order
Limit=30
)
items = response.get('Items', [])
if items:
latest_items = items
return latest_items
else:
return []
except Exception as e:
print("Error querying DynamoDB:", str(e))

View File

@@ -0,0 +1,25 @@
import boto3
from botocore.exceptions import ClientError
def get_secret():
secret_name = "assistente-produtos-servicos"
region_name = "us-east-1"
# Create a Secrets Manager client
session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
region_name=region_name
)
try:
get_secret_value_response = client.get_secret_value(
SecretId=secret_name
)
except ClientError as e:
# For a list of exceptions thrown, see
# https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
raise e
secret = get_secret_value_response['SecretString']
return secret

37
front/Dockerfile Normal file
View File

@@ -0,0 +1,37 @@
# Use uma imagem base Python oficial.
# Escolha uma versão que seja compatível com suas dependências.
FROM python:3.12-slim
# Copia os arquivos de requisitos primeiro para aproveitar o cache do Docker
COPY requirements.txt ./requirements.txt
# Instala as dependências do backend
RUN pip install --no-cache-dir -r requirements.txt
# Copia o restante dos diretórios e arquivos da aplicação
COPY ./ ./
# Garante que o script de inicialização seja executável
RUN chmod +x ./entrypoint.sh
# Cria os diretórios que a API FastAPI pode precisar (se eles não existirem)
# Estes diretórios serão usados para persistência se volumes forem montados.
#RUN mkdir -p /app/faiss_index_store && \
# mkdir -p /app/uploaded_pdfs
# Expõe as portas que os aplicativos usarão
# Porta 8000 para a API FastAPI
EXPOSE 8000
# Porta 8501 para o aplicativo Streamlit
EXPOSE 8501
# Define a variável de ambiente GROQ_API_KEY.
# É ALTAMENTE RECOMENDADO passar esta variável em tempo de execução
# em vez de embuti-la aqui por questões de segurança.
# Exemplo: docker run -e GROQ_API_KEY="sua_chave_aqui" ...
# ENV GROQ_API_KEY="SUA_CHAVE_GROQ_AQUI_SE_NECESSARIO_MAS_NAO_RECOMENDADO_EMBUTIR"
# Comando para executar quando o contêiner iniciar
# Executa o script start.sh que gerencia os dois processos
CMD ["./entrypoint.sh"]

Binary file not shown.

69
front/app/front.py Normal file
View File

@@ -0,0 +1,69 @@
import streamlit as st
from typing import Set
import requests
import json
import yaml
import st_auth
import boto3
from botocore.exceptions import ClientError
import jwt
headers = st.context.headers
# The ID token contains user claims
id_token = headers.get('x-amzn-oidc-data')
decoded = jwt.decode(id_token, options={"verify_signature": False})
# Tenta diferentes campos onde o user_id pode estar
user_id = (
decoded.get("sub") or # Subject (padrão JWT)
decoded.get("cognito:username") or # Username do Cognito
decoded.get("username") or # Username alternativo
decoded.get("user_id") # Campo customizado
)
st.header("Assistente Produtos Servicos")
url="https://xexm2wsz07-vpce-05915540d0592b921.execute-api.us-east-1.amazonaws.com/dev"
payload=[]
message_history=[]
if "user_prompt_history" not in st.session_state:
st.session_state["user_prompt_history"]=[]
if "chat_answer_history" not in st.session_state:
st.session_state["chat_answer_history"]=[]
if "chat_history" not in st.session_state:
st.session_state["chat_history"] = []
prompt=st.chat_input(placeholder="Digite uma mensagem...",key="prompt")
for generated_response, user_query in zip(st.session_state["chat_answer_history"],st.session_state["user_prompt_history"]):
st.chat_message("user").write(user_query)
st.chat_message("assistant").write(generated_response)
def create_sources_string(source_urls: Set[str])->str:
if not source_urls:
return ""
source_list=list(source_urls)
source_list.sort()
sources_string="source:\n"
for i, source in enumerate(source_list):
sources_string+=f"{i+1}, {source}\n"
return sources_string
if prompt:
st.chat_message("user").write(prompt)
with st.spinner("Generating response.."):
payload=[{"role":"user","content":prompt}]
content={"message":payload,"chat_history":st.session_state["chat_history"],"username":user_id}
headers={"Content-type":"application/json","x-api-key":json.loads(st_auth.get_secret())['api-gateway-api-key']}
generated_response=json.loads(requests.post(url,json=content,headers=headers).text)
if 'chat_history' in generated_response:
if st.session_state["chat_history"] == []:
st.session_state["chat_history"] = generated_response['chat_history']
if 'json' in generated_response:
generated_response=generated_response['json']
if 'message' in generated_response and generated_response['message']=="Endpoint request timed out":
generated_response="Falta de dados: Por favor encaminhe a conversa para a equipe desenvolvedora"
#generated_response=[{"role":"user","content":prompt}]
# sources= set([doc.metadata["source"] for doc in generated_response['context']])
#formatted_response=f"{generated_response['answer']} \n\n {create_sources_string(sources)}"
formatted_response=generated_response
st.chat_message("assistant").write(formatted_response)
st.session_state["user_prompt_history"].append(prompt)
st.session_state["chat_answer_history"].append(formatted_response)
st.session_state["chat_history"]=st.session_state["chat_history"]+[{"role":"user","content":prompt}]+[{"role":"assistant","content":formatted_response}]
st.session_state.user_input=""

102
front/app/st_auth.py Normal file
View File

@@ -0,0 +1,102 @@
import streamlit_authenticator as stauth
import yaml
from yaml.loader import SafeLoader
import streamlit as st
import boto3
from botocore.exceptions import ClientError
def get_authenticator():
# with open('.streamlit/users.yaml') as file:
# cred_config = yaml.load(file, Loader=SafeLoader)
file_content = read_text_file_from_s3('chatbot-editais-auth', 'config.yaml')
# Parse the YAML content safely
cred_config = yaml.safe_load(file_content)
# Pre-hashing all plain text passwords once
# hash_credentials = stauth.Hasher.hash_passwords(config['credentials'])
authenticator = stauth.Authenticate(
cred_config['credentials'],
cred_config['cookie']['name'],
cred_config['cookie']['key'],
cred_config['cookie']['expiry_days']
)
return authenticator
def st_authenticate(authenticator: stauth.Authenticate):
# authenticator = get_authenticator()
try:
authenticator.login(
location='sidebar',
fields=dict(Username="Usuário",
Password="Senha")
)
except Exception as e:
st.error(e)
authenticator.cookie_controller.delete_cookie()
st.warning('Caso o erro persistir, tente recarregar a página.')
st.stop()
if st.session_state['authentication_status']:
with st.sidebar:
st.write(f'Usuário: {st.session_state["name"]}')
authenticator.logout()
elif st.session_state['authentication_status'] is False:
with st.sidebar:
st.error('Usuário/senha incorreto')
st.stop()
elif st.session_state['authentication_status'] is None:
st.warning('Por favor, informe o seu usuário e senha no painel lateral')
st.stop()
def read_text_file_from_s3(bucket, key):
"""
Read a YAML file from an S3 bucket using provided AWS credentials.
Args:
bucket (str): Name of the S3 bucket
key (str): Path to the YAML file in the bucket
aws_access_key_id (str): AWS Access Key ID
aws_secret_access_key (str): AWS Secret Access Key
Returns:
dict: Parsed YAML content
"""
try:
# Create an S3 client
s3_client = boto3.client('s3')
# Download the file from S3
response = s3_client.get_object(Bucket=bucket, Key=key)
# Read the file content
file_content = response['Body'].read().decode('utf-8')
return file_content
except Exception as e:
st.error(f"Error reading file from S3: {e}")
return None
def get_secret():
secret_name = "assistente-produtos-servicos"
region_name = "us-east-1"
# Create a Secrets Manager client
session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
region_name=region_name
)
try:
get_secret_value_response = client.get_secret_value(
SecretId=secret_name
)
except ClientError as e:
# For a list of exceptions thrown, see
# https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
raise e
secret = get_secret_value_response['SecretString']
return secret

23
front/entrypoint.sh Normal file
View File

@@ -0,0 +1,23 @@
#!/bin/bash
# Define o diretório base da aplicação dentro do contêiner
APP_DIR="/app"
# Navega para o diretório do backend e inicia a API FastAPI em segundo plano
#echo "Iniciando API FastAPI na porta 8000..."
#python app/backend/main.py &
# Aguarda alguns segundos para garantir que a API tenha tempo de iniciar
# Isso é opcional, mas pode ajudar a evitar problemas de conexão imediata do frontend
#echo "Aguardando a API iniciar..."
#sleep 10 # Ajuste o tempo conforme necessário
# Navega para o diretório do frontend e inicia o aplicativo Streamlit em primeiro plano
echo "Iniciando aplicativo Streamlit na porta 8501..."
# --server.headless=true é importante para rodar Streamlit em ambientes sem GUI (como Docker)
# --server.address=0.0.0.0 permite que o Streamlit seja acessado de fora do contêiner
# --server.enableCORS=false pode ser necessário dependendo da configuração, mas geralmente não para localhost
streamlit run app/front.py --server.port 8501 --server.address 0.0.0.0 --server.headless true
# O comando 'streamlit run' manterá o contêiner em execução.
# Se o Streamlit parar por algum motivo, o script e, consequentemente, o contêiner, terminarão.

1633
front/poetry.lock generated Normal file

File diff suppressed because it is too large Load Diff

17
front/pyproject.toml Normal file
View File

@@ -0,0 +1,17 @@
[tool.poetry]
name = "front"
version = "0.1.0"
description = "Front para o ChatBot editais do IFSP"
authors = ["Lucas DNX"]
readme = "README.md"
package-mode = false
[tool.poetry.dependencies]
python = "^3.12"
streamlit = "^1.49.1"
streamlit-authenticator = "^0.4.2"
boto3 = "^1.40.37"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

6
front/requirements.txt Normal file
View File

@@ -0,0 +1,6 @@
streamlit
requests
pyyaml
boto3
streamlit-authenticator
jwt

View File

@@ -0,0 +1,11 @@
config:
aws:region: us-east-1
dynamo:account_id: "277048801940"
dynamo:project_name: assistente-produtos-servicos-memoria-dynamodb
dynamo:environment: dev
dynamo:tags:
project: assistente-produtos-servicos
env: dev
costCenter: AI
owner: ai-team

View File

@@ -0,0 +1,3 @@
name: dynamodb-dev
runtime: python
description: Infraestrutura da aplicação Dynamodb

View File

@@ -0,0 +1,18 @@
import pulumi
import pulumi_aws as aws
import conf as config
basic_dynamodb_table = aws.dynamodb.Table(config.project_name,
name="assistente-produtos-servicos-memoria",
billing_mode="PAY_PER_REQUEST",
hash_key="UserId",
range_key="Timestamp",
attributes=[
{
"name": "UserId",
"type": "S",
},
{
"name": "Timestamp",
"type": "N",
}
])

View File

@@ -0,0 +1,13 @@
import pulumi
from autotag.taggable import is_taggable
# registerAutoTags registers a global stack transformation that merges a set
# of tags with whatever was also explicitly added to the resource definition.
def register_auto_tags(auto_tags):
pulumi.runtime.register_stack_transformation(lambda args: auto_tag(args, auto_tags))
# auto_tag applies the given tags to the resource properties if applicable.
def auto_tag(args, auto_tags):
if is_taggable(args.type_):
args.props['tags'] = {**(args.props['tags'] or {}), **auto_tags}
return pulumi.ResourceTransformationResult(args.props, args.opts)

View File

@@ -0,0 +1,12 @@
{
"all": "mandatory",
"check-required-tags": {
"requiredTags": [
"user:project",
"user:env",
"user:account",
"user:costCenter",
"user:owner"
]
}
}

View File

@@ -0,0 +1,234 @@
# isTaggable returns true if the given resource type is an AWS resource that supports tags.
def is_taggable(t):
return t in taggable_resource_types
# taggable_resource_types is a list of known AWS type tokens that are taggable.
taggable_resource_types = [
'aws:accessanalyzer/analyzer:Analyzer',
'aws:acm/certificate:Certificate',
'aws:acmpca/certificateAuthority:CertificateAuthority',
'aws:alb/loadBalancer:LoadBalancer',
'aws:alb/targetGroup:TargetGroup',
'aws:apigateway/apiKey:ApiKey',
'aws:apigateway/clientCertificate:ClientCertificate',
'aws:apigateway/domainName:DomainName',
'aws:apigateway/restApi:RestApi',
'aws:apigateway/stage:Stage',
'aws:apigateway/usagePlan:UsagePlan',
'aws:apigateway/vpcLink:VpcLink',
'aws:applicationloadbalancing/loadBalancer:LoadBalancer',
'aws:applicationloadbalancing/targetGroup:TargetGroup',
'aws:appmesh/mesh:Mesh',
'aws:appmesh/route:Route',
'aws:appmesh/virtualNode:VirtualNode',
'aws:appmesh/virtualRouter:VirtualRouter',
'aws:appmesh/virtualService:VirtualService',
'aws:appsync/graphQLApi:GraphQLApi',
'aws:athena/workgroup:Workgroup',
'aws:autoscaling/group:Group',
'aws:backup/plan:Plan',
'aws:backup/vault:Vault',
'aws:cfg/aggregateAuthorization:AggregateAuthorization',
'aws:cfg/configurationAggregator:ConfigurationAggregator',
'aws:cfg/rule:Rule',
'aws:cloudformation/stack:Stack',
'aws:cloudformation/stackSet:StackSet',
'aws:cloudfront/distribution:Distribution',
'aws:cloudhsmv2/cluster:Cluster',
'aws:cloudtrail/trail:Trail',
'aws:cloudwatch/eventRule:EventRule',
'aws:cloudwatch/logGroup:LogGroup',
'aws:cloudwatch/metricAlarm:MetricAlarm',
'aws:codebuild/project:Project',
'aws:codecommit/repository:Repository',
'aws:codepipeline/pipeline:Pipeline',
'aws:codepipeline/webhook:Webhook',
'aws:codestarnotifications/notificationRule:NotificationRule',
'aws:cognito/identityPool:IdentityPool',
'aws:cognito/userPool:UserPool',
'aws:datapipeline/pipeline:Pipeline',
'aws:datasync/agent:Agent',
'aws:datasync/efsLocation:EfsLocation',
'aws:datasync/locationSmb:LocationSmb',
'aws:datasync/nfsLocation:NfsLocation',
'aws:datasync/s3Location:S3Location',
'aws:datasync/task:Task',
'aws:dax/cluster:Cluster',
'aws:directconnect/connection:Connection',
'aws:directconnect/hostedPrivateVirtualInterfaceAccepter:HostedPrivateVirtualInterfaceAccepter',
'aws:directconnect/hostedPublicVirtualInterfaceAccepter:HostedPublicVirtualInterfaceAccepter',
'aws:directconnect/hostedTransitVirtualInterfaceAcceptor:HostedTransitVirtualInterfaceAcceptor',
'aws:directconnect/linkAggregationGroup:LinkAggregationGroup',
'aws:directconnect/privateVirtualInterface:PrivateVirtualInterface',
'aws:directconnect/publicVirtualInterface:PublicVirtualInterface',
'aws:directconnect/transitVirtualInterface:TransitVirtualInterface',
'aws:directoryservice/directory:Directory',
'aws:dlm/lifecyclePolicy:LifecyclePolicy',
'aws:dms/endpoint:Endpoint',
'aws:dms/replicationInstance:ReplicationInstance',
'aws:dms/replicationSubnetGroup:ReplicationSubnetGroup',
'aws:dms/replicationTask:ReplicationTask',
'aws:docdb/cluster:Cluster',
'aws:docdb/clusterInstance:ClusterInstance',
'aws:docdb/clusterParameterGroup:ClusterParameterGroup',
'aws:docdb/subnetGroup:SubnetGroup',
'aws:dynamodb/table:Table',
'aws:ebs/snapshot:Snapshot',
'aws:ebs/snapshotCopy:SnapshotCopy',
'aws:ebs/volume:Volume',
'aws:ec2/ami:Ami',
'aws:ec2/amiCopy:AmiCopy',
'aws:ec2/amiFromInstance:AmiFromInstance',
'aws:ec2/capacityReservation:CapacityReservation',
'aws:ec2/customerGateway:CustomerGateway',
'aws:ec2/defaultNetworkAcl:DefaultNetworkAcl',
'aws:ec2/defaultRouteTable:DefaultRouteTable',
'aws:ec2/defaultSecurityGroup:DefaultSecurityGroup',
'aws:ec2/defaultSubnet:DefaultSubnet',
'aws:ec2/defaultVpc:DefaultVpc',
'aws:ec2/defaultVpcDhcpOptions:DefaultVpcDhcpOptions',
'aws:ec2/eip:Eip',
'aws:ec2/fleet:Fleet',
'aws:ec2/instance:Instance',
'aws:ec2/internetGateway:InternetGateway',
'aws:ec2/keyPair:KeyPair',
'aws:ec2/launchTemplate:LaunchTemplate',
'aws:ec2/natGateway:NatGateway',
'aws:ec2/networkAcl:NetworkAcl',
'aws:ec2/networkInterface:NetworkInterface',
'aws:ec2/placementGroup:PlacementGroup',
'aws:ec2/routeTable:RouteTable',
'aws:ec2/securityGroup:SecurityGroup',
'aws:ec2/spotInstanceRequest:SpotInstanceRequest',
'aws:ec2/subnet:Subnet',
'aws:ec2/vpc:Vpc',
'aws:ec2/vpcDhcpOptions:VpcDhcpOptions',
'aws:ec2/vpcEndpoint:VpcEndpoint',
'aws:ec2/vpcEndpointService:VpcEndpointService',
'aws:ec2/vpcPeeringConnection:VpcPeeringConnection',
'aws:ec2/vpcPeeringConnectionAccepter:VpcPeeringConnectionAccepter',
'aws:ec2/vpnConnection:VpnConnection',
'aws:ec2/vpnGateway:VpnGateway',
'aws:ec2clientvpn/endpoint:Endpoint',
'aws:ec2transitgateway/routeTable:RouteTable',
'aws:ec2transitgateway/transitGateway:TransitGateway',
'aws:ec2transitgateway/vpcAttachment:VpcAttachment',
'aws:ec2transitgateway/vpcAttachmentAccepter:VpcAttachmentAccepter',
'aws:ecr/repository:Repository',
'aws:ecs/capacityProvider:CapacityProvider',
'aws:ecs/cluster:Cluster',
'aws:ecs/service:Service',
'aws:ecs/taskDefinition:TaskDefinition',
'aws:efs/fileSystem:FileSystem',
'aws:eks/cluster:Cluster',
'aws:eks/fargateProfile:FargateProfile',
'aws:eks/nodeGroup:NodeGroup',
'aws:elasticache/cluster:Cluster',
'aws:elasticache/replicationGroup:ReplicationGroup',
'aws:elasticbeanstalk/application:Application',
'aws:elasticbeanstalk/applicationVersion:ApplicationVersion',
'aws:elasticbeanstalk/environment:Environment',
'aws:elasticloadbalancing/loadBalancer:LoadBalancer',
'aws:elasticloadbalancingv2/loadBalancer:LoadBalancer',
'aws:elasticloadbalancingv2/targetGroup:TargetGroup',
'aws:elasticsearch/domain:Domain',
'aws:elb/loadBalancer:LoadBalancer',
'aws:emr/cluster:Cluster',
'aws:fsx/lustreFileSystem:LustreFileSystem',
'aws:fsx/windowsFileSystem:WindowsFileSystem',
'aws:gamelift/alias:Alias',
'aws:gamelift/build:Build',
'aws:gamelift/fleet:Fleet',
'aws:gamelift/gameSessionQueue:GameSessionQueue',
'aws:glacier/vault:Vault',
'aws:glue/crawler:Crawler',
'aws:glue/job:Job',
'aws:glue/trigger:Trigger',
'aws:iam/role:Role',
'aws:iam/user:User',
'aws:inspector/resourceGroup:ResourceGroup',
'aws:kinesis/analyticsApplication:AnalyticsApplication',
'aws:kinesis/firehoseDeliveryStream:FirehoseDeliveryStream',
'aws:kinesis/stream:Stream',
'aws:kms/externalKey:ExternalKey',
'aws:kms/key:Key',
'aws:lambda/function:Function',
'aws:lb/loadBalancer:LoadBalancer',
'aws:lb/targetGroup:TargetGroup',
'aws:licensemanager/licenseConfiguration:LicenseConfiguration',
'aws:lightsail/instance:Instance',
'aws:mediaconvert/queue:Queue',
'aws:mediapackage/channel:Channel',
'aws:mediastore/container:Container',
'aws:mq/broker:Broker',
'aws:mq/configuration:Configuration',
'aws:msk/cluster:Cluster',
'aws:neptune/cluster:Cluster',
'aws:neptune/clusterInstance:ClusterInstance',
'aws:neptune/clusterParameterGroup:ClusterParameterGroup',
'aws:neptune/eventSubscription:EventSubscription',
'aws:neptune/parameterGroup:ParameterGroup',
'aws:neptune/subnetGroup:SubnetGroup',
'aws:opsworks/stack:Stack',
'aws:organizations/account:Account',
'aws:pinpoint/app:App',
'aws:qldb/ledger:Ledger',
'aws:ram/resourceShare:ResourceShare',
'aws:rds/cluster:Cluster',
'aws:rds/clusterEndpoint:ClusterEndpoint',
'aws:rds/clusterInstance:ClusterInstance',
'aws:rds/clusterParameterGroup:ClusterParameterGroup',
'aws:rds/clusterSnapshot:ClusterSnapshot',
'aws:rds/eventSubscription:EventSubscription',
'aws:rds/instance:Instance',
'aws:rds/optionGroup:OptionGroup',
'aws:rds/parameterGroup:ParameterGroup',
'aws:rds/securityGroup:SecurityGroup',
'aws:rds/snapshot:Snapshot',
'aws:rds/subnetGroup:SubnetGroup',
'aws:redshift/cluster:Cluster',
'aws:redshift/eventSubscription:EventSubscription',
'aws:redshift/parameterGroup:ParameterGroup',
'aws:redshift/snapshotCopyGrant:SnapshotCopyGrant',
'aws:redshift/snapshotSchedule:SnapshotSchedule',
'aws:redshift/subnetGroup:SubnetGroup',
'aws:resourcegroups/group:Group',
'aws:route53/healthCheck:HealthCheck',
'aws:route53/resolverEndpoint:ResolverEndpoint',
'aws:route53/resolverRule:ResolverRule',
'aws:route53/zone:Zone',
'aws:s3/bucket:Bucket',
'aws:s3/bucketObject:BucketObject',
'aws:sagemaker/endpoint:Endpoint',
'aws:sagemaker/endpointConfiguration:EndpointConfiguration',
'aws:sagemaker/model:Model',
'aws:sagemaker/notebookInstance:NotebookInstance',
'aws:secretsmanager/secret:Secret',
'aws:servicecatalog/portfolio:Portfolio',
'aws:sfn/activity:Activity',
'aws:sfn/stateMachine:StateMachine',
'aws:sns/topic:Topic',
'aws:sqs/queue:Queue',
'aws:ssm/activation:Activation',
'aws:ssm/document:Document',
'aws:ssm/maintenanceWindow:MaintenanceWindow',
'aws:ssm/parameter:Parameter',
'aws:ssm/patchBaseline:PatchBaseline',
'aws:storagegateway/cachesIscsiVolume:CachesIscsiVolume',
'aws:storagegateway/gateway:Gateway',
'aws:storagegateway/nfsFileShare:NfsFileShare',
'aws:storagegateway/smbFileShare:SmbFileShare',
'aws:swf/domain:Domain',
'aws:transfer/server:Server',
'aws:transfer/user:User',
'aws:waf/rateBasedRule:RateBasedRule',
'aws:waf/rule:Rule',
'aws:waf/ruleGroup:RuleGroup',
'aws:waf/webAcl:WebAcl',
'aws:wafregional/rateBasedRule:RateBasedRule',
'aws:wafregional/rule:Rule',
'aws:wafregional/ruleGroup:RuleGroup',
'aws:wafregional/webAcl:WebAcl',
'aws:workspaces/directory:Directory',
'aws:workspaces/ipGroup:IpGroup',
]

16
infra/dynamodb/conf.py Normal file
View File

@@ -0,0 +1,16 @@
import pulumi
import pulumi_aws as aws
from autotag.autotag import register_auto_tags
config = pulumi.Config("dynamo")
project_name = config.require("project_name")
stack_name = pulumi.get_stack()
environment = config.require("environment")
account_id = config.require("account_id")
tags = config.require_object("tags")
aws_region = aws.get_region().id
current = aws.get_caller_identity()
register_auto_tags(tags)

1
infra/ecr Submodule

Submodule infra/ecr added at 6fce961de1

View File

@@ -0,0 +1,50 @@
config:
aws:region: us-east-1
app-ecs:account_id: "277048801940" # dnxbrasil-nonprod
app-ecs:project_name: assistente-serv
app-ecs:environment: dev
# app-ecs:bedrock_api_key:
# secure: you-can-put-your-pulumi-encrypted-secure-string-here
app-ecs:tags:
project: assistente-servico-produtos
env: dev # dev, test, stage, prod
account: nonprod # prod, nonprod, dataScience
costCenter: AI # AWSGeneral, AI, data, productName
owner: AI # team or a preson responsible
app-ecs:network:
vpc_id: vpc-0c83ac3bfb36f79b4
alb_internal: false
alb_subnet_ids: # 2+ private subnets if alb_internal else public subnets in the same region and vpc
- subnet-0f4729d5fc489dac6 # public-us-east-1a-subnet
- subnet-0c32829a234877a0b # public-us-east-1b-subnet
alb_allow_ingress_cidr:
- 206.43.253.179/32 # DNX-Thallys-1
ecs_subnet_ids:
- subnet-044cc28c8838f890f # private-us-east1a
- subnet-029d5802bc109a3db # private-us-east1a
app-ecs:ecs:
- task_name: assisnte-produtos-servicos-front
ecr_repo_name: assistente-produtos-servicos-frontend-dev
ecr_image_tag: latest
ecr_image_digest: sha256:8115ef755398bb077628cc0dc12440f023c86da89d24b5dab79c2e025818be39
cpu: 256
memory: 512
desired_count: 1
sgs_allowing_ingress: {}
use_load_balancer: true
auto_scaling:
min_capacity: 1
max_capacity: 3
target_value: 60.0
lb_config:
name: listener
listener_port: 8501
target_port: 8501
container_port: 8501
env_variables: {}
# SECRET_NAME: dev/ai-pge-doc-classification
# BEDROCK_REGION: us-east-1
# LANGCHAIN_TRACING_V2: "true"
# LANGCHAIN_PROJECT: pge-doc-classification-dev
app-ecs:cloudwatch:
log_group_name: pge-classify

View File

@@ -0,0 +1,6 @@
name: app-ecs
runtime:
name: python
options:
virtualenv: venv
description: AWS ECS application deploy

71
infra/ecs_alb/README.md Normal file
View File

@@ -0,0 +1,71 @@
# GenAI project infratructure with Pulumi
Nesta documentação apresentamos o setup da IaC do projeto de GenAI.
## 🚀 Deploying Infrastructure to AWS
Para deployar a infraestrutura referente o projeto de GenAI, é utilizado uma stack IaC Pulumi.
Para isso, o desenvolvedor deve seguir os passos:
1. Dentro do diretório raiz do projeto, crie um ambiente virtual pelos comandos:
```shell
# pip install virtualenv
python3.11 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
```
2. (opcional) Configure o seu Pulumi Token:
```shell
export PULUMI_ACCESS_TOKEN="your-access-token"
```
3. Pulumi Login:
```shell
pulumi login
```
4. (opcional) Select a stack to work on:
```shell
pulumi stack select
```
5. Suba a stack do pulumi:
```shell
pulumi up #selecione o stack se não tiver selecionado
```
Após estes passo, os serviços e dependências do projeto serão criados/atualizados, gerando a fundação para a aplicação.
#### Observação 1:
Lembre-se de configurar o usuário IAM registrado como profile no aws-cli, para detectar a conta AWS a ser utilizada:
```shell
export AWS_PROFILE=myorg-nonprod
```
Se não tiver configurado o profile o aws-cli, exporte as seguintes variáveis:
```shell
export AWS_DEFAULT_REGION=
export AWS_ACCESS_KEY_ID=
export AWS_SECRET_ACCESS_KEY=
```
#### Observação 2: Registro de imagem Docker no ECR
Para que a infraestrutura projetada anteriormente consiga referenciar as imagens de cada projeto, é necessário indicar o nome do repositório no argumento `ecr_repo_name` no arquivo YAML.
Como a versão da imagem a ser deployada, indique ou `ecr_image_tag` ou `ecr_image_digest`, sem indicar ambos.
Para registrar corretamente a imagem Docker da sua aplicação no ECR, siga os passos descritos na seguinte documentação:
- https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-push-ecr-image.html
Para incluir variáveis de ambiente no container, informe-as como dicionário (chave-valor) em `env_variables`.
## 🤝 Agradecimentos
* Agradecemos por toda a parceria durante o projeto. Conte conosco! 📢

60
infra/ecs_alb/__main__.py Normal file
View File

@@ -0,0 +1,60 @@
import pulumi
import pulumi_aws as aws
import conf as config
import iam
import ecs
# ECS Cluster Setup
app_ecs_cluster = aws.ecs.Cluster(f"{config.project_name}-ecs-cluster",
configuration=aws.ecs.ClusterConfigurationArgs(
execute_command_configuration=aws.ecs.ClusterConfigurationExecuteCommandConfigurationArgs(
logging="DEFAULT",
),
),
settings=[aws.ecs.ClusterSettingArgs(
name="containerInsights",
value="disabled",
)],
tags={"Name": f"{config.project_name}-{config.stack_name}"},
)
ecs_cluster_capacity_providers = aws.ecs.ClusterCapacityProviders(f"{config.project_name}-cluster-capacity-providers",
cluster_name=app_ecs_cluster.name,
capacity_providers=["FARGATE", "FARGATE_SPOT"],
)
# Security Group Setup
alb_security_group = aws.ec2.SecurityGroup(f"{config.project_name}-security-group",
vpc_id=config.network["vpc_id"],
ingress=[aws.ec2.SecurityGroupIngressArgs(
protocol="-1",
from_port=0,
to_port=0,
cidr_blocks=config.network["alb_allow_ingress_cidr"],
),
],
egress=[aws.ec2.SecurityGroupEgressArgs(
protocol="-1",
from_port=0,
to_port=0,
cidr_blocks=["0.0.0.0/0"],
)],
)
# Load Balancer Setup
app_load_balancer = aws.lb.LoadBalancer(
f"alb-{config.project_name}",
load_balancer_type="application",
security_groups=[alb_security_group.id],
subnets=config.network["alb_subnet_ids"],
idle_timeout=(1200),
internal=config.network['alb_internal'],
)
for ecs_app in config.ecs:
ecs.deploy_app(ecs_app, app_ecs_cluster, alb_security_group, app_load_balancer.arn)
# Export the ALB DNS Name
pulumi.export("url", app_load_balancer.dns_name.apply(lambda dns_name: f"http://{dns_name}"))

View File

@@ -0,0 +1,13 @@
import pulumi
from autotag.taggable import is_taggable
# registerAutoTags registers a global stack transformation that merges a set
# of tags with whatever was also explicitly added to the resource definition.
def register_auto_tags(auto_tags):
pulumi.runtime.register_stack_transformation(lambda args: auto_tag(args, auto_tags))
# auto_tag applies the given tags to the resource properties if applicable.
def auto_tag(args, auto_tags):
if is_taggable(args.type_):
args.props['tags'] = {**(args.props['tags'] or {}), **auto_tags}
return pulumi.ResourceTransformationResult(args.props, args.opts)

View File

@@ -0,0 +1,12 @@
{
"all": "mandatory",
"check-required-tags": {
"requiredTags": [
"user:project",
"user:env",
"user:account",
"user:costCenter",
"user:owner"
]
}
}

View File

@@ -0,0 +1,234 @@
# isTaggable returns true if the given resource type is an AWS resource that supports tags.
def is_taggable(t):
return t in taggable_resource_types
# taggable_resource_types is a list of known AWS type tokens that are taggable.
taggable_resource_types = [
'aws:accessanalyzer/analyzer:Analyzer',
'aws:acm/certificate:Certificate',
'aws:acmpca/certificateAuthority:CertificateAuthority',
'aws:alb/loadBalancer:LoadBalancer',
'aws:alb/targetGroup:TargetGroup',
'aws:apigateway/apiKey:ApiKey',
'aws:apigateway/clientCertificate:ClientCertificate',
'aws:apigateway/domainName:DomainName',
'aws:apigateway/restApi:RestApi',
'aws:apigateway/stage:Stage',
'aws:apigateway/usagePlan:UsagePlan',
'aws:apigateway/vpcLink:VpcLink',
'aws:applicationloadbalancing/loadBalancer:LoadBalancer',
'aws:applicationloadbalancing/targetGroup:TargetGroup',
'aws:appmesh/mesh:Mesh',
'aws:appmesh/route:Route',
'aws:appmesh/virtualNode:VirtualNode',
'aws:appmesh/virtualRouter:VirtualRouter',
'aws:appmesh/virtualService:VirtualService',
'aws:appsync/graphQLApi:GraphQLApi',
'aws:athena/workgroup:Workgroup',
'aws:autoscaling/group:Group',
'aws:backup/plan:Plan',
'aws:backup/vault:Vault',
'aws:cfg/aggregateAuthorization:AggregateAuthorization',
'aws:cfg/configurationAggregator:ConfigurationAggregator',
'aws:cfg/rule:Rule',
'aws:cloudformation/stack:Stack',
'aws:cloudformation/stackSet:StackSet',
'aws:cloudfront/distribution:Distribution',
'aws:cloudhsmv2/cluster:Cluster',
'aws:cloudtrail/trail:Trail',
'aws:cloudwatch/eventRule:EventRule',
'aws:cloudwatch/logGroup:LogGroup',
'aws:cloudwatch/metricAlarm:MetricAlarm',
'aws:codebuild/project:Project',
'aws:codecommit/repository:Repository',
'aws:codepipeline/pipeline:Pipeline',
'aws:codepipeline/webhook:Webhook',
'aws:codestarnotifications/notificationRule:NotificationRule',
'aws:cognito/identityPool:IdentityPool',
'aws:cognito/userPool:UserPool',
'aws:datapipeline/pipeline:Pipeline',
'aws:datasync/agent:Agent',
'aws:datasync/efsLocation:EfsLocation',
'aws:datasync/locationSmb:LocationSmb',
'aws:datasync/nfsLocation:NfsLocation',
'aws:datasync/s3Location:S3Location',
'aws:datasync/task:Task',
'aws:dax/cluster:Cluster',
'aws:directconnect/connection:Connection',
'aws:directconnect/hostedPrivateVirtualInterfaceAccepter:HostedPrivateVirtualInterfaceAccepter',
'aws:directconnect/hostedPublicVirtualInterfaceAccepter:HostedPublicVirtualInterfaceAccepter',
'aws:directconnect/hostedTransitVirtualInterfaceAcceptor:HostedTransitVirtualInterfaceAcceptor',
'aws:directconnect/linkAggregationGroup:LinkAggregationGroup',
'aws:directconnect/privateVirtualInterface:PrivateVirtualInterface',
'aws:directconnect/publicVirtualInterface:PublicVirtualInterface',
'aws:directconnect/transitVirtualInterface:TransitVirtualInterface',
'aws:directoryservice/directory:Directory',
'aws:dlm/lifecyclePolicy:LifecyclePolicy',
'aws:dms/endpoint:Endpoint',
'aws:dms/replicationInstance:ReplicationInstance',
'aws:dms/replicationSubnetGroup:ReplicationSubnetGroup',
'aws:dms/replicationTask:ReplicationTask',
'aws:docdb/cluster:Cluster',
'aws:docdb/clusterInstance:ClusterInstance',
'aws:docdb/clusterParameterGroup:ClusterParameterGroup',
'aws:docdb/subnetGroup:SubnetGroup',
'aws:dynamodb/table:Table',
'aws:ebs/snapshot:Snapshot',
'aws:ebs/snapshotCopy:SnapshotCopy',
'aws:ebs/volume:Volume',
'aws:ec2/ami:Ami',
'aws:ec2/amiCopy:AmiCopy',
'aws:ec2/amiFromInstance:AmiFromInstance',
'aws:ec2/capacityReservation:CapacityReservation',
'aws:ec2/customerGateway:CustomerGateway',
'aws:ec2/defaultNetworkAcl:DefaultNetworkAcl',
'aws:ec2/defaultRouteTable:DefaultRouteTable',
'aws:ec2/defaultSecurityGroup:DefaultSecurityGroup',
'aws:ec2/defaultSubnet:DefaultSubnet',
'aws:ec2/defaultVpc:DefaultVpc',
'aws:ec2/defaultVpcDhcpOptions:DefaultVpcDhcpOptions',
'aws:ec2/eip:Eip',
'aws:ec2/fleet:Fleet',
'aws:ec2/instance:Instance',
'aws:ec2/internetGateway:InternetGateway',
'aws:ec2/keyPair:KeyPair',
'aws:ec2/launchTemplate:LaunchTemplate',
'aws:ec2/natGateway:NatGateway',
'aws:ec2/networkAcl:NetworkAcl',
'aws:ec2/networkInterface:NetworkInterface',
'aws:ec2/placementGroup:PlacementGroup',
'aws:ec2/routeTable:RouteTable',
'aws:ec2/securityGroup:SecurityGroup',
'aws:ec2/spotInstanceRequest:SpotInstanceRequest',
'aws:ec2/subnet:Subnet',
'aws:ec2/vpc:Vpc',
'aws:ec2/vpcDhcpOptions:VpcDhcpOptions',
'aws:ec2/vpcEndpoint:VpcEndpoint',
'aws:ec2/vpcEndpointService:VpcEndpointService',
'aws:ec2/vpcPeeringConnection:VpcPeeringConnection',
'aws:ec2/vpcPeeringConnectionAccepter:VpcPeeringConnectionAccepter',
'aws:ec2/vpnConnection:VpnConnection',
'aws:ec2/vpnGateway:VpnGateway',
'aws:ec2clientvpn/endpoint:Endpoint',
'aws:ec2transitgateway/routeTable:RouteTable',
'aws:ec2transitgateway/transitGateway:TransitGateway',
'aws:ec2transitgateway/vpcAttachment:VpcAttachment',
'aws:ec2transitgateway/vpcAttachmentAccepter:VpcAttachmentAccepter',
'aws:ecr/repository:Repository',
'aws:ecs/capacityProvider:CapacityProvider',
'aws:ecs/cluster:Cluster',
'aws:ecs/service:Service',
'aws:ecs/taskDefinition:TaskDefinition',
'aws:efs/fileSystem:FileSystem',
'aws:eks/cluster:Cluster',
'aws:eks/fargateProfile:FargateProfile',
'aws:eks/nodeGroup:NodeGroup',
'aws:elasticache/cluster:Cluster',
'aws:elasticache/replicationGroup:ReplicationGroup',
'aws:elasticbeanstalk/application:Application',
'aws:elasticbeanstalk/applicationVersion:ApplicationVersion',
'aws:elasticbeanstalk/environment:Environment',
'aws:elasticloadbalancing/loadBalancer:LoadBalancer',
'aws:elasticloadbalancingv2/loadBalancer:LoadBalancer',
'aws:elasticloadbalancingv2/targetGroup:TargetGroup',
'aws:elasticsearch/domain:Domain',
'aws:elb/loadBalancer:LoadBalancer',
'aws:emr/cluster:Cluster',
'aws:fsx/lustreFileSystem:LustreFileSystem',
'aws:fsx/windowsFileSystem:WindowsFileSystem',
'aws:gamelift/alias:Alias',
'aws:gamelift/build:Build',
'aws:gamelift/fleet:Fleet',
'aws:gamelift/gameSessionQueue:GameSessionQueue',
'aws:glacier/vault:Vault',
'aws:glue/crawler:Crawler',
'aws:glue/job:Job',
'aws:glue/trigger:Trigger',
'aws:iam/role:Role',
'aws:iam/user:User',
'aws:inspector/resourceGroup:ResourceGroup',
'aws:kinesis/analyticsApplication:AnalyticsApplication',
'aws:kinesis/firehoseDeliveryStream:FirehoseDeliveryStream',
'aws:kinesis/stream:Stream',
'aws:kms/externalKey:ExternalKey',
'aws:kms/key:Key',
'aws:lambda/function:Function',
'aws:lb/loadBalancer:LoadBalancer',
'aws:lb/targetGroup:TargetGroup',
'aws:licensemanager/licenseConfiguration:LicenseConfiguration',
'aws:lightsail/instance:Instance',
'aws:mediaconvert/queue:Queue',
'aws:mediapackage/channel:Channel',
'aws:mediastore/container:Container',
'aws:mq/broker:Broker',
'aws:mq/configuration:Configuration',
'aws:msk/cluster:Cluster',
'aws:neptune/cluster:Cluster',
'aws:neptune/clusterInstance:ClusterInstance',
'aws:neptune/clusterParameterGroup:ClusterParameterGroup',
'aws:neptune/eventSubscription:EventSubscription',
'aws:neptune/parameterGroup:ParameterGroup',
'aws:neptune/subnetGroup:SubnetGroup',
'aws:opsworks/stack:Stack',
'aws:organizations/account:Account',
'aws:pinpoint/app:App',
'aws:qldb/ledger:Ledger',
'aws:ram/resourceShare:ResourceShare',
'aws:rds/cluster:Cluster',
'aws:rds/clusterEndpoint:ClusterEndpoint',
'aws:rds/clusterInstance:ClusterInstance',
'aws:rds/clusterParameterGroup:ClusterParameterGroup',
'aws:rds/clusterSnapshot:ClusterSnapshot',
'aws:rds/eventSubscription:EventSubscription',
'aws:rds/instance:Instance',
'aws:rds/optionGroup:OptionGroup',
'aws:rds/parameterGroup:ParameterGroup',
'aws:rds/securityGroup:SecurityGroup',
'aws:rds/snapshot:Snapshot',
'aws:rds/subnetGroup:SubnetGroup',
'aws:redshift/cluster:Cluster',
'aws:redshift/eventSubscription:EventSubscription',
'aws:redshift/parameterGroup:ParameterGroup',
'aws:redshift/snapshotCopyGrant:SnapshotCopyGrant',
'aws:redshift/snapshotSchedule:SnapshotSchedule',
'aws:redshift/subnetGroup:SubnetGroup',
'aws:resourcegroups/group:Group',
'aws:route53/healthCheck:HealthCheck',
'aws:route53/resolverEndpoint:ResolverEndpoint',
'aws:route53/resolverRule:ResolverRule',
'aws:route53/zone:Zone',
'aws:s3/bucket:Bucket',
'aws:s3/bucketObject:BucketObject',
'aws:sagemaker/endpoint:Endpoint',
'aws:sagemaker/endpointConfiguration:EndpointConfiguration',
'aws:sagemaker/model:Model',
'aws:sagemaker/notebookInstance:NotebookInstance',
'aws:secretsmanager/secret:Secret',
'aws:servicecatalog/portfolio:Portfolio',
'aws:sfn/activity:Activity',
'aws:sfn/stateMachine:StateMachine',
'aws:sns/topic:Topic',
'aws:sqs/queue:Queue',
'aws:ssm/activation:Activation',
'aws:ssm/document:Document',
'aws:ssm/maintenanceWindow:MaintenanceWindow',
'aws:ssm/parameter:Parameter',
'aws:ssm/patchBaseline:PatchBaseline',
'aws:storagegateway/cachesIscsiVolume:CachesIscsiVolume',
'aws:storagegateway/gateway:Gateway',
'aws:storagegateway/nfsFileShare:NfsFileShare',
'aws:storagegateway/smbFileShare:SmbFileShare',
'aws:swf/domain:Domain',
'aws:transfer/server:Server',
'aws:transfer/user:User',
'aws:waf/rateBasedRule:RateBasedRule',
'aws:waf/rule:Rule',
'aws:waf/ruleGroup:RuleGroup',
'aws:waf/webAcl:WebAcl',
'aws:wafregional/rateBasedRule:RateBasedRule',
'aws:wafregional/rule:Rule',
'aws:wafregional/ruleGroup:RuleGroup',
'aws:wafregional/webAcl:WebAcl',
'aws:workspaces/directory:Directory',
'aws:workspaces/ipGroup:IpGroup',
]

31
infra/ecs_alb/conf.py Normal file
View File

@@ -0,0 +1,31 @@
import pulumi
import pulumi_aws as aws
from autotag.autotag import register_auto_tags
config = pulumi.Config()
pulumi_project = pulumi.get_project()
project_name = config.require("project_name")
stack_name = pulumi.get_stack()
aws_region = aws.get_region().id
current = aws.get_caller_identity()
current = aws.get_caller_identity_output()
account_id1 = current.account_id
account_id = config.require("account_id")
network = config.get_object("network")
ecs = config.get_object("ecs")
ecr = config.get_object("ecr")
environment = config.require("environment")
register_auto_tags(config.get_object('tags'))
def get(x):
return config.get(x)
def get_bool(x):
return config.get_bool(x)

100
infra/ecs_alb/ecr.py Normal file
View File

@@ -0,0 +1,100 @@
import pulumi
import pulumi_aws as aws
import conf as config
import json
def create_ecr_repo():
ecr_repositories = []
for repo in config.ecr["repos"]:
if repo["create_ecr_repo"]:
ecr_repository = aws.ecr.Repository(
repo,
name=f"{repo}",
force_delete=True)
token = aws.ecr.get_authorization_token_output(registry_id=ecr_repository.registry_id)
langserve_ecr_life_cycle_policy = aws.ecr.LifecyclePolicy(f"{repo}-ecr-life-cycle-policy",
repository=ecr_repository.name,
policy=json.dumps({
"rules": [{
"rulePriority": 1,
"description": "Expire images when they are more than 10 available",
"selection": {
"tagStatus": "any",
"countType": "imageCountMoreThan",
"countNumber": 10,
},
"action": {
"type": "expire",
},
}],
}))
policy_ecr = aws.iam.get_policy_document(statements=[{
"sid": "new policy",
"effect": "Allow",
"principals": [{
"type": "AWS",
"identifiers": [config.account_id],
}],
"actions": [
"ecr:GetDownloadUrlForLayer",
"ecr:BatchGetImage",
"ecr:BatchCheckLayerAvailability",
"ecr:PutImage",
"ecr:InitiateLayerUpload",
"ecr:UploadLayerPart",
"ecr:CompleteLayerUpload",
"ecr:DescribeRepositories",
"ecr:GetRepositoryPolicy",
"ecr:ListImages",
"ecr:DeleteRepository",
"ecr:BatchDeleteImage",
"ecr:SetRepositoryPolicy",
"ecr:DeleteRepositoryPolicy",
],
}])
attach_policy = aws.ecr.RepositoryPolicy(f"{repo}-policy_ecr",
repository=ecr_repository.name,
policy=policy_ecr.json)
else:
ecr_repository = aws.ecr.get_repository_output(name=repo['name'])
token = aws.ecr.get_authorization_token_output(registry_id=ecr_repository.registry_id)
repo['ecr_repo_resource'] = ecr_repository
repo['ecr_token'] = token
ecr_repositories.append(repo)
return ecr_repositories
def get_image(ecr_repo_name, image_tag=None, image_digest=None):
assert (image_tag is not None) != (image_digest is not None), 'User either tag or image_digest, not both, to identify ECR image version.'
if image_tag:
return aws.ecr.get_image(repository_name=ecr_repo_name, image_tag=image_tag)
elif image_digest:
return aws.ecr.get_image(repository_name=ecr_repo_name, image_digest=image_digest)
def build_and_push(ecr_repositories):
ecr_repo_images = {}
for repo in ecr_repositories:
ecr_repo = repo['ecr_repo_resource']
container_context = config.get("container-context")
if container_context is None:
container_context = "."
container_file = config.get("container-file")
if container_file is None:
container_file = "./Dockerfile"
assert ('tag' in repo.keys()) != ('image_digest' in repo.keys()), 'User must provide either tag or image_digest, but not both, to identify image version'
if 'tag' in repo.keys():
ecr_image=aws.ecr.get_image(repository_name=ecr_repo.name, image_tag=repo['tag'])
elif 'image_digest' in repo.keys():
ecr_image=aws.ecr.get_image(repository_name=ecr_repo.name, image_digest=repo['image_digest'])
repo['ecr_image'] = ecr_image
ecr_repo_images[repo['name']] = repo
#ecr_repo_images.append(repo)
return ecr_repo_images

238
infra/ecs_alb/ecs.py Normal file
View File

@@ -0,0 +1,238 @@
import pulumi
import pulumi_aws as aws
import conf as config
import iam
import ecr
import json
def deploy_app(config_ecs_app, app_ecs_cluster, alb_security_group, app_load_balancer_arn):
lb_config = config_ecs_app["lb_config"]
target_group = aws.lb.TargetGroup(f"app-target-group-{lb_config['listener_port']}",
port=lb_config["target_port"],
protocol="HTTP",
vpc_id=config.network["vpc_id"],
target_type="ip",
health_check=aws.lb.TargetGroupHealthCheckArgs(
path="/", # TODO if it doesn't work, can use /docs for fastapi
protocol="HTTP",
port="traffic-port",
healthy_threshold=2,
unhealthy_threshold=2,
timeout=5,
interval=30,
matcher="200-499",
),
)
aws.lb.Listener(f"app-listener-{lb_config['listener_port']}",
load_balancer_arn=app_load_balancer_arn,
port=lb_config["listener_port"],
protocol="HTTP",
default_actions=[aws.lb.ListenerDefaultActionArgs(
type="forward",
target_group_arn=target_group.arn,
)],
)
# target_groups.append(target_group)
# Build and Push ECR
# ecr_repos = ecr.create_ecr_repo(config_ecs_app['ecr_repo_name'])
# assert ('ecr_image_tag' in config_ecs_app.keys()) != ('ecr_image_digest' in config_ecs_app.keys()), 'User must provide either tag or image_digest, but not both, to identify image version'
if 'ecr_image_tag' in config_ecs_app.keys():
ecr_repo_image = ecr.get_image(config_ecs_app['ecr_repo_name'], image_tag=config_ecs_app['ecr_image_tag'])
elif 'ecr_image_digest' in config_ecs_app.keys():
ecr_repo_image = ecr.get_image(config_ecs_app['ecr_repo_name'], image_digest=config_ecs_app['ecr_image_digest'])
# Log Group Setup #TODO move into ecs
app_log_group = aws.cloudwatch.LogGroup(f"{config.project_name}-{config_ecs_app['task_name']}-log-group", retention_in_days=7)
# if key
# ssm_parameter, key = kms.setup_kms()
# iam.create_execution_role_with_keys(ssm_parameter, key)
# IAM Roles Setup
app_execution_role = iam.create_execution_role()
app_task_role = iam.create_task_role()
# summarization_repo_image = config_ecs_app['ecr_image']
if config_ecs_app['use_load_balancer']:
environemnt_variables = [dict(name=k, value=v) for k,v in config_ecs_app['env_variables'].items()]
print(environemnt_variables)
# ECS Task Definition Setup
app_task_definition = aws.ecs.TaskDefinition(f"{config.project_name}-{config_ecs_app['task_name']}-task-definition",
family=f"{config.project_name}-{config_ecs_app['task_name']}-{config.environment}",
cpu=config_ecs_app["cpu"],
memory=config_ecs_app["memory"],
network_mode="awsvpc",
execution_role_arn=app_execution_role.arn,
task_role_arn=app_task_role.arn,
requires_compatibilities=["FARGATE"],
container_definitions=pulumi.Output.all(ecr_repo_image.image_uri,
# ecr_repo_image.image_digest,
app_log_group.name,
environemnt_variables,
# config_ecs_app["secret_name"],
).apply(lambda args: json.dumps([{
"name": f"{config.project_name}-{config_ecs_app['task_name']}-{config.environment}-service",
"image": args[0],
"cpu": 0,
"portMappings": [
{
"name": "api",
"containerPort": lb_config["container_port"],
"hostPort": lb_config["target_port"],
"protocol": "tcp",
}
# } for lb_config_item in lb_configs
],
"essential": True,
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": args[1],
"awslogs-region": config.aws_region,
"awslogs-stream-prefix": "pulumi-langserve",
},
},
"environment": args[2],
}])),
)
# ECS Security Group Setup
app_ecs_security_group = aws.ec2.SecurityGroup(f"{config.project_name}-{config_ecs_app['task_name']}-ecs-security-group",
vpc_id=config.network["vpc_id"],
ingress=[aws.ec2.SecurityGroupIngressArgs(
protocol="-1",
from_port=0,
to_port=0,
security_groups=[alb_security_group.id],
)],
egress=[aws.ec2.SecurityGroupEgressArgs(
protocol="-1",
from_port=0,
to_port=0,
cidr_blocks=["0.0.0.0/0"],
)],
)
# Security Group Rules for Ingress
for sg_name, sg_id in config_ecs_app["sgs_allowing_ingress"].items():
aws.ec2.SecurityGroupRule(f"sgr-{sg_name}-allow_in_from-{config.project_name}",
type="ingress",
from_port=0,
to_port=0,
protocol="-1",
security_group_id=sg_id,
source_security_group_id=app_ecs_security_group.id,
description=f"Allow from {config.project_name} ECS SG",
)
# Service Discovery Namespace Setup
app_service_discovery_namespace = aws.servicediscovery.PrivateDnsNamespace(f"{config.project_name}-{config_ecs_app['task_name']}-service-discovery-namespace",
name=f"{config.environment}.{config.project_name}.local",
vpc=config.network["vpc_id"],
)
# ECS Service Setup
load_balancer = aws.ecs.ServiceLoadBalancerArgs(
target_group_arn=target_group.arn,
container_name=f"{config.project_name}-{config_ecs_app['task_name']}-{config.environment}-service",
container_port=lb_config["target_port"],
)
app_service = aws.ecs.Service(f"{config.project_name}-{config_ecs_app['task_name']}-service",
cluster=app_ecs_cluster.arn,
task_definition=app_task_definition.arn,
desired_count=config_ecs_app["desired_count"],
launch_type="FARGATE",
network_configuration=aws.ecs.ServiceNetworkConfigurationArgs(
assign_public_ip=True,
security_groups=[app_ecs_security_group.id],
subnets=config.network["ecs_subnet_ids"],
),
load_balancers=[load_balancer],
scheduling_strategy="REPLICA",
service_connect_configuration=aws.ecs.ServiceServiceConnectConfigurationArgs(
enabled=True,
namespace=app_service_discovery_namespace.arn,
),
tags={"Name": f"{config.project_name}-{config_ecs_app['task_name']}-{config.environment}"},
)
#defining an auto-scaling for summarization
scalable_target = aws.appautoscaling.Target("app-svc-target",
max_capacity=config_ecs_app['auto_scaling']['max_capacity'],
min_capacity=config_ecs_app['auto_scaling']['min_capacity'],
resource_id=pulumi.Output.all(app_ecs_cluster.name, app_service.name).apply(lambda args: f"service/{args[0]}/{args[1]}"),
scalable_dimension="ecs:service:DesiredCount",
service_namespace="ecs",
)
# Define an auto-scaling policy on CPU utilization
scaling_policy = aws.appautoscaling.Policy("app-svc-policy",
policy_type="TargetTrackingScaling",
resource_id=scalable_target.resource_id,
scalable_dimension="ecs:service:DesiredCount",
service_namespace="ecs",
target_tracking_scaling_policy_configuration={
"target_value": config_ecs_app['auto_scaling']['target_value'], # Target CPU utilization (30%)
"predefined_metric_specification": {
"predefined_metric_type": "ECSServiceAverageCPUUtilization"
},
},
)
else:
# classification_repo_image = ecr_repo_images['ai-med-exam-classification']['ecr_image']
# ECS without Load Balancer
new_ecs_task_definition = aws.ecs.TaskDefinition("classification-theia-poc-task-definition",
family="classification-theia-poc",
cpu=config_ecs_app["cpu"],
memory=config_ecs_app["memory"],
network_mode="awsvpc",
execution_role_arn=app_execution_role.arn,
task_role_arn=app_task_role.arn,
requires_compatibilities=["FARGATE"],
container_definitions=pulumi.Output.all(ecr_repo_image.image_uri,
# classification_repo_image.image_digest,
app_log_group.name).apply(lambda args: json.dumps([{
"name": "classification-theia-poc-service",
"image": args[0],
"cpu": 0,
"portMappings": [
{
"name": "api",
"containerPort": 80, # Define the container port without Load Balancer
"hostPort": 80,
"protocol": "tcp",
}
],
"essential": True,
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": args[1],
"awslogs-region": config.aws_region,
"awslogs-stream-prefix": "pulumi-classification-theia-poc",
},
},
}])),
)
# ecs without load balancer
new_ecs_service = aws.ecs.Service("classification-theia-poc-service",
cluster=app_ecs_cluster.arn,
task_definition=new_ecs_task_definition.arn,
desired_count=config_ecs_app["desired_count"],
launch_type="FARGATE",
network_configuration=aws.ecs.ServiceNetworkConfigurationArgs(
assign_public_ip=True,
security_groups=[app_ecs_security_group.id],
subnets=config.network["ecs_subnet_ids"],
),
scheduling_strategy="REPLICA",
service_connect_configuration=aws.ecs.ServiceServiceConnectConfigurationArgs(
enabled=True,
namespace=app_service_discovery_namespace.arn,
),
tags={"Name": "classification-theia-poc"},
)

241
infra/ecs_alb/iam.py Normal file
View File

@@ -0,0 +1,241 @@
import pulumi
import pulumi_aws as aws
import conf as config
import json
def create_execution_role():
execution_role = aws.iam.Role(f"{config.project_name}-execution-role",
assume_role_policy=json.dumps({
"Statement": [{
"Action": "sts:AssumeRole",
"Effect": "Allow",
"Principal": {
"Service": "ecs-tasks.amazonaws.com",
},
}],
"Version": "2012-10-17",
}),
inline_policies=[aws.iam.RoleInlinePolicyArgs(
name=f"{config.project_name}-{config.stack_name}-service-secrets-policy",
policy=json.dumps({
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ecr:GetAuthorizationToken",
"ecr:BatchCheckLayerAvailability",
"ecr:GetDownloadUrlForLayer",
"ecr:GetRepositoryPolicy",
"ecr:DescribeRepositories",
"ecr:ListImages",
"ecr:DescribeImages",
"ecr:BatchGetImage",
"ecr:GetLifecyclePolicy",
"ecr:GetLifecyclePolicyPreview",
"ecr:ListTagsForResource",
"ecr:DescribeImageScanFindings"
],
"Resource": "*"
}
],
}),
)],
managed_policy_arns=["arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"])
return execution_role
def create_execution_role_with_keys(ssm_parameter, key):
execution_role = aws.iam.Role(f"{config.project_name}-execution-role",
assume_role_policy=json.dumps({
"Statement": [{
"Action": "sts:AssumeRole",
"Effect": "Allow",
"Principal": {
"Service": "ecs-tasks.amazonaws.com",
},
}],
"Version": "2012-10-17",
}),
inline_policies=[aws.iam.RoleInlinePolicyArgs(
name=f"{config.project_name}-{config.stack_name}-service-secrets-policy",
policy=pulumi.Output.all(ssm_parameter.arn, key.arn).apply(lambda args: json.dumps({
"Version": "2012-10-17",
"Statement": [
{
"Action": ["ssm:GetParameters"],
"Condition": {
"StringEquals": {
"ssm:ResourceTag/pulumi-application": config.project_name,
"ssm:ResourceTag/pulumi-environment": config.stack_name,
},
},
"Effect": "Allow",
"Resource": [args[0]],
},
{
"Action": ["kms:Decrypt"],
"Condition": {
"StringEquals": {
"aws:ResourceTag/pulumi-application": config.project_name,
"aws:ResourceTag/pulumi-environment": config.stack_name,
},
},
"Effect": "Allow",
"Resource": [args[1]],
"Sid": "DecryptTaggedKMSKey",
},
{
"Effect": "Allow",
"Action": [
"ecr:GetAuthorizationToken",
"ecr:BatchCheckLayerAvailability",
"ecr:GetDownloadUrlForLayer",
"ecr:GetRepositoryPolicy",
"ecr:DescribeRepositories",
"ecr:ListImages",
"ecr:DescribeImages",
"ecr:BatchGetImage",
"ecr:GetLifecyclePolicy",
"ecr:GetLifecyclePolicyPreview",
"ecr:ListTagsForResource",
"ecr:DescribeImageScanFindings"
],
"Resource": "*"
}
],
})),
)],
managed_policy_arns=["arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"])
return execution_role
def create_task_role():
task_role = aws.iam.Role(f"{config.project_name}-task-role",
assume_role_policy=json.dumps({
"Statement": [{
"Action": "sts:AssumeRole",
"Effect": "Allow",
"Principal": {
"Service": "ecs-tasks.amazonaws.com",
},
}],
"Version": "2012-10-17",
}),
inline_policies=[
aws.iam.RoleInlinePolicyArgs(
name="ExecuteCommand",
policy=json.dumps({
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"ssmmessages:CreateControlChannel",
"ssmmessages:OpenControlChannel",
"ssmmessages:CreateDataChannel",
"ssmmessages:OpenDataChannel",
],
"Effect": "Allow",
"Resource": "*",
},
{
"Action": [
"logs:CreateLogStream",
"logs:DescribeLogGroups",
"logs:DescribeLogStreams",
"logs:PutLogEvents",
],
"Effect": "Allow",
"Resource": "*",
},
],
}),
),
aws.iam.RoleInlinePolicyArgs(
name="DenyIAM",
policy=json.dumps({
"Version": "2012-10-17",
"Statement": [{
"Action": "iam:*",
"Effect": "Deny",
"Resource": "*",
}],
}),
),
aws.iam.RoleInlinePolicyArgs(
name="BedrockS3SQSAccess",
policy=json.dumps({
"Version": "2012-10-17",
"Statement": [
# S3
{
"Effect": "Allow",
"Action": [
"s3:*",
"s3-object-lambda:*"
],
"Resource": "*"
},
# SQS
{
"Effect": "Allow",
"Action": [
"sqs:StartMessageMoveTask",
"sqs:DeleteMessage",
"sqs:GetQueueUrl",
"sqs:ListDeadLetterSourceQueues",
"sqs:ListMessageMoveTasks",
"sqs:PurgeQueue",
"sqs:ReceiveMessage",
"sqs:GetQueueAttributes",
"sqs:ListQueueTags"
],
"Resource": "arn:aws:sqs:us-east-1:673991670544:ai-med-dev-queue-63cb463"
},
{
"Effect": "Allow",
"Action": "sqs:ListQueues",
"Resource": "*"
},
# Bedrock
{
"Effect": "Allow",
"Action": [
"bedrock:*"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"kms:DescribeKey"
],
"Resource": "arn:*:kms:*:*:key/*"
},
{
"Effect": "Allow",
"Action": [
"iam:ListRoles",
"ec2:DescribeVpcs",
"ec2:DescribeSubnets",
"ec2:DescribeSecurityGroups"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"iam:PassRole"
],
"Resource": "arn:aws:iam::*:role/*AmazonBedrock*",
"Condition": {
"StringEquals": {
"iam:PassedToService": "bedrock.amazonaws.com"
}
}
}
]
})
),
])
return task_role

74
infra/ecs_alb/kms.py Normal file
View File

@@ -0,0 +1,74 @@
import pulumi
import pulumi_aws as aws
import pulumi_docker as docker
import conf as config
import json
def setup_kms():
# KMS Key Setup
app_key = aws.kms.Key(f"{config.project_name}-key",
description="Key for encrypting secrets",
enable_key_rotation=True,
policy=json.dumps({
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Sid": "",
"Principal": {
"AWS": f"arn:aws:iam::{config.account_id}:root",
},
"Action": [
"kms:Create*", "kms:Describe*", "kms:Enable*", "kms:List*", "kms:Put*", "kms:Update*",
"kms:Revoke*", "kms:Disable*", "kms:Get*", "kms:Delete*", "kms:ScheduleKeyDeletion",
"kms:CancelKeyDeletion", "kms:Tag*", "kms:UntagResource",
],
"Resource": "*",
},
{
"Effect": "Allow",
"Principal": {
"AWS": f"arn:aws:iam::{config.account_id}:root",
},
"Action": [
"kms:Encrypt", "kms:Decrypt", "kms:ReEncrypt*", "kms:GenerateDataKey*", "kms:DescribeKey",
],
"Resource": "*",
},
{
"Sid": 'Allow access to EFS for all principals in the account that are authorized to use EFS',
"Effect": 'Allow',
"Principal": {"AWS": "*"},
"Action": [
"kms:Encrypt", "kms:Decrypt", "kms:ReEncrypt*", "kms:GenerateDataKey*",
"kms:CreateGrant", "kms:DescribeKey",
],
"Resource": "*",
"Condition": {
"StringEquals": {
"kms:ViaService": f"elasticfilesystem.{config.aws_region}.amazonaws.com",
"kms:CallerAccount": config.account_id,
},
},
},
],
}),
tags={
"pulumi-application": config.project_name,
"pulumi-environment": config.stack_name,
},
)
# SSM Parameter Setup
app_ssm_parameter = aws.ssm.Parameter(f"{config.project_name}-ssm-parameter",
type="SecureString",
value=config.config.require_secret("bedrock_api_key"),
key_id=app_key.key_id,
name=f"/{config.project_name}/{config.stack_name}/BEDROCK_API_KEY",
tags={
"pulumi-application": config.project_name,
"pulumi-environment": config.stack_name,
},
)
return app_ssm_parameter, app_key

View File

@@ -0,0 +1,5 @@
pulumi>=3.0.0,<4.0.0
pulumi-aws==6.19.0
pulumi-docker==4.5.1
boto3
setuptools

View File

@@ -0,0 +1,11 @@
config:
aws:region: us-east-1
dynamo:account_id: "277048801940"
dynamo:project_name: assistente-produtos-servicos-memoria-dynamodb
dynamo:environment: dev
dynamo:tags:
project: assistente-produtos-servicos
env: dev
costCenter: AI
owner: ai-team

View File

@@ -0,0 +1,3 @@
name: dynamodb-dev
runtime: python
description: Infraestrutura da aplicação Dynamodb

View File

@@ -0,0 +1,18 @@
import pulumi
import pulumi_aws as aws
import conf as config
basic_dynamodb_table = aws.dynamodb.Table(config.project_name,
name="assistente-produtos-servicos-memoria",
billing_mode="PAY_PER_REQUEST",
hash_key="UserId",
range_key="Timestamp",
attributes=[
{
"name": "UserId",
"type": "S",
},
{
"name": "Timestamp",
"type": "N",
}
])

View File

@@ -0,0 +1,13 @@
import pulumi
from autotag.taggable import is_taggable
# registerAutoTags registers a global stack transformation that merges a set
# of tags with whatever was also explicitly added to the resource definition.
def register_auto_tags(auto_tags):
pulumi.runtime.register_stack_transformation(lambda args: auto_tag(args, auto_tags))
# auto_tag applies the given tags to the resource properties if applicable.
def auto_tag(args, auto_tags):
if is_taggable(args.type_):
args.props['tags'] = {**(args.props['tags'] or {}), **auto_tags}
return pulumi.ResourceTransformationResult(args.props, args.opts)

View File

@@ -0,0 +1,12 @@
{
"all": "mandatory",
"check-required-tags": {
"requiredTags": [
"user:project",
"user:env",
"user:account",
"user:costCenter",
"user:owner"
]
}
}

View File

@@ -0,0 +1,234 @@
# isTaggable returns true if the given resource type is an AWS resource that supports tags.
def is_taggable(t):
return t in taggable_resource_types
# taggable_resource_types is a list of known AWS type tokens that are taggable.
taggable_resource_types = [
'aws:accessanalyzer/analyzer:Analyzer',
'aws:acm/certificate:Certificate',
'aws:acmpca/certificateAuthority:CertificateAuthority',
'aws:alb/loadBalancer:LoadBalancer',
'aws:alb/targetGroup:TargetGroup',
'aws:apigateway/apiKey:ApiKey',
'aws:apigateway/clientCertificate:ClientCertificate',
'aws:apigateway/domainName:DomainName',
'aws:apigateway/restApi:RestApi',
'aws:apigateway/stage:Stage',
'aws:apigateway/usagePlan:UsagePlan',
'aws:apigateway/vpcLink:VpcLink',
'aws:applicationloadbalancing/loadBalancer:LoadBalancer',
'aws:applicationloadbalancing/targetGroup:TargetGroup',
'aws:appmesh/mesh:Mesh',
'aws:appmesh/route:Route',
'aws:appmesh/virtualNode:VirtualNode',
'aws:appmesh/virtualRouter:VirtualRouter',
'aws:appmesh/virtualService:VirtualService',
'aws:appsync/graphQLApi:GraphQLApi',
'aws:athena/workgroup:Workgroup',
'aws:autoscaling/group:Group',
'aws:backup/plan:Plan',
'aws:backup/vault:Vault',
'aws:cfg/aggregateAuthorization:AggregateAuthorization',
'aws:cfg/configurationAggregator:ConfigurationAggregator',
'aws:cfg/rule:Rule',
'aws:cloudformation/stack:Stack',
'aws:cloudformation/stackSet:StackSet',
'aws:cloudfront/distribution:Distribution',
'aws:cloudhsmv2/cluster:Cluster',
'aws:cloudtrail/trail:Trail',
'aws:cloudwatch/eventRule:EventRule',
'aws:cloudwatch/logGroup:LogGroup',
'aws:cloudwatch/metricAlarm:MetricAlarm',
'aws:codebuild/project:Project',
'aws:codecommit/repository:Repository',
'aws:codepipeline/pipeline:Pipeline',
'aws:codepipeline/webhook:Webhook',
'aws:codestarnotifications/notificationRule:NotificationRule',
'aws:cognito/identityPool:IdentityPool',
'aws:cognito/userPool:UserPool',
'aws:datapipeline/pipeline:Pipeline',
'aws:datasync/agent:Agent',
'aws:datasync/efsLocation:EfsLocation',
'aws:datasync/locationSmb:LocationSmb',
'aws:datasync/nfsLocation:NfsLocation',
'aws:datasync/s3Location:S3Location',
'aws:datasync/task:Task',
'aws:dax/cluster:Cluster',
'aws:directconnect/connection:Connection',
'aws:directconnect/hostedPrivateVirtualInterfaceAccepter:HostedPrivateVirtualInterfaceAccepter',
'aws:directconnect/hostedPublicVirtualInterfaceAccepter:HostedPublicVirtualInterfaceAccepter',
'aws:directconnect/hostedTransitVirtualInterfaceAcceptor:HostedTransitVirtualInterfaceAcceptor',
'aws:directconnect/linkAggregationGroup:LinkAggregationGroup',
'aws:directconnect/privateVirtualInterface:PrivateVirtualInterface',
'aws:directconnect/publicVirtualInterface:PublicVirtualInterface',
'aws:directconnect/transitVirtualInterface:TransitVirtualInterface',
'aws:directoryservice/directory:Directory',
'aws:dlm/lifecyclePolicy:LifecyclePolicy',
'aws:dms/endpoint:Endpoint',
'aws:dms/replicationInstance:ReplicationInstance',
'aws:dms/replicationSubnetGroup:ReplicationSubnetGroup',
'aws:dms/replicationTask:ReplicationTask',
'aws:docdb/cluster:Cluster',
'aws:docdb/clusterInstance:ClusterInstance',
'aws:docdb/clusterParameterGroup:ClusterParameterGroup',
'aws:docdb/subnetGroup:SubnetGroup',
'aws:dynamodb/table:Table',
'aws:ebs/snapshot:Snapshot',
'aws:ebs/snapshotCopy:SnapshotCopy',
'aws:ebs/volume:Volume',
'aws:ec2/ami:Ami',
'aws:ec2/amiCopy:AmiCopy',
'aws:ec2/amiFromInstance:AmiFromInstance',
'aws:ec2/capacityReservation:CapacityReservation',
'aws:ec2/customerGateway:CustomerGateway',
'aws:ec2/defaultNetworkAcl:DefaultNetworkAcl',
'aws:ec2/defaultRouteTable:DefaultRouteTable',
'aws:ec2/defaultSecurityGroup:DefaultSecurityGroup',
'aws:ec2/defaultSubnet:DefaultSubnet',
'aws:ec2/defaultVpc:DefaultVpc',
'aws:ec2/defaultVpcDhcpOptions:DefaultVpcDhcpOptions',
'aws:ec2/eip:Eip',
'aws:ec2/fleet:Fleet',
'aws:ec2/instance:Instance',
'aws:ec2/internetGateway:InternetGateway',
'aws:ec2/keyPair:KeyPair',
'aws:ec2/launchTemplate:LaunchTemplate',
'aws:ec2/natGateway:NatGateway',
'aws:ec2/networkAcl:NetworkAcl',
'aws:ec2/networkInterface:NetworkInterface',
'aws:ec2/placementGroup:PlacementGroup',
'aws:ec2/routeTable:RouteTable',
'aws:ec2/securityGroup:SecurityGroup',
'aws:ec2/spotInstanceRequest:SpotInstanceRequest',
'aws:ec2/subnet:Subnet',
'aws:ec2/vpc:Vpc',
'aws:ec2/vpcDhcpOptions:VpcDhcpOptions',
'aws:ec2/vpcEndpoint:VpcEndpoint',
'aws:ec2/vpcEndpointService:VpcEndpointService',
'aws:ec2/vpcPeeringConnection:VpcPeeringConnection',
'aws:ec2/vpcPeeringConnectionAccepter:VpcPeeringConnectionAccepter',
'aws:ec2/vpnConnection:VpnConnection',
'aws:ec2/vpnGateway:VpnGateway',
'aws:ec2clientvpn/endpoint:Endpoint',
'aws:ec2transitgateway/routeTable:RouteTable',
'aws:ec2transitgateway/transitGateway:TransitGateway',
'aws:ec2transitgateway/vpcAttachment:VpcAttachment',
'aws:ec2transitgateway/vpcAttachmentAccepter:VpcAttachmentAccepter',
'aws:ecr/repository:Repository',
'aws:ecs/capacityProvider:CapacityProvider',
'aws:ecs/cluster:Cluster',
'aws:ecs/service:Service',
'aws:ecs/taskDefinition:TaskDefinition',
'aws:efs/fileSystem:FileSystem',
'aws:eks/cluster:Cluster',
'aws:eks/fargateProfile:FargateProfile',
'aws:eks/nodeGroup:NodeGroup',
'aws:elasticache/cluster:Cluster',
'aws:elasticache/replicationGroup:ReplicationGroup',
'aws:elasticbeanstalk/application:Application',
'aws:elasticbeanstalk/applicationVersion:ApplicationVersion',
'aws:elasticbeanstalk/environment:Environment',
'aws:elasticloadbalancing/loadBalancer:LoadBalancer',
'aws:elasticloadbalancingv2/loadBalancer:LoadBalancer',
'aws:elasticloadbalancingv2/targetGroup:TargetGroup',
'aws:elasticsearch/domain:Domain',
'aws:elb/loadBalancer:LoadBalancer',
'aws:emr/cluster:Cluster',
'aws:fsx/lustreFileSystem:LustreFileSystem',
'aws:fsx/windowsFileSystem:WindowsFileSystem',
'aws:gamelift/alias:Alias',
'aws:gamelift/build:Build',
'aws:gamelift/fleet:Fleet',
'aws:gamelift/gameSessionQueue:GameSessionQueue',
'aws:glacier/vault:Vault',
'aws:glue/crawler:Crawler',
'aws:glue/job:Job',
'aws:glue/trigger:Trigger',
'aws:iam/role:Role',
'aws:iam/user:User',
'aws:inspector/resourceGroup:ResourceGroup',
'aws:kinesis/analyticsApplication:AnalyticsApplication',
'aws:kinesis/firehoseDeliveryStream:FirehoseDeliveryStream',
'aws:kinesis/stream:Stream',
'aws:kms/externalKey:ExternalKey',
'aws:kms/key:Key',
'aws:lambda/function:Function',
'aws:lb/loadBalancer:LoadBalancer',
'aws:lb/targetGroup:TargetGroup',
'aws:licensemanager/licenseConfiguration:LicenseConfiguration',
'aws:lightsail/instance:Instance',
'aws:mediaconvert/queue:Queue',
'aws:mediapackage/channel:Channel',
'aws:mediastore/container:Container',
'aws:mq/broker:Broker',
'aws:mq/configuration:Configuration',
'aws:msk/cluster:Cluster',
'aws:neptune/cluster:Cluster',
'aws:neptune/clusterInstance:ClusterInstance',
'aws:neptune/clusterParameterGroup:ClusterParameterGroup',
'aws:neptune/eventSubscription:EventSubscription',
'aws:neptune/parameterGroup:ParameterGroup',
'aws:neptune/subnetGroup:SubnetGroup',
'aws:opsworks/stack:Stack',
'aws:organizations/account:Account',
'aws:pinpoint/app:App',
'aws:qldb/ledger:Ledger',
'aws:ram/resourceShare:ResourceShare',
'aws:rds/cluster:Cluster',
'aws:rds/clusterEndpoint:ClusterEndpoint',
'aws:rds/clusterInstance:ClusterInstance',
'aws:rds/clusterParameterGroup:ClusterParameterGroup',
'aws:rds/clusterSnapshot:ClusterSnapshot',
'aws:rds/eventSubscription:EventSubscription',
'aws:rds/instance:Instance',
'aws:rds/optionGroup:OptionGroup',
'aws:rds/parameterGroup:ParameterGroup',
'aws:rds/securityGroup:SecurityGroup',
'aws:rds/snapshot:Snapshot',
'aws:rds/subnetGroup:SubnetGroup',
'aws:redshift/cluster:Cluster',
'aws:redshift/eventSubscription:EventSubscription',
'aws:redshift/parameterGroup:ParameterGroup',
'aws:redshift/snapshotCopyGrant:SnapshotCopyGrant',
'aws:redshift/snapshotSchedule:SnapshotSchedule',
'aws:redshift/subnetGroup:SubnetGroup',
'aws:resourcegroups/group:Group',
'aws:route53/healthCheck:HealthCheck',
'aws:route53/resolverEndpoint:ResolverEndpoint',
'aws:route53/resolverRule:ResolverRule',
'aws:route53/zone:Zone',
'aws:s3/bucket:Bucket',
'aws:s3/bucketObject:BucketObject',
'aws:sagemaker/endpoint:Endpoint',
'aws:sagemaker/endpointConfiguration:EndpointConfiguration',
'aws:sagemaker/model:Model',
'aws:sagemaker/notebookInstance:NotebookInstance',
'aws:secretsmanager/secret:Secret',
'aws:servicecatalog/portfolio:Portfolio',
'aws:sfn/activity:Activity',
'aws:sfn/stateMachine:StateMachine',
'aws:sns/topic:Topic',
'aws:sqs/queue:Queue',
'aws:ssm/activation:Activation',
'aws:ssm/document:Document',
'aws:ssm/maintenanceWindow:MaintenanceWindow',
'aws:ssm/parameter:Parameter',
'aws:ssm/patchBaseline:PatchBaseline',
'aws:storagegateway/cachesIscsiVolume:CachesIscsiVolume',
'aws:storagegateway/gateway:Gateway',
'aws:storagegateway/nfsFileShare:NfsFileShare',
'aws:storagegateway/smbFileShare:SmbFileShare',
'aws:swf/domain:Domain',
'aws:transfer/server:Server',
'aws:transfer/user:User',
'aws:waf/rateBasedRule:RateBasedRule',
'aws:waf/rule:Rule',
'aws:waf/ruleGroup:RuleGroup',
'aws:waf/webAcl:WebAcl',
'aws:wafregional/rateBasedRule:RateBasedRule',
'aws:wafregional/rule:Rule',
'aws:wafregional/ruleGroup:RuleGroup',
'aws:wafregional/webAcl:WebAcl',
'aws:workspaces/directory:Directory',
'aws:workspaces/ipGroup:IpGroup',
]

View File

@@ -0,0 +1,16 @@
import pulumi
import pulumi_aws as aws
from autotag.autotag import register_auto_tags
config = pulumi.Config("dynamo")
project_name = config.require("project_name")
stack_name = pulumi.get_stack()
environment = config.require("environment")
account_id = config.require("account_id")
tags = config.require_object("tags")
aws_region = aws.get_region().id
current = aws.get_caller_identity()
register_auto_tags(tags)

View File

@@ -0,0 +1,97 @@
import json
import pulumi
import pulumi_aws as aws
def create_roles_and_policies():
# IAM Role (Job Scheduler)
role_job_scheduler = aws.iam.Role("assitente-produtos-servicos-role-role",
assume_role_policy=json.dumps({
"Version": "2012-10-17",
"Statement": [{
"Sid": "AmazonBedrockKnowledgeBaseTrustPolicy",
"Effect": "Allow",
"Principal": {
"Service": "bedrock.amazonaws.com"
},
"Action": "sts:AssumeRole",
"Condition": {
"StringEquals": {
"aws:SourceAccount": "277048801940"
},
"ArnLike": {
"aws:SourceArn": "arn:aws:bedrock:us-east-1:277048801940:knowledge-base/*"
}
}
}]
}),
)
aws.iam.RolePolicy("assistente-produtos-servicos-role-role-policy",
role=role_job_scheduler.id,
policy=json.dumps({
"Version": "2012-10-17",
"Statement": [
{
"Sid": "BedrockInvokeModelStatement",
"Effect": "Allow",
"Action": [
"bedrock:InvokeModel"
],
"Resource": [
"arn:aws:bedrock:us-east-1::foundation-model/amazon.titan-embed-text-v2:0"
]
},{
"Sid": "S3ListBucketStatement",
"Effect": "Allow",
"Action": [
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::frente-corretora-assistente-produtos-servicos-doc-storage"
],
"Condition": {
"StringEquals": {
"aws:ResourceAccount": [
"277048801940"
]
}
}
},
{
"Sid": "S3GetObjectStatement",
"Effect": "Allow",
"Action": [
"s3:GetObject"
],
"Resource": [
"arn:aws:s3:::frente-corretora-assistente-produtos-servicos-doc-storage/*"
],
"Condition": {
"StringEquals": {
"aws:ResourceAccount": [
"277048801940"
]
}
}
},{
"Sid": "S3VectorsPermissions",
"Effect": "Allow",
"Action": [
"s3vectors:GetIndex",
"s3vectors:QueryVectors",
"s3vectors:PutVectors",
"s3vectors:GetVectors",
"s3vectors:DeleteVectors"
],
"Resource": "arn:aws:s3vectors:us-east-1:277048801940:bucket/bedrock-knowledge-base-icy5rp/index/bedrock-knowledge-base-default-index",
"Condition": {
"StringEquals": {
"aws:ResourceAccount": "277048801940"
}
}
}
]
}),
)
return role_job_scheduler

Submodule infra/lambda_api_gateway added at 1a1307999e

1
infra/langfuse Submodule

Submodule infra/langfuse added at 0885f08b7f