技術(tech)

Smartphone Development Made Easy! Claude Code + AWS EC2 for $3/Month AI Development Environment

Smartphone Development Made Easy! Claude Code + AWS EC2 for $3/Month AI Development Environment

What you’ll learn from this article

  • Building an AI-driven development environment using Claude Code CLI
  • Secure connection methods from smartphones to AWS EC2
  • Safe network construction using Tailscale VPN
  • Specific implementation steps for an AI development environment at $3/month server cost
  • Automation and cost management with Terraform + Lambda

📋 Table of Contents

  1. Why Do We Need a Smartphone Development Environment?
  2. Technology Selection: Why Tailscale?
  3. System Architecture and Security Design
  4. Implementation Steps: Infrastructure
  5. Implementation Steps: Security
  6. Operations and Cost Management

Why Do We Need a Smartphone Development Environment?

🤖 Anxiety About the Future of Programming

Looking at recent AI coding tools, I honestly became anxious:

"Will there be no need to write code by hand in the future?"

Claude Code, GitHub Copilot, Cursor… these tools can already generate complete code from natural language instructions. This means:

Previously, we wrote code line by line with keyboards, but now we can generate complete code just by instructing "create a ○○ function."

If that’s the case, what’s the point of carrying heavy PCs? Wouldn’t it be enough to just give instructions from a smartphone?

This concern was the catalyst for this project.

📱 Proposing a New Development Style

Have you ever experienced these situations?

Wanting to quickly test ideas that come to mind during commutes, wanting to code casually while lounging at home, wanting to use AI pair programming even when out and about, needing emergency bug fixes while away from home, wanting to develop lightweight without carrying heavy laptops, being concerned about the cost of always-on servers for personal development.

In an AI-driven era, a system that allows access to a full-fledged development environment from just a smartphone would be ideal.

What This Article Achieves

We realize a "just give instructions" development experience through AI-driven development with Claude Code CLI, and build a development environment at the ultra-low cost of $3/month server fees. We provide security through secure VPN connections, flexibility accessible from anywhere, and automated cost management and operations.

Implementation Result: We built an AI development environment including Claude Code CLI on AWS EC2 and connected securely from smartphones via Tailscale VPN. At the low cost of $3-4/month server fees, we realized an environment where you can casually do a bit of development while commuting or lounging around.

Pricing Prerequisites: Assuming coding while moving around or lounging at home, with operating hours of about 1-2 hours per day (automatic stop function reduces wasteful costs). Server costs are $3-4/month for AWS server fees only. Claude Code requires separate fees to Anthropic.

⚠️ Disadvantages and Challenges: Manual stopping inconvenience (stopping frequently is realistically troublesome), spot instance anxiety (possibility of being stopped without notice), connection complexity (initial setup of Tailscale settings and SSH connections required), long-term usage costs (using 5-8 hours per day costs about $10-15/month).

⚠️ Important Security Notes: Always use Tailscale IP addresses (100.x.x.x) when connecting. Public IP connections are intentionally blocked by security settings. Never publish actual Tailscale IP addresses. This article displays actual IP addresses as masked (xxx).

Technologies Used: Claude Code CLI, AWS EC2, Tailscale VPN, Terraform, Lambda, EventBridge

Why Claude Code CLI?

The biggest feature of this development environment is AI-driven development with Claude Code CLI.

What is Claude Code CLI?

Anthropic’s AI pair programming tool. Enables code generation, review, and debugging in natural language.

Actual Usage Examples

# Actual development examples on smartphone
$ claude "Create a REST API with Express.js, with user authentication"
# → Complete code generated instantly

$ claude "Check this code for security issues"
# → Vulnerability detection and fix code presentation

Why Did We Choose Tailscale?

There are many VPN technology options, but let me explain why we chose Tailscale after actual consideration.

Free to Use

Completely free for personal use (up to 20 devices). Commercial VPN services typically cost $5-15/month, so this alone is quite beneficial. Self-hosting OpenVPN or WireGuard also involves effort and costs, but Tailscale can be used immediately.

Secure Communication

P2P encrypted communication connects devices directly with encryption, without going through intermediate servers.

Ease of Setup

Automatic configuration eliminates the need for complex firewall settings – just install the app. It supports Windows, Mac, Linux, Android, and iOS.

Conclusion: Tailscale, which provides enterprise-level security and usability while being free, was the optimal choice for individual developers. When you actually use it, you’ll be amazed by its convenience.

System Architecture Diagram

Overall Architecture

Configuration of the implemented overall system:

Smartphone Side: Composed of Android smartphone, Termux app, and Tailscale VPN.

Tailscale Network: Provides secure connections through P2P encrypted communication.

AWS Cloud: Built with EC2 instance (100.xxx.xx.xx), security group (Tailscale IP only allowed), Lambda auto-stop (23:00, 13:00 JST), EventBridge (periodic execution), and VPC (10.0.0.0/16).

AI Development Environment: Ubuntu 22.04, Node.js 20 LTS, Claude Code CLI (AI pair programming), Git, tmux, and vim are installed.

Security Configuration

We adopted a multi-layered defense security design:

Security Layers: Multi-layered defense implemented with public IP (xx.xx.xxx.xxx), security groups, SSH key authentication, and Tailscale VPN.

Connection Path Comparison: We avoid dangerous connections (via internet, direct public IP) and adopt secure connections (via Tailscale VPN, encrypted tunnel).

1. 🏗️ Infrastructure Setup

Cost-Optimized EC2 Configuration

First, we set up a cost-optimized EC2 instance using spot instances:

# ec2.tf
resource "aws_instance" "claude_code_server" {
  # Spot instance configuration for cost optimization
  instance_market_options {
    market_type = "spot"
    spot_options {
      instance_interruption_behavior = "stop"
      spot_instance_type            = "persistent"
      max_price                     = "0.005"  # Limit: $0.005/hour
    }
  }

  ami           = "ami-0d52744d6551d851e"  # Ubuntu 22.04 LTS
  instance_type = "t3.micro"               # 1vCPU, 1GB RAM
  subnet_id     = aws_subnet.public.id

  vpc_security_group_ids = [aws_security_group.claude_code_sg.id]

  # EBS configuration for data persistence
  root_block_device {
    volume_type           = "gp3"
    volume_size           = 20
    delete_on_termination = false  # Retain data on termination
    encrypted            = true
  }

  user_data = templatefile("user-data.sh", {
    enable_tailscale   = var.enable_tailscale
    tailscale_auth_key = var.tailscale_auth_key
  })

  tags = {
    Name    = "claude-code-server"
    Project = "claude-code-smartphone"
    Type    = "development"
  }
}

Implementation Points: Achieved 70% cost reduction with spot instances vs on-demand instances, and EBS volumes persist data after instance stops. Encrypted EBS volumes ensure security, and maximum price settings prevent cost overruns.

Automated Cost Management with Lambda

Lambda function for automatic EC2 stopping:

# lambda/auto_stop_ec2.py
import boto3
import json
import logging
from datetime import datetime

logger = logging.getLogger()
logger.setLevel(logging.INFO)

def lambda_handler(event, context):
    """
    Automatically stop EC2 instances with specific tags
    Execution time: Daily 23:00 JST, Weekdays 13:00 JST
    """

    ec2 = boto3.client('ec2')

    try:
        # Search instances by tags
        response = ec2.describe_instances(
            Filters=[
                {'Name': 'tag:Project', 'Values': ['claude-code-smartphone']},
                {'Name': 'instance-state-name', 'Values': ['running']}
            ]
        )

        instance_ids = []
        for reservation in response['Reservations']:
            for instance in reservation['Instances']:
                instance_ids.append(instance['InstanceId'])
                logger.info("Found running instance: " + instance['InstanceId'])

        if not instance_ids:
            logger.info("No running instances found")
            return {'statusCode': 200, 'body': json.dumps('No instances to stop')}

        # Stop instances
        stop_response = ec2.stop_instances(InstanceIds=instance_ids)
        logger.info("Stopping instances: " + str(instance_ids))

        return {
            'statusCode': 200,
            'body': json.dumps({
                'message': 'Successfully stopped ' + str(len(instance_ids)) + ' instances',
                'instances': instance_ids,
                'timestamp': datetime.utcnow().isoformat()
            })
        }

    except Exception as e:
        logger.error("Error stopping instances: " + str(e))
        return {'statusCode': 500, 'body': json.dumps({'error': str(e)})}

Implementation Intent:
Tag-based dynamic instance search ensures flexibility, detailed log output and error handling are implemented. Automatic execution daily at 23:00 and weekdays at 13:00 ensures reliable cost reduction.

2. 🔒 Security Implementation

Security Group Configuration

Configuration that allows SSH connections only from Tailscale IPs:

# security_group.tf
resource "aws_security_group" "claude_code_sg" {
  name_prefix = "claude-code-sg"
  vpc_id      = aws_vpc.main.id

  tags = {
    Name    = "claude-code-security-group"
    Project = "claude-code-smartphone"
  }
}

# Tailscale Mac IP
resource "aws_security_group_rule" "ssh_tailscale_mac" {
  type              = "ingress"
  from_port         = 22
  to_port           = 22
  protocol          = "tcp"
  cidr_blocks       = ["100.xxx.x.xx/32"]  # Actual Mac Tailscale IP
  security_group_id = aws_security_group.claude_code_sg.id
  description       = "SSH from Mac via Tailscale"
}

# Tailscale Android IP
resource "aws_security_group_rule" "ssh_tailscale_android" {
  type              = "ingress"
  from_port         = 22
  to_port           = 22
  protocol          = "tcp"
  cidr_blocks       = ["100.xxx.x.xx/32"]  # Actual Android Tailscale IP
  security_group_id = aws_security_group.claude_code_sg.id
  description       = "SSH from Android via Tailscale"
}

# EC2 Instance Connect (Emergency use)
resource "aws_security_group_rule" "ssh_ec2_instance_connect" {
  type              = "ingress"
  from_port         = 22
  to_port           = 22
  protocol          = "tcp"
  cidr_blocks       = ["3.112.23.0/29"]  # EC2 Instance Connect IP range
  security_group_id = aws_security_group.claude_code_sg.id
  description       = "SSH from EC2 Instance Connect"
}

# Allow all outbound
resource "aws_security_group_rule" "egress_all" {
  type              = "egress"
  from_port         = 0
  to_port           = 0
  protocol          = "-1"
  cidr_blocks       = ["0.0.0.0/0"]
  security_group_id = aws_security_group.claude_code_sg.id
}

Operating Principle: By allowing only 100.x.x.x IP addresses assigned by Tailscale, access is possible only from authenticated devices. This configuration completely blocks direct access from public IPs.

Tailscale Integration

Manages Tailscale authentication keys and automatic configuration on EC2.

EC2 Initialization Script

Automatic configuration script when EC2 starts:

#!/bin/bash
# user-data.sh - Automatic configuration when EC2 starts

# Update basic packages
apt update && apt upgrade -y

# Install Node.js 20 LTS
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt-get install -y nodejs

# Install required packages
apt-get install -y git curl tmux vim htop unzip python3 python3-pip

# Install Tailscale
curl -fsSL https://tailscale.com/install.sh | sh

# Tailscale configuration (conditional)
# Note: The following uses Terraform template notation
if [ "ENABLE_TAILSCALE" = "true" ] && [ "TAILSCALE_AUTH_KEY" != "" ]; then
  sudo tailscale up --authkey=TAILSCALE_AUTH_KEY --ssh --accept-routes
else
  echo "Tailscale installed but not configured"
fi

# Install Claude Code CLI
npm install -g @anthropic-ai/claude-code

# SSH key configuration (spot restart support)
mkdir -p /home/ubuntu/.ssh
# Note: Please set actual public keys according to your environment
echo "ssh-rsa YOUR_PUBLIC_KEY_HERE" >> /home/ubuntu/.ssh/authorized_keys
chmod 700 /home/ubuntu/.ssh
chmod 600 /home/ubuntu/.ssh/authorized_keys
chown -R ubuntu:ubuntu /home/ubuntu/.ssh

# Basic configuration
sudo -H -u ubuntu git config --global init.defaultBranch main
sudo -H -u ubuntu git config --global core.editor vim

# Alias configuration
cat >> /home/ubuntu/.bashrc << 'EOF'
alias ll='ls -alF'
alias ..='cd ..'
alias dev='cd ~/development'
alias c='claude'
alias t='tmux'
EOF

chown -R ubuntu:ubuntu /home/ubuntu

Implementation Points:
Terraform template functionality enables conditional branching for Tailscale configuration, realizes automatic Tailscale connection through authentication keys, and automates development environment setup including Claude Code CLI.

Security Points:

  1. Authentication Key Management: Separate sensitive information with terraform.tfvars
  2. IP Restrictions: Strict limitations to 100.x.x.x/32
  3. Multi-layer Authentication: Tailscale authentication + SSH authentication
  4. Automatic Configuration: Consistent environment construction with user-data.sh

Summary: AI Development Environment for /Month Server Cost

🎉 Implementation Results

We successfully built a casual AI development environment accessible from smartphones at $3.2/month server cost.

Usage Assumption: Casual development while moving around or lounging at home (about 1-2 hours per day)

Main Achievements: We realized a casual development experience where ideas can be immediately coded with Claude Code CLI, achieved 70% cost reduction from traditional VPS ($15-20/month). We strengthened security with safe private connections via Tailscale VPN, automated operations with Lambda + EventBridge automatic stop and cost management, and provided flexibility accessible whether commuting or in bed.

Important: The above is AWS server cost only (assuming 1-2 hours daily usage). Claude Code usage fees are separate.

Realistic Constraints: Automatic stop limitations where the system might be stopped when you want to use it even with full automation, spot instance risks where AWS might stop without notice, initial setup complexity where Tailscale, SSH, and Terraform configuration is difficult for beginners, and network dependency where development experience is affected by mobile connection quality.

Lessons Learned

  1. Importance of Technology Selection: Tailscale adoption balanced security and cost
  2. Spot Instance Utilization: Achieved 70% cost reduction with proper configuration
  3. Value of Automation: Significantly reduced operational costs and human errors
  4. Security Design: Robust environment construction through multi-layered defense
  5. Balance with Reality: Trade-offs between ideal automation and practicality

Future Prospects

Multi-region support for disaster recovery and latency optimization, containerization for further efficiency with Docker environments, CI/CD integration with enhanced GitHub Actions collaboration, and operational improvements with mechanisms to mitigate spot instance constraints.

Application Possibilities

This configuration can also be applied to low-cost experimental environments for personal project development, programming learning servers for study and research, rapid environment construction for prototyping and idea validation, and secure development environment access for remote work.

Reference Links: Tailscale Official Documentation, AWS EC2 Spot Instances, Terraform AWS Provider, AWS Lambda Development Guide.