brew install awscli
aws configure

based on japanese material

free tier stuff

configuration

aws-cli

aws configure

/.aws/credentials ’Create New Access Key’ https://us-east-1.console.aws.amazon.com/iam/home?region=us-east-1#/security_credentials

[default]
aws_access_key_id = XXX
aws_secret_access_key = YYY

/.aws/config

[profile default]
region = us-east-1
output = json

cdk

command to run aws scripts

npm install -g aws-cdk
cdk bootstrap aws://{ACCOUNT_NUMBER}/{REGION}
  • account number
aws sts get-caller-identity --profile default | jq .Account
  • region
aws configure get region

api reference

ssh-key for ec2

’create ssh-key’

export KEY_NAME="XXX"
aws ec2 create-key-pair --key-name ${KEY_NAME} --query 'KeyMaterial' --output text > ${KEY_NAME}.pem
ssh -i ${KEY_NAME}.pem ec2-user@ip

services

jargon what it does
--- ---
vpc network
security group firewall
ec2 virtual machine
fargate es2 but for containers
ecs containers
lambda serverless ’functions’
s3 storage
cloudfront CDN for the storage, HTTPS
dynamo database
sns messages: lambda <-> dynamo

lambda might be great, but you might be locking down yourself into aws…

just make a simple vm(ec2) to start with

this uses typescript

ec2-test

mkdir ~/code/ec2-test
cd ~/code/ec2-test
cdk init --language typescript

~/code/ec2-test/bin/ec2-test.ts

#!/usr/bin/env node
import 'source-map-support/register';
import * as cdk from 'aws-cdk-lib';
import { WebsiteStack } from '../lib/yasushisakai.com-stack';

const app = new cdk.App();
new WebsiteStack(app, 'yasushisakai', app.node.tryGetContext('key_name'), {
    env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION }
});

~/code/ec2-test/lib/ec2-test-stack.ts

import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import { InstanceType, SubnetType } from 'aws-cdk-lib/aws-ec2';

export class WebsiteStack extends cdk.Stack {
    constructor(scope: Construct, id: string, keyName: string, props?: cdk.StackProps) {
        super(scope, id, props);

        const vpc = new ec2.Vpc(
            this, `${id}-VPC`, {
            cidr: '10.10.0.0/23',
            maxAzs: 1,
            subnetConfiguration: [
                {
                    subnetType: ec2.SubnetType.PUBLIC,
                    name: "public"
                }
            ],
            natGateways: 0
        });

        const securityGroup = new ec2.SecurityGroup(
            this, `${id}-SecurityGroup`, {
            vpc,
            allowAllOutbound: true
        });

        [22, 80, 443].forEach(
            p => securityGroup.addIngressRule(
                ec2.Peer.anyIpv4(),
                ec2.Port.tcp(p)));

        const vpcSubnets: ec2.SubnetSelection = {
            subnetType: ec2.SubnetType.PUBLIC
        };

        const host = new ec2.Instance(
            this, `${id}-Instance`,
            {
                instanceType: new ec2.InstanceType('t2.micro'),
                machineImage: ec2.MachineImage.latestAmazonLinux({
                    generation: ec2.AmazonLinuxGeneration.AMAZON_LINUX_2
                }),
                vpc,
                vpcSubnets,
                securityGroup,
                keyName
            }
        );

        new cdk.CfnOutput(this, "InstancePublicDnsName", {value: host.instancePublicDnsName});
        new cdk.CfnOutput(this, "InstancePublicIP", {value: host.instancePublicIp});
    }
}

in python (not maintained)

mkdir ec2
cd ec2
# cdk init --language python
python3 -m venv .env
source .env/bin/activate
pip install aws-cdk.aws-ec2

~/code/ec2/app.py

from aws_cdk import (
    core,
    aws_ec2 as ec2,
)
import os

class FireupEc2(core.Stack):

    def __init__(self, scope: core.App, name: str, key_name: str, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        vpc = ec2.Vpc(
            self, f"{name}-vpc",
            max_azs=1,
            cidr="10.10.0.0/23",
            subnet_configuration=[
                ec2.SubnetConfiguration(
                    name="public",
                    subnet_type=ec2.SubnetType.PUBLIC,
                )
            ],
            nat_gateways=0,
        )

        sg = ec2.SecurityGroup(
            self, f"{name}-security_group",
            vpc=vpc,
            allow_all_outbound=True,
        )

        sg.add_ingress_rule(
            peer=ec2.Peer.any_ipv4(),
            connection=ec2.Port.tcp(22), # ssh
        )

        sg.add_ingress_rule(
            peer=ec2.Peer.any_ipv4(),
            connection=ec2.Port.tcp(80), # http
        )

        sg.add_ingress_rule(
            peer=ec2.Peer.any_ipv4(),
            connection=ec2.Port.tcp(443), # https
        )

        host = ec2.Instance(
            self, f"{name}-ec2",
            instance_type=ec2.InstanceType("t2.micro"),
            machine_image=ec2.MachineImage.latest_amazon_linux(),
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
            security_group=sg,
            key_name=key_name
        )

        # print the server address
        core.CfnOutput(self, "InstancePublicDnsName", value=host.instance_public_dns_name)
        core.CfnOutput(self, "InstancePublicIp", value=host.instance_public_ip)

app = core.App()
FireupEc2(
    app, "test",
    key_name=app.node.try_get_context("key_name"),
    env={
        "region": os.environ["CDK_DEFAULT_REGION"],
        "account": os.environ["CDK_DEFAULT_ACCOUNT"],
    }
)

app.synth()
cdk deploy --app "python3 app.py" -c key_name="{KEY}"

deploy

cdk deploy -c key_name="{KEY}"

write down the ip. (naturally) you will need it to ssh

destroy

cdk destroy

you might want to delete the key pair too.

aws ec2 delete-key-pair --key-name "{KEY}"
rm ~/.ssh/{KEY}.pem

ssh-in

ssh -i ~/.ssh/KEY.pem ec2-user@IP

amazon linux 2

nginx

sudo yum install docker
sudo systemclt start docker

docker compose https://gist.github.com/npearce/6f3c7826c7499587f00957fee62f8ee9

amazon linux

amazonlinux 1.0 may not have systemd

sudo yum update
sudo yum install xxx
sudo service xxx

few things I did…

sudo yum install nginx
sudo service nginx start
vi /etc/nginx/nginx.conf

docker 経由で certbot の sslcertificate を取得する

let’s encrypt

docker run --rm -it --env AWS_CONFIG_FILE="$HOME/aws_credentials" -v "/etc/letsencrypt:/etc/letsencrypt" certbot/dns-route53 certonly --dns-route53 -d mirage.city -d www.mirage.city -d api.mirage.city --agree-tos

domain sits in amazon aws route 53

awscredentials is the same as ~/.aws/credentials

-d for domains and sub domains

this will generate certkeys at /etc/letsencrypt/live/mirage.city

IAM > Roles > yasushisakai….

you need to change permissions to get the credential access to route 53 related things. (AmazonRoute53FullAccess)

renew certificate

awscredentials の位置が違うっぽいけどうまくいくからいいや。

docker run --rm -it --env AWS_CONFIG_FILE="$HOME/aws_credentials" -v "/etc/letsencrypt:/etc/letsencrypt" certbot/dns-route53 renew --dns-route53 --agree-tos
docker container restart nginx

簡単

<2023-10-30 Mon> 更新した <2024-05-05 Sun> 更新した

docker-compose に certbot を記述した場合

I keep coming back to this article

  certbot:
    image: certbot/certbot:latest
    volumes:
      - ./certbot/www/:/var/www/certbot/:rw
      - ./certbot/conf/:/etc/letsencrypt/:rw
docker compose run --rm certbot renew

how to start a service

  1. create aws ec2 instance through aws
  2. transfer or acquire domain using route 53
  3. clone mirage-city

Date: 2022-09-01 Thu 08:52