npm package: @netizen-experience/ssm-to-env
Description: Fetch ssm parameters given a path and save it to env file
Latest version: 0.1.3

# ssm-to-env

[![npm version](https://badge.fury.io/js/@netizen-experience%2Fssm-to-env.svg)](https://badge.fury.io/js/@netizen-experience%2Fssm-to-env)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A command-line tool that fetches parameters from AWS Systems Manager Parameter Store and saves them to environment files (`.env`). Perfect for synchronizing your application configuration across different environments.

## 🚀 Features

- **Simple CLI interface** - Easy to use command-line tool
- **Batch parameter fetching** - Retrieves all parameters under a specified path
- **Environment file generation** - Automatically creates `.env` files
- **Flexible output** - Customize the output file name
- **AWS integration** - Works with existing AWS credential configurations
- **TypeScript support** - Built with TypeScript for better reliability

## 📦 Installation

### Global Installation (Recommended)

```bash
npm install -g @netizen-experience/ssm-to-env
```

### Local Installation

```bash
npm install @netizen-experience/ssm-to-env
```

### Using npx (No Installation Required)

```bash
npx @netizen-experience/ssm-to-env -p /your/parameter/path/
```

## 🔧 Usage

### Basic Usage

```bash
ssm-to-env -p /myapp/production/
```

This will fetch all parameters under `/myapp/production/` and save them to a `.env` file in the current directory.

### Advanced Usage

```bash
# Specify a custom output file
ssm-to-env -p /myapp/dev/ -f .env.local

# Using long options
ssm-to-env --parameter-path /myapp/staging/ --file config.env
```

### Command Line Options

| Option             | Short | Description                        | Required |
| ------------------ | ----- | ---------------------------------- | -------- |
| `--parameter-path` | `-p`  | AWS SSM parameter path to fetch    | ✅       |
| `--file`           | `-f`  | Output file name (default: `.env`) | ❌       |
| `--help`           | `-h`  | Show help message                  | ❌       |

### Examples

```bash
# Fetch production parameters
ssm-to-env -p /myapp/production/

# Fetch development parameters to a specific file
ssm-to-env -p /myapp/dev/ -f .env.development

# Fetch staging parameters
ssm-to-env --parameter-path /myapp/staging/ --file .env.staging
```

## ⚙️ Configuration

### AWS Credentials Setup

Before using `ssm-to-env`, you need to configure your AWS credentials. The tool supports all standard AWS credential configuration methods:

#### Method 1: AWS CLI Configuration

```bash
aws configure
```

#### Method 2: Environment Variables

```bash
export AWS_ACCESS_KEY_ID=your_access_key
export AWS_SECRET_ACCESS_KEY=your_secret_key
export AWS_DEFAULT_REGION=us-east-1
```

#### Method 3: AWS Profile

```bash
export AWS_PROFILE=your-profile-name
ssm-to-env -p /myapp/production/
```

#### Method 4: IAM Roles (for EC2/ECS/Lambda)

When running on AWS infrastructure, the tool automatically uses the attached IAM role.

### Required AWS Permissions

Your AWS credentials need the following IAM permissions:

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["ssm:GetParametersByPath"],
      "Resource": "arn:aws:ssm:*:*:parameter/your/parameter/path/*"
    }
  ]
}
```

## 📋 Parameter Naming Convention

The tool transforms SSM parameter names to environment variable names by removing the path prefix:

- SSM Parameter: `/myapp/production/DATABASE_URL`
- Environment Variable: `DATABASE_URL`

- SSM Parameter: `/myapp/production/api/SECRET_KEY`
- Environment Variable: `SECRET_KEY`

## 🔍 Example Workflow

1. **Store parameters in AWS SSM:**

   ```bash
   aws ssm put-parameter --name "/myapp/production/DATABASE_URL" --value "postgresql://..." --type "SecureString"
   aws ssm put-parameter --name "/myapp/production/API_KEY" --value "your-api-key" --type "SecureString"
   aws ssm put-parameter --name "/myapp/production/DEBUG" --value "false" --type "String"
   ```

2. **Fetch parameters:**

   ```bash
   ssm-to-env -p /myapp/production/
   ```

3. **Generated `.env` file:**
   ```env
   DATABASE_URL=postgresql://...
   API_KEY=your-api-key
   DEBUG=false
   ```

## 🛠️ Development

### Prerequisites

- Node.js 18+
- npm or yarn
- AWS CLI (for testing)

### Setup

```bash
# Clone the repository
git clone https://github.com/netizen-experience/ssm-to-env.git
cd ssm-to-env

# Install dependencies
npm install

# Build the project
npm run build

# Test the CLI
node ./dist/index.js --help
```

### Available Scripts

| Script                | Description                      |
| --------------------- | -------------------------------- |
| `npm run build`       | Compile TypeScript to JavaScript |
| `npm run lint`        | Run ESLint for code quality      |
| `npm run check-types` | Type-check without compilation   |
| `npm test`            | Run tests in watch mode          |
| `npm run test:run`    | Run tests once                   |
| `npm run test:coverage` | Run tests with coverage report |

### Project Structure

```
ssm-to-env/
├── src/
│   ├── index.ts          # Main CLI entry point
│   ├── envUpdater.ts     # Environment file writing logic
│   ├── cliUtils.ts       # CLI utilities and helper functions
│   └── __tests__/        # Test files
│       ├── cliUtils.test.ts      # Unit tests for CLI utilities
│       ├── envUpdater.test.ts    # Unit tests for env file writer
│       └── integration.test.ts   # Integration tests
├── dist/                 # Compiled JavaScript (generated)
├── coverage/             # Test coverage reports (generated)
├── package.json          # Package configuration
├── tsconfig.json         # TypeScript configuration
├── vitest.config.ts      # Vitest test configuration
├── eslint.config.mjs     # ESLint configuration
└── README.md            # This file
```

### Testing

The project includes comprehensive test coverage using [Vitest](https://vitest.dev/):

- **Unit Tests**: Test individual functions and modules
- **Integration Tests**: Test the complete workflow with mocked dependencies
- **Coverage Reports**: Track test coverage across the codebase

Run tests with:

```bash
# Run tests in watch mode (for development)
npm test

# Run tests once
npm run test:run

# Run tests with coverage report
npm run test:coverage
```

The test suite covers:

- ✅ Environment file creation and formatting
- ✅ CLI argument parsing and validation  
- ✅ SSM parameter transformation logic
- ✅ Error handling scenarios
- ✅ Edge cases (empty values, special characters, etc.)
- ✅ Integration workflow simulation

## 🤝 Contributing

We welcome contributions! Please follow these steps:

1. **Fork the repository**
2. **Create a feature branch:**
   ```bash
   git checkout -b feature/your-feature-name
   ```
3. **Make your changes and add tests if applicable**
4. **Ensure code quality:**
   ```bash
   npm run lint
   npm run check-types
   npm run build
   npm test
   ```
5. **Commit your changes:**
   ```bash
   git commit -m "feat: add your feature description"
   ```
6. **Push to your fork:**
   ```bash
   git push origin feature/your-feature-name
   ```
7. **Create a Pull Request**

### Coding Standards

- Follow the existing TypeScript and ESLint configuration
- Write clear, descriptive commit messages
- Add documentation for new features
- Ensure all builds and lints pass

## 🐛 Troubleshooting

### Common Issues

**Error: "Could not load credentials from any providers"**

- Ensure your AWS credentials are properly configured
- Check that your AWS profile (if using one) exists and is valid
- Verify your IAM permissions include `ssm:GetParametersByPath`

**Error: "Missing required parameter path"**

- Make sure you provide the `-p` or `--parameter-path` option
- Verify the parameter path exists in AWS SSM

**Error: "No parameters found"**

- Check that parameters exist at the specified path in AWS SSM
- Ensure your AWS credentials have access to the parameter path
- Verify you're working in the correct AWS region

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🙏 Acknowledgments

- Built with [AWS SDK for JavaScript](https://aws.amazon.com/sdk-for-javascript/)
- CLI parsing powered by [yargs](https://github.com/yargs/yargs)
- Environment file handling with [dotenv](https://github.com/motdotla/dotenv)

---

Made with ❤️ by [Netizen Experience](https://github.com/netizen-experience)