# Mobingi Wave 官方用户指南

Mobingi Wave的官方用户指南

从使用Mobingi Wave的提前准备中讲解UI等的基本的操作方法。

根据功能的添加・更改将更新本用户指南。

请从左侧菜单中选择您要阅读的项目。

Mobingi Wave: <https://app.mobingi.com/wave>.

如果您无法通过本用户指南解决，请通过<support@mobingi.com>与我们联系。

Mobingi Website: <https://mobingi.com>.


# 提前准备

在将引进 Wave 前的准备

* 为了使Mobingi的每小时报告分析有效、将讲解需要用在您的AWS帐户的执行任务和需要提交给Mobingi的信息。
* 作业后提交给Mobingi的信息如下。 请您记录每个阶段的作业。 （作业后也可以确认。)

```
- AWS帐户ID（12位数）

- 已创建的报告的信息

    - 报告名

    - S3存储桶

    - 报告路径前缀，或报告路径

- 授权指定存储桶用的 IAM角色的ARN (例如: arn:aws:iam::xxxxxxxxxxxx:role/crossacounnt-access-for-mobingi)
```

## 步骤1：创建S3存储桶以及每小时报告（任意） <a href="#step1" id="step1"></a>

* 使用帐单信息共享的AWS帐户创建每小时报告。
* 如果您已有以下的报告定义条件，可跳过此操作。

  `时间单位: 每小时`

  `报告含有的项目的资源ID将有效`

  `在存储桶中不包含Mobingi不能浏览的对象（为了给整个存储桶阅读访问权）`

### 步骤1-1：创建S3存储桶

* 从S3控制台中用任意的名称创建存储桶。 选项可为默认值。

  因要使用此为报告的输出目标，请记录存储桶名称。

### 步骤1-2：创建每小时报告

* 从AWS管理控制台中，打开“帐单信息和成本管理控制面板”，转到报告菜单内。

进行创建报告。

![](/files/-LIiktbQFkRQSL9LnKbQ)

* 在“第1步：选择内容”页面，请填写以下内容进行下一步。
  * 报告名称：任意
  * 时间单位： **每小时**
  * 包含: 选择 **资源ID**
  * 对以下内容启用支持: 任意

![](/files/-LNxZqZ28JcRw_ClB3yX)

* 在“第2步：选择交付选项”页面，为包括S3存储桶的操作，按以下步骤进行。
  * 输入S3存储桶（之前创建的）名称
  * 示例策略的显示和复制（※请务必在填写S3存储桶名称后在显示）

![](/files/-LIiukMGUOHJ306ZPWB1)

![](/files/-LIivyF4Pr1_R9KGk_cH)

* 复制策略示列后，打开**先前创建的S3存储桶** 的详细信息。（※建议在另一个标签或窗口上操作）
* 在S3中，按“权限”>>“存储桶策略”操作菜单。
* 在存储桶策略编辑器中，适用之前的样本策略

![](/files/-LIoKESI522gBJbicM4H)

返回到“第2步：选择交付选项”，输入以下项目并进行下一步。

* 报告路径前缀：任意（※也可忽略）
* 圧缩：任意

如果存储桶策略不正确，在验证不会成为“有效桶”。

请再次确认S3菜单。

![](/files/-LIsJjP-QUmpv5EW59Bj)

检查“第3步：审核”的显示内容中是否有错误并点击查看和完成。

![](/files/-LOQg6v9SMoFc5-4hOYD)

## 步骤2：创建一个授权Mobingi可以读取的IAM角色 <a href="#step2" id="step2"></a>

从AWS管理控制台中，打开IAM服务并转到“角色”>>“创建角色”菜单。

![](/files/-LIiwIm8fP_1B6oxnETQ)

在“选择受信任实体的类型”中选择“其他AWS帐户”，输入下面的Mobingi帐户ID。

* Mobingi帐户ID： 131920598436

![](/files/-LInCQYhLo-uLiB20P-j)

在“Attach permissions policies”菜单中，选择“创建策略”。

![](/files/-LIiweFSBhuvUSmbT0Qb)

由于在另一个标签（窗口）中打开“创建策略”菜单，选择JSON作为输入格式，以以下的内容输入策略。请将 Resource的`{replace_to_report_bucket}`部分置换为 **要使用的报告的存储桶名称**。

```bash
{
    "Version": "2012-10-17",
   "Statement": [
         {
               "Effect": "Allow",
               "Action": [
                     "s3:Get*",
                     "s3:List*"
               ],
               "Resource": [
                     "arn:aws:s3:::{replace_to_report_bucket}",
                     "arn:aws:s3:::{replace_to_report_bucket}/*"
               ]
         }
   ]
}
```

![](/files/-LIoyTtdOodS15EXiOUE)

进入“查看策略”，输入以下项目并创建策略。

* 名称： 任意(※必須)
* 描述：任意

![](/files/-LIoKKhqUYRq0ztPXRDM)

返回“创建角色”菜单并更新列表，显示之前创建的策略。 激活选项，进入下一步确认。

![](/files/-LIsVtAyzEVr1Mhit9fP)

在“确认”菜单中，输入以下项目。

* 角色名称：任意（\*必填）
* 角色描述：任意

确认是否已适用“可信任实体”和“策略”，并创建角色。

![](/files/-LIsWe0cYCjM7Gj-t3nn)

记录已创建的角色的ARN。

![](/files/-LIsYIHOtJr_OBQsaisy)


# Mobingi Wave 概述

## 注册Mobingi Wave

![](/files/-LIjVctBT27xxdryZkBW)

* 请从 <https://app.mobingi.com/wave/login> 输入必要的信息，然后点击“注册”。

## 菜单结构

![](/files/-LIjVgt52AX0-3a2h2sZ)

* 控制面板：在贵公司使用的所有的AWS帐户的利用状况（合计）可视化。
* 报告：帐户单位，群组单位，标签单位的利用状况可视化，报告参照。
* RI：显示Reserved Instance列表和利用状况。

## 控制面板

![](/files/-LJSTghvWUdPYCJlS4eL)

* 关于每日数据更新
  * 定时更新：毎天
  * 数据新鲜度：大约两天前的数据
* 关于每月数据更新
  * 定时更新：每月5号左右
  * 数据新鲜度：显示上个月以上的使用状况

## 控制面板 - Analysis

![](/files/-LJS2QDBrob-nB1hrOeM)

* Daily
  * 合计：本月的利用额的累计（Usage hr x on-demand rate）
  * 每日数据的平均额：本月的每日利用额的变化（Usage hr x on-demand rate）
* Monthly
  * 过去12个月的利用额的推移（Usage hr x true rate） 颜色区别每个帐户

## 报告 - 帐户

您可以查看每个选定帐户的使用实绩。

![](/files/-LIjXTdDcmjD6HMAuBpn)

* Payer : Payer account （主帐户）
* ![](/files/-LEhCWO4NLTr3qptgRVo): 已设置预算（警报通知）。&#x20;

向下滚动并选择，年月，服务，则会显示报告。\
从年月旁边的按钮可以作为CSV下载。

![](/files/-LIvLhgi3FJiMLzzquIW)

## 报告 - 群组

将复数帐户分组并显示每个组的使用额。&#x20;

![](/files/-LIjXZNNd9YdyQrBjiO9)

## 报告 - 标签

可以掌握在AWS中利用的标签的每个标签的利用额。

![](/files/-LIoV3A9XxWJFaA1poTw)

详细请查看 [掌握标签的使用量](https://docs.mobingi.com/v/wave/mobingi-wave/tag-report) 。

## RI - Reserved Instance

可以查看已购买的RI

![](/files/-LIjXpjcRHgybM45aEyz)

## 帐单

可以查看每个月的帐单。

## 设置

可以更改以下的设置。

* 更改密码
* 更改语言（日语/英语/中文）
* 通知设置（邮件/ Slack）


# 帐单的确认方法

帐户每的利用额的查看方式。

## 在Mobingi Wave查看帐单

* 点击菜单上的`报告`。

![](/files/-LIjY8B-p1hKZNJkwZZh)

* 在报告中，您可以查看帐户个别的利用状况。如果有多个AWS帐户在组织内利用，则所有帐户都将列在画面左侧。选择要查看的帐户的帐单。 向下滚动屏幕并显示项目。

![](/files/-LIjYBHhgnnCl8rEFzjx)

* 帐单可以分月别，服务查看。选择您想要查看的月份和AWS的服务，则会显示该当帐单。

![](/files/-LIjYE5uo_3vOcB2jxdX)

## 帐单的确认，下载

* 选择屏幕左侧菜单的帐单后会显示帐单数据。您可以查看以已发行的帐单（指定年月）。您可以从下载按钮中把帐单作为PDF文件下载。

![](/files/-LIjYIbakro1nN2hA77W)


# 掌握标签的使用量

介绍标签功能的利用方法

## 激活标签功能

在Wave上，`inactive`是标签默认值，点击更改为`Active`。

更改为`Active`2天后开始收集数据。

## 掌握每个标签的使用量

从菜单中选择 报告→ 标签。\
选择`TagKey`和`TagValue`后，会和每个帐户的帐单同样，显示当月的数据和服务排行榜。

![](/files/-LIoLljs9EmOA3QXpEcH)

向下滚动页面，通过选择年月可以来查看每月报告。每月报告分为各服务显示。

从年月旁边的按钮可下载CSV数据。CSV文件中包含所选择的标签的所有服务的利用数据。\
如果您想对CSV数据适用折扣或货币兑换，请参阅[折扣和货币兑换的适用](https://docs.mobingi.com/v/wave/mobingi-wave/apply-jpy)。

![CSV数据样本](/files/-LI9tzoK75MpUlSQ1soG)


# 报告和CSV的看法

控制面板上的报告和CSV报告的比较说明。

* 在此页面对照控制面板的报告和已下载的CSV，讲解各项目。

  在报告和CSV有同意词但不一样的单词和缩写的项目。

  下图中用相同颜色包围的部分是相同的项目。

![](/files/-LHG7k-nKUwPIz8ixvgt)

1. AccountID: AWS的帐户ID
   * 由于报告以每个帐户为单位表示/下载，因此每个CSV仅显示一个ID。
2. ServiceCode: AWS的每个服务名称
   * Elastic Cpmpute Cloud等，然而，在CSV中， `Elastic Compute Cloud` 为 `AmazonEC2` ，`Simple Storage Service` 为 `AmazonS3`等以缩写表示。
3. CostBeforeTax: 不含税的每月利用额
   * 报告中小数显示到小数第2位。 比如在此列报告中的 `$21.18` 和在CSV中的 `21.18966134` 是一致的。
4. Region: 地区
   * 在此例中，在控制面板显示为 `Asia Pacific(Tokyo)` ，而在CSV中则显示为`ap-northeast-1` 。 两者都是指东京地区。
5. UsageQuantity: 利用量
   * 此例在报告中是`1,394.05` 和在CSV中的 `1,394.056667` 是一致的。
6. InstanceType: 实例类型
   * 此例在报告和CSV都是 `t2.micro`，是一致的。
7. ItemDescription: 详细
   * 在此例中，报告和CSV都是`$0.0152 per on-demand t2.micro EC2 instance hour (or partial hour)` ，是一致的。


# 折扣和货币兑换的适用

如果您想要每月报告显示日元和想适用折扣时可利用的功能

## 1. 登陆折扣率和汇率

从屏幕右上角的下拉菜单中选择设置。\
从`Additional Setting`输入折扣率和汇率然后`Save`。

![设置画面](/files/-LIoUL0InEC3VgTcJhZU)

请在月初登陆上个月利用的统计适用的折扣率和汇率。

{% hint style="info" %}
&#x20;如果您在8月初登陆5％的折扣率和110.42的汇率，则7月份的每项目利用额按5％折扣，汇率以110.42相乘之后的金额计算。
{% endhint %}

如果不登陆折扣率和汇率，将不会创建每月报告。

{% hint style="danger" %}
如果您在登陆之前创建了报告，想在创建后更改登录内容，请通过<support@mobingi.com>与我们联系。
{% endhint %}

您可以通过`查看到上个月为止的设置`来浏览过去的注册信息。

## 2. 下载CSV报告

在登录折扣率和汇率后，将开始创建报告。

{% hint style="danger" %}
目前，**仅对帐户，标签的CSV**适用折扣率，汇率。（它不会向控制面板的报告反应）
{% endhint %}

请转到帐户或标签页面并下载CSV报告然后查看。

![](/files/-LIjYoKQMfVUPIqRv1mP)


# 各种设置

设置画面的说明。

从控制台右上角的下拉菜单中选择设置。

![设置画面](/files/-LIoTx5gqEpi4qmStuYF)

### 在设置画面上可以设置的内容

1. 更改密码

   * 如果您忘记了当前的密码，麻烦你请通过<support@mobingi.com>与联系我们。

2. 语言选择

   * 可选日语，英语和中文。

3. 通知设置

   * 超过在报告画面设置的预算时，会从邮件或slack通知您。

4. Additional Setting
   * 您可以设置折扣率和汇率。关于使用方法您可以查看[折扣和货币兑换的适用](https://docs.mobingi.com/v/wave/mobingi-wave/apply-jpy)。


# Overview

Mobingi Documentation

{% hint style="warning" %}
**This product is already deprecated.**
{% endhint %}

## Overview

### Overview

[mobingi](https://github.com/mobingi/mobingi) is the official command line interface for [Mobingi](https://mobingi.com/) services.

To view a list of the available commands, just run mobingi without arguments:

```bash
$ mobingi
Command line interface for Mobingi API and services.

Usage:
  mobingi [command]

Available Commands:
  creds       manage your credentials
  help        help about any command
  login       login to Mobingi API
  rbac        manage role based access control features
  registry    manage your Mobingi docker registry
  reset       reset config to defaults
  stack       manage your stack
  svrconf     manage your server config file
  template    manage your ALM templates
  version     print the version

Flags:
      --token string    access token
      --url string      base url for API
      --rurl string     base url for Docker Registry
      --apiver string   API version (default "v3")
  -f, --fmt string      output format (values depends on command)
  -o, --out string      full file path to write the output
      --indent int      indent padding when fmt is 'json' (default 2)
      --timeout int     timeout in seconds (default 120)
      --verbose         verbose output
      --debug           debug mode when error occurs
  -h, --help            help for mobingi

Use "mobingi [command] --help" for more information about a command.
```

To get help for any command, pass the -h flag to the command. For example, to see help about the stack command:

```bash
$ mobingi stack -h
Manage your infrastructure/application stack.                    

Usage:                                                           
  mobingi stack [flags]                                      
  mobingi stack [command]                                    

Available Commands:                                              
  create      create a stack                                     
  delete      delete a stack                                     
  describe    display stack details                              
  list        list all stacks                                    
  pem         print stack pem file                               
  ssh         ssh to your instance                               
  update      update a stack                                     

Flags:                                                           
  -h, --help   help for stack                                    

Global Flags:                                                    
      --apiver string   API version (default "v3")
      --debug           debug mode when error occurs
  -f, --fmt string      output format (values depends on command)
      --indent int      indent padding when fmt is 'json' (default 2)
  -o, --out string      full file path to write the output
      --rurl string     base url for Docker Registry
      --timeout int     timeout in seconds (default 120)
      --token string    access token
      --url string      base url for API
      --verbose         verbose output

Use "mobingi stack [command] --help" for more information about a command.
```


# Global flags

## Global flags

Global flags are all optional and can be applied to any subcommand. You can use '=' or whitespace when assigning a value to the flag. This applies to any command's local flags as well. For example, you can login using any of these commands:

```bash
# Using the '=' for assignment
$ mobingi login --client-id=foo --client-secret=bar
[mobingi]: info: Login successful.

# Using whitespace for assignment
$ mobingi login --client-id foo --client-secret bar
[mobingi]: info: Login successful.
```

`--token`

The access token to use in the command. By default, mobingi will save your access token to the config file after login (see [login](broken://pages/-LYkD7XBUWBJT9opPNML#login) command).

`--url`

The base API url to use in the command. By default, this is set to <https://api.mobingi.com>. You can use this flag if you are hosting your own backend. This is used by devs when testing the cli against the dev and test environments.

`--rurl`

The base registry url to use in the command. This is applicable to Mobingi Registry related commands. By default, this is set to <https://registry.mobingi.com>. This is used by devs when testing the cli against the dev and test environments.

`--apiver`

Specify the API version used in the current command. The default version is v3. The only other supported version is v2.

`--fmt, -f`

Output format of the command. Valid values are: *raw*, *json*. Not all commands support this flag.

`--out, -o`

Full path of the file to write the command output. Not all commands support this flag.

`--indent`

Padding/indentation (or the number of whitespaces to be added) when the output format used is *json*. By default, this is set to 2.

`--timeout`

The timeout value (in seconds) for the command's http request (if applicable). By default, this is set to 120 seconds.

`--verbose`

When set to true, the command will print additional information during the command's execution.

`--debug`

When set to true, the command will print a stack trace when error occurs during the command's execution.


# Commands

### login  <a href="#login" id="login"></a>

Log in to your Mobingi account.

**Flags**

* `--client-id, -i`

  Your Mobingi client id.
* `--client-secret, -s`

  Your Mobingi client secret.
* `--grant-type, -g`

  Grant type. Default value is "password".
* `--username, -u`

  Username. You can use your main (master) account to login as root. Or you can use any subuser name.
* `--password, -p`

  Password
* `--endpoints`

  Setup endpoints after login. If you have a Mobingi dev or qa account(s), you can set this to *dev* or *qa*.

This is the first command you need to run to use the other commands. To login, run

```bash
# Login as root
$ mobingi login --client-id=foo --client-secret=bar \
    --username=master@mobingi.com --password=1234
[mobingi]: info: Login successful.

# Login as subuser
$ mobingi login --client-id=foo --client-secret=bar \
    --username=subuser01 --password=pass
[mobingi]: info: Login successful.

# If you don't want to show your password, remove the --password flag
$ mobingi login --client-id=foo --client-secret=bar --username=subuser01
Password: xxxx
[mobingi]: info: Login successful.
```

If login is successful, cli will create a file `config.yml` under `$HOME/.mobingi/` folder that will contain the configuration values set during login. Cli will also attempt to store your credentials in the platform's native store (i.e. Keychain for OSX), if available. If not successful, the retrieved token during login will be saved in the *config.yml* file. This token has an expiration so you will probably need to relogin at some point when this happens.

For Windows and OSX, cli can use the native credential store directly; wincred for Windows, Keychain for OSX. For Linux, cli uses [pass](https://www.passwordstore.org/) as storage. The following is an example of how to setup pass in Ubuntu systems.

```bash
# Install `pass`
$ sudo apt-get install pass

# Generate your own key using gpg2, do not use a passphrase
$ gpg2 --gen-key

# If the cmd seems stuck due to lack of entropy, you can open
# another window and run the ff cmd:
# $ dd if=/dev/sda of=/dev/zero

# List your keys
$ gpg2 --list-keys
/home/user/.gnupg/pubring.kbx
------------------------------
pub   rsa2048/5486B0F6 2017-09-22 [SC]
uid         [ultimate] IamGroot <iamgroot@mobingi.com>
sub   rsa2048/CDC4C430 2017-09-22 [E]

# Initialize pass (use the pub key id)
$ pass init 5486B0F6

# You can now do a mobingi login ...
```

By default, all endpoints are set to Mobingi production during login. You can use the --endpoints flag to target alternative endpoints. For example, if you have a Mobingi dev account, you can use the following login command:

```bash
$ mobingi login --client-id foo --client-secret bar \
    --username subuser01 --password 1234 --endpoints dev
[mobingi]: info: Login successful.
```

### stack list  <a href="#stack-list" id="stack-list"></a>

List your stacks.

Example:

```bash
$ mobingi stack list
STACK ID      STACK NAME                   PLATFORM     STATUS              ...
mo-xxx-tk     small lunch behave           AWS          CREATE_COMPLETE     ...
mo-xxx-tk     chronic leaflet flourish     AWS          CREATE_COMPLETE     ...
```

### stack describe  <a href="#stack-describe" id="stack-describe"></a>

Describe a stack.

**Flags**

* `--id` - The stack id to describe.

Example:

```bash
$ mobingi stack describe --id mo-58c2297d25645-PxviFSJQV-tk
{
  "auth_token": "...",
  "update_time": "2017-08-30T11:32:42+09:00",
  "user_id": "...",
  "configuration": {
    "description": "This template creates a sample stack with EC2 instance on AWS",
    "label": "template version label #1",
    "version": "2017-03-03",
    "vendor": {
      ...
    },
    "configurations": [
      {
        ...
      }
    ],
    "AWS_ACCOUNT_NAME": "..."
  },
  "nickname": "chronic leaflet flourish",
  "create_time": "2017-08-29T18:47:49+09:00",
  "stack_outputs": [],
  "stack_id": "mo-58c2297d25645-PxviFSJQV-tk",
  "stack_status": "CREATE_COMPLETE",
  "version_id": "jbyW_PxMAauQmOS31dUhij4KIqHAtqW2",
  "instances": []
}
```

### stack create  <a href="#stack-create" id="stack-create"></a>

Create a stack.

**Flags**

* `--alm-template`

  Path to your ALM template. This is required in v3.
* `--vendor`

  Stack vendor. For now, only AWS is supported.
* `--cred`

  Your vendor credential ID. If not set, cli will try to get your list of credentials and use the first one in the list, if not empty.
* `--region`

  Region code. By default, this is set to *ap-northeast-1* (Tokyo).
* `--nickname`

  Your stack's nickname.
* `--arch`

  Stack type. Valid values are: "art\_single", "art\_elb". By default, this is set to "art\_elb".
* `--type`

  Instance type. By default, this is set to *m3.medium*.
* `--image`

  Docker registry path to deploy. If you are using *hub.docker.com*, you can omit the domain part (ex. *grayltc/lamp*). Otherwise, specify the full path (ex. *registry.mobingi.com/wayland/lamp*). By default, this is set to *mobingi/ubuntu-apache2-php7:7.1*.
* `--dhub-user`

  Your Docker hub username if repository is private.
* `--dbuh-pass`

  Your Docker hub password if repository is private.
* `--min`

  Minimum number of instances in your autoscaling group when --arch is set to art\_elb. By default, this is set to 2.
* `--max`

  Maximum number of instances in your autoscaling group when --arch is set to art\_elb. By default, this is set to 10.
* `--spot-range`

  Percentage of spot instance to deploy to autoscaling group. For example, if you have a total of 20 instances running and your spot range is 50 (50%), then there will be a fleet of 10 spot instances and 10 on-demand instances. By default, this is set to 50.
* `--code`

  Your git repository url. This can be updated anytime. By default, this is set to *github.com/mobingilabs/default-site-php*.
* `--code-ref`

  Repository branch. By default, this is set to *master*.
* `--code-privkey`

  Private key if git repository is private.
* `--usedb`

  Set to true if you want to deploy a database.
* `--dbengine`

  Your database engine. Valid values are: "db\_mysql", "db\_postgresql". Requires --usedb flag.
* `--dbtype`

  Database instance/class type. Requires --usedb flag.
* `--dbstorage`

  Database storage in GB. Set between 5 to 6144. Requires --usedb flag.
* `--dbread-replica1`

  Read replica 1. Requires --usedb flag.
* `--dbread-replica2`

  Read replica 2. Requires --usedb flag.
* `--dbread-replica3`

  Read replica 3. Requires --usedb flag.
* `--dbread-replica4`

  Read replica 4. Requires --usedb flag.
* `--dbread-replica5`

  Read replica 5. Requires --usedb flag.
* `--use-elasticache`

  Set to true if you want to use elasticache.
* `--elasticache-engine`

  Either *Redis* or *Memcached*. Requires --use-elasticache flag.
* `--elasticache-nodetype`

  Elasticache node size. For example, *cache.r3.large*. Requires --use-elasticache flag.
* `--elasticache-nodecount`

  If Redis, range is 1 to 6. If Memcached, range is 1 to 20. Requires --use-elasticache flag.

**API v3**

Starting in v3, we create stacks using ALM Templates. Below is an example of a very simple template that creates a single EC2 instance:

```bash
{
  "version": "2017-03-03",
  "label": "template version label #1",
  "description": "This template creates a sample stack with EC2 instance on AWS",
  "vendor": {
    "aws": {
      "cred": "Your AWS Security Key ID",
      "secret": "Your AWS Security Key Secret",
      "region": "ap-northeast-1"
    }
  },
  "configurations": [
    {
      "role": "web",
      "flag": "Single1",
      "provision": {
        "instance_type": "t2.micro",
        "instance_count": 1,
        "keypair": false,
        "subnet": {
          "cidr": "10.0.1.0/24",
          "public": true,
          "auto_assign_public_ip": true
        },
        "availability_zone": "ap-northeast-1c"
      }
    }
  ]
}
```

Example:

```bash
$ mobingi stack create --alm-template=/home/user/aws-single-ec2.json
[mobingi]: info: [201 Created] return payload:
{
  "status": "success",
  "stack_status": "CREATE_IN_PROGRESS",
  "stack_id": "mo-58c2297d25645-GbdINZdY-tk",
  "version_id": "5RnOOvRQ4U52hpY89o_._ArIXgu_xzzg"
}
```

**API v2**

Examples:

```bash
$ mobingi stack create --nickname=sample --apiver=v2
$ mobingi stack create --nickname=sample --min=2 --max=2 --apiver=v2
```

### stack update  <a href="#stack-update" id="stack-update"></a>

Update an existing stack.

**Flags**

* `--alm-template`

  Path to your updated ALM template file. Required in v3.
* `--id`

  The stack id to update.
* `--type`

  Instance type. See stack create command for more information.
* `--min`

  Minimum number of instances in your autoscaling group. See stack create command for more information.
* `--max`

  Maximum number of instances in your autoscaling group. See stack create command for more information.
* `--spot-range`

  Percentage of spot instance to deploy to autoscaling group. See stack create command for more information.

**API v3**

Similar to stack creation, you only need to update some parts of your ALM template to update your stack.

```bash
$ mobingi stack update --id mo-58c2297d25645-q38pTmeey-tk \
      --alm-template /home/user/aws-single_ec2_update.json
[mobingi]: info: [202 Accepted] return payload:
{
  "status": "success",
  "stack_status": "UPDATE_IN_PROGRESS",
  "stack_id": "mo-58c2297d25645-q38pTmeey-tk",
  "version_id": "yypuLitarqIWhMoITLolNOh79fED6QME"
}
```

**API v2**

Examples:

```bash
$ mobingi stack update --id=foo --min=5 --max=20 --apiver=v2
$ mobingi stack update --id=foo --spot-range=25 --apiver=v2
```

### stack delete  <a href="#stack-delete" id="stack-delete"></a>

Delete a stack.

**Flags**

* `--id`

  The stack id to delete.

Example:

```bash
$ mobingi stack delete --id mo-58c2297d25645-GbdINZdY-tk
[mobingi]: info: [200 OK] return payload:
{
  "status": "DELETE_IN_PROGRESS"
}
```

### stack ssh  <a href="#stack-ssh" id="stack-ssh"></a>

Try to establish an ssh connection to your instances.

**Flags**

* `--id`

  The stack id the instance belongs to.
* `--ip`

  The IP address of the instance you want to connect.
* `--flag`

  The configuration flag.
* `--user`

  The ssh username. By default, this is set to *ec2-user*. Set to *root* when vendor is Alibaba Cloud.
* `--browser`

  Try to open the url using the user's default browser.

Examples:

```bash
# open an ssh connection via cli
$ mobingi stack ssh --id mo-58c2297d25645-Sd2aHRDq0-tk \
    --ip 54.238.234.202 --flag web01
[ec2-user@ip-10-0-1-96 ~]$ pwd
/home/ec2-user
[ec2-user@ip-10-0-1-96 ~]$ exit
logout
Connection to 54.238.234.202 closed.

# open an ssh connection using default browser
$ mobingi stack ssh --id mo-58c2297d25645-Sd2aHRDq0-tk \
    --ip 54.238.234.202 --flag web01 --browser
[mobingi]: info: open link with a browser (if not opened automatically): \
https://sesha3.mobingi.com:port/some-random-link/
```

### stack exec  <a href="#stack-exec" id="stack-exec"></a>

Try to execute a bash script to one or more instances.

**Flags**

* `--target`

  The target instance to execute the script. The format is stack-id|ip:flag. This flag can be specified more than once.
* `--script`

  The script file to execute.

Examples:

```bash
# For example, we have a script with the following contents
# (stored in home folder as test.sh):
#!/bin/bash
pwd
uname -a
env

# run the script on a single instance
$ mobingi stack exec \
    --target "mo-58c2297d25645-rkIEPmust-tk|root@47.74.5.170:Single" \
    --script ~/test.sh
[mobingi]: info: [0]output: mo-58c2297d25645-rkIEPmust-tk, instance: ...
/root
Linux iZ6weeq9e4ktok8f9o2910Z 3.10.0-514.26.2.el7.x86_64 #1 ...
XDG_SESSION_ID=43623
SHELL=/bin/bash
SSH_CLIENT=54.238.178.1 45328 22
USER=root
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
MAIL=/var/mail/root
PWD=/root
LANG=en_US.UTF-8
HOME=/root
SHLVL=2
LOGNAME=root
SSH_CONNECTION=54.238.178.1 45328 10.1.0.106 22
LESSOPEN=||/usr/bin/lesspipe.sh %s
XDG_RUNTIME_DIR=/run/user/0
_=/usr/bin/env

# run the same script to an aws ec2 instance and an alibabacloud vm
$ mobingi stack exec \
    --target "mo-58c2297d25645-rkIEPmust-tk|root@47.74.5.170:Single" \
    --target "mo-58c2297d25645-M5EIHEaOC-tk|ec2-user@13.230.9.8:web0" \
    --script ~/test.sh
[mobingi]: info: [0]output: mo-58c2297d25645-rkIEPmust-tk, instance: ...
/root
Linux iZ6weeq9e4ktok8f9o2910Z 3.10.0-514.26.2.el7.x86_64 #1 ...
XDG_SESSION_ID=43631
SHELL=/bin/bash
SSH_CLIENT=54.238.178.1 45386 22
USER=root
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
MAIL=/var/mail/root
PWD=/root
LANG=en_US.UTF-8
HOME=/root
SHLVL=2
LOGNAME=root
SSH_CONNECTION=54.238.178.1 45386 10.1.0.106 22
LESSOPEN=||/usr/bin/lesspipe.sh %s
XDG_RUNTIME_DIR=/run/user/0
_=/usr/bin/env

[mobingi]: info: [1]output: mo-58c2297d25645-M5EIHEaOC-tk, instance: ...
/home/ec2-user
Linux ip-10-0-1-63 4.9.51-10.52.amzn1.x86_64 #1 ...
LESS_TERMCAP_mb=
LESS_TERMCAP_md=
LESS_TERMCAP_me=
SHELL=/bin/bash
SSH_CLIENT=54.238.178.1 37174 22
EC2_AMITOOL_HOME=/opt/aws/amitools/ec2
LESS_TERMCAP_ue=
USER=ec2-user
EC2_HOME=/opt/aws/apitools/ec2
LESS_TERMCAP_us=
PATH=/usr/local/bin:/bin:/usr/bin:/opt/aws/bin
MAIL=/var/mail/ec2-user
PWD=/home/ec2-user
JAVA_HOME=/usr/lib/jvm/jre
LANG=en_US.UTF-8
AWS_CLOUDWATCH_HOME=/opt/aws/apitools/mon
HOME=/home/ec2-user
SHLVL=2
AWS_PATH=/opt/aws
AWS_AUTO_SCALING_HOME=/opt/aws/apitools/as
LOGNAME=ec2-user
SSH_CONNECTION=54.238.178.1 37174 10.0.1.63 22
AWS_ELB_HOME=/opt/aws/apitools/elb
LESSOPEN=||/usr/bin/lesspipe.sh %s
LESS_TERMCAP_se=
_=/bin/env
```

### stack pem  <a href="#stack-pem" id="stack-pem"></a>

Print the stack's pem file (and save to file optionally), if available. Useful if you want to connect to your instances using other tools.

**Flags**

* `--id`

  The stack id to query.
* `--flag`

  The configuration flag.

Example:

```bash
# print pem file
$ mobingi stack pem --id mo-58c2297d25645-Sd2aHRDq0-tk --flag web01
[mobingi]: info: payload:
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAiy5kdqROYbjke0BE8rcT7qUtSKyaaIgqiJLYxlduov2wvnRHSo5O8m67v8UD
Pkxz4fR/gQXYcpV4/T/3zqTVaGcVNK8ZCE1jRfKt/5QFQkPOJRkDWZZzQqSwUMhnMiK1iE+33fmp
ITvktdL9OMT0RXjZ4qKq+aifaY9D0XzbR3HWLFcWZ+0tmzUTJDM8F6LivsPUjR8uitiic7KXvlDV
...
-----END RSA PRIVATE KEY-----

# print pem file and save to home directory as test.pem
$ mobingi stack pem --id mo-58c2297d25645-Sd2aHRDq0-tk --flag web01 --out ~/test.pem
[mobingi]: info: payload:
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAiy5kdqROYbjke0BE8rcT7qUtSKyaaIgqiJLYxlduov2wvnRHSo5O8m67v8UD
Pkxz4fR/gQXYcpV4/T/3zqTVaGcVNK8ZCE1jRfKt/5QFQkPOJRkDWZZzQqSwUMhnMiK1iE+33fmp
ITvktdL9OMT0RXjZ4qKq+aifaY9D0XzbR3HWLFcWZ+0tmzUTJDM8F6LivsPUjR8uitiic7KXvlDV
...
-----END RSA PRIVATE KEY-----

# you can now use ssh tool to connect your instance
$ ssh -i ~/test.pem user@ipaddr
```

### template versions  <a href="#template-versions" id="template-versions"></a>

List available template versions of a stack.

**Flags**

* `--id`

  The stack id owning the template versions to be listed.

Example:

```bash
# list stacks first to get the stack id
$ mobingi stack list
STACK ID      STACK NAME                   PLATFORM     STATUS              ...
mo-xxx-tk     small lunch behave           AWS          CREATE_COMPLETE     ...
mo-xxx-tk     chronic leaflet flourish     AWS          CREATE_COMPLETE     ...
# then list the template versions
$ mobingi template versions --id mo-58c2297d25645-PxviFSJQV-tk
VERSION ID                           LATEST     LAST MODIFIED                     SIZE
jbyW_PxMAauQmOS31dUhij4KIqHAtqW2     true       Wed, 30 Aug 2017 02:32:43 UTC     472
1xoPd.cg3juHK94vC8IdUh1bexx7sQ1T     false      Tue, 29 Aug 2017 09:47:50 UTC     453
```

### template compare  <a href="#template-compare" id="template-compare"></a>

Compare two template versions.

You can compare template versions from the same stack, versions from different stacks, or a local template file to a specific template version.

**Flags**

* `--src-sid`

  The stack id of the first (or source) template. This flag is required.
* `--src-vid`

  The version id of the first (or source) template. This flag is required.
* `--tgt-sid`

  The stack id of the second (or target) template. If not set, cli will assume you are comparing templates of the same stack.
* `--tgt-vid`

  The version id of the second (or target) template. This flag is required if you are not providing the --tgt-body flag.
* `--tgt-body`

  Path of the template file you want to compare to the first (or source) template. If you set this flag, do not set the --tgt-sid and the --tgt-vid flags as they are ignored.

Example:

```bash
# using the examples above
$ mobingi template compare --src-sid mo-58c2297d25645-PxviFSJQV-tk \
      --src-vid jbyW_PxMAauQmOS31dUhij4KIqHAtqW2 \
      --tgt-vid 1xoPd.cg3juHK94vC8IdUh1bexx7sQ1T
[mobingi]: info: diff:
{
  "new": [],
  "removed": [],
  "edited": {
    "label": {
      "oldvalue": "template version label #1",
      "newvalue": "template version label #1 (update)"
    },
    "description": {
      "oldvalue": "Creates a sample stack with EC2 instance on AWS",
      "newvalue": "Creates a sample stack with EC2 instance on AWS (update)"
    },
    "configurations\/provision\/instance_type": {
      "oldvalue": "t2.micro",
      "newvalue": "m3.medium"
    },
    "configurations\/provision\/instance_count": {
      "oldvalue": 1,
      "newvalue": 2
    }
  }
}
```

### rbac describe  <a href="#rbac-describe" id="rbac-describe"></a>

List all defined role(s) or per-user role(s). Only your root account has the permissions to run this command.

If --user is not provided, this command will list all defined roles.

**Flags**

* `--user`

  Subuser name. Optional.

### rbac sample  <a href="#rbac-sample" id="rbac-sample"></a>

Print a sample role.

This is useful when creating roles and you want something to start with. You can use this command to write to a file (using the --out global flag), edit the contents and use the file for role creation.

Example:

```bash
$ mobingi rbac sample --out=/home/user/sample.json
{
  "Version": "2017-05-05",
  "Statement": [
    {
      "Effect": "Deny",
      "Action": [
        "stack:describeStacks"
      ],
      "Resource": [
        "mrn:alm:stack:mo-xxxxxxx"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "*"
      ],
      "Resource": [
        "*"
      ]
    }
  ]
}
[mobingi]: info: sample written to /home/user/sample.json
```

### rbac create  <a href="#rbac-create" id="rbac-create"></a>

Define a role.

**Flags**

* `--type`

  Create type. Valid values are *role* and *user*. Default is *role*.
* `--name`

  Role name when --type is *role*.
* `--scope`

  Path to role file.
* `--allow-all`

  When set to true, --scope is ignored, the resulting role will allow all actions to all resources.

Example:

```bash
# use the sample generated in the previous command
$ mobingi rbac create --name testrole --scope /home/user/sample.json
[mobingi]: info: 200 OK
{
  "status":"success",
  "role_id":"morole-58c2297d25645-F6HUEJG57"
}
```

### rbac attach  <a href="#rbac-attach" id="rbac-attach"></a>

Attach a role to a user.

**Flags**

* `--user`

  The subuser name to attach the role to.
* `--role-id`

  The role id to attach.

Example:

```bash
$ mobingi rbac attach --user subuser --role-id morole-58c2297d25645-BtXGMSRsI
[mobingi]: info: 200 OK
{
  "status": "success",
  "user_role_id": "mour-subuser-icxUQ91SO"
}
```

### rbac delete  <a href="#rbac-delete" id="rbac-delete"></a>

Delete a role.

**Flags**

* `--role-id`

  The role id to delete. You can get the role id from the *describe* command.

### svrconf show  <a href="#svrconf-show" id="svrconf-show"></a>

Show a stack's serverconfig (server configuration) contents. Starting from v3, server config options are replaced by ALM templates. The following commands are still valid for v2.

**Flags**

* `--id`

  The stack id to query.

Example:

```bash
$ mobingi svrconf show --id=foo --apiver=v2
```

### svrconf update  <a href="#svrconf-update" id="svrconf-update"></a>

Update a stack's serverconfig (server configuration).

**Flags**

* `--id`

  The stack id to update.
* `--env` A comma-separated key/value pair(s) for environment variables. If you have whitespaces in the input, enclose it with double quotes. You can also set this flag to "null" to clear all environment variables.
* `--filepath`

  New filepath value if you want to update your filepath.

Examples:

```bash
# env examples
$ mobingi svrconf update --id=foo \
    --env=KEY1:value1,KEY2:value2,KEYx:valuex --apiver=v2
$ mobingi svrconf update --id=foo \
    --env="KEY1: value1, KEY2: value2, KEYx: valuex" --apiver=v2
$ mobingi svrconf update --id=foo --env=null --apiver=v2
# filepath example
$ mobingi svrconf update --id=foo \
    --filepath=git://github.com/mobingilabs/default --apiver=v2
```

Note that when you provide update options simultaneously (for example, you provide `--env=FOO:bar` and `--filepath=test` at the same time), the tool will send each option as a separate request.

### creds list  <a href="#creds-view" id="creds-view"></a>

List vendor credentials.

**Flags**

* `--vendor`

  The vendor to list credentials. Valid values: *aws*, *alicloud*. Default value is *aws*.

Examples:

```bash
$ mobingi creds list
VENDOR     ID                       ACCOUNT     LAST MODIFIED
aws        xxxxxxxxxxxxxxxxxxxx     user        Wed, 05 Jul 2017 07:52:14 UTC
```

### registry catalog  <a href="#registry-list-catalog" id="registry-list-catalog"></a>

List images under logged in username.

This command is inherently slow.

Registry related commands will use the login user/password credentials, if native store is supported. Otherwise, you will have to provide the user/password credentials using the --username and --password flags.

**Flags**

* `--username`

  Username (Mobingi account subuser)
* `--password`

  Password (Mobingi account subuser)
* `--service`

  Authentication service. By default, this is set to "Mobingi Docker Registry".
* `--scope`

  Authentication scope. See <https://docs.docker.com/registry/spec/auth/scope/> for more information on scopes.

Examples:

```bash
# user/password credentials are stored in native store
$ mobingi registry catalog
[mobingi]: info: Catalog list for user: subuser01
subuser01/foo

# no native store support
$ mobingi registry catalog --username=subuser01 --password=xxxxxx
[mobingi]: info: Catalog list for user: subuser01
subuser01/foo
```

### registry tags  <a href="#registry-list-tags" id="registry-list-tags"></a>

List image tags.

**Flags**

* `--username`

  Username (Mobingi account subuser)
* `--password`

  Password (Mobingi account subuser)
* `--service`

  Authentication service. By default, this is set to "Mobingi Docker Registry".
* `--scope`

  Authentication scope. See <https://docs.docker.com/registry/spec/auth/scope/> for more information on scopes.
* `--image`

  Image name to list.

Example:

```bash
$ mobingi registry tags --image foo
IMAGE                   TAG
subuser01/foo           latest
subuser01/foo           2.1
```

### registry manifest  <a href="#registry-tag-manifest" id="registry-tag-manifest"></a>

Display a tag's manifest.

**Flags**

* `--username`

  Username (Mobingi account subuser)
* `--password`

  Password (Mobingi account subuser)
* `--service`

  Authentication service. By default, this is set to "Mobingi Docker Registry".
* `--scope`

  Authentication scope. See <https://docs.docker.com/registry/spec/auth/scope/> for more information on scopes.
* `--image`

  Image tag to query. Format is *image:tag*.

Example:

```bash
$ mobingi registry manifest --image foo:latest
{
   "schemaVersion": 1,
   "name": "subuser01/foo",
   "tag": "latest",
   "architecture": "amd64",
   "fsLayers": [
      {
         "blobSum": "sha256:a3ed95caeb02ffe68..."
      },
      ...
   ],
   "history": [
      {
         "v1Compatibility": "..."
      },
      ...
   ],
   "signatures": [
      {
         "header": {
            "jwk": {
               ...
            },
            "alg": "ES256"
         },
         "signature": "...",
         "protected": "..."
      }
   ]
}
```

### command: registry delete  <a href="#registry-tag-delete" id="registry-tag-delete"></a>

Delete a tag.

**Flags**

* `--username`

  Username (Mobingi account subuser)
* `--password`

  Password (Mobingi account subuser)
* `--service`

  Authentication service. By default, this is set to "Mobingi Docker Registry".
* `--scope`

  Authentication scope. See <https://docs.docker.com/registry/spec/auth/scope/> for more information on scopes.
* `--image`

  Image tag to query. Format is *image:tag*.

Example:

```bash
$ mobingi registry delete --username=subuser1 --password=xxxxxx \
      --image=foo:latest --apiver=v2
```

### registry token  <a href="#registry-get-token" id="registry-get-token"></a>

Get an access token for Mobingi Docker Registry access.

**Flags**

* `--username`

  Username (Mobingi account subuser)
* `--password`

  Password (Mobingi account subuser)
* `--service`

  Authentication service. By default, this is set to "Mobingi Docker Registry".
* `--scope`

  Authentication scope. See <https://docs.docker.com/registry/spec/auth/scope/> for more information on scopes.

Example:

```bash
$ mobingi registry token \
      --username=foo \
      --password=bar \
      --service="Mobingi Docker Registry" \
      --scope="repository:foo/container:*"
```

This is useful when you want to access the registry directly using other tools. For example, you can use the token when using Docker Registry API via `curl`.

```bash
$ curl -H "Authorization: Bearer token" \
      -H "Accept application/vnd.docker.distribution.manifest.v2+json" \
      https://registry.mobingi.com/v2/foo/container/manifests/latest
```

### reset  <a href="#reset" id="reset"></a>

Reset all configuration values to default. It will also delete all credential information stored in the platform's native store.

Example:

```bash
$ mobingi reset
$ cat ~/.mobingi-cli/config.yml
access_token: ""
api_url: https://api.mobingi.com
registry_url: https://registry.mobingi.com
api_version: v3
indent: 2
timeout: 120
verbose: false
debug: false
```

### version  <a href="#version" id="version"></a>

Prints the cli version.

```bash
$ mobingi version
v0.2.3-beta
```


# What is ALM?

Mobingi Documentation

{% hint style="warning" %}
This product is already deprecated.
{% endhint %}

## What is ALM?

### What is ALM?

ALM (*Application Lifecycle Management*) is Mobingi's product offering that helps you manage the whole lifecycle of your application from provisioning to different cloud providers to application deployment and monitoring. At the moment, we support the following cloud providers:

* [Amazon Web Services (AWS)](/v3.0-english/getting-started/adding-aws-account)
* [Microsoft Azure](/v3.0-english/getting-started/adding-azure-account)
* [Alibaba Cloud](/v3.0-english/getting-started/adding-alibaba-account)
* [Google Cloud Platform](/v3.0-english/getting-started/adding-gcp-account)
* [Fujitsu K5](/v3.0-english/getting-started/adding-fujitsu-k5-account)

We provide an [easy-to-use Web UI](https://alm.mobingi.com) for you to manage your infrastructure and deployments from the comfort of your browser. If you prefer a little bit of customization, please have a look at our [ALM Template](https://docs.mobingi.com/mobingi-alm/alm-template/what-is-alm-template) documentation.

For more information, please visit <https://mobingi.com/products/alm>.


# Getting started

{% content-ref url="/pages/-LYkD7Wl2D8HRr27lQfr" %}
[Login for the first time](/v3.0-english/getting-started/login-for-the-first-time)
{% endcontent-ref %}

{% content-ref url="/pages/-LYkD7WmyLmTdPEovBpX" %}
[Adding AWS account](/v3.0-english/getting-started/adding-aws-account)
{% endcontent-ref %}

{% content-ref url="/pages/-LYkD7Wnyrh5UWxRrw0w" %}
[Adding Azure account](/v3.0-english/getting-started/adding-azure-account)
{% endcontent-ref %}

{% content-ref url="/pages/-LYkD7Wou1UWnrwQIJsb" %}
[Adding Alibaba account](/v3.0-english/getting-started/adding-alibaba-account)
{% endcontent-ref %}

{% content-ref url="/pages/-LYkD7WpIAaAxhkHgbod" %}
[Adding GCP account](/v3.0-english/getting-started/adding-gcp-account)
{% endcontent-ref %}

{% content-ref url="/pages/-LYkD7WqlUSNvHqd3Prw" %}
[Adding Fujitsu K5 account](/v3.0-english/getting-started/adding-fujitsu-k5-account)
{% endcontent-ref %}


# Login for the first time

## Provide your Cloud Account Credentials

Before you can use the software, you need to setup your vendor credentials first. For tutorials on steps to finding and providing credentials, please refer to each cloud vendor's references in the side menu.

## Create Roles & User Accounts

Mobingi ALM Enterprise Edition provides multiple user accounts accessibility and collaboration modules. You start with creating ALM user accounts that will be used for log in to ALM console. Users can collaborate on provisioning, deploying or monitoring resources on your cloud account. You should also assign them roles to limit the actions for each individual user account (or groups) on accessing certain resources which you want to protect by [RBAC](https://docs.mobingi.com/mobingi-alm/rbac/overview).


# Adding AWS account

{% embed url="<https://www.youtube.com/watch?v=VM-f8ov_Gy8&t=1s>" %}


# Adding Azure account

{% hint style="info" %}
To complete the instructions, you’ll need an Azure subscription. If you don’t already have one, you can sign up for an account [here](https://azure.microsoft.com/ja-jp/).
{% endhint %}

Microsoft Azure requires the credentials below to allow access to specific Azure resources.

1. Application ID
2. Secret Access key
3. Subscription ID
4. Directory ID

As a prerequisite, you must have sufficient permissions in both your Azure Active Directory and your Azure subscription. Specifically, you must be able to create an app in the Active Directory, and assign a role to the service principal.[(Check Permission)](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal#required-permissions)

## Using [Azure portal](https://portal.azure.com)  to create necessary credentials

{% hint style="warning" %}
If you already have the *Application ID*, *Secret Access key*, *Subscription ID*, *Directory ID*, you can skip to [**Adding Azure credential to your ALM account**](/v3.0-english/getting-started/adding-azure-account#adding-azure-credential-to-your-alm-account) section.
{% endhint %}

● [Create an Azure Active Directory application](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal#create-an-azure-active-directory-application)

● [Get Created Application ID and Add authentication key](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal#create-an-azure-active-directory-application)

● [Get Tenant ID(Your tenant ID is your Directory ID)](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal#get-tenant-id)

● [Assign application to role/subscription](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal#assign-application-to-role)

## Adding Azure credential to your ALM account

{% hint style="info" %}
If you do not have yet a Mobingi ALM account, you can sign up [here](https://mobingi.com/products/alm/pricing?hsCtaTracking=83291ee6-f70a-486a-909c-ed2bcca0629b|7cb2af36-bc9f-49f1-8e3f-f3848b2c5295) or [contact us](https://pages.mobingi.com/form-general?hsCtaTracking=0f1d2eb6-a1fc-4c4b-ab8e-934ffd3e8e94|504bc5ea-bcd0-4ae1-ba28-a6ec174cb93a).
{% endhint %}

1. After logging-in to your [Mobingi ALM](https://alm.mobingi.com/login) account, in the upper right corner of the page click your `username` and then `General Settings`

![](/files/-LF188m7PblnhbVAU5qs)

1. In the left side-menu, click `Setup Credentials` and select `Azure`

![](/files/-LF1L7GLNMALXEowEMzY)

1. Enter your preferred account name and the `Application ID`, `Secret Access Key`, `Subscription ID`, `Directory ID` you created in the ***Using*** [***Azure portal***](https://portal.azure.com) ***to create necessary credentials*** section and click ***Add Account*** button

![](/files/-LF18mn-Pp6L6u6VcPbi)

{% hint style="success" %}
Your credential is added at the bottom of the page.
{% endhint %}

![](/files/-LEhy117ZwU68Uvkyedu)


# Adding Alibaba account

ALM requires the credentials below to allow access to specific Alibaba Cloud resources.

* AccessKeyID
* AccessKeySecret

We recommend you to use RAM user as Alibaba Cloud credentials to ALM. To create a RAM user, please follow the steps below:

**Step 1**: Log into your Alibaba Cloud console and find "Resource Access Management (RAM)" section, create the policy.

The contents of the policy can be checked on ALM:

![](/files/-LEr0BJsxPuu01-0yPXM)

Copy the above the policy contents and create the policy on Alibaba Cloud console:

![](/files/-LEr4_GLpSqG53oRJQ0A)

**Step 2**: Create the RAM user and attach the policy.

Create the RAM user:

![](/files/-LEr5US0uF5KvNUQM528)

Attach the previously created policy to the RAM user:

![](/files/-LEr6CGbzMed4C97h-ZH)

**Step 3**: Create an access key and enter it on ALM.

![](/files/-LEr8GVhU-_zjxcf31BG)

![](/files/-LEr9dpPdbnWS_opiTn8)


# Adding GCP account

We recommend you to use [service accounts](https://cloud.google.com/compute/docs/access/service-accounts) as GCP credentials to ALM. To create a service account, please follow the steps below:

Go to "Service accounts" menu under "IAM & admin" section of Google Cloud Platform's main menu. Click "CREATE SERVICE ACCOUNT" button.

![](/files/-LEOrS_JMG5IMRLIkDuC)

Give it a name and make sure the following permissions are added:

* Editor
* Deployment Manager Editor

Make sure to check "Furnish a new private key" with JSON as option. You will be prompted to download and save the file. Save it to a safe location.

![](/files/-LEOswqCbUvuAKiE_mvw)

Now go to [ALM's "General Settings"](https://alm.mobingi.com/settings/account) menu and go "Setup Credentials". Select GCP and fill up the required fields. Under "Service Account" field, copy and paste all the contents of the Service Account JSON file you created from the previous steps.

![](/files/-LESuy109B07QjDZCpFp)


# Adding Fujitsu K5 account

Setting up Fujitsu K5 account on Mobingi ALM is different from AWS nor Alibaba Cloud. Instead of providing Access Key ID and Access Key Secret, you enter Fujitsu K5 username, password and contract number.

**Step 1**: Log into your Fujitsu K5 portal and find "User Management" section, create the user with necessary roles.

![](/files/-LEOVd5YUpQMkrUG6XwQ)

**Step 2**: Head back to Mobingi ALM console and enter your Fujitsu K5's username, password and contract number, then hit "Add Account" button.

![](/files/-LEOVlvZfJ66djFXckID)


# ALM Template

{% content-ref url="/pages/-LYkD7WscylhdJDEzh6j" %}
[What is ALM Template?](/v3.0-english/alm-template/what-is-alm-template)
{% endcontent-ref %}

{% content-ref url="/pages/-LYkD7WuE6Dtnx0IDnif" %}
[Reference (2017-03-03)](/v3.0-english/alm-template/reference-2017-03-03)
{% endcontent-ref %}

{% content-ref url="/pages/-LYkD7WvqibNGZ-14NYn" %}
[ALM Template Language](/v3.0-english/alm-template/alm-template-language)
{% endcontent-ref %}

{% content-ref url="/pages/-LYkD7WwJwufwRstBisp" %}
[Example ALM Templates](/v3.0-english/alm-template/example-alm-templates)
{% endcontent-ref %}


# What is ALM Template?

{% hint style="info" %}
We are in the process of updating the current template to a new version suited for multi-application, multi-stack, and multi-vendor deployments. It will be a YAML-based template (although JSON is also supported). We will be releasing these new features in the coming months. Stay tuned!
{% endhint %}

## What is ALM Template?

### Concepts  <a href="#concepts" id="concepts"></a>

* ALM Template is a JSON-formatted configuration file which defines your cloud-native application's architecture design and runtime configuration.
* ALM Template is cloud platform agnostic. You write your template once and it works on any cloud platforms such as AWS, GCP, Azure, AliCloud, etc.
* You can save and reuse ALM Templates at anytime.

## How does it work

ALM Template is a component of [ALM](https://mobingi.com/how-mobingi-alm-works). You write your ALM Template in code blocks and paste it on ALM console (or through CLI, or API) and it will be converted into each cloud platform's native configuration standards, then ALM will provision all resources on your behalf.

If you specify the runtime configurations of your application in the `container` section of the ALM Template, then ALM will also deploy an [ALM-agent](https://docs.mobingi.com/mobingi-alm/alm-agent) on each provisioned node to perform application runtime setup and continuous code deployment.

## ALM Template formats

ALM Template is designed in JSON format. You can also write your template in YAML format and then convert it into JSON file when you deploy your stacks on ALM UI (or through CLI, or API).

{% hint style="info" %}
Official YAML format support is in-progress.
{% endhint %}

## ALM Template components

ALM Template top-level components consist of `version`, `label`, `description`, `vendor`, `configurations`. For more information about these components, see the reference section.


# Reference (2017-03-03)

## Template structure

Below is a tree view of all possible components within an ALM Template. The following structure is not a working demo template, but rather to explain all possible key names that may contain in the template body.

```yaml
version: string
label: string
description: string
vendor: object
  aws: object
  azure: object
  gcp: object
  alicloud: object
  k5: object
configurations: array of objects
  role: string
  flag: string
  provision: object
    vpc_id: string
    availability_zone: string
    instance_type: string
    image: string
    instance_count: number
    volume_type: string
    volume_size: number
    keypair: boolean
    subnet: object
    security_group: object
    network_acl: object
    load_balancer: object
    auto_scaling: object
  container: object
    container_image: string
    container_registry_username: string
    container_registry_password: string
    container_code_dir: string
    container_code_repo: string
    container_git_reference: string
    container_git_private_key: string
    container_ports: array of numbers
    container_users: object
    container_env_vars: object
```

## version

The version of ALM Template release. This value is always **2017-03-03**.

## label

The label of the ALM Template. You can use this section to mark the labels for each of your ALM Template versions. This is useful when you update your template. This value can be empty, and you can write up to 64 characters in length.

## description

The description of the ALM Template. You can use this section to describe the purpose of the ALM Template. For example: production app stack. This value can be empty, and you can write up to 255 characters in length.

## vendor

The cloud platform vendor of which the template will be deployed to. You need to specify the vendor in every ALM Template you write, and can only specify one vendor at a time.

Valid values:

{% tabs %}
{% tab title="AWS" %}
cre&#x64;*: ALM credential name created under AWS vendor*\
regio&#x6E;*: vendor region for your deployment*

```yaml
"vendor": {
    "aws": {
      "cred": "change this to your AWS Security Key ID",
      "region": "ap-northeast-1"
    }
}
```

{% endtab %}

{% tab title="AZURE" %}
cre&#x64;*: ALM credential name created under Azure vendor*\
regio&#x6E;*: vendor region for your deployment*

```yaml
"vendor": {
    "azure": {
      "cred": "your-credential-name-in-alm",
      "region": "japaneast"
    }
}
```

{% endtab %}

{% tab title="ALIBABA CLOUD" %}
cre&#x64;*: ALM credential name created under Alibaba cloud vendor*\
regio&#x6E;*: vendor region for your deployment*

```yaml
"vendor": {
    "alicloud": {
      "cred": "your-credential-name-in-alm",
      "region": "ap-northeast-1"
    }
 }
```

{% endtab %}

{% tab title="GCP" %}
cre&#x64;*: ALM credential name created under AWS vendor*\
regio&#x6E;*: vendor region for your deployment*\
project\_i&#x64;*: your GCP project id*

```yaml
 "vendor": {
    "gcp": {
       "cred": "your-credential-name-in-alm",
       "region": "asia-northeast1",
       "project_id": "GCP-project-id"
      }
  }
```

{% endtab %}

{% tab title="K5" %}
*Not yet supported in this document.*
{% endtab %}
{% endtabs %}

## configurations

The configurations of the stack which ALM Template is about to deploy. In the configurations section, you specify one or multiple configuration layers of your application's provision and container runtime settings. Inside each layer, there are four sections you need to specify:

### **role**

The "role" of which the stack layer defines to.

You deploy multiple layers within one ALM Template, for example two *web* layers, one *bastion* layer and one *database* layer. The current available role names:

* `web`
* `bastion`

### **flag**

The unique identifier of each layer.

You must specify the *flag* name for each configuration layer. The value must between 4 to 18 characters in length and contains only alphanumeric characters.

### provision

The infrastructure provisioning configurations.

#### vpc\_id

Reserved key name, not supported yet.

Currently, a new VPC will be created with every ALM Template execution and the default VPC has a fixed CIDR range of **10.0.0.0/16** and you cannot customize it at the moment, so when you specifying your subnets please make sure the CIDR setting for your subnets are sitting within the VPC CIDR range.

For GCP, all deployments use the region's default public network. For GCP's predefined network ranges, you can refer to this [page](https://cloud.google.com/vpc/docs/vpc#ip-ranges).

#### availability\_zone

| Type   | Required | Description                                                                                            |
| ------ | -------- | ------------------------------------------------------------------------------------------------------ |
| string | Yes      | The availability zone of which the stack deploys to. You must specify this value in your ALM Template. |

Valid values:

{% tabs %}
{% tab title="AWS" %}

```yaml
"availability_zone": "ap-northeast-1c"
```

Below are the valid availability zones for each regions on AWS.

```
    (North Virginia)
    us-east-1a
    us-east-1b
    us-east-1c
    us-east-1d
    us-east-1e

    (Ohio)
    us-east-2a
    us-east-2b
    us-east-2c

    (North Carolina)
    us-west-1b
    us-west-1c

    (Oregon)
    us-west-2a
    us-west-2b
    us-west-2c

    (Canada)
    ca-central-1a
    ca-central-1b

    (Ireland)
    eu-west-1a
    eu-west-1b
    eu-west-1c

    (Frankfurt)
    eu-central-1a
    eu-central-1b

    (London)
    eu-west-2a
    eu-west-2b

    (Singapore)
    ap-southeast-1a
    ap-southeast-1b

    (Sydney)
    ap-southeast-2a
    ap-southeast-2b
    ap-southeast-2c

    (Seoul)
    ap-northeast-2a
    ap-northeast-2c

    (Tokyo)
    ap-northeast-1a
    ap-northeast-1c

    (Mumbai)
    ap-south-1a
    ap-south-1b

    (Sao Paulo)
    sa-east-1a
    sa-east-1b
    sa-east-1c
```

{% endtab %}

{% tab title="AZURE" %}

```yaml
"availability_zone": "ap-northeast-1c"
```

Below are the valid availability zones for Azure.

```c
AustraliaEast
AustraliaSoutheast
BrazilSouth
CanadaCentral
CanadaEast
CentralIndia
CentralUs
ChinaEast
ChinaNorth
EastAsia
EastUs
EastUs2
GermanyCentral
GermanyNortheast
JapanEast
JapanWest
KoreaCentral
KoreaSouth
NorthCentralUs
NorthEurope
SouthCentralUs
SoutheastAsia
SouthIndia
UkSouth
UkWest
WestCentralUs
WestEurope
WestIndia
WestUs
WestUs2
```

{% endtab %}

{% tab title="ALIBABA CLOUD" %}

```
"availability_zone": "ap-northeast-1"
```

{% endtab %}

{% tab title="GCP" %}
Example:

```yaml
"availability_zone": "asia-northeast1-a"
```

You can refer to this [page](https://cloud.google.com/compute/docs/regions-zones/) for supported availability zones in GCP.
{% endtab %}

{% tab title="K5" %}

```yaml
"availability_zone": "ap-northeast-1"
```

{% endtab %}
{% endtabs %}

#### instance\_type

The type of instances (**VM**s). If value is not provided in the template, the default values will be used for each cloud platform.

Valid values:

{% tabs %}
{% tab title="AWS" %}
Default: t2.micro

```yaml
"instance_type": "t2.micro"
```

Below are the valid instance types for AWS.

```
    t2.nano
    t2.micro [default]
    t2.small
    t2.medium
    t2.large
    t2.xlarge
    t2.2xlarge
    m4.large
    m4.xlarge
    m4.2xlarge
    m4.4xlarge
    m4.10xlarge
    m4.16xlarge
    m3.medium
    m3.large
    m3.xlarge
    m3.2xlarge
    c5.large
    c5.xlarge
    c5.2xlarge
    c5.4xlarge
    c5.9xlarge
    c5.18xlarge
    c4.large
    c4.xlarge
    c4.2xlarge
    c4.4xlarge
    c4.8xlarge
    c3.large
    c3.xlarge
    c3.2xlarge
    c3.4xlarge
    c3.8xlarge
    x1.16large
    x1.32xlarge
    x1e.xlarge
    x1e.2xlarge
    x1e.4xlarge
    x1e.8xlarge
    x1e.16xlarge
    x1e.32xlarge
    r4.large
    r4.xlarge
    r4.2xlarge
    r4.4xlarge
    r4.8xlarge
    r4.16xlarge
    r3.large
    r3.xlarge
    r3.2xlarge
    r3.4xlarge
    r3.8xlarge
    p3.2xlarge
    p3.8xlarge
    p3.16xlarge
    p2.xlarge
    p2.8xlarge
    p2.16xlarge
    g3.4xlarge
    g3.8xlarge
    g3.16xlarge
    f1.2xlarge
    f1.16xlarge
    i3.large
    i3.xlarge
    i3.2xlarge
    i3.4xlarge
    i3.8xlarge
    i3.16large
    d2.xlarge
    d2.2xlarge
    d2.4xlarge
    d2.8xlarge
```

{% endtab %}

{% tab title="ALIBABA CLOUD" %}
Default: xn4.small.

```yaml
    "instance_type": "xn4.small"
```

{% endtab %}

{% tab title="AZURE" %}
Default: Standard\_B1s.

```yaml
    "instance_type": "Standard_B1s"
```

{% endtab %}

{% tab title="GCP" %}
Default type: `n1-standard-1`

Refer to this [page](https://cloud.google.com/compute/docs/machine-types) for information on GCP machine types.
{% endtab %}

{% tab title="K5" %}
Default: 1101.

```yaml
    "instance_type": "1101"
```

{% endtab %}
{% endtabs %}

#### image

| Type   | Required | Description                                         |
| ------ | -------- | --------------------------------------------------- |
| string | no       | The machine image (id) used to launch the instance. |

Default values will be applied for each cloud platform (see below for default values). However, you can also specify this value for launching with a customized machine image.

Note: If you specify this value and also specify the [container](https://docs.mobingi.com/mobingi-alm/alm-template/reference-2017-03-03#container) section in the ALM Template to take the advantage of application lifecycle management, you need to make sure the base machine image operating system supports ALM-agent installation. For supported operating systems by ALM-agent, please refer to [this guide](https://docs.mobingi.com/mobingi-alm/alm-agent/getting-started#prerequisites).

Valid values:

{% tabs %}
{% tab title="AWS" %}
Below is also the default value for AWS.

```yaml
    "image": "ami-2a69be4c"
```

{% endtab %}

{% tab title="ALIBABA CLOUD" %}
Below is also the default value for Alibaba Cloud.

```yaml
    "image": "centos_7_03_64_40G_alibase_20170710.vhd"
```

{% endtab %}

{% tab title="Azure" %}
This is not supported yet.
{% endtab %}

{% tab title="GCP" %}
This is not supported yet.
{% endtab %}

{% tab title="K5" %}
Below is also the default value for K5.

```yaml
    "image": "58fd966f-b055-4cd0-9012-cf6af7a4c32b"
```

{% endtab %}
{% endtabs %}

#### instance\_count

| Type | Required | Description                                                                                                                                 |
| ---- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| int  | no       | Number of instances (VMs) to provision. This is only applicable to non-autoscaled stacks.For autoscaled stacks, see `auto_scaling` section. |

If you don't specify this declarative, the default value of *1* will be applied.

Valid values:

{% tabs %}
{% tab title="AWS" %}

```yaml
    "instance_count": 1
```

{% endtab %}

{% tab title="ALIBABA CLOUD" %}

```yaml
    "instance_count": 1
```

{% endtab %}

{% tab title="AZURE" %}

```yaml
    "instance_count": 1
```

{% endtab %}

{% tab title="GCP" %}
This value is only valid when > zero **AND** `auto_scaling.min` and `auto_scaling.max` are both set to zero. See [auto\_scaling](https://docs.mobingi.com/mobingi-alm/alm-template/alm-template-reference#auto_scaling) section for more information about autoscaling.
{% endtab %}

{% tab title="K5" %}

```yaml
    "instance_count": 1
```

{% endtab %}
{% endtabs %}

#### volume\_type

| Type   | Required | Description                  |
| ------ | -------- | ---------------------------- |
| string | no       | The volume type of instance. |

Valid values:

{% tabs %}
{% tab title="AWS" %}
If you don't specify this declarative, the default value of gp2 will be applied.

```yaml
    gp2 - General Purpose SSD
    io1 - Provisioned IOPS SSD
    st1 - Throughput Optimized HDD
    sc1 - Cold HDD
    standard - Magnetic volumes
```

{% endtab %}

{% tab title="Azure" %}
This is not supported yet.
{% endtab %}

{% tab title="GCP" %}
This is not supported yet.
{% endtab %}
{% endtabs %}

#### volume\_size

| Type   | Required | Description                                  |
| ------ | -------- | -------------------------------------------- |
| string | no       | The size of the volume, in gibibytes (GiBs). |

Valid values:

{% tabs %}
{% tab title="AWS" %}

```
    Constraints: 1-16384 for gp2, 4-16384 for io1, 500-16384 for st1, 500-16384 for sc1, and 1-1024 for standard (magnetic disk).

    Default volume size in GB for each volume types:

    - gp2: 50
    - io1: 50
    - st1: 500
    - sc1: 500
    - standard: 50
```

{% endtab %}

{% tab title="ALIBABA CLOUD" %}
This section hasn't been covered by documentation.
{% endtab %}

{% tab title="AZURE" %}
Current initial deployment size is *50GB*.

{% hint style="info" %}
**Note:** Soon to support other sizes.
{% endhint %}
{% endtab %}

{% tab title="GCP" %}
Default value is 50GB.
{% endtab %}

{% tab title="K5" %}
This section hasn't been covered by documentation.
{% endtab %}
{% endtabs %}

#### keypair

The ssh key pair used to access instances.

| Type    | Required | Description                                                                    |
| ------- | -------- | ------------------------------------------------------------------------------ |
| boolean | no       | Enable SSH key pair to be used to access instances. Default value is **true**. |

#### subnet

| Type   | Required | Description          |
| ------ | -------- | -------------------- |
| object | no       | The subnet settings. |

A *subnet* section contains 3 key names.

* `cidr` (string)

  The IPv4 CIDR block that you want the subnet to cover (for example, "10.0.0.0/24").

  *Required:* No

  If you don't specify this declarative, the default CIDR block settings will be applied. See below for default values on each cloud platform.
* `public` (boolean)

  Defines whether this subnet is public or private. This value is either *true* or *false*.

  If you don't specify this declarative, the default value of *true* will be applied.

  *Required:* No
* `auto_assign_public_ip` (boolean)

  Defines whether automatically assigns a public IP when instance launched into the subnet. This value is either *true* or *false*.

  *Required:* No

  If you don't specify this declarative, the default value of *true* will be applied.

  If you set `public` as *false*, then this declarative will be ignored.

Valid values:

{% tabs %}
{% tab title="AWS" %}
Example below is also the default settings when deploying to AWS.

```yaml
"subnet": {
  "cidr": "10.0.0.0/24",
  "public": true,
  "auto_assign_public_ip": true
}
```

{% endtab %}

{% tab title="ALIBABA CLOUD" %}
Example below is also the default settings when deploying to Alibaba Cloud.

```yaml
"subnet": {
  "cidr": "192.168.199.0/24",
  "public": true,
  "auto_assign_public_ip": true
}
```

{% endtab %}

{% tab title="AZURE" %}
Example below is also the default settings when deploying to Azure.

```yaml
"subnet": {
  "cidr": "10.0.0.0/16",
  "public": true,
  "auto_assign_public_ip": true
}
```

{% endtab %}

{% tab title="GCP" %}
This is not supported yet.
{% endtab %}

{% tab title="K5" %}
Example below is also the default settings when deploying to K5.

```
"subnet": {
  "cidr": "10.1.0.0/24",
  "public": true,
  "auto_assign_public_ip": true
}
```

{% endtab %}
{% endtabs %}

#### network\_acl

The network action control list for a virtual private cloud. **This section supports AWS only.**

| Type  | Required | Description                                                                                      |
| ----- | -------- | ------------------------------------------------------------------------------------------------ |
| array | no       | The network action control list for a virtual private cloud. **This section supports AWS only.** |

A *network\_acl* section contains a list of network\_acl entry items. Each item contains the following declaratives:

* `rule_number` (int)

  Rule number to assign to the entry, such as 100. ACL entries are processed in ascending order by rule number. Entries can't use the same rule number unless one is an egress rule and the other is an ingress rule.

  *Required:* Yes

  For more on valid values, please refer to [this guide](http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateNetworkAclEntry.html) on aws documentation site.
* `protocol` (string)

  The IP protocol that the rule applies to. You must specify -1 or a protocol number. You can specify -1 for all protocols.

  *Required:* Yes

  For more on protocol numbers, please refer to [this guide](http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml).
* `rule_action` (string)

  Whether to allow or deny traffic that matches the rule; valid values are "allow" or "deny".

  *Required:* Yes
* `acl_egress` (boolean)

  Whether this rule applies to egress traffic from the subnet (true) or ingress traffic to the subnet (false).

  *Required:* No

  If you don't specify this declarative, the default value of *false* will be applied.
* `cidr_block` (string)

  The IPv4 CIDR range to allow or deny, in CIDR notation (e.g., 172.16.0.0/24).

  *Required:* Yes

For more information about network acl please refer to [AWS Documentation](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_ACLs.html)

Valid values:

{% tabs %}
{% tab title="AWS" %}
Example below is also the default settings when deploying to AWS.

```yaml
"network_acl": [
  {
    "rule_number": 100,
    "protocol": "-1",
    "rule_action": "allow",
    "cidr_block": "0.0.0.0/0"
  },
  {
    "rule_number": 100,
    "protocol": "-1",
    "rule_action": "allow",
    "acl_egress": false,
    "cidr_block": "0.0.0.0/0"
  }
]
```

{% endtab %}

{% tab title="ALIBABA CLOUD" %}
This section hasn't been covered by documentation.
{% endtab %}

{% tab title="AZURE" %}
This is not supported yet.
{% endtab %}

{% tab title="GCP" %}
This is not supported yet.
{% endtab %}

{% tab title="K5" %}
This section hasn't been covered by documentation.
{% endtab %}
{% endtabs %}

#### security\_group

| Type   | Required | Description                                                                                                                                                                                    |
| ------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| object | no       | The security groups for your virtual private cloud. Security groups are associated with network interfaces and acts as a virtual firewall that controls the traffic for one or more instances. |

A *security group* section contains two entry items, `ingress` and `egress`.

* ingress (array)
* egress (array)

Each *ingress* or *egress* contains the following 4 declarative:

* `cidr_ip` (string)

  An IPv4 CIDR range.

  *Required:* Yes

  (For more information on cidr calculations, there are tools like [this](http://www.subnet-calculator.com/cidr.php) to helping you get started.)
* `from_port` (int)

  Start of port range for the TCP and UDP protocols, or an ICMP type number. If you specify icmp for the IpProtocol property, you can specify -1 as a wildcard (i.e., any ICMP type number).

  *Required:* Yes
* `ip_protocol` (string)

  IP protocol name or number.

  *Required:* Yes
* `to_port` (int)

  End of port range for the TCP and UDP protocols, or an ICMP code. If you specify icmp for the IpProtocol property, you can specify -1 as a wildcard (i.e., any ICMP code).

  *Required:* Yes

Valid values:

{% tabs %}
{% tab title="AWS" %}
Example below is also the default settings when deploying to AWS.

```yaml
"security_group": {
        "ingress": [
            {
                "cidr_ip": "0.0.0.0/0",
                "from_port": 80,
                "ip_protocol": "tcp",
                "to_port": 80
            },
            {
                "cidr_ip": "0.0.0.0/0",
                "from_port": 443,
                "ip_protocol": "tcp",
                "to_port": 443
            },
            {
                "cidr_ip": "0.0.0.0/0",
                "from_port": 22,
                "ip_protocol": "tcp",
                "to_port": 22
            }
        ],
        "egress": [
            {
                "cidr_ip": "0.0.0.0/0",
                "from_port": 0,
                "ip_protocol": "-1",
                "to_port": 65535
            }
        ]
    }
```

{% endtab %}

{% tab title="ALIBABA CLOUD" %}
This section hasn't been covered by documentation.
{% endtab %}

{% tab title="AZURE" %}

```yaml
"security_group": {
    "ingress": [
        {
            "cidr_ip": "0.0.0.0/0",
            "from_port": 80,
            "ip_protocol": "tcp",
                   "to_port": 80
        },
        {
            "cidr_ip": "0.0.0.0/0",
            "from_port": 443,
               "ip_protocol": "tcp",
            "to_port": 443
        },
        {
            "cidr_ip": "0.0.0.0/0",
            "from_port": 22,
            "ip_protocol": "tcp",
            "to_port": 22
        }
    ],
       "egress": [
        {
            cidr_ip": "0.0.0.0/0",
            "from_port": 0,
               "ip_protocol": "tcp",
            "to_port": 65535
        }
    ]
}
```

{% endtab %}

{% tab title="GCP" %}
For GCP deployments, the default network where the stack is deployed will, by default, open ports **22** and **80** from source **0.0.0.0/0**.
{% endtab %}

{% tab title="K5" %}
This section hasn't been covered by documentation.
{% endtab %}
{% endtabs %}

#### auto\_scaling

| Type              | Required | Description                                                                                                                                                                                             |
| ----------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| object, or string | no       | The `auto_scaling` group defines the configuration to automatically scale up or down the number of compute resources that are being allocated to your application based on its needs at any given time. |

If you are deploying an *application* type of load balancer (you define in [`load_balancer`](/v3.0-english/alm-template/reference-2017-03-03#load_balancer) declarative), you can omit the required parameters below and use the ATL function `#share` to share the same auto scaling group which you defined in another layer. [Click here](https://docs.mobingi.com/mobingi-alm/alm-template/alm-template-language) for more on ATL functions.

{% hint style="warning" %}
[**ATL**](https://docs.mobingi.com/mobingi-alm/alm-template/alm-template-language) is only supported by AWS at the moment.
{% endhint %}

The `auto_scaling` section contains the following declarative:

* `min` (int)

  The minimum size of the whole (total) autoscaling group.

  Require&#x64;*:* No

  If you don't specify this declarative, the default value of 1 will be applied.
* `max` (int)

  The maximum size of the whole (total) autoscaling group.

  Required: No

  If you don't specify this declarative, the default value of 1 will be applied.
* `spot_to_ondemand_ratio` (int) The percentage of min/max values to deploy as spot/preemptible/low-priority instances. For example, if you have 10 as `min` and 100 as `max`, a `spot_to_ondemand_ratio` value of 60 (or 60 percent) will have the following results: Spot min: 6 (60% of 10) Spot max: 60 (60% of 100) On-demand min: 4 On-demand max: 40 For calculations that results to fractions, like 50% of 3, the results will be rounded off to the nearest integer such as `1.5 = 2`, `3.9 = 4`, `2.3 = 2`, etc. For example, if you have a `min` value of 3 and 50 as `spot_to_ondemand_ratio`, you will have a minimum of 2 spot instances (50% of 3 is 1.5, rounded off to 2) and a single on-demand instance.
* `spot_min` (int) **\[DEPRECATED]**

  The minimum size of the spot instances in the autoscaling group. This key will still work with AWS- and GCP-based stacks. For other cloud vendors, please use `spot_to_ondemand_ratio` key.

  Required: No
* `spot_max` (int) **\[DEPRECATED]**

  The maximum size of the spot instances in the autoscaling group. This key will still work with AWS- and GCP-based stacks. For other cloud vendors, please use `spot_to_ondemand_ratio` key.

  Required: No
* `availability_zones` (string)

  The list of availability zones for the Auto Scaling group.

  Required: Yes
* `cooldown` (string)

  The number of seconds after a scaling activity is completed before any further scaling activities can start.

  Required: No

  If you don't specify this declarative, the default value of *360* will be applied.
* `healthcheck_grace_period` (string)

  The length of time in seconds after a new instance comes into service that Auto Scaling starts checking its health.

  Required: No

  If you don't specify this declarative, the default value of *360* will be applied.

Valid values:

{% tabs %}
{% tab title="AWS" %}

```yaml
"auto_scaling": {
  "min": 1,
  "max": 1,
  "availability_zones": "${use(FlagName1.provision.availability_zone, FlagName2.provision.availability_zone)}",
  "cooldown": "360",
  "healthcheck_grace_period": "360"
}
```

{% endtab %}

{% tab title="ALIBABA CLOUD" %}
This section hasn't been covered by documentation.
{% endtab %}

{% tab title="AZURE" %}

```yaml
"auto_scaling":{
    "min": 3,
    "max":3,
    "spot_to_ondemand_ratio": 50
},
```

{% endtab %}

{% tab title="GCP" %}
For GCP, the system will check if `min` is > 0, `max` is > `min`, and `instance_type` is zero before proceeding.

For [preemptible](https://cloud.google.com/compute/docs/instances/preemptible) instances, the system will calculate the values based on the provided `spot_to_ondemand_ratio` value. For compatibility with the deprecated `spot_min` and `spot_max` keys, it will also check if `spot_min` > 0, `spot_max` > `spot_min` and `instance_type` is zero before proceeding.
{% endtab %}

{% tab title="K5" %}
This section hasn't been covered by documentation.
{% endtab %}
{% endtabs %}

#### load\_balancer

| Type   | Required | Description                                       |
| ------ | -------- | ------------------------------------------------- |
| object | no       | The `load_balancer` for the `auto_scaling` group. |

The *load balancer* section contains the following declarative:

* `lb_type` (string)

  Either *classic*, *application* or *networking*.

  In usual case, ALM creates the classic (standard) load balancer.

  On AWS specifically, you can also create the *application* load balancer and a *networking* load balancer. For more on these two AWS load balancer types, please refer to [this guide](https://aws.amazon.com/elasticloadbalancing).

  *Required:* No

  If you don't specify this declarative, the default value of *classic* will be applied.
* `scheme` (string)

  Either *internet-facing* or *internal*.

  Specify *internal* to create an internal load balancer with a DNS name that resolves to private IP addresses or *internet-facing* to create a load balancer with a publicly resolvable DNS name, which resolves to public IP addresses.

  *Required:* No

  If you don't specify this declarative, the default value of *internet-facing* will be applied.
* `security_groups` (string)

  Specifies a list of security groups assigned to this load balancer.

  *Required:* No

  **Note:** This value is in string type and can only be the reference to [`security_group`](/v3.0-english/alm-template/reference-2017-03-03#security_group) section you defined in same or other layers. For example if you have two layers of configurations named "Layer1" and "Layer2", you can reference the *security group* defined in Layer2 to Layer1 by writing:

  ```javascript
    { "security_groups": "#ref(Layer2.provision.security_group)"}
  ```
* `subnets` (string)

  Specifies a list of subnets assigned to this load balancer defined in `lb_type` parameter above.

  *Required:* No

  **Note:** Only specify this value if you are deploying an ALB type of load-balancer.

  **Note:** This value is in string type and can only be the reference to [`subnet`](/v3.0-english/alm-template/reference-2017-03-03#subnet) section you defined in same or other layers. For example if you have two layers of configurations named "Layer1" and "Layer2", you can reference the *subnets* to use both of them by:

  ```javascript
    { "subnets": "#ref(Layer2.provision.subnet,Layer1.provision.subnet)"}
  ```
* `listeners` (array)

  One or more listeners for this load balancer. Each listener must be registered for a specific port, and you cannot have more than one listener for a given port.

  *Required:* Yes. *You must specify at least one entry item for this section.*

  A *listeners* section contains a list of entry items with each item contains the following declarative:

  * `load_balancer_port` (string)

    Specifies the external load balancer port number.

    *Required:* Yes
  * `protocol` (string)

    Specifies the load balancer transport protocol to use for routing: *HTTP*, *HTTPS*, *TCP* or *SSL*.

    *Required:* Yes
  * `instance_port` (string)

    Specifies the TCP port on which the instance server listens.

    *Required:* Yes
  * `instance_protocol` (string)

    Specifies the protocol to use for routing traffic to back-end instances: *HTTP*, *HTTPS*, *TCP* or *SSL*. You can't modify this property during the life of the load balancer.

    *Required:* No

    **Note:**

    * If the front-end protocol is HTTP or HTTPS, *instance protocol* must be on the same protocol layer (HTTP or HTTPS). Likewise, if the front-end protocol is TCP or SSL, *instance protocol* must be TCP or SSL.
    * If there is another Listener with the same *instance port* whose *instance protocol* is secure, (using HTTPS or SSL), the *instance protocol* of the Listener must be secure (using HTTPS or SSL). If there is another Listener with the same *instance port* whose *instance protocol* is HTTP or TCP, the *instance protocol* of the Listener must be either HTTP or TCP.
  * `cert_domain` (string)

    **(AWS Only)**

    Specifies the domain name to be used for issuing SSL certificate via AWS ACM service.

    *Required:* No

    When you provide the domain name here, a verification email will be sent to the domain owner (sent by AWS), and you have to click link found in email to approve the issuance of the SSL certificate before the stack provision can be finished.

    Once the provision deployment is successfully done, the SSL certificate will be attached to your load-balancer automatically.
* `health_check` (object)

  **(AWS Only)**

  Application health check for the instances.

  *Required:* No

  A *health check* section contains the following declarative:

  * `healthy_threshold` (string)

    Specifies the number of consecutive health probe successes required before moving the instance to the Healthy state.

    *Required:* Yes
  * `interval` (string)

    Specifies the approximate interval, in seconds, between health checks of an individual instance. Valid values are 5 to 300.

    *Required:* Yes
  * `target` (string)

    Specifies the instance's protocol and port to check. The protocol can be TCP, HTTP, HTTPS, or SSL. The range of valid ports is 1 through 65535.

    *Required:* Yes
  * `timeout` (string)

    Specifies the amount of time, in seconds, during which no response means a failed health probe. This value must be less than the value for *interval*.

    *Required:* No
  * `unhealthy_threshold` (string)

    Specifies the number of consecutive health probe failures required before moving the instance to the Unhealthy state.

    *Required:* No

Valid values:

{% tabs %}
{% tab title="AWS" %}

```yaml
"load_balancer": {
        "lb_type": "classic",
        "scheme": "internet-facing",
        "listeners": [
            {
                "load_balancer_port": "443",
                "instance_port": "80",
                "protocol": "HTTPS",
                "cert_domain": "www.example.com"
            }
        ],
        "health_check": {
            "healthy_threshold": "2",
            "interval": "10",
            "target": "TCP:80",
            "timeout": "5",
            "unhealthy_threshold": "10"
        }
    }
```

{% endtab %}

{% tab title="ALIBABA CLOUD" %}
This section hasn't been covered by documentation.
{% endtab %}

{% tab title="GCP" %}
For now, GCP only supports the classic load balancer. It uses `listeners.load_balancer_port` and `health_check.target` keys for configuration and always creates an internet-facing load balancer.
{% endtab %}

{% tab title="K5" %}
This section hasn't been covered by documentation.
{% endtab %}
{% endtabs %}

#### rds

| Type   | Required | Description                                         |
| ------ | -------- | --------------------------------------------------- |
| object | no       | The `rds` is a managed relational database service. |

The *rds* section contains the following declarative:

* `db_instance_type` (string)

  If you don't specify this declarative, the default values will be applied for each cloud platform.

  *Required:* Yes
* `engine` (string)

  If you don't specify this declarative, the default values will be applied for each cloud platform.

  *Required:* Yes
* `version` (string)

  If you don't specify this declarative, the default values will be applied for each cloud platform.

  *Required:* Yes
* `storage` (int)

  Constraints: 5-3072 (managemet disk).

  *Required:* Yes
* `multi_az` (boolean)

  Create replica in an availability zone different from the DB instance. Defines whether this nulti\_az is AZ or No AZ. This value is either true or false.

  *Required:* Yes
* `replica` (int)

  Constraints: 1-5 (replica counts).

  *Required:* No

Valid values:

{% tabs %}
{% tab title="AWS" %}
Default: db.t2.micro

```yaml
 "rds": {
        "db_instance_type": "db.t2.micro",
        "engine": "mysql",
        "version": "5.6"
        "storage": 10,
        "multi_az": true,
        "replica": 1
    }
```

Below are the valid db instance types for AWS.

```
    db.t2.micro [default]
    db.t2.small
    db.t2.medium
    db.t2.large
    db.t2.xlarge
    db.t2.2xlarge
    db.m4.large
    db.m4.xlarge
    db.m4.2xlarge
    db.m4.4xlarge
    db.m4.10xlarge
    db.m4.16xlarge
    db.m3.medium
    db.m3.large
    db.m3.xlarge
    db.m3.2xlarge
    db.r3.large
    db.r3.xlarge
    db.r3.2xlarge
    db.r3.4xlarge
    db.r3.8xlarge
    db.r4.large
    db.r4.xlarge
    db.r4.2xlarge
    db.r4.4xlarge
    db.r4.8xlarge
    db.r4.16xlarge
    db.m2.xlarge
    db.m2.2xlarge
    db.m2.4xlarge
    db.m1.small
    db.m1.medium
    db.m1.large
    db.m1.xlarge
```

Below are the valid engine and version for AWS.

```
    mysql
        - 5.6
        - 5.7
    postgres
        - 9.6
        - 10
```

{% endtab %}

{% tab title="ALIBABA CLOUD" %}
This section hasn't been covered by documentation.
{% endtab %}

{% tab title="AZURE" %}
This section hasn't been covered by documentation
{% endtab %}

{% tab title="GCP" %}
This is not supported yet.
{% endtab %}

{% tab title="K5" %}
This section hasn't been covered by documentation
{% endtab %}
{% endtabs %}

### container

The software runtime configurations *(defined as docker images)* and code deployment requirement for each instance node.

#### container\_image

| Type   | Required | Description                                           |
| ------ | -------- | ----------------------------------------------------- |
| string | no       | The docker image to be used to launch base container. |

Example:

| `registry.mobingi.com/tompson/ubuntu-nginx-php:latest` |
| ------------------------------------------------------ |

#### container\_registry\_username

The docker image registry's username if this is a private image repository.

| Type   | Example Value | Required | Supported Platforms |
| ------ | ------------- | -------- | ------------------- |
| string | N/A           | No       | Platform Stateless  |

#### container\_registry\_password

| Type   | Required | Description                                                                 |
| ------ | -------- | --------------------------------------------------------------------------- |
| string | no       | The docker image registry's password if this is a private image repository. |

#### container\_code\_dir

| Type   | Required | Supported Platforms                                                       |
| ------ | -------- | ------------------------------------------------------------------------- |
| string | no       | The directory of the instance where application code will be deployed to. |

Example:

| `/var/www/html` |
| --------------- |

#### container\_git\_repo

| Type   | Required | Description                                                 |
| ------ | -------- | ----------------------------------------------------------- |
| string | no       | The git repository url of where application code is hosted. |

Example:

| `https://github.com/mobingilabs/default-site-php.git` |
| ----------------------------------------------------- |

#### container\_git\_reference

| Type   | Required | Description                                                    |
| ------ | -------- | -------------------------------------------------------------- |
| string | no       | The git repository branch of where application code is hosted. |

Example:

```
master
```

#### container\_git\_private\_key

| Type   | Required | Description                                                          |
| ------ | -------- | -------------------------------------------------------------------- |
| string | no       | The private key of the git repository if it is a private repository. |

#### container\_ports

| Type  | Required | Description                                        |
| ----- | -------- | -------------------------------------------------- |
| array | no       | The ports for connection to be used by containers. |

Example:

| `[ 80 ]` |
| -------- |

#### container\_users

This parameter is not yet supported.

#### container\_env\_vars

| Type   | Required | Description                                                                 |
| ------ | -------- | --------------------------------------------------------------------------- |
| object | no       | The environment variables to be defined for the container operating system. |

An example `container` configuration:

```yaml
"container": {
  "container_image": "mobingi/ubuntu-apache2-php7",
  "container_code_dir": "/var/www/html",
  "container_git_repo": "https://github.com/mobingilabs/default-site-php.git",
  "container_git_reference": "master",
  "container_ports": [80],
  "container_env_vars": {
    "display_errors": "Off",
    "my_variable": "Some value"
  }
}
```


# ALM Template Language

ALM Template provides several built-in functions that help you manage your ALM Template. These functions are named **ATL**, short for **A**LM **T**emplate **L**anguage. Not to be confused with Microsoft's [ATL](https://msdn.microsoft.com/en-us/library/3ax346b7.aspx).

Use ATL functions in your templates to assign values to properties that are not available until runtime.

{% hint style="info" %}
For now, ATL is only supported in AWS. Support for other cloud vendors will be available soon.\
You can use ATL functions only in specific parts of a template. Please refer to each functions' document for detailed explanation.
{% endhint %}

## computed  <a href="#computed" id="computed"></a>

*Usage:*

`${computed}`

This function is used to calculate the valid value for supported declarative in your ALM Template.

Example:

```javascript
"instance_type": "${computed}"
```

## use  <a href="#use" id="use"></a>

*Usage:*

`${use( .. )}`

This function is used to reference the value that you defined in other declarative already.

*Example:*

```javascript
"availability_zones": "${use(Layer1.provision.availability_zone),use(Layer2.provision.availability_zone)}"
```

**Note:** This function can only be used if the origin value is type of *string*, it cannot be applied to any other type of values. For referencing values such as object or array, you use `${copy( .. )}`.

## copy  <a href="#copy" id="copy"></a>

*Usage:*

`${copy( .. )}`

This function is used to copy the whole value that you defined in other declarative already.

*Example:*

```javascript
"security_group": "${copy(Layer1.provision.security_group)}"
```

## ref  <a href="#ref" id="ref"></a>

*Usage:*

`#ref( .. )`

Currently, this function can be used only in:

1. load\_balancer : security\_groups

   ```javascript
   "load_balancer": {
     "security_groups": "#ref(Layer2.provision.security_group)",
   },
   ```

   *Use case explanation:*

   When the load balancer requires specified security groups, you can use this function to reference the security groups that are defined in `security_group` declarative.

## share  <a href="#share" id="share"></a>

Usage:

`#share( .. )`

Currently, this function can be used in two declarative:

1. load\_balancer : subnets

   ```javascript
   "load_balancer": {
     "subnets": "#share(Layer1.provision.subnet,Layer2.provision.subnet)",
   },
   ```

   *Use case explanation:*

   When you deploy an *application* or *networking* load balancer on AWS, by default each load balancer requires at least two subnets, so you use this function to define the target subnets which will be used by this load balancer.
2. auto\_scaling

   ```javascript
   {
     "auto_scaling": "#share(Layer1.provision.auto_scaling)"
   }
   ```

   *Use case explanation:*

   When you register multiple load balancers to the instances that are in the same auto scaling group, you use this function to define the target auto scaling group which will be shared with this load balancer.


# Example ALM Templates

{% hint style="info" %}
We moved all sample templates to a public repository in GitHub:\
<https://github.com/mobingi/alm-template-examples>
{% endhint %}


# ALM Agent

{% content-ref url="/pages/-LYkD7WyFtEOYVfDxbS7" %}
[Overview](/v3.0-english/alm-agent/overview)
{% endcontent-ref %}

{% content-ref url="/pages/-LYkD7WkbpiobvDt7skX" %}
[Getting started](/v3.0-english/getting-started)
{% endcontent-ref %}

{% content-ref url="/pages/-LYkD7X--0BfG\_r9UaIa" %}
[Agent](/v3.0-english/alm-agent/agent)
{% endcontent-ref %}

{% content-ref url="/pages/-LYkD7X0Z-Ld3ohxO5e1" %}
[Commands](/v3.0-english/alm-agent/commands)
{% endcontent-ref %}

{% content-ref url="/pages/-LYkD7X1DMZ691sL4CAb" %}
[Add-ons](/v3.0-english/alm-agent/add-ons)
{% endcontent-ref %}

{% content-ref url="/pages/-LYkD7X2k1K7QPAiX6Vt" %}
[Contributing](/v3.0-english/alm-agent/contributing)
{% endcontent-ref %}


# Overview

## What is ALM-agent?  <a href="#what-is-alm-agent" id="what-is-alm-agent"></a>

The ALM-agent is software for Mobingi ALM. ALM-agent is the primary component of container management.

ALM-agent runs on instances, manages Docker containers and deploys code to instances on behalf of you.

ALM-agent works with [ALM Template](https://docs.mobingi.com/mobingi-alm/alm-template/what-is-alm-template). When you run the ALM-agent, the agent on the instance processes the ALM Template and configures the instance as specified.

## Characteristics of ALM Agent  <a href="#characteristics-of-alm-agent" id="characteristics-of-alm-agent"></a>

The ALM-agent is a tool for managing container and continuous deployment for your application. It provides several key features:

* Container Management
  * ALM-agent can manage container lifecycle (create container, start or stop container, renew container image, deploy application code and manage log containers, etc.).
* Blue-Green Deployment using Container
  * ALM-agent uses Blue-Green Deployment to achieve zero-downtime deployment of your application code.
* Health Checking
  * ALM-agent checks not only the instance status but also the container status.
* Multi Cloud
  * ALM-agent can run at any Cloud Service such as AWS, Alibaba Cloud, Azure, GCP, Fujitsu K5, etc.


# Getting Started

## Prerequisites  <a href="#prerequisites" id="prerequisites"></a>

ALM-agent includes the following prerequisites.

| **REQUIREMENT**              | **DESCRIPTION**                                                                                                                                                                             |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| *Supported Operating System* | Instances must run on a supported version of Linux.   `Amazon Linux 2016.09` or later, `Ubuntu Server 14.04 LTS` or later, `CentOS7` or later, `Red Hat Enterprise Linux(RHEL) 7` or later. |
| *Internet Access*            | If your server configuration design requires services to access the public Internet (*e.g. GitHub, DockerHub, etc..*), verify that your instances have outbound Internet access first.      |
| *Docker*                     | Instances should have Docker installed.                                                                                                                                                     |
| *Git*                        | Instances should have Git installed.                                                                                                                                                        |

## Install ALM agent  <a href="#install-alm-agent" id="install-alm-agent"></a>

There are two ways to installing ALM Agent:

1. Using a precompiled binary
2. Installing from source

{% hint style="info" %}
Download and install from a precompiled binary is the recommended option.
{% endhint %}

### ***Using a precompiled binarys***

ALM-agent is distributed as a binary package. To install ALM-agent, you can download it from this [link](https://download.labs.mobingi.com/alm-agent/master/current/alm-agent.tgz).

ALM-agent is packaged as a tgz archive. After downloading ALM-agent, untgz the package. ALM-agent runs as a single binary named `alm-agent`.

```bash
$ mkdir -p /opt/mobingi/alm-agent /opt/mobingi/etc
$ wget https://download.labs.mobingi.com/alm-agent/develop/current/alm-agent.tgz
$ tar xvzf alm-agent.tgz -C /opt/mobingi/alm-agent
$ ln -sf /opt/mobingi/alm-agent/v* /opt/mobingi/alm-agent/current
```

### ***Installing from source***

We prepare Vagrantfile to compile from source. You will need VirtualBox and Vagrant installed. You can compile in virtual machine.

```bash
$ git clone https://github.com/mobingi/alm-agent
$ cd alm-agent
$ vagrant up default
$ vagranth ssh default
vagrant $ cd /home/vagrant/src/github.com/mobingi/alm-agent/
vagrant $ make build
```

## Verifying the Installation  <a href="#verifying-the-installation" id="verifying-the-installation"></a>

After installing ALM-agent, verify the installation works and check that `alm-agent` is available.

By executing `alm-agent` you should see the help output similar to this:

```bash
$ alm-agent
NAME:
   alm-agent

USAGE:
   alm-agent [global options] command [command options] [arguments...]

VERSION:
   v0.3.1504270893

COMMANDS:
     register  initialize alm-agent and start containers
     ensure    start or update containers
     stop      stop active container
     noop      run without container actions.
     help, h   Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --autoupdate, -U                  auto update before run
   --disablereport, -N               Do not send crash report to rollbar.
   --provider Provider, -P Provider  set Provider (default: "aws")
   --verbose, -V                     show debug logs
   --help, -h                        show help
   --version, -v                     print the version
```


# Agent

## Usage  <a href="#usage" id="usage"></a>

ALM-agent is a very simple and easy-to-use tool. It can be used like a CLI (not a Daemon).

Executing ALM-agent will start the containers, the code will be deployed, and the command will be terminated.

To view a list of the available options and commands at any time, just run `alm-agent` with `--help, -h` arguments:

```bash
$ alm-agent --help
NAME:
   alm-agent

USAGE:
   alm-agent [global options] command [command options] [arguments...]

VERSION:
   v0.3.1504270893

COMMANDS:
     register  initialize alm-agent and start containers
     ensure    start or update containers
     stop      stop active container
     noop      run without container actions.
     help, h   Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --autoupdate, -U                  auto update before run
   --disablereport, -N               Do not send crash report to rollbar.
   --provider Provider, -P Provider  set Provider (default: "aws")
   --verbose, -V                     show debug logs
   --help, -h                        show help
   --version, -v                     print the version
```

## Global Options  <a href="#global-options" id="global-options"></a>

* *--autoupdate,  -U*   Before running, ALM-agent checks the new version and updates the agent itself  if there is a new version. (self-update)&#x20;
* *--disablereport, -N*  We are using rollbar for error monitoring. If you do not want to send crash report to rollbar,   use this option.&#x20;
* *--provider Provider, -P Provider*  set Provider (default: "aws", available providers: "aws", "alicloud", "k5", "localtest")&#x20;
* *--verbose, -V*  show debug logs&#x20;
* *--help, -h*  show help&#x20;
* *--version, -v*  print the version


# Commands

## register  <a href="#register" id="register"></a>

Initialize ALM-agent self register and start containers.

The necessary folders for ALM-agent are created, and if the provider is any value other than `localtest`, cron job will be created. Then, ALM-agent starts the containers.

```bash
$ alm-agent register -h
NAME:
   alm-agent register - initialize alm-agent and start containers

USAGE:
   alm-agent register [command options] [arguments...]

OPTIONS:
   --config FILE, -c FILE        Load configuration from FILE (default: "/opt/mobingi/etc/alm-agent.cfg")
   --serverconfig URL, --sc URL  Load ServerConfig from URL. ask to API by default
```

## ensure  <a href="#ensure" id="ensure"></a>

Start or update containers.

```bash
$ alm-agent ensure -h
NAME:
   alm-agent ensure - start or update containers

USAGE:
   alm-agent ensure [command options] [arguments...]

OPTIONS:
   --config FILE, -c FILE        Load configuration from FILE (default: "/opt/mobingi/etc/alm-agent.cfg")
   --serverconfig URL, --sc URL  Load ServerConfig from URL. ask to API by default
```

## stop  <a href="#stop" id="stop"></a>

Stop active containers.

```bash
$ alm-agent stop -h
NAME:
   alm-agent stop - stop active container

USAGE:
   alm-agent stop [command options] [arguments...]

OPTIONS:
   --config FILE, -c FILE        Load configuration from FILE (default: "/opt/mobingi/etc/alm-agent.cfg")
   --serverconfig URL, --sc URL  Load ServerConfig from URL. ask to API by default
```

## noop  <a href="#noop" id="noop"></a>

Run without container actions.

```bash
$ alm-agent noop -h
NAME:
   alm-agent noop - run without container actions.

USAGE:
   alm-agent noop [command options] [arguments...]

OPTIONS:
   --config FILE, -c FILE        Load configuration from FILE (default: "/opt/mobingi/etc/alm-agent.cfg")
   --serverconfig URL, --sc URL  Load ServerConfig from URL. ask to API by default
```

## help  <a href="#help" id="help"></a>

Shows a list of commands or help for one command.

```bash
$ alm-agent help
NAME:
   alm-agent

USAGE:
   alm-agent [global options] command [command options] [arguments...]

VERSION:
   v0.3.1504270893

COMMANDS:
     register  initialize alm-agent and start containers
     ensure    start or update containers
     stop      stop active container
     noop      run without container actions.
     help, h   Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --autoupdate, -U                  auto update before run
   --disablereport, -N               Do not send crash report to rollbar.
   --provider Provider, -P Provider  set Provider (default: "aws")
   --verbose, -V                     show debug logs
   --help, -h                        show help
   --version, -v                     print the version
```


# Add-ons

In order to support various unique functions for different cloud providers, we provide add-ons.

## AWS  <a href="#aws" id="aws"></a>

The ALM-agent enables you to perform specific actions when Auto Scaling Instances or Spot Instances are terminated.

### How ALM Agent Works

* Deregisters the instance from the load balancer.
  * After the instance is deregistered, it no longer receives traffic from the load balancer.
* Executes the specified script.
  * If you put the script named `pre_shutdown.sh` under the root (`/`) folder in the Docker Image, the ALM-agent executes the script.

### Conditions

* Auto Scaling puts the instance into `Terminating:Wait`.
* Amazon EC2 will interrupt Spot Instances.


# Contributing

We welcome your contributions and feedbacks!

Mobingi ALM-agent is an open source software, you can find the source code at <https://github.com/mobingi/alm-agent>.

If you want to fix something or have proposals, you can send Pull Requests and open issues via [GitHub](https://github.com/mobingi/alm-agent).


# RBAC

{% content-ref url="/pages/-LYkD7X4fvTWZ5VZjtWm" %}
[Overview](/v3.0-english/rbac/overview)
{% endcontent-ref %}

{% content-ref url="/pages/-LYkD7X5fzYaXaYDxvY1" %}
[What is RBAC?](/v3.0-english/rbac/what-is-rbac)
{% endcontent-ref %}

{% content-ref url="/pages/-LYkD7X6vgL524oTgGDt" %}
[Getting started](/v3.0-english/rbac/getting-started)
{% endcontent-ref %}

{% content-ref url="/pages/-LYkD7X7deUHqp0FQFEe" %}
[Working with RBAC](/v3.0-english/rbac/working-with-rbac)
{% endcontent-ref %}

{% content-ref url="/pages/-LYkD7X8cVE8fbEQ7m69" %}
[Release history](/v3.0-english/rbac/release-history)
{% endcontent-ref %}

{% content-ref url="/pages/-LYkD7X9UsXwptk-DhSV" %}
[Example RBAC roles](/v3.0-english/rbac/example-rbac-roles)
{% endcontent-ref %}


# Overview

ALM supports Role Based Access Control (**RBAC**) to let you grant resource access to your user accounts.

* Role Based Access Control (**RBAC**) feature is shipped with **Mobingi Enterprise Edition**.
* RBAC feature helps you centralize activities and assign role based access control to all members in your organization. It allows you to securely control access to all resources for your users.

Using RBAC, you can segregate duties within your team and grant only the amount of access to users that they need to perform their jobs instead of giving everybody unrestricted permissions in your ALM console, you can allow only certain actions. For example, use RBAC to let one employee manage stack creation and update, while another can only view the stack resource(s).


# What is RBAC?

RBAC is a policy document that formally states one or more permissions. To assign permissions to a user, you create a policy, which is a document that explicitly lists permissions.

## Concepts

### Create roles

* Create roles can be done by root account only. *(Root account is the one you login using your email address.)*
* Create roles action can be performed through CLI, API or UI.
* Editing roles is simple and straightforward. All users under your root account will be able to view their roles that assigned to them.

### Attach roles to users or teams

* Role can be created by root account only.
* Role can be assigned to *Users* and *Teams.*
* *Users* or *Teams* can be attached with one Role only.
* Roles assigned on *Team* will overwrite the roles assigned on *User.*

### End user effect

* When users login to Mobingi ALM dashboard (or interacting through CLI or API), roles that attached to them will be evaluated on every action request.
* If an action isn't granted by the role definition, such action will be denied.
* If an action is grated by the role definition, the action will be allowed.

## How does RBAC work?

Before any requests goes in, the RBAC module will check for the current user's role settings first, then it passes or denies the request.

![](/files/-LErwhKLCL-u9U_G5uam)

For the requests being passed, there is no other actions need to perform.

For the requests been denied, the client (usually UI console, or API and CLI) will returned with the following error:

```javascript
HTTP Status Code 403
{
    "RBAC": "Action not allowed"
}
```

As an example, apply the following to your ALM user to allow performing every action excepts *deleting stacks*:

```javascript
{
    "version": "2017-05-05",
    "statement": [
        {
            "effect": "allow",
            "action": "*",
            "resource": "*"
        },
        {
            "effect": "deny",
            "action": "delete:alm.stack",
            "resource": "*"
        }
    ]
}
```


# Getting started

## Step-by-step guide

First time customers, use your root account to login to ALM dashboard, then navigate to settings page.

**Step 1**: Go to roles settings page, click on button "Create New Role".

![](/files/-LErzEQUUIFK7nvPaGi1)

**Step 2**: Create a new role with pre-defined role examples.

![](/files/-LEs9dkoPqdK9repw8ze)

Click on the button at bottom to create the new role. You can customize the role policy body. For details on how to write your own policy document, please refer to [working with RBAC](https://learn.mobingi.com/enterprise/working-with-rbac) guide.

**Step 3**: Go to User Settings Page.

![](/files/-LEs9scYjrUM7C74PQjf)

Select the user you want to assign role to. Click on the button "Edit" to the right.

**Step 4**: Attach role to user.

![](/files/-LEsA2c-NNZC0xUptzpF)

Finally, on the popup window, click on "Role" button and select the role you just create before and save to assign to the user.


# Working with RBAC

## Permission priority

When a request is made, the RBAC service decides whether a given request should be allowed or denied. The evaluation logic follows these rules:

* By default, all requests are denied (*Note: when you creating a new user on Mobingi ALM, by default, this user has no permissions* )
* An explicit allow overrides this default
* Deny pattern always overrides allow pattern against same resources
* An explicit deny overrides any allows

  The order in which the policies are evaluated has no effect on the outcome of the evaluation. All policies are evaluated, and the result is always that the request is either allowed or denied.

## Apply order

* Allow pattern always applies first.
* Deny pattern overrides allows.
* Additionally, when the action performing user belongs to a *Team* and both its user role and team role are attached, the *Team* role will overwrite the user role.


# Release history

## 2017-05-05

The current stable release is 2017-05-05 version. You always use this release in your role body policies.


# Example RBAC roles

## Allow all

```ruby
{
    "version": "2017-05-05",
    "statement": [
        {
            "effect": "allow",
            "action": "*",
            "resource": "*"
        }
    ]
}
```

## Allow UI login

```ruby
{
    "version": "2017-05-05",
    "statement": [
        {
            "effect": "allow",
            "action": "view:user.login",
            "resource": "*"
        }
    ]
}
```

## Deny credentials

```ruby
{
    "version": "2017-05-05",
    "statement": [
        {
            "effect": "allow",
            "action": "*",
            "resource": "*"
        },
        {
            "effect": "deny",
            "action": "*:credentials",
            "resource": ["AKIAJ7Z8PGXEZTIJOL6IQ"]
        }
    ]
}
```

## Deny list stacks

```ruby
{
    "version": "2017-05-05",
    "statement": [
        {
            "effect": "allow",
            "action": "*",
            "resource": "*"
        },
        {
            "effect": "deny",
            "action": "view:alm.stack",
            "resource": "*"
        }
    ]
}
```

## Deny list stacks by resource

```ruby
{
    "version": "2017-05-05",
    "statement": [
        {
            "effect": "allow",
            "action": "*",
            "resource": "*"
        },
        {
            "effect": "deny",
            "action": "view:alm.stack",
            "resource": ["mo-590fdb7bad55s-tJZpgRCBs-tk", "mo-590fdb7bad55s-ugMgQQ1TE-tk"]
        }
    ]
}
```

## Deny deleting stacks by resource

```ruby
{
    "version": "2017-05-05",
    "statement": [
        {
            "effect": "allow",
            "action": "*",
            "resource": "*"
        },
        {
            "effect": "deny",
            "action": "delete:alm.stack",
            "resource": ["mo-590fdb7bad55s-tJZpgRCBs-tk"]
        }
    ]
}
```


# Overview

## Users

There are two types of Alphaus users; root users and subusers. Root users are account owners and super admins. These are the accounts you register to Alphaus and are in email address form. Subusers are users that are created by root users and are typically given minimal access to perform specific roles although subusers can also be admins.

## RBAC

Alphaus RBAC is a organization-wide role-based access control system that provides fine-grained access management to Alphaus features and resources. In using Alphaus RBAC, you can grant only the amount of access to users that they need to perform their jobs.

Alphaus RBAC is defined around users, namespaces, roles, and permissions. Users can be actual users in your organization, or a virtual user used in scripts or automation codes. Roles are job functions or groups that have a certain level of authority, or a list of permissions attached to it. Examples are `Admin`, `Developers`, etc. You can assign up to five (5) roles to a user per namespace.

Roles and permissions in Alphaus RBAC are isolated based on namespaces. What this means is that a role can only be created under a specific namespace, with namespace-specific permissions attached to it.

Alphaus root users are always super admins, or have unrestricted access across namespaces. Typically, root users should create subusers and assign specific roles to them.

## Namespaces

The following table lists the supported namespaces under Mobingi RBAC.

| Product/domain | Namespace |
| -------------- | --------- |
| Ripple         | `ripple`  |
| Wave           | `wave`    |
| Users          | `users`   |
| RBAC           | `rbac`    |


# Permissions

{% hint style="warning" %}
This is still a draft version.
{% endhint %}

## Permissions

The following tables list all supported permissions under Mobingi RBAC across all namespaces.

* The permissions are hierarchical. Any user with permissions in the higher hierarchy will have permissions in the lower hierarchy as well. For example, `Admin` will have all permissions in the respective namespace.
* Some permissions can have resources filter. Empty filter will mean all resources allowed. Resources filter also follow the same hierarchical logic and only `Allow` effect is supported as of now.

### RBAC permissions

The following table lists the permissions supported under RBAC management. RBAC permissions belong to the `rbac` namespace.

| Permission          | Description                                                  | Resources Supported |
| ------------------- | ------------------------------------------------------------ | ------------------- |
| Admin               | No restrictions. Root user, by default, has this permission. |                     |
| \|--ModifyRoles     | Allowed to modify RBAC roles.                                |                     |
| \|--ModifyUserRoles | Allowed to modify user-role mappings.                        |                     |
| \|----ReadOnly      | View RBAC permissions, roles, and mappings.                  |                     |

### Wave permissions

The following table lists the permissions supported under RBAC for Wave. Wave permissions belong to the `wave` namespace.

| Permission                | Description                                                  | Resources Supported |
| ------------------------- | ------------------------------------------------------------ | ------------------- |
| Admin                     | No restrictions. Root user, by default, has this permission. |                     |
| \|--ReadAccount           | View account list only.                                      | Accounts            |
| \|--ModifyAccountSettings | Allowed to modify account level settings.                    | Accounts            |
| \|----ReadAccountSettings | View account level settings only.                            | Accounts            |
| \|--DownloadBulk          | Allowed to download bulk CSV.                                |                     |
| \|--ModifyGroups          | Allowed to modify groups.                                    | Account groups      |
| \|----ReadGroups          | View groups only.                                            | Account groups      |
| \|--ReadInvoice           | View invoices only                                           |                     |
| \|--ReadRi                | View RIs only                                                |                     |
| \|--ReadSavingsPlan       | View savings plan only                                       |                     |
| \|--ModifySettings        | Allowed to modify global Wave settings.                      |                     |
| \|----ReadSettings        | View global Wave settings only.                              |                     |
| \|--ModifyTags            | Allowed to modify tags.                                      |                     |
| \|----ReadTags            | View tags only.                                              |                     |

### Ripple permissions

The following table lists the permissions supported under RBAC for Ripple. Ripple permissions belong to the `ripple` namespace.

| Permission                      | Description                                                  | Resources Supported |
| ------------------------------- | ------------------------------------------------------------ | ------------------- |
| Admin                           | No restrictions. Root user, by default, has this permission. |                     |
| \|--ModifyBillingGroup          | Allowed to modify billing group settings.                    | Billing groups      |
| \|----ReadBillingGroup          | View billing group only.                                     | Billing groups      |
| \|------ModifyAccount           | Allowed to modify account section settings.                  | Billing groups      |
| \|--------ReadAccount           | View account section only.                                   | Billing groups      |
| \|------ModifyInvoice           | Allowed to modify invoice section settings.                  | Billing groups      |
| \|--------ReadInvoice           | View invoice section only.                                   | Billing groups      |
| \|------ModifyInvoiceSettings   | Allowed to modify invoice settings.                          | Billing groups      |
| \|--------- ReadInvoiceSettings | View invoice settings only.                                  | Billing groups      |
| \|------ModifyReseller          | Allowed to modify reseller section settings.                 | Billing groups      |
| \|--------ReadReseller          | View reseller section only.                                  | Billing groups      |
| \|--ModifyCustomField           | Allowed to modify custom field settings.                     |                     |
| \|----ReadCustomField           | View custom field settings.                                  |                     |
| \|--ModifyCustomService         | Allowed to modify custom services settings.                  |                     |
| \|----ReadCustomService         | Read custom service settings only.                           |                     |
| \|--ModifyInvoiceTemplate       | Allowed to modify invoice templates.                         |                     |
| \|----ReadInvoiceTemplate       | View invoice templates only.                                 |                     |
| \|--ModifyOriginalCost          | Allowed to modify original cost settings.                    |                     |
| \|----ReadOriginalCost          | Read original cost only                                      |                     |
| \|--ModifyProject               | Allowed to modify projects.                                  |                     |
| \|----ReadProject               | Read projects only.                                          |                     |
| \|--ReadReport                  | Read reports only.                                           |                     |
| \|--ModifyRi                    | Allowed to modify RI section settings.                       |                     |
| \|----ReadRi                    | View RI section only.                                        |                     |
| \|--ReadSavingsPlan             | Read savings plan only.                                      |                     |
| \|--ModifySettings              | Allowed to modify global Ripple settings.                    |                     |
| \|----ReadSettings              | View global Ripple settings only.                            |                     |
| \|--ModifyTags                  | Allowed to modify tags.                                      |                     |
| \|----ReadTags                  | View tags only.                                              |                     |

### User permissions

The following table lists the permissions supported under user management. User permissions belong to the `user` namespace.

| Permission      | Description                                                  | Resources Supported |
| --------------- | ------------------------------------------------------------ | ------------------- |
| Admin           | No restrictions. Root user, by default, has this permission. |                     |
| \|--ModifyUsers | Allowed to modify user attributes.                           |                     |
| \|----ReadOnly  | View user information, including API clients.                |                     |


# Mobingi Ripple Help Center

For Mobingi Ripple users, here are some information and tips for using Ripple. If you have additional questions, please feel free to contact <ripple_cs@mobingi.com>.


# What is Mobingi Ripple?

## Overview

Mobingi Ripple is an AWS invoice auto-calculation and invoicing tool for AWS resellers, MSPs.

This tool reduces labor costs by automating traditional Excel manual calculations. Please read this for details.

## What you can do with Ripple

* Manage the relationship between customer and AWS account
* Re-calculate the blend of RIs and output the correct unblended invoice.&#x20;

　・Streamline billing operations

　・ Improve reseller revenue

## 1.Streamline billing operations

By automating traditional manual tasks, you can reduce working time, standardize calculation methods and eliminate mistakes caused by human work.

## 2.Improve profitability of resellers

Buy and use the proper amount of RI at the right timing.

## Mobingi Ripple and Mobingi Wave

Based on the Ripple data registered by reseller, the appropriate usage charge can be calculated, and the end user can check the billing information on Wave.


# Ripple settings

Be sure to set the following items before using Ripple:&#x20;

{% content-ref url="/pages/-LETNdCbuScODBPoPG85" %}
[Preparation](/ripple-en/mobingi-ripple/ripplenosettoappu/introduction)
{% endcontent-ref %}

Set up below before start creating invoice:&#x20;

{% content-ref url="/pages/-LejTMEtrUPccv-NU0iw" %}
[Invoice setting](/ripple-en/mobingi-ripple/ripplenosettoappu/qiu-ding)
{% endcontent-ref %}


# Preparation

* This page explains things you need to be done on your AWS account for start using Mobingi Ripple.
* After finishing preparation, you will need to give Mobingi the below informations.&#x20;

```
- AWS account ID (12 digit numbers).

- Information of the report you made.

    - Report name

    - S3 bucket

    - Report path prefix, or Report path

- ARN of IAM Role which allow the specific bucket.(Ex: arn:aws:iam::xxxxxxxxxxxx:role/crossacounnt-access-for-mobingi)
```

## Step 1 : Create S3 bucket and daily report (option) <a href="#step1" id="step1"></a>

* Create daily repot with the AWS account you want to share the billing information with Ripple.
* You can skip if you already have the report definition with below conditions.

  `Time unit:` `Hourly`

  `Rsource IDsis included in the report.`

  `There is no object which Mobingi shouldn't see.(Since the access atuhority will be a whole bucket).`

### Step1-1: **Create S3 bucket**

* Create bucket with any name from S3 bucket. Option can leave as default.

  Please keep the bucket name for using it as output destination of report.

### Step1-2: Create daily report

* Choose **Billing** from AWS management console and move to **Reports**.

Click **Create report**.

![](/files/-LIOgRG3_avdKD30zae4)

* Fill out `Step 1: Select Content` same as below.
  * Report name: Any
  * Time unit: **Hourly**
  * Include: **Resource IDs**
  * Enable support for...: Optional

![](/files/-LNwmUKCPN2a-tHp6BHy)

* `Step2: Select Delivery Options` will be the following process.
  * Put S3 bucket name (you made at Step1-1)
  * Display and copy **Sample policy** (\* make sure to click after you entered S3 bucket name)

![](/files/-LNwm_N5JlakvI_PiQpw)

![](/files/-LIOjN11YZ8VXI-P4kT7)

* After copy **sample policy,** open the **S3 bucket which you create on step1-1** and open detail (\* we suggest to open the page with new window or new tab).
* On S3 page, go to **Permissions** >> **Bucket Policy.**
* Put the policy you copied at before into **Bucket policy editor** and Save.

![](/files/-LIOnVSCnSHb5s4vee-1)

Go back to `Step2: Select Delivery Options` and put below info.

* Report path prefix: Optional  (\*blank also works)&#x20;
* Compression: Optional

It shows **Valid Bucket** only when the bucket policy is correct.

Check your S3 again.

![](/files/-LNwmf-PVVBjsAW96zgi)

Check the info again and click **Review and Complete.**

![](/files/-LNwml6cxEDp0N4vglQS)

## Step 2 : Create IAM role for Mobingi <a href="#step2" id="step2"></a>

From AWS management console, select **IAM** service and click **Roles** >> **Create role.**

![](/files/-LIiFOMlOXismoU7Y_Tq)

Choose **Another AWS Account** at `Select type of trusted entity`and put Mobingi account ID.

* Mobingi Account ID: 131920598436

![](/files/-LIiGT4sBGfZ4xKWnQ9H)

Click **Create policy**.

![](/files/-LIiGvwlVshnEL6lGAek)

New tab or window will open. Choose JSON as input format and type the policy same as below. Make sure to change`{replace_to_report_bucket}` at "Resource" to **the bucket name you use for report.**

```bash
{
    "Version": "2012-10-17",
    "Statement": [
         {
               "Effect": "Allow",
               "Action": [
                     "s3:Get*",
                     "s3:List*"
               ],
               "Resource": [
                     "arn:aws:s3:::{replace_to_report_bucket}",
                     "arn:aws:s3:::{replace_to_report_bucket}/*"
               ]
         }
   ]
}
```

![](/files/-LYdjugo94_Cm8941hZZ)

After fill the informations below, you can finish to create policy.

* Name: Any (\*required)
* Description: Option

![](/files/-LIiFgJCKNMA3R9_Zi3Y)

Go back to **Create Role** and refresh, the policy suppose to display on the list. Active the policy and move to review page. *\*\**

![](/files/-LIiI6Exnwh5jADTN7Dx)

At **Review**, fill the informations below.

* Role name: Any (\*required)
* Role description: Option

After check **Trusted entities** and **Policies** are correctly applied, click **Create role**.

![](/files/-LIiK5CyayelVEmWrwY1)

Keep the ARN of the role.


# Invoice setting

{% hint style="info" %}
&#x20;This item is provided as a standard plan of Ripple.
{% endhint %}

The following settings can edit from `Preferences`> `Invoice Settings` page, left menu.

* Rounding: Rounding down, rounding up and rounding off  .You can set the treatment of decimal places at the time the usage converted to Japanese yen.


# Monthly Invoicing Procedure

Here is an orderly description of what you need to do every beginning of the month.

{% content-ref url="/pages/-LejThZfSR3BhGVHhMwL" %}
[1. Notification of confirmation of billing data](/ripple-en/mobingi-ripple/routine/click-button)
{% endcontent-ref %}

{% content-ref url="/pages/-LetL9YRvvcrcX8YZJ2c" %}
[2. Exchange rate setting](/ripple-en/mobingi-ripple/routine/2.-exchange-rate-setting)
{% endcontent-ref %}

{% content-ref url="/pages/-LetLLru5Bft8V6Id2-\_" %}
[3. Include the cost of the shot in the bill](/ripple-en/mobingi-ripple/routine/3.-include-the-cost-of-the-shot-in-the-bill)
{% endcontent-ref %}

{% content-ref url="/pages/-LetE6-YN5y88SGV3S\_6" %}
[4. Create invoice](/ripple-en/mobingi-ripple/routine/4-no)
{% endcontent-ref %}

{% content-ref url="/pages/-LetEGHQKBDKViTPBUb8" %}
[5. Check the invoice data](/ripple-en/mobingi-ripple/routine/5-shitanotodaunrdo)
{% endcontent-ref %}

{% content-ref url="/pages/-LetEQlqfhPMqpyRtb9F" %}
[6. Present invoice details to end user](/ripple-en/mobingi-ripple/routine/6-endoyzniwo)
{% endcontent-ref %}


# 1. Notification of confirmation of billing data

You will receive an invoice from AWS between 3rd to 7th day of every month. When you receive the invoice, click the `Report billing finalization` button on the Ripple Dashboard.

Within 2 business days, our support team (<ripple_cs@mobingi.com>) send an e-mail with the title of `[Company name] x (month) Complete notification of billing data calculation request.` If you receive this email, please proceed to the next step.

{% hint style="info" %}
If you would like to include a temporary fee in the bill that does not appear on your regular invoice, such as AWS support fee, AWS-provided credit, refund, etc., please click the " Report billing finalization" after 7th day of month.
{% endhint %}


# 2. Exchange rate setting

Let's set the exchange rate for this month.

1\. The exchange rate settings can be made by following process.

Click Invoices> `Conversion rate setting` on the left menu

Click `Register Exchange Rate` in the upper right

Enter the exchange rate for Set month.

Resetting the rate will overwrite the rate for the current month. You can not change past data.


# 3. Include the cost of the shot in the bill

Here's how to check your AWS support fee, Reserved Instance (RI) prepayment, Marketplace purchase costs, AWS-issued credits, refunds, and other non-invoice bill shots and how to include them in your bill.

Click Invoices> `Invoice recalculation summary`  on the left menu.

This page displays a list of shot costs. These lump sums are fixed around the 7th of every month.


# 4. Create invoice

After pressing the confirmation button, the email will be sent from our support within 2 business days. Please proceed to below steps after receiving the email.

## How to bulk create invoice.

{% hint style="info" %}
You can change the invoice settings temporarily, such as changing the discount rate only for that month.&#x20;
{% endhint %}

1. Go to Invoice> `Create Invoice` from the left menu.
2. Select the billing month.
3. You can create invoices in bulk by clicking `Create Invoice`> `Invoice creation`> `Bulk create for all items`  at the top right of the screen.<br>

## How to create individually

Discount rates, consumption tax rates, agency fees, etc. can be reflected individually in the relevant month or in any billing group.

1. Go to Invoice> `Create Invoice` from the left menu.
2. Select the billing month.
3. Check the check box of the billing group you want to create individually (multiple selections possible).
4. You can create invoices individually by clicking `Create Invoice`> `Create for selected items` > Batch on the top right of the screen.


# 5. Check the invoice data

You can check the details of the invoice you created on the screen. You can also download it as CSV data.

## Confirm the item from the screen

From the left menu, select Invoices> `Create Invoices`, and you will see a list of issued invoices. Click on the items of the billing group and you check the details of that invoices.

* By printing that page, you can use it as an invoice / billing statement.
* Invoices created once are saved in Ripple.
* If you re-create the invoice, it will be overwritten.

## Download CSV data

CSV data of billing statement can be downloaded for one month at a time.

You can download data by `account / service unit` or `Tag unit`.

{% hint style="info" %}
Please see here for creating billing data in tags.
{% endhint %}

You can download the CSV data of all billing groups by clicking the download button next to the display of "Invoicing" from Invoices> `Create Invoice` from the left menu.


# 6. Present invoice details to end user

Here are two ways to present invoice details to end users.

## Present invoices to customers in PDF file format

You can check the billing statement for any billing group by clicking Check invoice. If you save the screen as a PDF file, you can present the PDF file to the customer.

## Use Wave for Reseller

By issuing a Wave for Reseller account for end users, the end users can view billing information online through Mobingi Wave.

{% content-ref url="/pages/-LeujNQgAaxJxRDvgLS9" %}
[What is Wave for Reseller?](/ripple-en/in-detail/what-is-wave-for-reseller)
{% endcontent-ref %}


# Invoice

Here, we introduce the functions of the "`Invoices`" section in the left menu.

## Create invoice

Create an invoice for each billing group.

{% content-ref url="/pages/-LetE6-YN5y88SGV3S\_6" %}
[4. Create invoice](/ripple-en/mobingi-ripple/routine/4-no)
{% endcontent-ref %}

## Recalculation billing data list

It shows RI prepayments, support charges, credits, refunds, etc.

If you make a mistake in the RI owner setting, or if you forgot to register the account you added on AWS, you need to request recalculation after setting and registering again.

There is no need to recalculate invoice settings such as fees and support charges, and you can create invoices immediately after changing the settings.

## Conversion rate setting

Set the monthly exchange rate required for billing.

{% content-ref url="/pages/-LetL9YRvvcrcX8YZJ2c" %}
[2. Exchange rate setting](/ripple-en/mobingi-ripple/routine/2.-exchange-rate-setting)
{% endcontent-ref %}


# Reserved Instance

Here, we introduce the functions of the " `Reserved Instances` " section in the left menu.

## RI management

Manage purchased RI. RI allocation can be done by clicking `•••`> `RI editing`.

{% content-ref url="/pages/-Leuivd3PgiEpsx\_esrv" %}
[Change RI allocation](/ripple-en/in-detail/change-ri-allocation)
{% endcontent-ref %}

## RI application rate

You can view the application status of your RI for the currently running instance.

## RI recommendation

Based on the application status, the maximum number of Reserved Instances that can be purchased is displayed.

If you select "full prepayment", "partial prepayment" or "no prepayment" for the payment option, simulation of reduction cost for each payment form is displayed.

You can view the details from the dropdown of each row.


# Account and Group

Here, we introduce the functions of the " `Account and Group` " section in the left menu.

## Billing group

You can create, review and edit billing groups. In addition, you can make settings such as commissions and support charges (with Invoice settings).

{% content-ref url="/pages/-Leu\_KhICmv6l6Erk3TG" %}
[Add a new customer](/ripple-en/in-detail/add-a-new-customer)
{% endcontent-ref %}

## Account

Manage the relevancy of each AWS account and billing group customer, and the relationship between AWS account and Payer Account.You can also add, edit and delete accounts from this page.

## Wave for Reseller

Wave for Reseller

Wave for Reseller is a page for Ripple users to issue Mobingi Wave login information for their company and customers.

{% content-ref url="/pages/-LeujNQgAaxJxRDvgLS9" %}
[What is Wave for Reseller?](/ripple-en/in-detail/what-is-wave-for-reseller)
{% endcontent-ref %}


# Preferences

Here, we introduce the functions of the " `Preferences`" section in the left menu.

## User Settings

You can change your Ripple account password.

Language settings can be selected from English and Japanese and Chinese.

## Payment account settings

You can add and delete AWS payment accounts (Payer Account).

## Invoice settings

Make common settings for all billing groups.

{% content-ref url="/pages/-LejTMEtrUPccv-NU0iw" %}
[Invoice setting](/ripple-en/mobingi-ripple/ripplenosettoappu/qiu-ding)
{% endcontent-ref %}

{% content-ref url="/pages/-LeujYt\_u5OQ0dzm2Y43" %}
[Setting of discounts and premium for each service](/ripple-en/in-detail/setting-of-discounts-and-premium-for-each-service)
{% endcontent-ref %}


# Add a new customer

## 1.Issue customer's AWS account from AWS

Issue an AWS account for the customer from the AWS Management Console.

## 2.Create billing group

From `Account and Groups`> `Billing Group` in the left menu, click `Add Billing group` on the top right of the screen.

## 3.Set invoice settings

Click `•••`> `Change invoice settings` for the billing group you created, and set up billing-related terms and conditions.

{% hint style="info" %}
It is necessary to set these beforehand to use “Invoice batch creation”.
{% endhint %}

## 4.Consolidate your AWS account to a billing group

From Account & Groups in the left menu, click Add Account in the upper right of the screen, and fill in the required fields and add.

{% hint style="danger" %}
**You cannot register duplicate account IDs that have already been registered.**
{% endhint %}

## More useful things to set:

### Register Wave for Reseller

By using Wave for Reseller, customers can check monthly billing information from the web.

{% content-ref url="/pages/-LeujNQgAaxJxRDvgLS9" %}
[What is Wave for Reseller?](/ripple-en/in-detail/what-is-wave-for-reseller)
{% endcontent-ref %}


# Change RI allocation

Mobingi Ripple automatically detects and displays the RI owned by the user.A notification will be displayed on the screen when a new RI is purchased.

Clicking on the notification takes you to the RI management screen.You can change the AWS account to attach by clicking `•••` > Edit RI.

If you change the owner of RI, re-aggregate the data on Ripple side, and then issue an invoice, it will be calculated with the changed data. The owner of RI on AWS does not change.

{% content-ref url="/pages/-LejT2UViTwRw5p7vWqB" %}
[Monthly Invoicing Procedure](/ripple-en/mobingi-ripple/routine)
{% endcontent-ref %}


# Create Billing data with tags

Here is the introduction of setting to create billing data with tags.

{% hint style="info" %}
The function to create billing data using tags is currently provided as an additional function to some customers. Please contact <ripple_cs@mobingi.com> if you are interested in.
{% endhint %}

1\. Activate the tag

First, you need to activate the tag you want to use for Ripple billing from the AWS screen.

(Move to Step 2 if already activated)

2.Change invoice settings to tags

Go to `Accounts and Group`> `Billing Groups` in the left menu.

Click `•••`> Change Invoice Settings for the billing group that you want to switch to tag aggregation within each billing group.

Change the aggregation type from `Account Aggregation` to `Tag Aggregation`.

When the Save button is clicked, a button for editing tag settings is displayed on `•••` in the billing group that reflects the settings.

3.Select the tag you want to include in the aggregation

Click Edit Tag Settings.

Select the tag values that you want to include in the aggregation.

After completing the settings 1 to 3 above, create billing data according to the normal billing procedure.

{% content-ref url="/pages/-LejT2UViTwRw5p7vWqB" %}
[Monthly Invoicing Procedure](/ripple-en/mobingi-ripple/routine)
{% endcontent-ref %}


# What is Wave for Reseller?

Wave for Reseller is a page for Ripple users to issue Mobingi Wave login information for their company and customers.

[What is Mobingi Wave?](https://mobingi.com/jp/product/wave/)

Wave for Reseller differs in functionality between "Ripple users " and "Ripple users' own company / customers ".

## Summary of function (for Ripple users)

Click View Wave and select the billing group you want to view.

You can check the details of usage during the month in the form of a graph or a table.

![](/files/-LeyLpJNCylB92fAQYtr)

## Summary of function (for Ripple users own company / customers)

Ripple users can offer Mobingi Wave with limited functionality to their own or customers.

You can view it by logging in from [this page ](https://app.mobingi.com/wave/login?redirect=%2Fdashboard)using the email / login ID and password registered in Wave for Reseller.

The available features are very simple and include the following features:

・Check the report for each account.

・Vheck the usage status of Reserved Instances (you can choose to show or not show).

・Check the usage details (you can choose to show or not show).

{% hint style="info" %}
If you would like your company or customers to provide usage details during the month, please contact <ripple_cs@mobingi.com>.
{% endhint %}


# Setting of discounts and premium for each service

Discounts and premiums can be set for each AWS service, such as EC2 and RDS.

・Set in bulk to all accounts

・Set for each account

{% hint style="info" %}
If you want to set by billing group, set one by one for each account.
{% endhint %}

## Set at once for all accounts

From `Preferences` on the left menu, click `Invoice Settings`> Per Service Settings. You can do this by setting up individual services.

The contents set here will be reflected from the next invoicing.

## Set per account

From `Preferences` on the left menu, click `Invoice Settings`> Per Service Settings.

Turn on the toggle button for Allow Per Account Settings.

Go to `Account and Groups`> `Account` on the left menu, and click on `•••`> Service-specific settings for the account you want to assign settings to display the settings screen.

For each account, you can set whether to activate / deactivate settings (The toggle button activates settings).


# Contents of CSV data

| Item             | Description                                                                          |
| ---------------- | ------------------------------------------------------------------------------------ |
| BillingGroupID   | Billing group ID of the billing group.                                               |
| BillingGroupName | Billing group name of the billing group.                                             |
| CompanypName     | Business name of the billing group.                                                  |
| CustomerID       | Account ID of AWS account registered in the billing group.                           |
| CustomerName     | Account name of the AWS account registered in the billing group.                     |
| ServiceType      | <p>Represents the type of service. One of Account, Product, or Service is displayed. |

</p><p>Account... ACCOUNT_TOTAL of ServiceName.</p><p>Product ... Indicates one of _SUPPORT_BUSINESS_JPY, _SUBSTITUTION_JPY, _TOTAL of ServiceName.</p><p>Service ... Indicates the value of lineItem / ProductCode of CUR.</p>                                                                                                                                                                                                                                                                                                                                     |
| ServiceName              | <p>Represents the name of the service. </p><p>_SUPPORT_BUSINESS_JPY ... AWS support costs (excl. Tax) set in the invoice settings of the billing group. </p><p>_SUBSTITUTION_JPY ... The agency fee (excl. Tax) set in the invoice settings of the billing group. </p><p>_TOTAL ... The total amount of BillingGroup ID (excluding tax). </p><p>_ACCOUNT_TOTAL ... Total amount per customer ID (excluding tax). </p><p>Other values ... AWS Cost and Usage Report (CUR) value of lineItem / ProductCode. <a href="https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/enhanced-lineitem-columns.html">Here</a> is the reference.</p><p></p> |
| Charge                   | Amount per ServiceName (excluding tax).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| DiscountCharge           | Discount amount (excluding tax).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| DiscountCharge - TaxFree | Discount amount (excluding tax).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| Tax                      | <p>Tax.</p><p> [DiscountCharge with ServiceName " _TOTAL" - TaxFree] * [Consumption tax rate set in invoice settings for billing group]</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| Total                    | <p>Total amount of BillingGroup ID (tax included). </p><p>[DiscountCharge with ServiceName "_TOTAL"] + [Tax]</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |


# Frequently asked Questions

I forgot my user ID or password.

Please contact <ripple_cs@mobingi.com>.

Does the operation in Ripple affect the billing from AWS?

It does not affect. Ripple is a tool for breaking the blend rate and knowing the correct amount of usage, so operations with Ripple do not affect the charges from AWS or the AWS account that you manage.

## Please tell me about the handling of the Marketplace.

Although it is included in the invoice and CSV together with the monthly usage fee, some charges shown as "Recurring fee" will be displayed on the "Recalculation Request Data List" page as a lump sum.

## When do I need to recalculate?

Please check the following "recalculation request data list" item.

{% content-ref url="/pages/-LetEt2gVVtKXIqSxRyY" %}
[Invoice](/ripple-en/search-by-features/qiu)
{% endcontent-ref %}

## Can I register multiple billing group IDs in one AWS account?

Customers can not register by themselves (as of April 2019).

Please contact <ripple_cs@mobingi.com> if you would like to.


# Overview

Alphaus provides an API for interacting with its services. The API is a RESTful API that can be accessed by an HTTP client such as `curl`, `wget`, or any HTTP library which is part of most modern programming languages.


# Endpoint limits

All Alphaus API endpoints are globally rate limited by default to 100 calls per second per user. To request for limit increase, please contact us through our various contact channels.


# Authentication

{% hint style="info" %}
Blue API (BETA) authentication is now available [here](https://alphauslabs.github.io/blueapi/authentication/apikey.html). Check it out.
{% endhint %}

{% hint style="info" %}
Authentication for [Wave (OpenAPI)](https://docs.mobingi.com/v/api-reference/wave-open-api/prerequest) is separated at the moment. We will be unifying all logins for all our APIs going forward. An announcement will be made once it's done.
{% endhint %}

Before you can access Alphaus API services, you need to get an access token first. You will then use this token in your succeeding calls to the API using the `Authorization: Bearer {token}` HTTP header. Alphaus API tokens are [JSON Web Tokens (JWT)](https://tools.ietf.org/html/rfc7519).

Use the following endpoints to acquire product-specific access tokens. Tokens are not compatible between the two. Ripple access tokens can only be used for Ripple endpoints; Wave access tokens are only valid on Wave endpoints.

```bash
# Ripple
https://login.alphaus.cloud/ripple/access_token

# Wave
https://login.alphaus.cloud/access_token
```

**Request**

To obtain an access token, send a POST message to the access token endpoint using the format described below.

```http
POST {access-token-url} HTTP1.1
Content-Type: multipart/form-data

{body formdata}
```

The following table describes the formdata you need to supply as your POST body.

| Name            | Value                                                                |
| --------------- | -------------------------------------------------------------------- |
| `grant_type`    | Valid values: `password`, `client_credentials`                       |
| `client_id`     | The client id you received from Alphaus or from API.                 |
| `client_secret` | The client secret you received from Alphaus or from API.             |
| `username`      | You account username. Required if `grant_type` is set to `password`. |
| `password`      | You account password. Required if `grant_type` is set to `password`. |
| `scope`         | Valid values: `openid`                                               |

**Response**

```ruby
HTTP/1.1 200 OK

{
  "id_token": "eyJ0eXAiOiJKV1Q...",
  "token_type": "Bearer",
  "expires_in": 86400,
  "access_token": "eyJ0eXAiOiJKV1Q...",
  "refresh_token": "def50200..."
}
```

**Using bluectl**

You can also use our [bluectl](https://github.com/alphauslabs/bluectl) CLI tool to generate access tokens. It is designed to work with the `client_credentials` grant type, although it supports the `password` grant type as well. To set the required environment variables for authentication, check out this [document](https://alphauslabs.github.io/blueapi/authentication/apikey.html).

```bash
# Simple version:
$ bluectl access-token

# You can also access our beta (next) environment:
$ bluectl access-token --beta

# Use with other commands (example):
$ curl -H "Authorization: Bearer $(bluectl access-token)" \
  https://some-ripple-endpoint/...
```


# Users

{% hint style="info" %}
New API available on <https://alphauslabs.github.io/blueapidocs/#/Iam>.
{% endhint %}

The following endpoint is the base url for the APIs below.

```
https://service.alphaus.cloud/m/u/
```

## Create subuser

Create new subuser.

**Request**

```http
POST /users HTTP1.1
authorization: Bearer {token}
content-type: application/json

{
  "username": "newsubuser",
  "password": "mysecretpassword",
  "email": "dev@mobingi.com",
  "notification": {
    "email": "false"
  }
}
```

Details for the POST `{body}`.

| Key                  | Value                                                                                                        |
| -------------------- | ------------------------------------------------------------------------------------------------------------ |
| `username`           | Required. Min: 4, max: 18, allowed characters: letters, numbers, \_ (underscore), . (period) and - (hyphen). |
| `password`           | Required. Min: 8, max: 18.                                                                                   |
| `notification.email` | Required. Enable or disable notifications. Valid values: `"true"`, `"false"`.                                |
| `email`              | Optional email address.                                                                                      |

**Response**

```ruby
HTTP/1.1 200 OK

[
  {
    "username":"mysubuser",
    "msp_user":"MSP-123456",
    "mobingi_user": "abcdef",
    "email":"mysubuser@domain.com",
    "nickname":"",
    ...
  }
]
```

## List subusers

List all subusers.

**Request**

```http
GET /users HTTP1.1
authorization: Bearer {token}
```

**Response**

```ruby
HTTP/1.1 200 OK

[
  {
    "username":"mysubuser",
    "msp_user":"MSP-123456",
    "mobingi_user": "abcdef",
    "email":"mysubuser@domain.com",
    "nickname":"",
    ...
  }
]
```


# API clients

{% hint style="info" %}
New API available on <https://alphauslabs.github.io/blueapidocs/#/Iam>.
{% endhint %}

The following endpoint is the base url for the APIs below.

```
https://service.alphaus.cloud/m/u/users/
```

## Create API client

Create a new API client under a specific user.

**Request**

```http
POST /client/:user HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{
  "name": "test-apiclient-name",
}
```

`:user` is either root user or subuser.

Details for the POST `{body}`.

| Key    | Value                                 |
| ------ | ------------------------------------- |
| `name` | Required. The name of the API client. |

**Response**

```ruby
HTTP/1.1 200 OK

{
  "client_id": "ripple-abcdef123456",
  "client_secret": "critical",
  "grant_type": "client_credentials",
  "create_time": "2020-06-27T11:26:46.257375295Z",
  "user_id": "id0001",
  "username": "someusername",
  "name": "test-apiclient-name"
}
```

## List API clients

List all API clients under a specific user.

**Request**

```http
GET /clients/:user HTTP1.1
Authorization: Bearer {token}
```

`:user` is either root user or subuser.

**Response**

```ruby
HTTP/1.1 200 OK

[
  {
    "client_id": "ripple-abcdef123456",
    "client_secret": "",
    "grant_type": "client_credentials",
    "create_time": "2020-06-15T05:07:50.258779172Z",
    "user_id": "id001",
    "name": "test-apiclient-name"
  },
  ...
]
```

## Delete API client

Delete an existing API client under a specific user.

**Request**

```http
DELETE /client/:user/:clientid HTTP1.1
Authorization: Bearer {token}
```

`:user` is either root user or subuser. `:clientid` is the client id to delete.

**Response**

```ruby
HTTP/1.1 200 OK

{
  "status": "success"
}
```


# Authorization (RBAC)

{% hint style="info" %}
New API available on <https://alphauslabs.github.io/blueapidocs/#/Iam>.
{% endhint %}

For general information about RBAC, check out this [link](https://docs.mobingi.com/v/ur-en/#rbac).

The following endpoint is the base url for the APIs below.

```
https://service.alphaus.cloud/m/auth/rbac/
```

## List permissions

List all permissions supported by RBAC in all namespaces. For reference, supported permissions can be found [here](https://github.com/mobingi/rbac-permissions).

**Request**

```http
GET /permissions HTTP1.1
authorization: Bearer {token}
```

**Response**

```ruby
HTTP/1.1 200 OK

[
  {
    "namespace":"wave",
    "permissions":[
      "Admin",
      "ModifySettings",
      "..."
    ]
  },
  {
    "namespace":"ripple",
    "permissions":[
      "Admin"
    ]
  }
]
```

## Create role

During role creation, if your `permissions` list contains an `Admin` entry, all other entries will be discarded except `Admin`.

Roles are root user-level. That means all roles created by the root user, or any subuser that has permissions to create roles, are available to all subusers.

**Request**

```http
POST /roles HTTP1.1
authorization: Bearer {token}
content-type: application/json

{
  "name":"testrole",
  "namespace":"wave",
  "permissions":[
    "ModifySettings",
    "ViewSettings",
    ...
  ]
}
```

Role names should have at least 6 characters in length and 32 characters maximum. It should also be alphanumeric. Hyphens and underscores are allowed in between. The regular expression used for validation is below:

```
^[A-Za-z0-9][A-Za-z0-9_-]*[A-Za-z0-9]$
```

**Response**

```ruby
HTTP/1.1 200 OK

{
  "name":"testrole",
  "namespace":"wave",
  "permissions":[
    "ModifySettings",
    "ViewSettings",
    ...
  ]
}
```

## List roles

**Request**

```http
GET /roles?namespace={namespace} HTTP1.1
authorization: Bearer {token}
```

The `{namespace}` parameter is optional. If not provided, all roles will be returned.

**Response**

```ruby
HTTP/1.1 200 OK

[
  {
    "name": "testrole",
    "namespace": "wave",
    "permissions": [
      "ModifySettings",
      "ViewSettings",
      "ModifyAccountSettings"
    ]
  },
  {
    "name": "waveAdmin",
    "namespace": "wave",
    "permissions": [
      "Admin"
    ]
  },
  ...
]
```

## Update role

Update role. If role name is different, rename mapped role name.

**Request**

```http
PATCH /roles/{namespace}/{rolename} HTTP1.1
authorization: Bearer {token}
content-type: application/json

{
  "namespace":"wave",
  "permissions":[
    "ModifySettings",
    "ViewSettings",
    ...
  ]
}
```

**Response**

```ruby
HTTP/1.1 200 OK

{
  "name": "testrole",
  "namespace":"wave",
  "permissions":[
    "ModifySettings",
    "ViewSettings",
    ...
  ]
}
```

## Delete role

Delete role. Deleting a role will also remove all mappings.

**Request**

```http
DELETE /roles/{namespace}/{rolename} HTTP1.1
authorization: Bearer {token}
```

## Map roles to user

You can only map (or attach) up to 5 roles to a user per namespace. There is no limit for filtering rules per user.

Valid values for `type` for filtering rules:

| Namespace | Value                       |
| --------- | --------------------------- |
| `wave`    | `linkAcct`, `group`, `tags` |
| `ripple`  | `billingGroup`              |

**Request**

```http
POST /userroles HTTP1.1
authorization: Bearer {token}
content-type: application/json

{
  "user_id":"subuser1",
  "roles":[
    {
      "namespace":"wave",
      "role": "somerole",
    },
    ...
    ]
}
```

**Response**

```ruby
HTTP/1.1 200 OK

{
  "success":[
    "somerole"
  ],
  "failed":[],
  "filters":[]
}
```

## List user role mappings

**Request**

For this endpoint, the returned role mappings are those attached to the caller.

```http
GET /userroles HTTP1.1
authorization: Bearer {token}
```

For listing role mappings of other subusers, use this endpoint.

```http
GET /{subuser}/userroles HTTP1.1
Authorization: Bearer {token}
```

`{subuser}` is the subuser name.

**Response**

```ruby
HTTP/1.1 200 OK

[
  {
    "root_user":"58c2297d25645",
    "sub_user":"subuser01",
    "namespace":"wave",
    "role":"testrole1"
  },
  {
    "root_user":"58c2297d25645",
    "sub_user":"subuser02",
    "namespace":"wave",
    "filter":"billingGroup:2222"
  },
  ...
]
```

## List user permissions

Retrieve all permissions to all roles attached to the `{subuser}`.

**Request**

```http
GET /{subuser}/permissions HTTP1.1
authorization: Bearer {token}
```

**Response**

```ruby
HTTP/1.1 200 OK

[
  {
    "namespace":"wave",
    "permissions":[
      "Admin",
      "ModifySettings",
      "..."
    ]
  },
  {
    "namespace":"ripple",
    "permissions":[
      "Admin"
    ]
  }
]
```

## Update map roles to user

You can only update map (or attach) up to 5 roles to a user per namespace. There is no limit for filtering rules per user.

Valid values for `type` for filtering rules:

| Namespace | Value                       |
| --------- | --------------------------- |
| `wave`    | `linkAcct`, `group`, `tags` |
| `ripple`  | `billingGroup`              |

This method replaces subuser's all roles to information in the request body.

**Request**

```http
PATCH /userroles HTTP1.1
authorization: Bearer {token}
content-type: application/json

{
  "roles":[
    {
      "namespace":"wave",
      "role": "somerole",
    },
    ...
    ]
}
```

```http
PATCH /{subuser}/userroles HTTP1.1
authorization: Bearer {token}
content-type: application/json

{
  "roles":[
    {
      "namespace":"wave",
      "role": "somerole",
    },
    ...
    ]
}
```

`{subuser}` is the subuser id.

**Response**

```ruby
HTTP/1.1 200 OK

{
  "success":[
    "somerole"
  ],
  "failed":[],
  "filters":[]
}
```


# Ripple

| Description  | Link                                  |
| ------------ | ------------------------------------- |
| API Base URL | `https://api.alphaus.cloud/m/ripple/` |


# User

ユーザーのAPIリファレンスは以下の通りです。

## Get user

ユーザー情報の取得

**Role actions**

* `ModifySettings`

**Request**

```http
GET /user HTTP1.1
Authorization: Bearer {token}
```

**Response**

```ruby
HTTP 200

{
  "msp_start": "2020-01",
  "language": "ja",
  "invoices_info": {},
  "invoice_meta": {},
  "meta": {},
  "services": [],
  "username": null,
  "support_fee": [],
  "msp_id": "MSP-5aa311904d5d6",
  "invoice_layout": {},
  "service_discount": {},
  "months": [],
  "export_digit": "up",
  "exchange_rate": [],
  "pay_accounts": [],
  "service_fee": null,
  "company_name": "Company Name",
  "reseller_lng": null,
  "email": "info@alphaus.cloud"
}
```

**exchange\_rate object例**

| Field | Type     | Description         |
| ----- | -------- | ------------------- |
| month | *string* | 月 format: `yyyy-mm` |
| rate  | *double* | 為替レート               |

```ruby
"exchange_rate": [
    {
      "month": "2020-04",
      "rate": 105.00
    }
]
```

**pay\_accounts object例**

vendor : aws

| Field               | Type     | Description          |
| ------------------- | -------- | -------------------- |
| vendor              | *string* | ベンダー                 |
| id                  | *string* | 支払いアカウント             |
| name                | *string* | 支払いアカウント名            |
| bucket\_name        | *string* | aws s3 bucket名       |
| prefix              | *string* | aws s3 bucket prefix |
| report\_name        | *string* | aws s3 report名       |
| role\_arn           | *string* | aws iam role arn     |
| report\_last\_saved | *string* | CUR更新日時              |

```ruby
"pay_accounts": [
    {
      "vendor": "aws",
      "id": "123456789109",
      "name": "Payer Account",
      "bucket_name": null,
      "prefix": null,
      "report_name": null,
      "role_arn": null,
      "report_last_saved": []
    }
]
```

vendor : azure

| Field             | Type     | Description            |
| ----------------- | -------- | ---------------------- |
| vendor            | *string* | ベンダー                   |
| id                | *string* | 支払いアカウント               |
| name              | *string* | 支払いアカウント名              |
| application\_name | *string* | azure application name |
| application\_id   | *string* | azure application id   |
| commerce\_id      | *string* | azure commerce id      |

```ruby
"pay_accounts": [
    {
      "vendor": "azure",
      "id": "1234567",
      "name": "Payer Account",
      "application_name": null,
      "application_id": null,
      "commerce_id": null
    }
]
```


# ExchangeRate

為替レートのAPIリファレンスは以下の通りです。

## Set exchange rate per month

月ごとの為替レートの更新

**Role actions**

* `ModifySettings`

**Request**

```http
POST /user/exchange HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
    "exchange_rate":
        {
            "rate":110,
            "month":"2020-01"
        }
}
```

**exchange\_rate object description**

| Field | Type     | Required | Validation | Description |
| ----- | -------- | -------- | ---------- | ----------- |
| rate  | *double* | Yes      | -          | 為替レート       |
| month | *string* | Yes      | -          | 対象月         |

**Response**

```ruby
HTTP 200

{
  "status": "success"
}
```

## List exchange rate

月ごとの為替レートの取得。ドキュメント[`get:/user`](https://docs.mobingi.com/v/api-reference/ripple/user) レスポンス`{exchange_rate}`から確認できます。

## List invoice id exchange rate per month

月ごとのInvoiceID為替レートの取得

**Role actions**

* `ModifySettings`
* `ReadSettings`

**Request**

```http
GET /invoiceid/exchangerate/{vendor}/{month} HTTP1.1
Authorization: Bearer {token}

{request body}
```

リクエストパラーメータの`{month}`のフォーマット: `yyyy-mm` 例: 2020-01 \
リクエストパラーメータの`{vendor}`のサポートベンダー: `aws`,`azure`

**Response**

```ruby
HTTP 200

[
  {
    "invoice_id":"738676530",
    "account_id":"128347567789",
    "exchange_rate":107.302
  },
  {
    "invoice_id":"123656789",
    "account_id":"987655467321",
    "exchange_rate": null
  }
]
```

## Set invoice id exchange rate per month

月ごとのInvoiceID為替レートの設定

**Role actions**

* `ModifySettings`

**Request**

```http
POST /invoiceid/exchangerate/{vendor}/{month} HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

リクエストパラーメータの`{month}`のフォーマット: `yyyy-mm` 例: 2020-01 \
リクエストパラーメータの`{vendor}`のサポートベンダー: `aws`,`azure`

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
  "settings": [
    {
      "account_id":"987655467321",
      "invoice_id":"123656789",
      "exchange_rate":101.07
    }
  ]
}
```

| Field          | Type     | Required | Validation | Description        |
| -------------- | -------- | -------- | ---------- | ------------------ |
| account\_id    | *string* | Yes      | -          | 支払いアカウント           |
| invoice\_id    | *string* | Yes      | -          | 支払いアカウントのInvoiceID |
| exchange\_rate | *double* | Yes      | -          | 為替レート              |

**Response**

```ruby
HTTP 200

{
  "status":"success",
  "error_data": []
}
```

## List payer account id exchange rate per month

月ごとのPayerAccountID為替レートの取得

**Role actions**

* `ModifySettings`
* `ReadSettings`

**Request**

```http
GET /payer/exchange_rate/{month} HTTP1.1
Authorization: Bearer {token}

{request body}
```

リクエストパラーメータの`{month}`のフォーマット: `yyyy-mm` 例: 2020-01

**Response**

```ruby
HTTP 200

[
  {
    "id":"128347567789",
    "vendor":"aws",
    "name":"Payer Account",
    "exchange_rate":109.154
  },
  {
    "id":"111345678911",
    "vendor":"aws",
    "name":"Payer Account2",
    "exchange_rate":108.02
  }
]
```

## Set payer account id exchange rate per month

月ごとのPayerAccountID為替レートの設定

**Role actions**

* `ModifySettings`

**Request**

```http
POST /payer/exchange_rate/{month} HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

リクエストパラーメータの`{month}`のフォーマット: `yyyy-mm` 例: 2020-01

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
  "settings": [
    {
      "vendor":"aws",
      "account_id":"128347567789",
      "exchange_rate":109.154
    }
  ]
}
```

| Field          | Type     | Required | Validation    | Description |
| -------------- | -------- | -------- | ------------- | ----------- |
| vendor         | *string* | Yes      | `aws`,`azure` | ベンダー        |
| account\_id    | *string* | Yes      | -             | 支払いアカウント    |
| exchange\_rate | *double* | Yes      | -             | 為替レート       |

**Response**

```ruby
HTTP 200

{
  "status":"success"
}
```

## Set invoice exchange rate per month

月ごとの請求書設定の為替レートの更新

**Role actions**

* `ModifyInvoice`

**Request**

```http
POST /invoices/exchangerate/{month} HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

リクエストパラーメータの`{month}`のフォーマット: `yyyy-mm` 例: 2020-01

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
  "vendor":"aws",
  "billing_groups": [
    "abcdfeg",
    "hijklmn"
  ],
  "exchange_rate":105.076
}
```

| Field           | Type     | Required | Validation           | Description |
| --------------- | -------- | -------- | -------------------- | ----------- |
| vendor          | *string* | Yes      | サポート: `aws`, `azure` | ベンダー        |
| billing\_groups | *object* | Yes      | -                    | 請求グループ一覧    |
| exchange\_rate  | *double* | Yes      | -                    | 為替レート       |

**Response**

```ruby
HTTP 200

{
  "status":"success"
}
```


# BillingGroup

請求グループのAPIリファレンスは以下の通りです。

## Create

請求グループの作成

**Role actions**

* `ModifyBillingGroup`&#x20;

**Request**

```http
POST /billinggroup HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
    "billinggroup_id":"Billing1",
    "billinggroup_name":"Billing1",
    "company_name":"Billing1 company",
    "phone":"03‐1234‐5678",
    "postal":"12345",
    "address":"123 street",
    "billing_title":"billing title",
    "personal":"personal name",
    "remarks":"test automation",
    "inv_aggregate":false,
    "language":"ja",
    "invoices": {
        "aws": {
            "calc_type":"account",
            "currency":"jpy",
            "discount_calc_logic":"usageamount",
            "discount_rate":0,
            "discount_target_usage":"cloudpaywithfee",
            "substitution_fee":"percent",
            "substitution_fee_calc_target":"nondiscount",
            "substitution_fee_calc_type":"allsum",
            "substitution_fee_target_usage":"cloudpaywithfee",
            "substitution_fix":0,
            "substitution_rate":0,
            "support_amount_target":"allusage",
            "support_fee":"fix",
            "support_fee_calc_target":"nondiscount",
            "support_fix":0,
            "support_rate":0,
            "tax_rate":0
        }
  }
}
```

**{request body} description**

| Field                 | Type      | Required | Validation       | Description                             |
| --------------------- | --------- | -------- | ---------------- | --------------------------------------- |
| billinggroup\_id      | *string*  | Yes      | -                | Billing group ID                        |
| billinggroup\_name    | *string*  | Yes      | -                | Billimg group name                      |
| company\_name         | *string*  | Yes      | -                | Company name                            |
| phone                 | *string*  | No       | -                | Tel                                     |
| postal                | *string*  | No       | -                | Postal                                  |
| address               | *string*  | No       | -                | Address                                 |
| billing\_title        | *string*  | No       | -                | Invoice title                           |
| personal              | *string*  | No       | -                | Personal name                           |
| remarks               | *string*  | No       | -                | Memo                                    |
| inv\_aggregate        | *boolean* | Yes      | -                | Displaying invoice in bulk or by vendor |
| project\_id           | *string*  | No       | -                | Project id                              |
| invoice\_template\_id | *string*  | No       | -                | Invoice template id                     |
| invoices              | \[object] | No       | -                | Invoice setting                         |
| language              | *string*  | No       | サポート: `ja`, `en` | Display invoice language setting        |

**invoices object description**

| Field                            | Type     | Required | Validation                                                                 | Description              |
| -------------------------------- | -------- | -------- | -------------------------------------------------------------------------- | ------------------------ |
| calc\_type                       | *string* | Yes      | - account   - tag                                                          | Invoice calculation type |
| currency                         | *string* | Yes      | - jpy   - usd                                                              | Currency                 |
| discount\_calc\_logic            | *string* | Yes      | - usageamount                                                              | -                        |
| discount\_rate                   | *double* | Yes      | 0.00 \~ 1.00                                                               | -                        |
| discount\_target\_usage          | *string* | Yes      | - cloudpaywithfee   - cloudpayonly                                         | -                        |
| substitution\_fee                | *string* | Yes      | - percent   - fix   - automatic   - usagetable                             | -                        |
| substitution\_fee\_calc\_target  | *string* | Yes      | - nondiscount   - discounted                                               | -                        |
| substitution\_fee\_calc\_type    | *string* | Yes      | - allsum   - account                                                       | -                        |
| substitution\_fee\_target\_usage | *string* | Yes      | - cloudpaywithfee   - cloudpayonly                                         | -                        |
| substitution\_fix                | *double* | Yes      | 00 \~ 1000000                                                              | -                        |
| substitution\_rate               | *double* | Yes      | 0.00 \~ 1.00                                                               | -                        |
| support\_amount\_target          | *string* | Yes      | - allusage                                                                 | -                        |
| support\_fee                     | *string* | Yes      | - fix   - percent   - aws\_developer   - aws\_business   - aws\_enterprise | -                        |
| support\_fee\_calc\_target       | *string* | Yes      | - nondiscount   - discounted                                               | -                        |
| support\_fix                     | *double* | Yes      | 0.00 \~ 1000000                                                            | -                        |
| support\_rate                    | *double* | Yes      | 0.00 \~ 1.00                                                               | -                        |
| tax\_rate                        | *double* | Yes      | 0.00 \~ 0.10                                                               | Tax                      |

**Response**

```ruby
HTTP 200

{
    "status":"success",
    "company_id":"RomwoEjdjhws",
    "billinggroup_id":"Billing1"
}
```

**Pythonでのサンプル**

```
import requests
import json

def get_token():
    # Note: you can see details https://docs.alphaus.cloud/v/api-reference/authentication
    # Assign generated values for client_id and client_secret
    params={
        "grant_type": "client_credentials",
        "client_id": "{client_id}",
        "client_secret": "{client_secret}",
        "scope": "openid",
    }
    try:
        response = requests.post(
            url="https://login.alphaus.cloud/ripple/access_token",
            headers={
            },
            params=params,
            files=params,
        )
    except requests.exceptions.RequestException:
        print('HTTP Request failed')

    r = response.json()
    return r['access_token'], r["token_type"]

def send_request(type, token):
    # Authorization header
    auth = type + " " + token
    try:
        response = requests.post(
            url="https://api.alphaus.cloud/m/ripple/billinggroup",
            headers={
                "Content-Type": "application/json;",
                "Authorization": auth
            },
            data=json.dumps({
                "display_cost": "true_unblended_cost",
                "phone": None,
                "billinggroup_id": "BG-SAMPLE-01",
                "billinggroup_name": "BG-SAMPLE-01",
                "inv_aggregate": True,
                "personal": None,
                "exchange_rate_type": None,
                "company_name": "BG-SAMPLE-01",
                "postal": None,
                "address": None,
                "billing_title": None,
                "remarks": None
            })
        )
        print('Response HTTP Status Code: {status_code}'.format(
            status_code=response.status_code))
        print('Response HTTP Response Body: {content}'.format(
            content=response.content))
    except requests.exceptions.RequestException:
        print('HTTP Request failed')

access_token, token_type = get_token()
send_request(token_type, access_token)
```

## List

請求グループリストの取得

**Role actions**

* `ReadBillingGroup`&#x20;
* `ModifyBillingGroup`&#x20;

**Request**

```http
GET /billinggroup HTTP1.1
Authorization: Bearer {token}
```

**Response**

```ruby
HTTP 200

[
    {
    "company_id":"RomwoEjdjhws",
    "billinggroup_id":"Billing1",
    "billinggroup_name":"Billing1",
    "name":"Billing1 Company",
    "invoices":{
        "aws": {
            "calc_type":"account",
            "currency":"jpy",
            "discount_calc_logic":"usageamount",
            "discount_rate":0,
            "discount_target_usage":"cloudpaywithfee",
            "substitution_fee":"percent",
            "substitution_fee_calc_target":"nondiscount",
            "substitution_fee_calc_type":"allsum",
            "substitution_fee_target_usage":"cloudpaywithfee",
            "substitution_fix":0,
            "substitution_rate":0,
            "support_amount_target":"allusage",
            "support_fee":"fix",
            "support_fee_calc_target":"nondiscount",
            "support_fix":0,
            "support_rate":0,
            "tax_rate":0
        }
        "azure": {
            "calc_type":"account",
            "currency":"jpy",
            "discount_calc_logic":"usageamount",
            "discount_rate":0,
            "discount_target_usage":"cloudpaywithfee",
            "substitution_fee":"percent",
            "substitution_fee_calc_target":"nondiscount",
            "substitution_fee_calc_type":"allsum",
            "substitution_fee_target_usage":"cloudpaywithfee",
            "substitution_fix":0,
            "substitution_rate":0,
            "support_amount_target":"allusage",
            "support_fee":"fix",
            "support_fee_calc_target":"nondiscount",
            "support_fix":0,
            "support_rate":0,
            "tax_rate":0
        }
    },
    "contact":"personal name",
    "address":"123 street",
    "postal":"12345",
    "phone":"03‐1234‐5678",
    "title":null,
    "req_generate":null,
    "remarks":null,
    "inv_aggregate":null,
    "project_id":null,
    "project_code":null,
    "project_label":null,
    "project_currency":null,
    "language":"ja",
    "qrcode":false,
    "invoice_template_id":null,
    "custom_fields":null,
    "untagged_groups":null,
    "account":[],
    "tag":[]
    },
    ...
]
```

## List details

請求グループ詳細の取得

**Role actions**

* `ReadBillingGroup`&#x20;
* `ModifyBillingGroup`&#x20;

**Request**

```http
GET /billinggroup/{id}/resource HTTP1.1
Authorization: Bearer {token}
```

リクエストパラーメータの`{id}`は請求グループ内部ID`{company_id}`です

**Response**

```ruby
HTTP 200

{
    "company_id":"RomwoEjdjhws",
    "billinggroup_id":"Billing1",
    "billinggroup_name":"Billing1",
    "name":"Billing1 Company",
    "invoices":{
        "aws": {
            "calc_type":"account",
            "currency":"jpy",
            "discount_calc_logic":"usageamount",
            "discount_rate":0,
            "discount_target_usage":"cloudpaywithfee",
            "substitution_fee":"percent",
            "substitution_fee_calc_target":"nondiscount",
            "substitution_fee_calc_type":"allsum",
            "substitution_fee_target_usage":"cloudpaywithfee",
            "substitution_fix":0,
            "substitution_rate":0,
            "support_amount_target":"allusage",
            "support_fee":"fix",
            "support_fee_calc_target":"nondiscount",
            "support_fix":0,
            "support_rate":0,
            "tax_rate":0
        }
        "azure": {
            "calc_type":"account",
            "currency":"jpy",
            "discount_calc_logic":"usageamount",
            "discount_rate":0,
            "discount_target_usage":"cloudpaywithfee",
            "substitution_fee":"percent",
            "substitution_fee_calc_target":"nondiscount",
            "substitution_fee_calc_type":"allsum",
            "substitution_fee_target_usage":"cloudpaywithfee",
            "substitution_fix":0,
            "substitution_rate":0,
            "support_amount_target":"allusage",
            "support_fee":"fix",
            "support_fee_calc_target":"nondiscount",
            "support_fix":0,
            "support_rate":0,
            "tax_rate":0
        }
    },
    "contact":"personal name",
    "address":"123 street",
    "postal":"12345",
    "phone":"03‐1234‐5678",
    "title":null,
    "req_generate":null,
    "remarks":null,
    "inv_aggregate":null,
    "project_id":null,
    "project_code":null,
    "project_label":null,
    "project_currency":null,
    "language":"ja",
    "qrcode":false,
    "invoice_template_id":null,
    "custom_fields":null,
    "untagged_groups":null,
    "account":[],
    "tag":[]
}
```

## Update

請求グループ情報の更新

**Role actions**

* `ModifyBillingGroup`&#x20;

**Request**

```http
POST /billinggroup/{id} HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
    "billinggroup_id":"Billing1",
    "billinggroup_name":"Billing1",
    "company_name":"Billing1 Company",
    "phone":"03-123-4567",
    "postal":"1243",
    "address":"updateed address",
    "billing_title":null,
    "personal":"Personal name",
    "remarks":"Some remarks data",
    "inv_aggregate":false,
    "project_id":"{created_project_id}",
    "language": "ja"
}
```

| Field              | Type      | Required | Validation       | Description                             |
| ------------------ | --------- | -------- | ---------------- | --------------------------------------- |
| billinggroup\_id   | *string*  | Yes      | -                | Billing group ID                        |
| billinggroup\_name | *string*  | Yes      | 長さ 1 \~ 100      | Billing group Name                      |
| company\_name      | *string*  | Yes      | 長さ 1 \~ 100      | Company name                            |
| phone              | *string*  | No       | 長さ 12 \~ 16      | Tel                                     |
| postal             | *string*  | No       | 長さ 4 \~ 10       | Postal                                  |
| address            | *string*  | No       | 長さ 1 \~ 100      | Address                                 |
| billing\_title     | *string*  | No       | 長さ 1 \~ 100      | Invoice title                           |
| personal           | *string*  | No       | 長さ 1 \~ 100      | Personal name                           |
| remarks            | *string*  | No       | 長さ 1 \~ 100      | Memo                                    |
| inv\_aggregate     | *boolean* | No       |                  | Displaying invoice in bulk or by vendor |
| project\_id        | *string*  | No       |                  | Project id                              |
| language           | *string*  | No       | サポート: `ja`, `en` | Display invoice language setting        |

**Response**

```ruby
HTTP 200

{"status":"success"}
```

## Update invoice setting

請求グループ請求書設定の更新

**Role actions**

* `ModifyBillingGroup`&#x20;

**Request**

```http
POST /billinggroup/{id}/invoices HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
  "invoices": {
    "calc_type":"account",
    "currency":"jpy",
    "discount_calc_logic":"usageamount",
    "discount_rate":0,
    "discount_target_usage":"cloudpaywithfee",
    "substitution_fee":"percent",
    "substitution_fee_calc_target":"nondiscount",
    "substitution_fee_calc_type":"allsum",
    "substitution_fee_target_usage":"cloudpaywithfee",
    "substitution_fix":0,
    "substitution_rate":0,
    "support_amount_target":"allusage",
    "support_fee":"fix",
    "support_fee_calc_target":"nondiscount",
    "support_fix":0,
    "support_rate":0,
    "tax_rate":0.10
  },
  "vendor":"{vendor}"
}
```

| Field                            | Type     | Required | Validation                                                                                | Description  |
| -------------------------------- | -------- | -------- | ----------------------------------------------------------------------------------------- | ------------ |
| calc\_type                       | *string* | Yes      | account,tag                                                                               | 計算タイプ        |
| currency                         | *string* | Yes      | jpy,usd                                                                                   | 通貨           |
| discount\_calc\_logic            | *string* | Yes      | usageamount,allamount                                                                     | 値引き対象        |
| discount\_rate                   | *double* | Yes      | 0 \~ 1                                                                                    | 値引率          |
| discount\_target\_usage          | *string* | Yes      | cloudpayonly ,cloudpaywithfee                                                             | 値引き計算方法      |
| substitution\_fee                | *string* | Yes      | percent, fix, automatic, usagetable                                                       | 代行手数料請求方法    |
| substitution\_fee\_calc\_target  | *string* | Yes      | cloudpayonly, cloudpaywithfee                                                             | 代行手数料計算対象    |
| substitution\_fee\_calc\_type    | *string* | Yes      | allsum, account                                                                           | 請求代行サービス計算方法 |
| substitution\_fee\_target\_usage | *string* | Yes      | nondiscount, discounted                                                                   | 請求代行手数料対象    |
| substitution\_fix                | *double* | Yes      | 0 \~ 1,000,000                                                                            | 代行手数料 固定     |
| substitution\_rate               | *double* | Yes      | 0 \~ 1                                                                                    | 代行手数料 (%)    |
| support\_amount\_target          | *string* | Yes      | allusage, cloudpayonlywithfee                                                             | 表示なし         |
| support\_fee                     | *string* | Yes      | - aws percent, aws\_developer, aws\_business, aws\_enterprise, fix   - azure percent, fix | サポート料請求方法    |
| support\_fee\_calc\_target       | *string* | Yes      | cloudpayonly, cloudpaywithfee                                                             | サポート料計算対象    |
| support\_fix                     | *double* | Yes      | 0 \~ 1,000,000                                                                            | サポート料 固定     |
| support\_rate                    | *double* | Yes      | 0 \~ 1                                                                                    | サポート料 %      |
| tax\_rate                        | *double* | Yes      | 0 \~ 0.08                                                                                 | 消費税率 %       |

**Response**

```ruby
HTTP 200

{"status":"success"}
```

## Update free format

請求グループその他費用の追加・更新

**Role actions**

* `ModifyBillingGroup`&#x20;

**Request**

```http
POST /billinggroup/{id}/freeformat/{vendor} HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

リクエストパラーメータの`{id}`は請求グループ内部ID`{company_id}`です。

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
    "additional_items":[
    {
        "enabled":true,
        "label":"testlabel",
        "unit_cost":1,
        "quantity":10000,
        "total":10000
    }
]
}
```

**additional\_items object description**

| Field      | Type      | Required | Validation | Description |
| ---------- | --------- | -------- | ---------- | ----------- |
| enabled    | *boolean* | Yes      | -          | 有効、無効       |
| label      | *string*  | Yes      | 長さ 1 \~ 60 | タイトル        |
| unit\_cost | *double*  | Yes      | -          | 単価          |
| quantity   | *double*  | Yes      | -          | 数量          |
| total      | *double*  | Yes      | -          | 金額          |

**Response**

```ruby
HTTP 200

{"status":"success"}
```

## Delete free format

請求グループその他費用の削除

**Role actions**

* `ModifyBillingGroup`&#x20;

**Request**

```http
DELETE /billinggroup/{id}/freeformat/{vendor} HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json
```

リクエストパラーメータの`{id}`は請求グループ内部ID`{company_id}`です。

請求グループに追加されているその他費用を全て削除します。

**Response**

```ruby
HTTP 200

{"status":"success"}
```

## Update Invoice Template

請求グループ請求テンプレートの更新

**Role actions**

* `ModifyBillingGroup`&#x20;

**Request**

```http
POST /billinggroup/{id}/invoicetemplate HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

リクエストパラーメータの`{id}`は請求グループ内部ID`{company_id}`です

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
    "invoice_template_id": "abcdefg"
}
```

**Response**

```ruby
HTTP 200

{"status":"success"}
```

## Delete

請求グループの削除

**Role actions**

* `ModifyBillingGroup`&#x20;

**Request**

```http
DELETE /billinggroup/{id} HTTP1.1
Authorization: Bearer {token}
```

**Response**

```ruby
HTTP 200

{"status":"success"}
```


# Account

アカウントのAPIリファレンスは以下の通りです。

## Create

アカウントの作成

**Role actions**

* `ModifyAccount`

**Request**

```http
POST /accts HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
    "vendor":"aws",
    "customer_id":"012345678912",
    "account_id":"919999618919"
    "company_id":"AJfdivbDjhvbpE",
    "name":"ripple customer1",
    "note":null
}
```

**{request body} description**

| Field        | Type     | Required | Validation                  | Description                              |
| ------------ | -------- | -------- | --------------------------- | ---------------------------------------- |
| customer\_id | *string* | Yes      | - AWS 12桁   - Azure 16\~36桁 | - AWS AccountID   - Azure SubscriptionID |
| account\_id  | *string* | Yes      | - AWS 12桁   - AZURE 7桁      | - AWS PayerAccountID   - Azure BillingID |
| company\_id  | *string* | Yes      | -                           | 請求グループ内部ID                               |
| vendor       | *string* | Yes      | - サポート: `aws`,`azure`       |                                          |
| name         | *string* | Yes      | - 長さ: 3 \~ 100              | 登録する顧客名                                  |
| note         | *string* | No       | -                           | 備考欄                                      |

**Response**

```ruby
HTTP 200

{"status":"success"}

HTTP 400 customer id が既に登録されている場合

{
  "code":"5005",
  "message":"account function exception",
  "description":"Customer id already exists."
}
```

**Pythonでのサンプル**

```
import requests
import json

def get_token():
    # Note: you can see details https://docs.alphaus.cloud/v/api-reference/authentication
    # Assign generated values for client_id and client_secret
    params={
        "grant_type": "client_credentials",
        "client_id": "{client_id}",
        "client_secret": "{client_secret}",
        "scope": "openid",
    }
    try:
        response = requests.post(
            url="https://login.alphaus.cloud/ripple/access_token",
            headers={
            },
            params=params,
            files=params,
        )
    except requests.exceptions.RequestException:
        print('HTTP Request failed')

    r = response.json()
    return r['access_token'], r["token_type"]

def send_request(type, token):
    # Authorization header
    auth = type + " " + token
    try:
        response = requests.post(
            url="https://api.alphaus.cloud/m/ripple/accts",
            headers={
                "Content-Type": "application/json;",
                "Authorization": auth
            },
            data=json.dumps({
                "account_id": "{account_id}",
                "vendor": "{vendor}",
                "customer_id": "{customer_id}",
                "note": None,
                "company_id": "{company_id}",
                "name": "customer_name"
            })
        )
        print('Response HTTP Status Code: {status_code}'.format(
            status_code=response.status_code))
        print('Response HTTP Response Body: {content}'.format(
            content=response.content))
    except requests.exceptions.RequestException:
        print('HTTP Request failed')

access_token, token_type = get_token()
send_request(token_type, access_token)
```

## List

アカウントリストの取得

**Role actions**

* `ReadAccount`&#x20;
* `ModifyAccount`

**Request**

```http
GET /accts?vendor={vendor} HTTP1.1
Authorization: Bearer {token}
```

以下に`{vendor}`のパラメータの例を示します。

**{vendor}**

* aws
* azure

**Response**

```ruby
HTTP 200

[
  {
    "billinggroup_id":"Billing1",
    "billinggroup_name":"Billing1",
    "company_id":"AJfdivbDjhvbpE",
    "customer_id":"012345678912",
    "customer_name":"ripple customer1",
    "account_id":"919999618919",
    "vendor":"aws",
    "note":null,
    "payer":false,
    "service_discount":null,
    "project_id":null,
    "azure_customer_id":null
  },
  ...
]
```

## Update

アカウントの更新

**Role actions**

* `ModifyAccount`

**Request**

```http
PUT /accts/{customer_id}/edit HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

以下に`{customer_id}`のパラメータの例を示します。

**{customer\_id}**

AWS AccountID or Azure SubscriptionID

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
    "vendor":"aws",
    "account_id":"919999618919"
    "company_id":"AJfdivbDjhvbpE",
    "name":"ripple customer1",
    "note":null
}
```

**{request body} description**

| Field       | Type     | Required | Validation             | Description                              |
| ----------- | -------- | -------- | ---------------------- | ---------------------------------------- |
| account\_id | *string* | Yes      | - AWS 12桁   - AZURE 7桁 | - AWS PayerAccountID   - Azure BillingID |
| company\_id | *string* | Yes      | -                      | 請求グループ内部ID                               |
| vendor      | *string* | Yes      | - サポート: `aws`,`azure`  |                                          |
| name        | *string* | Yes      | - 長さ: 3 \~ 100         | 登録する顧客名                                  |
| note        | *string* | No       | -                      | 備考欄                                      |

**Response**

```ruby
HTTP 200

{"status":"success"}

HTTP 400 customer id が登録されていない場合

{
  "code":"5005",
  "message":"account function exception",
  "description":"Customer id is not exists."
}
```

## Delete

アカウントの削除

**Role actions**

* `ModifyAccount`

**Request**

```http
DELETE /accts/{vendor}/{id} HTTP1.1
Authorization: Bearer {token}
```

以下に`{vendor}`のパラメータの例を示します。

**{vendor}**

* aws
* azure

以下に`{id}`フォーマットのパラメータの例を示します。

**{id}**

`{customer_id}|{account_id}`。 エンドポイント例: `/accts/aws/012345678912|919999618919`

**Response**

```ruby
HTTP 200

{"status":"success"}

HTTP 400 customer id が登録されていない場合

{
  "code":"5005",
  "message":"account function exception",
  "description":"Customer id is not exists."
}
```


# Wave for Reseller

リセラーのAPIリファレンスは以下の通りです。

## Create reseller account

リセラーアカウントの発行

**Role actions**

* `ModifyReseller`

**Request**

```http
POST /reseller HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
  "email":"alphaus-cloud@alphaus.cloud",
  "company_id":"company1",
  "input_type":"Auto",
  "notification":true,
  "password":null
}
```

**request body description**

| Field        | Type      | Required | Validation      | Description                                                |
| ------------ | --------- | -------- | --------------- | ---------------------------------------------------------- |
| email        | *string*  | Yes      | -               | Eメールアドレス                                                   |
| company\_id  | *string*  | Yes      | -               | 請求グループ内部ID                                                 |
| input\_type  | *string*  | Yes      | - Auto / Custom | Auto: パスワード自動生成 Custom: passwordを入力                        |
| notification | *boolean* | Yes      | -               | 作成時に通知をする/しない                                              |
| password     | *string*  | No       | -               | パスワード                                                      |
| meta         | \[object] | Yes      | -               | Wave機能表示設定。[metaについて](/api-reference/ripple/reseller#meta) |

**Response**

```ruby
HTTP 200

{
  "status":"success"
}
```

**Pythonでのサンプル**

```
import requests
import json

def get_token():
    # Note: you can see details https://docs.alphaus.cloud/v/api-reference/authentication
    # Assign generated values for client_id and client_secret
    params={
        "grant_type": "client_credentials",
        "client_id": "{client_id}",
        "client_secret": "{client_secret}",
        "scope": "openid",
    }
    try:
        response = requests.post(
            url="https://login.alphaus.cloud/ripple/access_token",
            headers={
            },
            params=params,
            files=params,
        )
    except requests.exceptions.RequestException:
        print('HTTP Request failed')

    r = response.json()
    return r['access_token'], r["token_type"]

def send_request(type, token):
    # Authorization header
    auth = type + " " + token
    try:
        response = requests.post(
            url="https://api.alphaus.cloud/m/ripple/reseller",
            headers={
                "Content-Type": "application/json;",
                "Authorization": auth
            },
            data=json.dumps({
                "email": "reseller@waveresellersample.cloud",
                "notification": True,
                "meta": {
                    "usage_report_download": True,
                    "usage_account_menu_fees_fee": False,
                    "ri_utilization": False,
                    "usage_account_menu_account_edit": False,
                    "usage_account": True,
                    "usage_account_graph": True,
                    "usage_tag_graph": True,
                    "usage_account_menu_fees_refund": False,
                    "invoice_download_csv_merged": False,
                    "invoice_download_csv_discount": False,
                    "usage_account_menu_fees_other_fees": False,
                    "usage_account_menu_fees_credit": False,
                    "ri_purchased": False,
                    "open_api": False,
                    "dashboard_graph": True,
                    "usage_group": True,
                    "report_filters": False,
                    "usage_tag": True,
                    "ri_recommendation": False,
                    "invoice": False,
                    "usage_crosstag_graph": True,
                    "users_management": False,
                    "usage_account_menu_budget": False,
                    "usage_account_menu_budget_edit": False,
                    "usage_group_graph": True,
                    "usage_crosstag": True,
                    "aq_coverage_ratio": False,
                    "aq_sp_management": False,
                    "aq_right_sizing": False,
                    "aq_ri_sp_instances": False,
                    "aq_ri_management": False,
                    "sp_purchased": False,
                    "aq_scheduling": False,
                    "aqua_link": False
                },
                "company_id": "{company_id}",
                "input_type": "Auto"
            })
        )
        print('Response HTTP Status Code: {status_code}'.format(
            status_code=response.status_code))
        print('Response HTTP Response Body: {content}'.format(
            content=response.content))
    except requests.exceptions.RequestException:
        print('HTTP Request failed')

access_token, token_type = get_token()
send_request(token_type, access_token)
```

## Get reseller account list

リセラーアカウントの取得

**Role actions**

* `ReadReseller`
* `ModifyReseller`

**Request**

```http
POST /reseller HTTP1.1
Authorization: Bearer {token}
```

**Response**

```ruby
HTTP 200

[
  {
    "user_id":"userid1",
    "billinggroup_id":"billing1",
    "billinggroup_name":"billingname1",
    "email":"alphaus-cloud@alphaus.cloud",
    "company_id":"company1",
    "update_time":null,
    "password_update_time":null,
    "wave_registered":"2020-01-01T10:00:00+09:00",
    "meta": {
      "aq_coverage_ratio":false
      "aq_ri_management":false
      "aq_ri_sp_instances":false
      "aq_right_sizing":false
      "aq_scheduling":false
      "aq_sp_management":false
      "dashboard_graph":true
      "usage_account":true
      "usage_account_graph":true
      "usage_account_menu_account_edit":false
      "usage_account_menu_budget":false
      "usage_account_menu_budget_edit":false
      "usage_account_menu_fees_fee":false
      "usage_account_menu_fees_credit":false
      "usage_account_menu_fees_refund":false
      "usage_account_menu_fees_other_fees":false
      "usage_report_download":true
      "usage_group":true
      "usage_group_graph":true
      "usage_tag":true
      "usage_tag_graph":true
      "usage_crosstag":true
      "usage_crosstag_graph":true
      "ri_purchased":true
      "ri_utilization":false
      "ri_recommendation":false
      "sp_purchased":false
      "invoice":false
      "invoice_download_csv_discount":false
      "invoice_download_csv_merged":false
      "open_api":false
      "users_management":false
      "report_filters":false
    }
  },
  ...
]
```

## Delete reseller account

リセラーアカウントの削除

**Role actions**

* `ModifyReseller`

**Request**

```http
DELETE /reseller/{user_id} HTTP1.1
Authorization: Bearer {token}
```

**{user\_id}**

リセラーアカウントのidを指定する

**Response**

```ruby
HTTP 200

{
  "status":"success"
}
```

## Update password for reseller account

リセラーアカウントパスワードの変更

**Role actions**

* `ModifyReseller`

**Request**

```http
PUT /reseller/{user_id}/password HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

**{user\_id}**

リセラーアカウントのidを指定する

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
  "input_type":"Auto",
  "notification":true,
  "password":null
}
```

**request body description**

| Field        | Type      | Required | Validation      | Description                         |
| ------------ | --------- | -------- | --------------- | ----------------------------------- |
| input\_type  | *string*  | Yes      | - Auto / Custom | Auto: パスワード自動生成 Custom: passwordを入力 |
| notification | *boolean* | Yes      | -               | 変更時に通知をする/しない                       |
| password     | *string*  | No       | -               | パスワード                               |

**Response**

```ruby
HTTP 200

{
  "status":"success"
}
```

## Update meta for reseller account

リセラーアカウントメタ情報の変更

**Role actions**

* `ModifyReseller`

**Request**

```http
PUT /reseller/{user_id}/meta HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

**{user\_id}**

リセラーアカウントのidを指定する

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
  "meta": {
      "aq_coverage_ratio":false
      "aq_ri_management":false
      "aq_ri_sp_instances":false
      "aq_right_sizing":false
      "aq_scheduling":false
      "aq_sp_management":false
      "dashboard_graph":true
      "usage_account":true
      "usage_account_graph":true
      "usage_account_menu_account_edit":false
      "usage_account_menu_budget":false
      "usage_account_menu_budget_edit":false
      "usage_account_menu_fees_fee":false
      "usage_account_menu_fees_credit":false
      "usage_account_menu_fees_refund":false
      "usage_account_menu_fees_other_fees":false
      "usage_report_download":true
      "usage_group":true
      "usage_group_graph":true
      "usage_tag":true
      "usage_tag_graph":true
      "usage_crosstag":true
      "usage_crosstag_graph":true
      "ri_purchased":true
      "ri_utilization":false
      "ri_recommendation":false
      "sp_purchased":false
      "invoice":false
      "invoice_download_csv_discount":false
      "invoice_download_csv_merged":false
      "open_api":false
      "users_management":false
      "report_filters":false
    }
}
```

**request body description**

| Field | Type      | Required | Validation | Description                                                |
| ----- | --------- | -------- | ---------- | ---------------------------------------------------------- |
| meta  | \[object] | Yes      | -          | Wave機能表示設定。[metaについて](/api-reference/ripple/reseller#meta) |

**Response**

```ruby
HTTP 200

{
  "status":"success"
}
```

### meta

metaのリストを示します。

`Default`はリセラーアカウントを発行する際に設定されるデフォルトの設定です。

| aq\_coverage\_ratio                     | *boolean* | false | Aqua インスタン適用率                | インスタン適用率ページの表示                        |
| --------------------------------------- | --------- | ----- | ---------------------------- | ------------------------------------- |
| aq\_ri\_management                      | *boolean* | false | Aqua RI管理                    | RI管理ページの表示                            |
| aq\_ri\_sp\_instances                   | *boolean* | false | Aqua RI/SP                   | RI/SPレコメンデーションページの表示                  |
| aq\_right\_sizing                       | *boolean* | false | Aqua ライトサイジング                | ライトサイジングページの表示                        |
| aq\_scheduling                          | *boolean* | false | Aqua スケジューリング                | スケジューリングページの表示                        |
| aq\_sp\_management                      | *boolean* | false | Aqua SP管理                    | SP管理ページの表示                            |
| dashboard\_graph                        | *boolean* | true  | ダッシュボード                      | ダッシュボードグラフの表示                         |
| usage\_account                          | *boolean* | true  | アカウントレポート                    | アカウント利用明細の表示 \[Account]               |
| usage\_account\_graph                   | *boolean* | true  | グラフの表示 \[アカウント]              | アカウント利用明細グラフの表示 \[Account]            |
| usage\_account\_menu\_account\_edit     | *boolean* | false | アカウント名の編集                    | アカウント名の編集 \[Account]                  |
| usage\_account\_menu\_budget            | *boolean* | false | バジェットの表示 \[アカウント]            | バジェット設定の表示 \[Account]                 |
| usage\_account\_menu\_budget\_edit      | *boolean* | false | バジェットの編集 \[アカウント]            | バジェット設定の編集 \[Account]                 |
| usage\_account\_menu\_fees\_fee         | *boolean* | false | Feeの表示 \[アカウント > その他明細情報]    | Feeの表示 \[Account]                     |
| usage\_account\_menu\_fees\_credit      | *boolean* | false | Creditの表示 \[アカウント > その他明細情報] | Creditの表示 \[Account]                  |
| usage\_account\_menu\_fees\_refund      | *boolean* | false | Refundの表示 \[アカウント > その他明細情報] | Refundの表示 \[Account]                  |
| usage\_account\_menu\_fees\_other\_fees | *boolean* | false | その他Feeの表示 \[アカウント > その他明細情報] | その他Feeの表示 \[Account]                  |
| usage\_report\_download                 | *boolean* | true  | レポートのダウンロード \[アカウント]         | 利用明細レポートのダウンロード表示 \[Account]          |
| usage\_group                            | *boolean* | true  | グループレポート                     | 利用明細の表示 \[Group]                      |
| usage\_group\_graph                     | *boolean* | true  | グラフの表示 \[グループ]               | 利用明細グラフの表示 \[Group]                   |
| usage\_tag                              | *boolean* | true  | タグレポート                       | 利用明細の表示 \[Tag]                        |
| usage\_tag\_graph                       | *boolean* | true  | グラフの表示 \[タグ]                 | 利用明細グラフの表示 \[Tag]                     |
| usage\_crosstag                         | *boolean* | true  | クロスタグレポート                    | 利用明細の表示 \[Cross Tag]                  |
| usage\_crosstag\_graph                  | *boolean* | true  | グラフの表示 \[クロスタグ]              | 利用明細グラフの表示 \[Cross Tag]               |
| ri\_purchased                           | *boolean* | true  | 購入済みRIの表示                    | 購入済みRIの表示                             |
| ri\_utilization                         | *boolean* | false | RI適用率の表示                     | RI適用率の表示                              |
| ri\_recommendation                      | *boolean* | false | レコメンデーションの表示                 | RIレコメンデーションの表示                        |
| sp\_purchased                           | *boolean* | false | 購入済みSavingsPlansの表示          | 購入済みSavingsPlansの表示                   |
| invoice                                 | *boolean* | false | 請求書の表示                       | ご利用明細の表示                              |
| invoice\_download\_csv\_discount        | *boolean* | false | 割引詳細CSVのダウンロード               | 割引詳細CSVのダウンロード \[Usage details]       |
| invoice\_download\_csv\_merged          | *boolean* | false | 請求書（統合版）CSVのダウンロード           | 請求書（統合版）CSVのダウンロード \[Usage details]   |
| open\_api                               | *boolean* | false | API アクセストークン                 | API アクセストークン \[Settings]              |
| users\_management                       | *boolean* | false | サブユーザー管理                     | サブユーザー管理 \[Settings]                  |
| report\_filters                         | *boolean* | false | レポートフィルター                    | レポートフィルター                             |
| budgetalerts                            | *boolean* | false | 予算超過通知                       | 予算に関するアラート \[Notification]\[Settings] |


# OriginalCost

原価データのAPIリファレンスは以下の通りです。

## Set exchange rate per InvoiceID

InvoiceIDの為替レート設定

**Role actions**

* `ModifyOriginalCost`

**Request**

```http
POST /invoiceid/:vendor/:month HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

リクエストパラーメータの`{month}`のフォーマット: `yyyy-mm` 例: 2020-01 \
リクエストパラーメータの`{vendor}`のサポートベンダー: `aws`

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
  "data":[
      {
        "invoice_id":"123456789",
        "exchange_rate":101.051
      },
      {
        "invoice_id":"468215697",
        "exchange_rate":100.02
      }
  ]
}
```

**request body description**

| Field          | Type     | Required | Validation | Description |
| -------------- | -------- | -------- | ---------- | ----------- |
| invoice\_id    | *string* | Yes      | -          | InvoiceID   |
| exchange\_rate | *double* | Yes      | -          | 登録する為替レート   |

**Response**

```ruby
HTTP 200

{
  "status":"success"
}
```

## Get InvoiceID list

InvoiceIDの取得

**Role actions**

* `ReadOriginalCost`
* `ModifyOriginalCost`

**Request**

```http
GET /invoiceid/:vendor/:month HTTP1.1
Authorization: Bearer {token}

{request body}
```

リクエストパラーメータの`{month}`のフォーマット: `yyyy-mm` 例: 2020-01 \
リクエストパラーメータの`{vendor}`のサポートベンダー: `aws`

**Response**

```ruby
HTTP 200

[
  {
    "invoice_id":"123456789",
    "exchange_rate":101.051
  },
  {
    "invoice_id":"468215697",
    "exchange_rate":100.02
  }
]
```

## Export InvoiceID CSV

InvoiceID CSVの出力

**Role actions**

* `ModifyOriginalCost`

**Request**

```http
POST /export/invoiceidcsv/:month HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

リクエストパラーメータの`{month}`のフォーマット: `yyyy-mm` 例: 2020-01

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
  "vendor":"aws",
  "exchange":true,
  "digit":"up"
}
```

**request body description**

| Field    | Type      | Required | Validation                   | Description          |
| -------- | --------- | -------- | ---------------------------- | -------------------- |
| vendor   | *string*  | Yes      | サポート: `aws`                  | ベンダー                 |
| exchange | *boolean* | Yes      | -                            | USDで出力または為替後(JPY)を出力 |
| digit    | *double*  | Yes      | サポート: `up`,`down`,`rounding` | 小数点丸め設定              |

**Response**

```ruby
HTTP 200

{
  "status":"success",
  "url":"csv link"
}
```


# RI management

RI管理のAPIリファレンスは以下の通りです。

## Get RI purchased list

RI管理データの取得

**Role actions**

* `ReadRi`
* `ModifyRi`

**Request**

```http
GET /ri/purchased?vendor={vendor} HTTP1.1
Authorization: Bearer {token}
```

リクエストパラーメータの`{vendor}`のサポートベンダー: `aws`,`azure`

**Response**

```ruby
HTTP 200

[
  {
    "billinggroup_id":"billinggroup1",
    "billinggroup_name":"billinggroup1",
    "customer_id":"012345678912",
    "customer_name":"customer1",
    "dest_customer_id":"",
    "end":"2021-12-03T00:00:00Z",
    "id":"ATEcVTAzVDA4pbnN6YW5jZXXFZbRmNGFlMTAtYWV",
    "arn":"arn:aws:ec2:ap-northeast-1:012345678912:reserved-instances\/adbcderf-cdef-xwcs-ecqx-5vfbk2767xxs",
    "instance_type":"t2.large",
    "modification_status":"Original",
    "normalization_factor":4,
    "number":1,
    "offer_class":"standard",
    "paid_by":"PaidByOwner",
    "payment_option":"All Upfront",
    "platform":"Linux\/UNIX",
    "region":"ap-northeast-1",
    "remove":false,
    "scope":"Region",
    "service":"AmazonEC2",
    "start":"2020-12-03T00:00:00Z",
    "tenancy":"Shared",
    "term_length":"1yr",
    "unblended_rate":0,
    "upfront_value":672,
    "usage_type":"APN1-HeavyUsage:t2.large",
    "vendor":"aws",
    "zone":"",
    "disabled":false
  },
  ...
]
```

## Move RI purchased

RI管理データの移動

**Role actions**

* `ModifyRi`

**Request**

```http
POST /ri/purchased/{ri_id} HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

リクエストパラーメータの`{ri_id}` `GET /ri/purchased?vendor={vendor}`から取得したid

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
    "customer_id":"123456789123",
    "number":1,
    "vendor":"aws"
}
```

**{request body} description**

| Field        | Type      | Required | Validation  | Description |
| ------------ | --------- | -------- | ----------- | ----------- |
| customer\_id | *string*  | Yes      | -           | 移動先の顧客ID    |
| number       | *integer* | Yes      | -           | 移動する数       |
| vendor       | *string*  | Yes      | サポート: `aws` | ベンダー        |

**Response**

```ruby
HTTP 200

{"status":"success"}
```

## Remove RI purchased

移動先のRI管理データを元のデータへ戻す

**Role actions**

* `ModifyRi`

**Request**

```http
POST /ri/purchased/{ri_id}/remove?vendor={vendor} HTTP1.1
Authorization: Bearer {token}
```

リクエストパラーメータの`{ri_id}` `GET /ri/purchased?vendor={vendor}`から取得したid \
リクエストパラーメータの`{vendor}`のサポートベンダー: `aws`

**Response**

```ruby
HTTP 200

{"status":"success"}
```


# Recalculation

再計算請求データのAPIリファレンスは以下の通りです。

## Get recalculation list

再計算請求データの取得

**Role actions**

* `ReadBillingGroup`
* `ModifyBillingGroup`

**Request**

```http
GET /billinggroup/recalculation/{month}?vendor={vendor} HTTP1.1
Authorization: Bearer {token}
```

リクエストパラーメータの`{month}`のフォーマット: `yyyy-mm` 例: 2020-01 \
リクエストパラーメータの`{vendor}`のサポートベンダー: `aws`,`azure`

**Response**

```ruby
HTTP 200

[
  {
    "customer_id":"012345678912",
    "customer_name":"customer1",
    "company_id":"company1",
    "billinggroup_id":"billing1",
    "billinggroup_name":"billing1",
    "project_code":null,
    "id": "recalculationid1",
    "calc_type":"Fee",
    "mobingi_type":"REGISTRAR",
    "description":"[OP-n4GB] Renewal",
    "product_name":"Amazon Registrar",
    "account_id":"012345678912",
    "currency_code":"USD",
    "product_code":"AmazonRegistrar",
    "unblended_cost":"90.0000000000",
    "time_interval":"2020-05-27T15:00:00Z\/2021-05-26T15:00:01Z",
    "usage_start":"2020-05-27T15:00:00Z",
    "apply":false,
    "exchange_rate":null,
    "tax_free":false,
    "vendor":"aws"
  },
  ...
]
```

## Apply recalculation

再計算請求データの適用・未適用の割当

**Role actions**

* `ModifyBillingGroup`

**Request**

```http
POST /billinggroup/recalculation HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
    "data": [
        "recalculationid1",
        "recalculationid2",
        "recalculationid3"
    ],
    "month": "2021-01",
    "exchange_rate":104.02,
    "tax_free":true,
    "apply":true,
    "vendor":"aws"
}
```

**{request body} description**

| Field          | Type      | Required | Validation        | Description   |
| -------------- | --------- | -------- | ----------------- | ------------- |
| data           | *array*   | Yes      | \[id1,id2,id3...] | 再計算請求データIDの一覧 |
| month          | *string*  | Yes      | -                 | 適用・未適用する対象月   |
| exchange\_rate | *double*  | Yes      | -                 | 適用・未適用する為替レート |
| tax\_free      | *boolean* | Yes      | -                 | 免税設定          |
| apply          | *boolean* | Yes      | -                 | 適用・未適用設定      |
| vendor         | *string*  | Yes      | -                 | ベンダー          |

**Response**

```ruby
HTTP 200

{"status":"success"}
```


# Invoice

請求関連のAPIリファレンスは以下の通りです。

## Get Account total cost list

アカウント合計一覧の取得

**Role actions**

* `ReadInvoice`
* `ModifyInvoice`

**Request**

```http
GET /invoice/{month}/details HTTP1.1
Authorization: Bearer {token}
```

リクエストパラーメータの`{month}`のフォーマット: `yyyy-mm` 例: 2020-01

**Response**

```ruby
HTTP 200

{
  "accounts": [
    {
      "customer_id": "012345678987",
      "customer_name": "customer 1",
      "total": 431,
      "total_exchanged": 43100,
      "adjustment_entries": [
        {
          "name": "upfront - Sign up charge for subscription: 000000000, planId: 000000000",
          "amount": 2,
          "amount_exchanged": 200
        }
      ]
    },
    {
      "customer_id": "123456789875",
      "customer_name": "customer 2",
      "total": 6,
      "total_exchanged": 600,
      "adjustment_entries": [
        {
          "name": "upfront - one-time fee for 1 year All Upfront ap-southeast-1 EC2 Savings Plan ID:0000000000 ",
          "amount": 1,
          "amount_exchanged": 100
        }
      ]
    }
  ],
  "billing_groups": [
    {
      "billing_group_id": "bgid1",
      "billing_group_name": "bg1",
      "vendor": "aws",
      "tax_excluded_amount": 0,
      "tax_excluded_amount_exchanged": 0,
      "tax": 0,
      "total_amount_exchanged": 0
    },
    {
      "billing_group_id": "bgid2",
      "billing_group_name": "bg2",
      "vendor": "aws",
      "tax_excluded_amount": 437,
      "tax_excluded_amount_exchanged": 43700,
      "tax": 4370,
      "total_amount_exchanged": 48070
    }
  ]
}
```

accountsの詳細

| Field               | Type     | Description        |
| ------------------- | -------- | ------------------ |
| customer\_id        | *string* | 顧客ID               |
| customer\_name      | *string* | 顧客名                |
| total               | *double* | $金額(税抜)            |
| total\_exchanged    | *double* | 換算後金額(税抜)          |
| adjustment\_entries | *list*   | 請求書に含んだ再計算請求データの一覧 |

billing\_groupsの詳細

| Field                            | Type     | Description  |
| -------------------------------- | -------- | ------------ |
| billing\_group\_id               | *string* | 請求グループID     |
| billing\_group\_name             | *string* | 請求グループ名      |
| vendor                           | *string* | ベンダー         |
| tax\_excluded\_amount            | *double* | $合計金額(税抜)    |
| tax\_excluded\_amount\_exchanged | *double* | $換算後合計金額(税抜) |
| tax                              | *double* | 消費税金額        |
| total\_amount\_exchanged         | *double* | 合計請求金額       |

## Get Invoice list

請求書一覧の取得

**Role actions**

* `ReadInvoice`
* `ModifyInvoice`

**Request**

```http
GET /invoices/{month} HTTP1.1
Authorization: Bearer {token}
```

リクエストパラーメータの`{month}`のフォーマット: `yyyy-mm` 例: 2020-01

**Response**

```ruby
HTTP 200

{
  "total": {
    "stock":108850,
    "sales":108850,
    "azure_stock":0,
    "azure_sales":0
  },
  "billinggroup": [
    {
      "company_id":"company1",
      "name":"company1",
      "billinggroup_id":"billinggroup1",
      "billinggroup_name":"billinggroup1",
      "project_id":null,
      "project_code":null,
      "project_label":null,
      "project_currency":null,
      "month":"2020-12",
      "invoice_no":"2020-12billing1",
      "created_data": {
        "aws": {
          "invoice_no":"2020-12billing1",
          "calc_type":"account",
          "currency":"jpy",
          "discount_rate":0.02,
          "discount_target_usage":"cloudpaywithfee",
          "discount_calc_logic":"usageamount",
          "tax_rate":0.10,
          "support_fee":"fix",
          "support_rate":0,
          "support_fee_calc_target":"nondiscount",
          "support_fix": 0,
          "substitution_fee":"percent",
          "substitution_rate":0,
          "substitution_fix":0,
          "substitution_fee_calc_target":"nondiscount",
          "substitution_fee_target_usage":"cloudpaywithfee",
          "substitution_fee_calc_type":"allsum",
          "exchange_rate":102.45,
          "memo":null,
          "additional_items": []
        },
        "azure":null
      },
      "saved_data": {
        "aws": {
          "invoice_no":null,
          "calc_type":"account",
          "currency":"jpy",
          "discount_rate":0.02,
          "discount_target_usage":"cloudpaywithfee",
          "discount_calc_logic":"usageamount",
          "tax_rate":0.10,
          "support_fee":"fix",
          "support_rate":0,
          "support_fee_calc_target":"nondiscount",
          "support_fix":0,
          "substitution_fee":"percent",
          "substitution_rate":0,
          "substitution_fix":0,
          "substitution_fee_calc_target":"nondiscount",
          "substitution_fee_target_usage":"cloudpaywithfee",
          "substitution_fee_calc_type":"allsum",
          "exchange_rate":102.45,
          "memo":null,
          "additional_items": []
        },
        "azure":null
      },
      "default_data": {
        "aws": {
          "invoice_no":null,
          "calc_type":"account",
          "currency":"jpy",
          "discount_rate":0.02,
          "discount_target_usage":"cloudpaywithfee",
          "discount_calc_logic":"usageamount",
          "tax_rate":0.10,
          "support_fee":"fix",
          "support_rate":0,
          "support_fee_calc_target":"nondiscount",
          "support_fix":0,
          "substitution_fee":"percent",
          "substitution_rate":0,
          "substitution_fix":0,
          "substitution_fee_calc_target":"nondiscount",
          "substitution_fee_target_usage":"cloudpaywithfee",
          "substitution_fee_calc_type":"allsum",
          "exchange_rate":null,
          "memo":null,
          "additional_items": []
        },
        "azure": {
          "invoice_no":null,
          "calc_type":"account",
          "currency":"jpy",
          "discount_rate":0,
          "discount_target_usage":"cloudpaywithfee",
          "discount_calc_logic":"usageamount",
          "tax_rate":0.10,
          "support_fee":"fix",
          "support_rate":0,
          "support_fee_calc_target":"nondiscount",
          "support_fix":0,
          "substitution_fee":"percent",
          "substitution_rate":0,
          "substitution_fix":0,
          "substitution_fee_calc_target":"nondiscount",
          "substitution_fee_target_usage":"cloudpaywithfee",
          "substitution_fee_calc_type":"allsum",
          "exchange_rate":null,
          "memo":null,
          "additional_items": []
        }
      },
      "accounts": [
        {
          "account_id":"012345678912",
          "customer_id":"012345678912",
          "customer_name":"customer1",
          "vendor":"aws",
          "service_discount":null
        },
        ...
      ],
      "create_time":"2020-12-21T11:26:55+09:00",
      "update_time":null,
      "total": {
        "aws":108850,
        "azure":0
      },
      "language":"ja"
    },
    ...
  ]
}
```

## 請求書設定の保存

**Role actions**

* `ModifyInvoice`

**Request**

```http
PUT /invoices/save/{month} HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

リクエストパラーメータの`{month}`のフォーマット: `yyyy-mm` 例: 2020-01

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
  "settings":[],
  "internal":true
}
```

| Field    | Type        | Required | Validation | Description                                             |
| -------- | ----------- | -------- | ---------- | ------------------------------------------------------- |
| settings | \_object\_  | Yes      | -          | 請求書設定                                                   |
| internal | \_boolean\_ | Yes      | -          | True: デフォルトの設定を請求書設定として一括で保存します。 False: settingsを参照します。 |

**Response**

```ruby
HTTP 200

{
  "status": "success"
}
```

## 請求書為替レートの保存

**Role actions**

* `ModifyInvoice`

```http
PUT /invoices/exchangerate/{month} HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

リクエストパラーメータの`{month}`のフォーマット: `yyyy-mm` 例: 2020-01

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
  "vendor":"aws",
  "billing_groups":["company id value1","company id value2"...],
  "exchange_rate":100
}

```

| Field           | Type       | Required | Validation           | Description              |
| --------------- | ---------- | -------- | -------------------- | ------------------------ |
| vendor          | \_string\_ | Yes      | サポート: `aws`, `azure` | ベンダー                     |
| billing\_groups | \_object\_ | Yes      | -                    | 請求グループ一覧。 company\_idを設定 |
| exchange\_rate  | \_double\_ | Yes      | -                    | 為替レート                    |

**Response**

```ruby
HTTP 200

{
  "status": "success"
}
```

## 請求書の作成

請求書の作成を行う前に以下のAPIで請求書の設定を行ってください。

1\. \[[`請求書設定の保存`](#no)]

2\. \[[`請求書為替レートの保存`](#rtono)]

**Role actions**

* `ModifyInvoice`

```http
POST /invoices/calculation/{month} HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

リクエストパラーメータの`{month}`のフォーマット: `yyyy-mm`例: 2020-01

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
  "vendor":"aws",
  "group":["company id value1","company id value2"...],
  "bulk":false
}
```

| Field  | Type        | Required | Validation                  | Description                                                             |
| ------ | ----------- | -------- | --------------------------- | ----------------------------------------------------------------------- |
| vendor | \_string\_  | Yes      | サポート: `aws`, `azure`, `gcp` | ベンダー                                                                    |
| group  | \_object\_  | Yes      | -                           | 請求グループ一覧。 company\_idを設定                                                |
| bulk   | \_boolean\_ | Yes      | -                           | <p>一括設定。<br>True:一括で請求書を作成。 </p><p>False: groupに設定された請求グループの請求書を作成。</p> |

**Response**

```ruby
HTTP 200

{
  "status": "success"
}
```


# Export

CSV出力に関するAPIリファレンスは以下の通りです。

## Get invoice csv(account)

請求書CSV(account)の出力

**Role actions**

* `ReadInvoice`
* `ModifyInvoice`

**Request**

```http
POST /export/csv/invoice_account/{month} HTTP1.1
Authorization: Bearer {token}
```

リクエストパラーメータの`{month}`のフォーマット: `yyyy-mm` 例: 2020-01

**Response**

```ruby
HTTP 200

{
  "status":"success",
  "url":"csv link"
}
```

CSVの内容

| Field                    | Description |
| ------------------------ | ----------- |
| BillingGroupID           | 請求グループID    |
| BillingGroupName         | 請求グループ名     |
| CompanyName              | 会社名         |
| Vendor                   | ベンダー        |
| CustomerID               | 顧客ID        |
| CustomerName             | 顧客名         |
| ServiceType              | サービスタイプ     |
| ServiceName              | サービス名       |
| Charge                   | 金額          |
| DiscountCharge           | 割引後額        |
| DiscountCharge - TaxFree | 割引後額 - 免税金額 |
| FreeFormat               | フリーフォーマット金額 |
| CustomService            | 請求サービス金額    |
| Tax                      | 消費税         |
| Total                    | 振込金額        |

## Get invoice csv(tag)

請求書CSV(tag)の出力

**Role actions**

* `ReadInvoice`
* `ModifyInvoice`

**Request**

```http
POST /export/csv/invoice_tag/{month} HTTP1.1
Authorization: Bearer {token}
```

リクエストパラーメータの`{month}`のフォーマット: `yyyy-mm` 例: 2020-01

**Response**

```ruby
HTTP 200

{
  "status":"success",
  "url":"csv link"
}
```

CSVの内容

| Field                    | Description |
| ------------------------ | ----------- |
| BillingGroupID           | 請求グループID    |
| BillingGroupName         | 請求グループ名     |
| CompanyName              | 会社名         |
| Vendor                   | ベンダー        |
| Tag                      | タグ詳細        |
| ServiceType              | サービスタイプ     |
| ServiceName              | サービス名       |
| Charge                   | 金額          |
| DiscountCharge           | 割引後額        |
| DiscountCharge - TaxFree | 割引後額 - 免税金額 |
| FreeFormat               | フリーフォーマット金額 |
| CustomService            | 請求サービス金額    |
| Tax                      | 消費税         |
| Total                    | 振込金額        |

## Get billing group csv

請求グループCSVの出力

**Role actions**

* `ReadBillingGroup`
* `ModifyBillingGroup`

**Request**

```http
POST /exportcsv/billing-group HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
  "redo":false
}
```

| Field | Type      | Required | Validation | Description                                               |
| ----- | --------- | -------- | ---------- | --------------------------------------------------------- |
| redo  | *boolean* | Yes      | -          | true:作成済みののCSVを出力。CSVがない場合はCSVを生成する。 false:新しいCSVを生成して出力。 |

**Response**

```ruby
HTTP 200

{
  "status":"success",
  "path":"csv link"
}
```

CSVの内容

| Field     | Description |
| --------- | ----------- |
| 請求グループID  | -           |
| 請求グループ名   | -           |
| 企業名       | -           |
| 郵便番号      | -           |
| 住所        | -           |
| 電話番号      | -           |
| 宛名        | -           |
| 請求書タイトル   | -           |
| コスト       | -           |
| カスタムフィールド | -           |

## Get billing group setting csv

請求グループ設定CSVの出力

**Role actions**

* `ReadBillingGroup`
* `ModifyBillingGroup`

**Request**

```http
POST /exportcsv/billing-group-setting HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
  "redo":false
}
```

| Field | Type      | Required | Validation | Description                                               |
| ----- | --------- | -------- | ---------- | --------------------------------------------------------- |
| redo  | *boolean* | Yes      | -          | true:作成済みののCSVを出力。CSVがない場合はCSVを生成する。 false:新しいCSVを生成して出力。 |

**Response**

```ruby
HTTP 200

{
  "status":"success",
  "path":"csv link"
}
```

CSVの内容

| Field           | Description |
| --------------- | ----------- |
| 請求グループID        | -           |
| 請求グループ名         | -           |
| ベンダー            | -           |
| 値引率             | -           |
| 消費税             | -           |
| AWSサポート請求方法     | -           |
| AWSサポート（一律%の場合） | -           |
| AWSサポート（固定）     | -           |
| 代行手数料請求方法       | -           |
| 代行手数料（％）        | -           |
| 代行手数料（固定）       | -           |
| 集計タイプ           | -           |
| 値引き対象           | -           |
| 請求代行サービス計算対象    | -           |


# Project

プロジェクトのAPIリファレンスは以下の通りです。

## Create project

プロジェクトの作成

**Role actions**

* `ModifyProject`

**Request**

```http
POST /project HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

以下に`{request body}`のリクエストペイロードの例を示します。

**{request body}**

```ruby
{
    "project_code":"project 1",
    "project_label":"project 1 description",
    "project_currency":"jpy"
}
```

**{request body} description**

| Field             | Type     | Required | Validation             | Description |
| ----------------- | -------- | -------- | ---------------------- | ----------- |
| project\_code     | *string* | Yes      | 1 \~ 40                | プロジェクトコード   |
| project\_label    | *string* | Yes      | 1 \~ 40                | プロジェクトラベル   |
| project\_currency | *string* | Yes      | support:\['jpy','usd'] | 表示通貨        |

**Response**

```ruby
HTTP 200

{"status":"success"}
```

## Edit project

プロジェクトの更新

**Role actions**

* `ModifyProject`

**Request**

```http
POST /project/{project_id} HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

以下に`{request body}`のリクエストペイロードの例を示します。

```ruby
{
    "project_code":"project 1",
    "project_label":"project 1 description",
    "project_currency":"jpy"
}
```

**{request body} description**

| Field             | Type     | Required | Validation             | Description |
| ----------------- | -------- | -------- | ---------------------- | ----------- |
| project\_code     | *string* | Yes      | 1 \~ 40                | プロジェクトコード   |
| project\_label    | *string* | Yes      | 1 \~ 40                | プロジェクトラベル   |
| project\_currency | *string* | Yes      | support:\['jpy','usd'] | 表示通貨        |

## Delete project

プロジェクトの削除

**Role actions**

* `ModifyProject`

**Request**

```http
DELETE /project/{project_id} HTTP1.1
Authorization: Bearer {token}
```

## Get project list

プロジェクト一覧の取得

**Role actions**

* `ReadProject`
* `ModifyProject`

**Request**

```http
GET /project HTTP1.1
Authorization: Bearer {token}
```

**Response**

```ruby
HTTP 200

[
  {
    "project_id": "prj-ad413e7b2006f3746r790a",
    "project_code": "プロジェクト1",
    "project_label": "プロジェクト1のラベル",
    "project_currency": "jpy"
  },
  {
    "project_id": "prj-fdf13fvf7vb61h0llr6519",
    "project_code": "プロジェクト2",
    "project_label": "プロジェクト2のラベル",
    "project_currency": "jpy"
  },...
]
```

## Get project list per month

月のプロジェクトデータの取得

**Role actions**

* `ReadProject`
* `ModifyProject`

**Request**

```http
GET /project/{month} HTTP1.1
Authorization: Bearer {token}
```

リクエストパラーメータの`{month}`のフォーマット: `yyyy-mm` 例: 2020-01

**Response**

```ruby
HTTP 200

[
  {
    "project_id": "prj-ad413e7b2006f3746r790a",
    "project_code": "プロジェクト1",
    "project_label": "プロジェクト1のラベル",
    "project_currency": "jpy",
    "amount": {
      "aws": {
        "profit": 0,
        "profit_exchanged": 0,
        "profit_exchanged_rate": 0,
        "profit_rate": 0,
        "sales": 0,
        "sales_exchanged": 0,
        "stock": 0,
        "stock_exchanged": 0
      },
      "total": {
        "profit": 0,
        "profit_exchanged": 0,
        "profit_exchanged_rate": 0,
        "profit_rate": 0,
        "sales": 0,
        "sales_exchanged": 0,
        "stock": 0,
        "stock_exchanged": 0
      }
    }
  },...
]
```

## Export project list per month

月のプロジェクトデータCSVの出力

**Role actions**

* `ReadProject`
* `ModifyProject`

**Request**

```http
GET /project/{month}/csv HTTP1.1
Authorization: Bearer {token}
```

リクエストパラーメータの`{month}`のフォーマット: `yyyy-mm` 例: 2020-01

**Response**

```ruby
HTTP 200

{
    "status":"success",
    "data":"csv url"
}
```


# Wave

| Description  | Link                              |
| ------------ | --------------------------------- |
| API Base URL | `https://wavereport.mobingi.com/` |


# Pre-request

open apiを使用するためのtokenを取得する必要があります。

**Response Format**

```
{
    token_type : string
    expires_in : number
    access_token : string
}
```

| Response value | type     | description |
| -------------- | -------- | ----------- |
| `token_type`   | *string* | 認証スキーム      |
| `expires_in`   | *number* | 期限 43200秒   |
| `access_token` | *string* | token値      |

## Token取得

openapiで使用するtokenを取得

**Request**

```http
POST /v1/access_token HTTP1.1
Content-Type: form-data

{request body}
```

`{request body}` の例

```ruby
{
  "grant_type":"client_credentials",
  "client_id":"test-client-id",
  "client_secret":"ABCDEFGHI"
}
```

| Body            | description |
| --------------- | ----------- |
| `grant_type`    | 固定値         |
| `client_id`     | 顧客ID        |
| `client_secret` | 顧客Secret    |


# Report

**基本的なResponse Format**

```javascript
{
    vendor : [
        {
            id : string
            name : string
            date : [
                {
                    blended_cost : number
                    date : string
                    timestamp : number
                    true_unblended_cost : number
                    unblended_cost : number
                },...
            ]
        },...
    ]
}
```

| Response value        | type     | description                                         |
| --------------------- | -------- | --------------------------------------------------- |
| `vendor`              | *array*  | パラメーターで指定したvendor 例 : `aws`                         |
| `id`                  | *string* | - `service` servicename    - `account` account id   |
| `name`                | *string* | - `service` servicename    - `account` account name |
| `date`                | *array*  | 取得したデータ一覧                                           |
| `date`                | *string* | - `monthly` : `YYYY-MM`   - `daily` : `YYYY-MM-DD`  |
| `timestamp`           | *number* | `date` のUNIXタイムスタンプ                                 |
| `blended_cost`        | *number* | AWS CURの `lineitem/blendedcost`                     |
| `unblended_cost`      | *number* | AWS CURの `lineitem/unblendedcost`                   |
| `true_unblended_cost` | *number* | mobingiで再計算したunblendedcost                          |

## レポートの取得

**Request**

```http
GET /v1/reports/{owner}/{resolution}?from={from}&to={to}&by={by}&vendor={vendor} HTTP1.1
Content-Type: application/json
```

`{Path Variables}` の例

| Path         | description                      |
| ------------ | -------------------------------- |
| `owner`      | 使用可能な値   - `company`             |
| `resolution` | 使用可能な値   - `monthly`   - `daily` |

`Request URL` の例

```ruby
GET /v1/reports/company/monthly?from=2019-01-01&to=2019-02-01&by=service&vendor=aws
```

| Params   | description                                                                                                       |
| -------- | ----------------------------------------------------------------------------------------------------------------- |
| `from`   | 型 : *string*   フォーマット : *YYYY-MM\_DD*   説明 :   Monthly は自動的に `YYYY-MM`へ変換されます。   Daily は自動的に `YYYY-MM-DD`へ変換されます。 |
| `to`     | 型 : *string*   フォーマット : *YYYY-MM\_DD*   説明 :   Monthly は自動的に `YYYY-MM`へ変換されます。   Daily は自動的に `YYYY-MM-DD`へ変換されます。 |
| `by`     | **使用可能な値**   型 : *string*   - `service`   - `account`                                                             |
| `vendor` | **使用可能な値**   型 : *string*   - `aws`                                                                               |


# Status

The following endpoint is the base url for the APIs below.

```
https://service.mobingi.com/m/status/
```

## List invoice calculation status

Get the current status of the invoice calculations.

**Request**

```http
GET calculations/status[?params] HTTP1.1
Authorization: Bearer {token}
```

Details for `params`.

| Key      | Value                                                                                        |
| -------- | -------------------------------------------------------------------------------------------- |
| `vendor` | Optional. Supported vendor is only `aws`  at the moment.                                     |
| `from`   | Optional. If not provided, default value is 2 months before current month. Format: `yyyymm`. |
| `to`     | Optional. If not provided, default value is current month. Format: `yyyymm`.                 |

**Response**

```ruby
HTTP/1.1 200 OK

[
  {
    "billing_month": "2020-04",
    "end_time": "",
    "finished": 3090,
    "id": "MSP-123456",
    "invoice_type": "account",
    "msp": "MSP-123456",
    "name": "Alphaus, Inc.",
    "run_id": "MSP-123456/76f20b9a-b7fa-4599-bc38-0691dbbd4ea3",
    "start_time": "2020-05-22T04:01:38Z",
    "status": "checking",
    "status_message": "checking",
    "total": 3090,
    "type": "msp",
    "vendor": "aws"
  },
  ...
]
```

Examples:

```bash
# Simple request. Get status for the past 2 months:
GET calculations/status

# If you want range from Oct 2019 - Jan 2020:
GET calculations/status?from=201910&to=202001
```


# Ocean

{% hint style="warning" %}
This API is already deprecated.
{% endhint %}

| Description  | Link                                   |
| ------------ | -------------------------------------- |
| API Base URL | `https://service.mobingi.com/m/ocean/` |


# Credentials

Before you can do any Ocean deployments, you need to register your cloud credentials to Ocean. These credentials will be used by Ocean to access your cloud account and deploy any resources you need in your Ocean deployments.

## Create a credential

Register a cloud credential to Ocean.

**Request**

```http
POST /v0/credentials HTTP1.1
Authorization: Bearer {token}
Content-Type: application/json

{request body}
```

The following are some example request payloads for `{request body}` per provider.

Alibaba:

```ruby
{
  "vendor":"alicloud",
  "name":"testalicloudcreds",
  "key":"ABCDEF",
  "secret":"somesecret"
}
```

AWS:

```ruby
{
  "vendor":"aws",
  "name":"testawscreds",
  "key":"ABCDEF",
  "secret":"somesecret"
}
```

Azure:

```ruby
{
  "vendor":"azure",
  "name":"testazurecreds",
  "key":"ABCDEF",
  "secret":"somesecret",
  "application":"997613dc-032a-440f-bead-2bb5b19ad002",
  "subscription":"c825c2bf-cdc5-4b96-9644-a1dd5144ae0f",
  "directory":"292cd594-02c7-4a56-86e7-e30615557e83"
}
```

GCP (for GCP, `secret` is your service account's JSON file):

```ruby
{
  "vendor":"gcp",
  "name":"testgcpcreds",
  "project_id":"gcp-project-id",
  "secret":"aGVsbG93b3JsZA==",
  "isbase64":true
}
```

**Response**

```ruby
HTTP 201

{
  "credential_id":"cred-aws-58c2297d25645-fa7vzi6E1l",
  "user_id":"1234567890",
  "username":"testsubuser",
  "name":"testawscreds",
  "key":"ABCDEF",
  "secret":"***",
  "create_time":"2019-04-04T04:16:02Z",
  "update_time":"2019-04-04T04:16:02Z",
  "vendor":"aws"
}
```

When creating [Ocean templates](https://docs.mobingi.com/v/ocean-en/reference-2018-07-02), you will use the credential's `name` part as the name for the template's credential entry. This name should be unique per account.

## List credentials

Return a list of registered credentials.

**Request**

```http
GET /v0/credentials[?vendor={vendor-name}] HTTP1.1
Authorization: Bearer {token}
```

**Response**

Example:

```ruby
HTTP 200

{
  "alicloud":[
    {
      "credential_id":"cred-alicloud-xx",
      "user_id":"1234",
      "username":"subuser",
      "name":"testalicloudcreds",
      "key":"ABCDEF",
      "secret":"***",
      "create_time":"2019-01-31T06:47:08Z",
      "update_time":"2019-01-31T06:47:08Z",
      "vendor":"alicloud"
    }
  ],
  "aws":[
    {
      "credential_id":"cred-aws-xx",
      "user_id":"1234",
      "username":"subuser",
      "name":"testawscreds",
      "key":"ADCDEF",
      "secret":"***",
      "create_time":"2019-04-04T04:16:02Z",
      "update_time":"2019-04-04T04:16:02Z",
      "vendor":"aws"
    }
  ],
  "gcp":[
    {
      "credential_id":"cred-gcp-xx",
      "user_id":"1234",
      "username":"subuser",
      "name":"testgcpcreds",
      "key":"testgcpcreds",
      "secret":"***",
      "project_id":"gcp-project-id",
      "create_time":"2018-05-21T17:15:36+09:00",
      "update_time":"2018-05-21T17:15:36+09:00",
      "vendor":"gcp"
    }
  ],
  "azure":[
    {
      "credential_id":"cred-azure-xx",
      "user_id":"1234",
      "username":"subuser",
      "name":"testazurecreds",
      "key":"ABCDEF",
      "secret":"***",
      "application_id":"997613dc-032a-440f-bead-2bb5b19ad002",
      "subscription_id":"c825c2bf-cdc5-4b96-9644-a1dd5144ae0f",
      "directory_id":"292cd594-02c7-4a56-86e7-e30615557e83",
      "create_time":"2018-05-21T17:15:36+09:00",
      "update_time":"2018-05-21T17:15:36+09:00",
      "vendor":"azure"
    }
  ]
}
```

## Describe a credential

Describe a specific credential specified by id.

**Request**

```http
GET /v0/credentials/{id} HTTP1.1
Authorization: Bearer {token}
```

**Response**

```ruby
HTTP 200

{
  "credential_id":"cred-gcp-xx",
  "user_id":"1234",
  "username":"subuser",
  "name":"testgcpcreds",
  "key":"testgcpcreds",
  "secret":"***",
  "project_id":"gcp-project-id",
  "create_time":"2018-05-21T17:15:36+09:00",
  "update_time":"2018-05-21T17:15:36+09:00",
  "vendor":"gcp"
}
```

## Delete a credential

Remove a registered credential from Ocean.

**Request**

```http
DELETE /v0/credentials/{id} HTTP1.1
Authorization: Bearer {token}
```

**Response**

```ruby
HTTP 200
```


# Deployments

The following is the API reference for working with Ocean deployments.

## Create a deployment

Deploy an Ocean template.

**Request**

```http
POST /v0/deployments HTTP1.1
Authorization: Bearer {token}

{template body}
```

**Response**

```ruby
HTTP 202
```

Check out <https://github.com/mobingi/ocean-template-examples> for examples about `{template body}`. For details on how to write Ocean templates, check out this [reference](https://docs.mobingi.com/v/ocean-en/template-2018-07-02).

## List deployments

{% hint style="warning" %}
This page is still a work in progress.
{% endhint %}

Get a list of available deployments.

```http
REQUEST
GET /v0/deployments HTTP1.1
Authorization: Bearer {token}

---
RESPONSE
HTTP 200
tbd
```

## Describe a deployment

Describe a specific deployment based on name.

**Request**

```http
GET /v0/deployments/{name} HTTP1.1
Authorization: Bearer {token}
```

`{name}` is the template (or deployment) name.

**Response**

```ruby
HTTP 200

{
  "deployment":"template-name",
  "stacks":[
    {
      "name":"stack-name",
      "items":[
        {
          "name":"eksmaster",
          "resources":[
            {
              "key": "AWS::EC2::InternetGateway",
              "value": "igw-040e7443b67d8cda2"
            },
            {
              "key": "AWS::EC2::Route",
              "value": "aws-5-Route-1PR9K4JNZTQRY"
            }
          ],
          "status": "creating|updating|completed|failed"
        },
        {
          "name":"cfnextra",
          "resources":[
            {
              "key": "AWS::SNS::SNSTopic",
              "value": "arn:aws:sns:ap-northeast-1:...cfnextra-sample-snstopic"
            },
          ],
          "status": "creating|updating|completed|failed"
        }
      ],
      "region": "ap-northeast-1"
    }     
  ]
}
```

## Delete a deployment

Delete a deployment and all associated applications and resources.

**Request**

```http
DELETE /v0/deployments/{name}[?force=true] HTTP1.1
Authorization: Bearer {token}
```

`{name}` is the template (or deployment) name. For templates that have dependency to other templates, API will return error stating the dependency. If the parameter `force=true` is specified, the template resources will be deleted including all dependencies.

**Response**

For successful responses, server will return `HTTP 202`. Errors will return `HTTP 422`.


# ALM (v3)

{% hint style="warning" %}
This API is already deprecated.
{% endhint %}

## Endpoint

```
https://api.mobingi.com
```

## OAuth Authentication

In order to interact with the API, your application must authenticate. Mobingi API handles this through **OAuth**. An OAuth token functions as a complete authentication request. In effect, it acts as a substitute for a username and password pair.

*To get an OAuth token, make a POST request to*

POST `/v3/access_token`

| **Parameters** | **Type** | **Required** | **Detail**                                                                                                                                                                                                                                                                                                                     |
| -------------- | -------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| client\_id     | string   | Yes          |                                                                                                                                                                                                                                                                                                                                |
| client\_secret | string   | Yes          |                                                                                                                                                                                                                                                                                                                                |
| grant\_type    | string   | Yes          | This value is either `client_credentials` or `password`.  If you grant with password, you are interacting the same as working around Mobingi UI; If you grant with client\_credentials, you are acting as an Alm-Agent, and most resource related permissions are denied by [RBAC](https://learn.mobingi.com/enterprise/rbac). |

Example Request:

```bash
curl -X POST https://api.mobingi.com/v3/access_token \
-H "Content-Type: application/json" \
-d '{"grant_type":"client_credentials","client_id":"lg-5447820c870e1-xBV0OpTEN-tm","client_secret":"sFVYDoe07fxPjNgYvauYGOYCeXbOTE"}'
```

Response Body:

```javascript
{
  "token_type": "Bearer",
  "expires_in": 43200,
  "access_token": "eyJ0eXAiOiJQiLCJhbGciOMeXzQfME"
}
```

You can then start making API requests by passing the `access_token` value to the *Authorization* Header

```
Authorization: Bearer eyJ0eXAiOiJQiLCJhbGciOMeXzQfME
```

## ALM Templates <a href="#alm-templates" id="alm-templates"></a>

### Apply Template <a href="#template-apply" id="template-apply"></a>

Applies the Mobingi Alm template and creates stack.

POST `/v3/alm/template`

| **Parameters**      | **Type** | **Required** | **Detail**                                      |
| ------------------- | -------- | ------------ | ----------------------------------------------- |
| { *template body* } | string   | Yes          | Mobingi Alm template body in json string format |

Request Header

```bash
Authorization: Bearer eyJ0eXAiOiJQiL...CJhbGciOMeXzQfME
Content-Type: application/json
```

Request body

```bash
{
  "version": "2017-03-03",
  "label": "template version label #1",
  "description": "This template creates a sample stack with EC2 instance on AWS",
  "vendor": {
    "aws": {
      "cred": "AKIAJ...DZLA",
      "region": "ap-northeast-1"
    }
  },
  "configurations": [
    {
      "role": "web",
      "flag": "Web01",
      "provision": {
        "image": "${computed}",
        "volume_type": "${computed}",
        "instance_type": "t2.micro",
        "instance_count": 1,
        "keypair": true
      }
    }
  ]
}
```

Response Body

```bash
HTTP/1.1 201 Created

{
  "status": "success",
  "stack_status": "CREATE_IN_PROGRESS",
  "stack_id": "mo-5447820c870e1-ZgNTSRM8K-tk",
  "version_id": "98O0jK6CQk8qLi14S2SLU8z3JIo3.JPx"
}
```

### Update Template <a href="#template-update" id="template-update"></a>

Updates the Mobingi Alm template and applies the changes to stack resources.

*Note:* `vendor` section will be ignored when performing this API call. You can not change cloud vendors after the stack is created.

PUT `/v3/alm/template/{stack_id}`

| **Parameters**      | **Type** | **Required** | **Detail**                                      |
| ------------------- | -------- | ------------ | ----------------------------------------------- |
| { *template body* } | string   | Yes          | Mobingi Alm template body in json string format |

Request Header

```bash
Authorization: Bearer eyJ0eXAiOiJQiL...CJhbGciOMeXzQfME
Content-Type: application/json
```

Request body

```bash
{
  "version": "2017-03-03",
  "label": "template version label #2",
  "description": "This template creates a sample stack with EC2 instance on AWS",
  "vendor": {
    "aws": {
      "cred": "AKIAJ...DZLA",
      "region": "ap-northeast-1"
    }
  },
  "configurations": [
    {
      "role": "web",
      "flag": "Web01",
      "provision": {
        "image": "${computed}",
        "instance_type": "m3.medium",
        "instance_count": 2,
        "keypair": true
      }
    }
  ]
}
```

Response Body

```bash
HTTP/1.1 202 Accepted

{
  "status": "success",
  "stack_status": "UPDATE_IN_PROGRESS",
  "stack_id": "mo-5447820c870e1-ZgNTSRM8K-tk",
  "version_id": "gCn2JuPhndwxMZuidOER0yyxM8jZB6Vn"
}
```

### Compare Templates <a href="#template-compare" id="template-compare"></a>

Compares the resource changes between two Mobingi Alm templates.

POST `/v3/alm/template/compare`

| **Parameters** | **Type** | **Required** | **Detail**                                     |
| -------------- | -------- | ------------ | ---------------------------------------------- |
| id             | array    | conditional  | items contain stack id and version information |
| body           | array    | conditional  | items contain template body source             |

*Note: You can compare two templates by retrieving them from their version id and stack id. Or, you can compare a target template body (posted in json format to* `body` *parameter) with a source template retrieved by its version id and stack id.*

*The current API version only supports two templates comparison, and you always should retrieve the source template by its version id and stack id. That being said, you have to always pass at least one item in parameter* `id` *array. Below are two examples:*

Request Header

```bash
Authorization: Bearer eyJ0eXAiOiJQiL...CJhbGciOMeXzQfME
Content-Type: application/json
```

Request body ( *Example 1* )

```bash
{
    "id": [
        {
            "mo-5447826c870e7-ZgNTSRM8K-tk": {
                "version": "98O0jK5CQk8gLi14S2SLU8z3JIo3.JPx"
            }
        },
        {
            "mo-5447826c870e7-ZgNTSRM8K-tk": {
                "version": "gCn2JuPhndwxMZuodOER0yyxM8jZB6Vn"
            }
        }
    ]
}
```

Request body ( *Example 2* )

```bash
{
    "id": [
        {
            "mo-5447826c870e7-9S3zWP7jM-tk": {
                "version": "dK7R9_PuclTqSysMniPTcmpE.5u58RVL"
            }
        }
    ],
    "body": [
        "{\n \"version\": \"2017-03-03\",\n \"label\": \"template version label #2\",\n \"description\": \"This template creates a sample stack with EC2 instance on AWS\",\n \"vendor\": {\n \"aws\": {\n \"cred\": \"AKIAJ...DZLA\",\n \"region\": \"ap-northeast-1\"\n }\n },\n \"configurations\": [\n {\n \"role\": \"web\",\n \"flag\": \"Web01\",\n \"provision\": {\n \"image\": \"${computed}\", \"instance_type\": \"m3.medium\",\n \"instance_count\": 2,\n \"keypair\": true,\n }\n }\n ]\n }"
    ]
}
```

Response Body

```bash
HTTP/1.1 202 Accepted

{
  "status": "success",
  "source":{
      "version": "2017-03-03",
      "label": "template version label #1",
      "description": "This template creates a sample stack with EC2 instance on AWS",
      "vendor": {
        "aws": {
          "cred": "AKIAJ...DZLA",
          "region": "ap-northeast-1"
        }
      },
      "configurations": [
        {
          "role": "web",
          "flag": "Web01",
          "provision": {
            "image": "${computed}",
            "instance_type": "t2.micro",
            "volume_type": "${computed}",
            "instance_count": 1,
            "keypair": true
          }
        }
      ]
  },
  "target": {
      "version": "2017-03-03",
      "label": "template version label #2",
      "description": "This template creates a sample stack with EC2 instance on AWS",
      "vendor": {
        "aws": {
          "cred": "AKIAJ...DZLA",
          "region": "ap-northeast-1"
        }
      },
      "configurations": [
        {
          "role": "web",
          "flag": "Web01",
          "provision": {
            "image": "${computed}",
            "instance_type": "m3.medium",
            "instance_count": 2,
            "keypair": true
          }
        }
      ]
  },
  "diff": {
    "new": [],
    "removed": {
      "configurations\/1\/provision\/volume_type": "${computed}"
    },
    "edited": {
      "label": {
        "oldvalue": "template version label #1",
        "newvalue": "template version label #2"
      },
      "configurations\/provision\/instance_type": {
        "oldvalue": "t2.micro",
        "newvalue": "m3.medium"
      },
      "configurations\/provision\/instance_count": {
        "oldvalue": 1,
        "newvalue": 2
      }
    }
  }
}
```

### Template Versions <a href="#template-list" id="template-list"></a>

List Mobingi Alm template versions

GET `/v3/alm/template`

| **Parameters** | **Type** | **Required** | **Detail**                                        |
| -------------- | -------- | ------------ | ------------------------------------------------- |
| stack\_id      | string   | Yes          | The unique id returned when applying the template |

Request Header

```bash
Authorization: Bearer eyJ0eXAiOiJQiL...CJhbGciOMeXzQfME
Content-Type: application/json
```

Response Body

```bash
HTTP/1.1 200 OK

[
  {
    "version_id": "1kk2HiGLxF1fThVLJvC0h6fd5z3QWOiM",
    "latest": true,
    "last_modified": "2017-08-25T10:40:29.000Z",
    "size": "2963"
  },
  {
    "version_id": "gCn2JuPhndwxMZuodOER0yyxM8jZB6Vn",
    "latest": false,
    "last_modified": "2017-08-25T10:20:38.000Z",
    "size": "211"
  },
  {
    "version_id": "98O0jK5CQk8gLi14S2SLU8z3JIo3.JPx",
    "latest": false,
    "last_modified": "2017-08-25T08:48:12.000Z",
    "size": "2940"
  }
]
```

### Describe Template <a href="#template-describe" id="template-describe"></a>

Describes the template body of a specific version.

GET `/v3/alm/template/{stack_id}`

| **Parameters** | **Type** | **Required** | **Detail**                                                                                                                             |
| -------------- | -------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------- |
| version\_id    | string   | No           | The id of the template version associated with the stack. If empty or "latest" provided, the most updated template version is returned |

Request Header

```bash
Authorization: Bearer eyJ0eXAiOiJQiL...CJhbGciOMeXzQfME
Content-Type: application/json
```

Response Body

```bash
HTTP/1.1 200 OK

{
  "version": "2017-03-03",
  "label": "template version label #2",
  "description": "This template creates a sample stack with EC2 instance on AWS",
  "vendor": {
    "aws": {
      "cred": "AKIAJ...DZLA",
      "region": "ap-northeast-1"
    }
  },
  "configurations": [
    {
      "role": "web",
      "flag": "Web01",
      "provision": {
        "image": "${computed}",
        "instance_type": "m3.medium",
        "instance_count": 2,
        "keypair": true
      }
    }
  ]
}
```

## Stacks <a href="#stacks" id="stacks"></a>

### List Stacks <a href="#stack-list" id="stack-list"></a>

List all stacks running under current organization account.

GET `/v3/alm/stack`

Request Header

```bash
Authorization: Bearer eyJ0eXAiOiJQiL...CJhbGciOMeXzQfME
Content-Type: application/json
```

Response Body

```bash
HTTP/1.1 200 OK

[
    {
      "auth_token": "zQT8zJ37o9iZDIAFOVOoZzLCu0nR",
      "user_id": "5447820c870e1",
      "configuration": {
        "version": "2017-03-03",
        "label": "template version label #2",
        "description": "This template creates a sample stack with EC2 instance on AWS",
        "vendor": {
          "aws": {
            "cred": "AKIAJ...DZLA",
            "region": "ap-northeast-1"
          }
        },
        "configurations": [
          {
            "role": "web",
            "flag": "Web01",
            "provision": {
              "image": "${computed}",
              "instance_type": "m3.medium",
              "instance_count": 2,
              "keypair": true
            }
          }
        ]
      },
      "nickname": "clean sail demonstrate",
      "create_time": "2017-08-26T19:31:25+09:00",
      "username": "thompson",
      "stack_id": "mo-5447820c870e1-ZgNTSRM8K-tk",
      "stack_status": "CREATE_COMPLETE",
      "version_id": "1kk2HiGLxF1fThVLJvC0h6fd5z3QWOiM"
  },
  {
      ..
  }
]
```

### Describe Stack <a href="#stack-describe" id="stack-describe"></a>

Describes the stack detail information.

GET `/v3/alm/stack/{stack_id}`

Request Header

```bash
Authorization: Bearer eyJ0eXAiOiJQiL...CJhbGciOMeXzQfME
Content-Type: application/json
```

Response Body

```bash
HTTP/1.1 200 OK

{
  "auth_token": "zQT8zJ37o9iZDIAFOVOoZzLCu0nR",
  "user_id": "5447820c870e1",
  "configuration": {
    "version": "2017-03-03",
    "label": "template version label #2",
    "description": "This template creates a sample stack with EC2 instance on AWS",
    "vendor": {
      "aws": {
        "cred": "AKIAJ...DZLA",
        "region": "ap-northeast-1"
      }
    },
    "configurations": [
      {
        "role": "web",
        "flag": "Web01",
        "provision": {
          "image": "${computed}",
          "instance_type": "m3.medium",
          "instance_count": 2,
          "keypair": true
        }
      }
    ]
  },
  "nickname": "clean sail demonstrate",
  "create_time": "2017-08-26T19:31:25+09:00",
  "username": "thompson",
  "stack_id": "mo-5447820c870e1-ZgNTSRM8K-tk",
  "stack_status": "CREATE_COMPLETE",
  "version_id": "1kk2HiGLxF1fThVLJvC0h6fd5z3QWOiM"
}
```

### Describe Container <a href="#describe-container" id="describe-container"></a>

Describes the stack container detail information.

GET `/v3/alm/container/{container_id}`

| **Parameters** | **Type** | **Required** | **Detail**                                         |
| -------------- | -------- | ------------ | -------------------------------------------------- |
| container\_id  | string   | Yes          | The id of the container associated with the stack. |

Request Header

```bash
Authorization: Bearer eyJ0eXAiOiJQiL...CJhbGciOMeXzQfME
Content-Type: application/json
```

Response Body

```javascript
HTTP/1.1 200 OK

{
    "container_id": "i-0c32760b85f60aca7",
    "agent_id": "e8b15d4f-f027-4c65-80f5-ded5858cd213",
    "update_time": "1510544332",
    "stack_id": "mo-5447820c870e1-ZgNTSRM8K-tk",
    "instance_id": "i-0c32760b85f60aca7",
    "status": "complete"
}
```

### List Containers <a href="#list-containers" id="list-containers"></a>

List the stack containers filtering by {stack\_id} or {instance\_id}

GET `/v3/alm/container`

| **Parameters** | **Type** | **Required** | **Detail**                                                                        |
| -------------- | -------- | ------------ | --------------------------------------------------------------------------------- |
| stack\_id      | string   | conditional  | If both {stack\_id} and {instance\_id} are presents, {stack\_id} will be ignored. |
| instance\_id   | string   | conditional  | The id of the instance.                                                           |

Request Header

```bash
Authorization: Bearer eyJ0eXAiOiJQiL...CJhbGciOMeXzQfME
Content-Type: application/json
```

Response Body

```javascript
HTTP/1.1 200 OK

[
    {
        "agent_id": "4e9a6b9a-2a1f-454e-be5e-847573b44f10",
        "container_id": "i-049a49d8881adf122",
        "update_time": "1510564361",
        "stack_id": "mo-5447820c870e1-ZgNTSRM8K-tk",
        "instance_id": "i-049a49d8881adf122",
        "status": "complete"
    },
    {
        "agent_id": "09afaa82-0a71-4680-a68a-91badaaaa134",
        "container_id": "i-0363778be4d1bc81f",
        "update_time": "1510564297",
        "stack_id": "mo-5447820c870e1-ZgNTSRM8K-tk",
        "instance_id": "i-0363778be4d1bc81f",
        "status": "complete"
    },
    {
        "agent_id": "9c075f08-81c9-4147-8974-f543640dccf6",
        "container_id": "i-02f27fcae984fc946",
        "update_time": "1510564348",
        "stack_id": "mo-5447820c870e1-ZgNTSRM8K-tk",
        "instance_id": "i-02f27fcae984fc946",
        "status": "complete"
    }
]
```

## RBAC <a href="#rbac" id="rbac"></a>

### Create Role <a href="#rbac-create-role" id="rbac-create-role"></a>

Creates a new role. (**Note: This endpoint can only be accessed by master account**)

POST `/v3/role`

| **Parameters** | **Type** | **Required** | **Detail**                         |
| -------------- | -------- | ------------ | ---------------------------------- |
| name           | string   | Yes          | Name of Mobingi Role               |
| scope          | string   | Yes          | Mobingi Role in json string format |

Request Header

```bash
Authorization: Bearer eyJ0eXAiOiJQiL...CJhbGciOMeXzQfME
Content-Type: application/x-www-form-urlencoded
```

Request body

```bash
{
  "name": "sample name",
  "scope": "{ _role scope body_ }"
```

Response Body

```bash
HTTP/1.1 200

{
  "status": "success",
  "role_id": "morole-544****0e1-ZgNTSRM8K-tk"
}
```

### Update Role <a href="#rbac-update-role" id="rbac-update-role"></a>

Updates an existing role.

**Note:** *This endpoint is denied to all users except master account, defined by* [*default RBAC scope*](https://learn.mobingi.com/enterprise/rbac-reference#default-roles)*, and this scope cannot be overwritten.*

PUT `/v3/role/{role_id}`

| **Parameters** | **Type** | **Required** | **Detail**                         |
| -------------- | -------- | ------------ | ---------------------------------- |
| name           | string   | Yes          | Name of Mobingi Role               |
| scope          | string   | Yes          | Mobingi Role in json string format |

Request Header

```bash
Authorization: Bearer eyJ0eXAiOiJQiL...CJhbGciOMeXzQfME
Content-Type: application/x-www-form-urlencoded
```

Request body

```bash
{
  "name": "sample name",
  "scope": "{ _role scope body_ }"
}
```

Response Body

```bash
HTTP/1.1 200

{
  "status": "success",
  "role_id": "morole-544****70e1-ZgNTSRM8K-tk"
}
```

### Delete Role <a href="#rbac-delete-role" id="rbac-delete-role"></a>

Deletes an existing Role.

**Note:** *This endpoint is denied to all users except master account, defined by* [*default RBAC scope*](https://learn.mobingi.com/enterprise/rbac-reference#default-roles)*, and this scope cannot be overwritten.*

DELETE `/v3/role/{role_id}`

Request Header

```bash
Authorization: Bearer eyJ0eXAiOiJQiL...CJhbGciOMeXzQfME
Content-Type: application/json
```

Response Body

```bash
HTTP/1.1 200

{
  "status": "success",
  "role_id": "morole-544****0e1-ZgN****M8K-tk"
}
```

### List Roles <a href="#rbac-list-roles" id="rbac-list-roles"></a>

Lists all roles created under current account.

**Note:** *This endpoint is denied to all users except master account, defined by* [*default RBAC scope*](https://learn.mobingi.com/enterprise/rbac-reference#default-roles)*, and this scope cannot be overwritten.*

GET `/v3/role`

Request Header

```bash
Authorization: Bearer eyJ0eXAiOiJQiL...CJhbGciOMeXzQfME
Content-Type: application/json
```

Response Body

```bash
HTTP/1.1 200
[
    {
        "role_id": "morole-544****0e1-ZgNT***M8K-tk",
        "user_id": "544****0e1",
        "name": "sample name",
        "scope": "{ _role scope body_ }",
        "create_time": "",
        "update_time": ""
    },
    {
        ....
    }
]
```

### Describe Roles <a href="#rbac-describe-roles" id="rbac-describe-roles"></a>

1. **Describe roles attached to the user**

   Lists all roles attached to a user specified by username.

   **Note:** *This endpoint is denied to all users except master account, defined by* [*default RBAC scope*](https://learn.mobingi.com/enterprise/rbac-reference#default-roles)*, and this scope cannot be overwritten.*

   GET `/v3/user/{username}/role`

````
Request Header
```bash
Authorization: Bearer eyJ0eXAiOiJQiL...CJhbGciOMeXzQfME
Content-Type: application/json
````

Response Body

```bash
HTTP/1.1 200
[
    {
        "role_id": "morole-544****0e1-ZgNT***M8K-tk",
        "user_id": "544****0e1",
        "name": "sample name",
        "scope": "{ _role scope body_ }",
        "create_time": "",
        "update_time": ""
    },
    {
        ....
    }

]
```

````
1. **Describe Current Logged In User Roles**

```text
Lists all roles attached to current user.

_This endpoint is requested by users instead of master account, and returns the roles that attached to them._

<div class="callout callout-info">
GET <code>/v3/user/role</code>
</div>



Request Header
```bash
Authorization: Bearer eyJ0eXAiOiJQiL...CJhbGciOMeXzQfME
Content-Type: application/json
````

Response Body

```bash
HTTP/1.1 200
[
    {
        "user_role_id": "mour-5447****0e1-TEW****dsIE-tk",
        "role_id": "morole-5447****0e1-ZgN****RM8K-tk",
        "user": "{ user_id: 5447****0e1, username: tes***est }",
        "scope": "{ _role scope body_ }",
        "create_time": "",
        "update_time": ""
    },
    {
        ....
    }

]
```

````
### Attach Role to User {#rbac-attach-user-role}

Attach an existing role to a user.

**Note:** _This endpoint is denied to all users except master account, defined by_ [_default RBAC scope_](https://learn.mobingi.com/enterprise/rbac-reference#default-roles)_, and this scope cannot be overwritten._

 POST `/v3/user/role`

| **Parameters** | **Type** | **Required** | **Detail** |
| --- | :---: | ---: | :--- |
| username | string | Yes | target user |
| role\_id | string | Yes | Mobingi Role Id |

Request Header

```bash
Authorization: Bearer eyJ0eXAiOiJQiL...CJhbGciOMeXzQfME
Content-Type: application/x-www-form-urlencoded
````

Request body

```bash
{
  "username": "testtest",
  "role_id": "morole-544****0e1-ZgN****8K-tk"
}
```

Response Body

```bash
HTTP/1.1 200
{
  "status": "success",
  "user_role_id": "mour-544****0e1-ZgN****M8K-tk"
}
```

### Reattach Role to User <a href="#rbac-reattach-user-role" id="rbac-reattach-user-role"></a>

Reattach a role to user.

**Note:** *This endpoint is denied to all users except master account, defined by* [*default RBAC scope*](https://learn.mobingi.com/enterprise/rbac-reference#default-roles)*, and this scope cannot be overwritten.*

PUT `/v3/user/role/{role_id}`

| **Parameters** | **Type** | **Required** | **Detail**  |
| -------------- | -------- | ------------ | ----------- |
| username       | string   | Yes          | target user |

Request Header

```bash
Authorization: Bearer eyJ0eXAiOiJQiL...CJhbGciOMeXzQfME
Content-Type: application/x-www-form-urlencoded
```

Request body

```bash
{
  "username": "testtest"
}
```

Response Body

```bash
HTTP/1.1 200

{
  "status": "success",
  "role_id": "morole-5447****0e1-ZgN***M8K-tk"
}
```

### Detach Role from User <a href="#rbac-detach-user-role" id="rbac-detach-user-role"></a>

Deatch a role from user.

**Note:** *This endpoint is denied to all users except master account, defined by* [*default RBAC scope*](https://learn.mobingi.com/enterprise/rbac-reference#default-roles)*, and this scope cannot be overwritten.*

DELETE `/v3/user/role/{role_id}`

| **Parameters** | **Type** | **Required** | **Detail**  |
| -------------- | -------- | ------------ | ----------- |
| username       | string   | Yes          | target user |

Request Header

```bash
Authorization: Bearer eyJ0eXAiOiJQiL...CJhbGciOMeXzQfME
Content-Type: application/json
```

Request body

```bash
{
  "username": "testtest"
}
```

Response Body

```bash
HTTP/1.1 200

{
  "status": "success",
  "role_id": "morole-5447****0e1-ZgN****M8K-tk"
}
```

### Describe Role Scope <a href="#rbac-describe-role-scope" id="rbac-describe-role-scope"></a>

Describes the role scope body.

GET `/v3/role/templates`

Request Header

```bash
Authorization: Bearer eyJ0eXAiOiJQiL...CJhbGciOMeXzQfME
Content-Type: application/json
```

Response Body

```bash
HTTP/1.1 200
[
    {
        "id": "admin",
        "name": "Management Role",
        "scope": {
            "version": "2017-05-05",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Action": [
                        "*"
                    ],
                    "Resource": [
                        "*"
                    ]
                }
            ]
        }
    },
    {
        ....
    }
]
```

## Alm-Agent <a href="#alm-agent" id="alm-agent"></a>

*In this section, all endpoints are designated to work with Mobingi alm-agent in order to perform application lifecycle automation by Mobingi. Mobingi alm-agent is the Linux server side program that automatically installed during instance launch and initialization. If you are a contributor to the OSS repo* [*github.com/mobingi/alm-agent*](https://github.com/mobingi/alm-agent)*, you're looking at the right reference here. If you are a developer working on integrating Mobingi ALM with your client applications or contributing to Mobingi API/UI only, you can ignore this API references section.*

### Register Agent Status <a href="#alm-agent-register-agent-status" id="alm-agent-register-agent-status"></a>

This endpoint listens to the notifications sent by Mobingi alm-agent for self status registration.

For example, when an instance is launched and Mobingi alm agent is installed, the agent will first call this endpoint to register itself.

Another example, when an AWS spot instance is scheduled to be shutdown, the agent will send notice to this endpoint and allow Mobingi system to perform other necessary actions (*such as spot replacement)*.

POST `/v3/alm/agent/agent_status`

| **Parameters** | **Type** | **Required** | **Detail**                                                                         |
| -------------- | -------- | ------------ | ---------------------------------------------------------------------------------- |
| stack\_id      | string   | Yes          | The stack id which this server instance is belonged to                             |
| agent\_id      | string   | Yes          | The agent's unique identifier                                                      |
| status         | string   | Yes          | Sample values: *starting*, *installing*, *error*, *notice*, spot\_terminate, etc.. |
| instance\_id   | string   | No           | The server instance id where Mobingi alm-agent is installed on                     |
| message        | string   | No           | Optional, a description of the status message, e.g: *image/repository not found*   |

Request Header

```bash
Authorization: Bearer eyJ0eXAiOiJQiL...CJhbGciOMeXzQfME
Content-Type: application/json
```

Response Body

```bash
HTTP/1.1 202 Accepted
```

### Register Container Status <a href="#alm-agent-register-container-status" id="alm-agent-register-container-status"></a>

This endpoint listens to the notifications sent by Mobingi alm-agent with the status updates during a container's lifecycle. Possible status examples: *starting*, *updating*, *restarting*, *running*, *terminated*, etc.

POST `/v3/alm/agent/container_status`

| **Parameters** | **Type** | **Required** | **Detail**                                                                          |
| -------------- | -------- | ------------ | ----------------------------------------------------------------------------------- |
| stack\_id      | string   | Yes          | The stack id which this server instance is belonged to                              |
| agent\_id      | string   | Yes          | The agent's unique identifier                                                       |
| container\_id  | string   | Yes          | The container unique id. \_Sometimes, this value could be an instance's id.         |
| status         | string   | Yes          | sample values: *starting*, *updating*, *restarting*, *running*, *terminated*, etc.. |
| instance\_id   | string   | No           | The server instance id where Mobingi alm-agent is installed on                      |

Request Header

```bash
Authorization: Bearer eyJ0eXAiOiJQiL...CJhbGciOMeXzQfME
Content-Type: application/json
```

Response Body

```bash
HTTP/1.1 202 Accepted
```

### Describe Container Configuration <a href="#alm-agent-container-config" id="alm-agent-container-config"></a>

This endpoint is used by Mobingi alm-agent to describing `container` section of the layer configuration from Mobingi Alm Template, identified by `flag` name.

GET `/v3/alm/agent/config`

| **Parameters** | **Type** | **Required** | **Detail**                                       |
| -------------- | -------- | ------------ | ------------------------------------------------ |
| stack\_id      | string   | Yes          | the stack id where the instance is associated to |
| flag           | string   | Yes          | The flag identifier of the configuration layer   |

Request Header

```bash
Authorization: Bearer eyJ0eXAiOiJQiL...CJhbGciOMeXzQfME
Content-Type: application/json
```

Response Body

```bash
HTTP/1.1 200 OK

{
  "image": "registry.mobingi.com/mobingi/ubuntu-apache2-php5",
  "environment_variables": {
    "Stage": "_development",
    "DB_USERNAME": "root",
    "DB_PSSSWORD": "7zk3FBP37",
    "my_secret": "D3nz!lwA_h1ngt0n"
  },
  "gitReference": "master",
  "gitPrivateKey": "-----BEGIN PRIVATE ...\n-----END PRIVATE KEY-----\n",
  "gitRepo": "https://github.com/mobingilabs/default-site-php.git",
  "updated": 1492161755
}
```

**Note:** *If the response has an empty body, it could mean that wrong* `flag` *name was provided, or it doesn't have any container config defined.*


# Overview

{% hint style="warning" %}
**This product is already deprecated.**
{% endhint %}

Ocean is Mobingi's product for end-to-end application lifecycle management, including infrastructure provisioning, application deployment, and monitoring in a multi-cloud environment.

You can do deployments in Ocean using Ocean templates. One template is equivalent to one deployment. You can define applications and stacks in a template. Applications are container-based. Stacks are the infrastructure definitions where you can deploy your applications. Ocean uses [Kubernetes](https://kubernetes.io/) as its default infrastructure for application deployment.

Ocean deploys your infrastructure and your applications to your cloud account, whether it's AWS, Azure, Alibaba Cloud or GCP. You need to register your cloud credentials to Ocean before you start deploying templates.

## Vendor codes

| Provider                  | Vendor code |
| ------------------------- | ----------- |
| Alibaba Cloud             | `alicloud`  |
| Amazon Web Services (AWS) | `aws`       |
| Microsoft Azure           | `azure`     |
| Google Cloud Platform     | `gcp`       |

These codes are used in [Ocean templates](https://docs.mobingi.com/v/ocean-en/reference-2018-07-02), as well as in API requests and responses, if any.


# Template (v20180702)

{% hint style="warning" %}
This page is still a work in progress.
{% endhint %}

The following is the proposed version of Ocean Template. By default, all keys are optional unless stated otherwise.

```yaml
---
version: 20180702 # required

# Required. Name should be unique across your account. Should be alphanumeric.
name: string

description: string

---
credentials:
# Required. The name of the credential to use. This credential should already
# be registered to your Mobingi account. Name is unique at account level.
- name: string

  # See vendor codes for valid values.
  provider: string

---
# The list of applications to be deployed.
applications:
# Required. The name of the application to deploy. Should be unique at
# deployment level.
- name: string

  # This should correspond to the credential used in creating the stack
  # this application will be installed to. 
  credential: string

  # Number of initial container instances to run.
  replicas: number

  # Application autoscaling minimum and maximum.
  min: number
  max: number

  # Containers to run in this application.
  containers:
  - name: string
    image: string
    args:
    - string
    envVars:
    - key: string
      value: string
    # If ports is empty, default value is a random valid port from 49152 to 65535.
    ports:
    - number

  service:
    # Valid values: LoadBalancer
    # If not provided, defaults to NodePort type.
    type: string

    # If not provided, defaults to port 80.
    port: number

    # If not provided, defaults to the first port number provided in the
    # first container.
    targetPort: number

  # So far, all key-values above are Mobingi-defined defaults for an application.
  # Set this to true if you want to skip deploying the application above.
  skip: bool

  # Use this key if you want to deploy raw Kubernetes apps to
  # your stack. All k8s resources are supported here.
  k8sExtra: |
    {Insert Kubernetes application deployments here}

  # The list of stacks where you want to deploy this application.
  # The following names should correspond to a cluster under the
  # `stacks` key.
  stacks:
  - string

---
# The list of stacks where you want to deploy your applications.
stacks:
#  Required. Stack name should be unique per account per provider.
- name: string

  # Valid values (for now:
  #   k8s
  type: string

  # This should correspond to a credential name you provided
  # somewhere in this template.
  credential: string

  # Region values depends on what cloud this stack belongs.
  region: string

  # Whether or not keypair is created for nodes.
  keyPair: bool

  master:
    # Optional. When you need zones in master, you can use this key.
    zones:
    - string

    # Optional: if setting the number of nodes for master is required,
    # use this key.
    nodeCount: number

  # Definitions of worker node groups for this cluster.
  workerGroups:
  # Cloud provider specific instance type, i.e. t2.medium
  - type: string

    # Optional. When you need zones in your worker nodes, you can use this key.
    zones:
    - string

    # Node autoscaling minimum and maximum values.
    min: number
    max: number

    # If true, this node group will use the cloud provider's low-cost
    # instances, i.e. Spot (AWS), Preemptive (GCP), Low priority (Azure), etc.
    lowCost: bool

  # So far, all key-values above are Mobingi-defined defaults for a k8s cluster.
  # Set this to true if you want to skip provisioning the cluster defined above.
  skip: bool

  # This key is provided if you want to provision any AWS resources using
  # CloudFormation.
  cfnExtra: |
    {Insert CloudFormation template here}

  # This key is provided if you want to provision any GCP resources using
  # Deployment Manager.
  dmExtra:
  - {filename}: |
      {Insert GCP Deployment Manager template here}

  # This key is provided if you want to provision any Azure resources using
  # Azure Resource Manager.
  armExtra: |
    {Insert Azure Resource Manager template here}

  # This key is provided if you want to provision any Alibaba resources using
  # Resource Orchestration Service.
  aliExtra: |
    {Insert Alibaba ROS template here}
```


# Ripple ヘルプセンター

Ripple をご利用のお客様向けに、Rippleを利用する上で必要な情報や便利な使い方をご紹介します。

本ヘルプガイドを読んでも分からないことがあれば、<ripple_cs@alphaus.cloud> までお気軽にお問い合わせください。


# Ripple とは？

## 概要

AWSリセラー、MSPのためのAWS請求書の自動計算と請求書発行ツールです。\
従来のExcelを利用したマニュアル計算を自動化し、そこにかかる人件費を削減します。詳しくは[こちら](https://mobingi.com/jp/product/ripple/)をご覧ください。

## Ripple で出来ること

* 顧客とAWSアカウントの関係を管理
* RIのブレンドレートを解除し、RIの適用実態に合致する明細を出力
  * 請求業務の効率化
  * リセラー収益の向上

### 1. 請求業務の効率化

従来の手作業による業務を自動化することにより、作業時間の短縮、計算方法の標準化や人的作業によるミスをなくします。

![](/files/-LEhLXCxs6_m2pgmnnMT)

### 2. リセラーの収益向上

最適な量のRIを適切なタイミングで購入し、運用しましょう。

## Ripple と Wave

リセラーがRippleに登録した内容を元に、適正な利用料金を計算し、エンドユーザーは Wave 上から請求内容を確認できます。

![](/files/-LEhM0t7zAbTuUYgV9pH)

![](/files/-LEhM5ZK2J6_SYrk4-Ep)


# Ripple のセットアップ

Ripple の利用を開始する前に必ず設定します：

{% content-ref url="/pages/-LM-zsyMLrybK\_4a6J1t" %}
[Hourlyレポート解析の有効化](/ripple/guide/set-up/prepare)
{% endcontent-ref %}

Ripple の利用を開始した直後、請求書を作成する前に設定します：

{% content-ref url="/pages/-LgjrtuhbR1GfH\_Sli0N" %}
[顧客登録](/ripple/guide/set-up/register-customer)
{% endcontent-ref %}

{% content-ref url="/pages/-LaY0SKE8L0FvRsnWGKX" %}
[請求書設定](/ripple/guide/set-up/invoice-setting)
{% endcontent-ref %}


# Hourlyレポート解析の有効化

Ripple の利用を開始するにあたり、事前に必要な設定をご説明します。

Alphaus のHourlyレポート解析を有効にするために、お客様のAWSアカウントで実施する必要がある作業と、Alphaus に提出する情報について記述します。

作業後、Alphaus に提出する情報については以下の通りです。 各段階の作業で控えていただくようお願いいたします。(作業後でも確認可能です。)

```
- AWSアカウントのID (数字12桁)

- 作成したレポートの情報

    - レポート名

    - S3バケット

    - レポートパスのプレフィックス、またはレポートのパス

- 特定バケット許可用の IAMロールのARN (例: arn:aws:iam::xxxxxxxxxxxx:role/crossacounnt-access-for-mobingi)
```

## 手順 1 : S3バケットおよびHourlyレポートの作成(任意) <a href="#step1" id="step1"></a>

* 請求情報を共有するAWSのアカウントで、Hourlyレポートを作成します。
* 以下の条件に当てはまるレポート定義がすでにある場合、この作業をスキップしてすることが可能です。

  `時間単位: 時間別`

  `レポートに含める項目で リソースID が有効`

  `バケット内にモビンギが 閲覧してはいけないオブジェクト を含まない(バケット全体に読み取りアクセスを付与するため)`

### 手順1-1: **S3バケットの作成**

* S3コンソールから任意の名称でバケットを作成します。オプションはデフォルトで構いません。

  レポートの出力先として利用するため、バケット名を控えておいてください。

### 手順1-2: **Hourlyレポートの作成**

* AWSのマネジメントコンソールから、『請求』を開き『Cost & Usage Reports 』メニューへ移動します。

レポートの作成へ進みます。

![](/files/-LhJPu3CgqHFXDE769Vy)

* 『ステップ 1: レポートの明細項目』を以下の要領で記入して次に進めます。
  * レポート名：任意
  * **リソースIDのインクルード**：チェック
  * データの更新設定：チェック推奨

![](/files/-LhJQhmbZH2yJmIu4Hlx)

* 『ステップ 2: 配信オプション』では、S3バケットの操作を含めるため、以下手順で進めます。
  * S3バケット名の設定ボタンをクリック
  * 『ステップ 1/2: S3 バケットの設定』で既存のバケットを選択
  * 『ステップ 2/2: ポリシーの確認』のポリシーの確認にチェックを入れ保存

![](/files/-LhJSiS1WRrB6gV5XzOz)

![](/files/-LhJTjF-VOUJmiB6TH-F)

![](/files/-LhJTmsULoVDzlQKezIr)

* 検証で「有効なバケット」と出ていることを確認し、下記の設定を行います。
  * レポートパスのプレフィックス: 任意 (※なしでも構いません)
  * 使用料の時間詳細度：**時間別**
  * レポートのバージョニング：新しいメールバージョンの作成
  * **レポートデータ統合の有効化: チェックしない**
  * 圧縮タイプ: GZIP もしくは ZIP を選択

{% hint style="danger" %}
レポートデータ統合を有効化すると正常に動かない場合があります。
{% endhint %}

* 『ステップ 3: 確認』表示されている内容に間違いがない確認し、完了します。

![](/files/-LhJWnfHjOd3UDojKDxU)

## 手順 2 :読み取り権限を委譲するIAMロールの作成 <a href="#step2" id="step2"></a>

AWSのマネジメントコンソールから、IAMサービスを開き、『ロール』>> 『ロールの作成』メニューへ移動します。

![](/files/-LhJc_CwBfUJH5Z-19yU)

『信頼されたエンティティの種類を選択』で、「別のAWSアカウントを」選択し、以下のAlphaus のアカウントIDを入力します。

* **AlphausアカウントID: 131920598436**

![](/files/-LhJcsbdvgiss9xcbLI0)

「Attach アクセス権限ポリシー」メニューで、『ポリシーの作成』を選択します。

![](/files/-LhJdQX245tORLh-YIv1)

別のタブ(ウィンドウ)で「ポリシーの作成」メニューが開くので、入力形式にJSONを選択し、以下の内容でポリシーを入力します。 Resourceの`{replace_to_report_bucket}`部分を **レポートに使用するバケット名** に置き換えてください。

```bash
{
    "Version": "2012-10-17",
   "Statement": [
         {
               "Effect": "Allow",
               "Action": [
                     "s3:Get*",
                     "s3:List*"
               ],
               "Resource": [
                     "arn:aws:s3:::{replace_to_report_bucket}",
                     "arn:aws:s3:::{replace_to_report_bucket}/*"
               ]
         }
   ]
}
```

![](/files/-LhJdyEgWugMArWw_KQO)

![](/files/-LhJeJ46E8C0UD92BqjA)

「ポリシーの確認」へ進み、以下の項目を入力してポリシーを作成します。

* 名前: 任意(※必須)
* 説明: 任意

![](/files/-LhJefIJnj_Ja-YZvuao)

『ロールの作成』メニューに戻り、リストを更新し、先ほど作成したポリシーを表示します。 チェックを有効にして、確認へ進みます。

![](/files/-LhJahKLmdiYsyxT1Mq_)

『次のステップ: タグ』をクリック。

* タグは任意で設定してください。

「確認」メニューで、以下の項目を入力します。

* ロール名: 任意(※必須)
* ロールの説明: 任意

「信頼されたエンティティ」、「ポリシー」が適用されていることを確認し、ロールを作成します。

![](/files/-LhJfeoy_MSusdbev7yk)

作成したロールのARNを控えます。

![](/files/-LhJfUkP2xmP6wmBujAx)


# 顧客登録

## 1-1. 請求グループの作成

{% hint style="info" %}
請求グループとは請求書を発行する単位のRipple上での名称です。
{% endhint %}

請求書を発行したい単位ごとに請求グループを作成する作業を行います。

(Rippleは請求書を発行したい単位が１請求グループになります)

* 顧客別
* 部署別
* 案件別　　等

左メニュー `アカウントとグループ` >`請求グループ`から、画面右上の`請求グループの追加`をクリックし、Rippleの画面に従って以下の項目をご入力ください。

| 名称       | 入力 | 変更     | 説明                                                                                    |
| -------- | -- | ------ | ------------------------------------------------------------------------------------- |
| 請求グループID | 必須 | \*変更不可 | 請求グループを管理するための固有のID                                                                   |
| 請求グループ名  | 必須 | 変更可    | <p>請求グループを管理するための名称</p><p>顧客には見えないため、</p><p>管理しやすい名称をご登録ください。</p><p>(例：顧客名、案件名など)</p> |
| 企業名      | 必須 | 変更可    | 請求書発行先の企業名                                                                            |

以下は任意項目です。

* 電話番号
* 郵便番号
* 住所
* 宛名
* 請求書タイトル
* プロジェクトコード
* 備考欄

　　　　　　　　　　　　　                      \*請求グループIDのみ、登録後の変更ができません。

## 1-2. 請求関連の諸条件を設定

請求書の値引きや手数料に関する計算を請求書単位で設定することが可能です。

1-1.で作成した請求グループの `•••` > `請求書設定の変更` をクリックし、請求関連の諸条件を設定します。

## 2. 請求グループにAWSアカウントを連結する

1-1.で作成した請求グループにAWSのアカウントを紐づける作業を行います。

左メニュー`アカウントとグループ`>`アカウント`から、画面右上`アカウントの追加`をクリックし、フィールドに必要項目を記入し追加します。

Payerアカウントの利用料も請求書に含めたい場合はこのページで再度ご登録ください。

{% hint style="danger" %}
**既に登録済みのアカウントIDを重複登録することはできません。**
{% endhint %}


# 請求書設定

{% hint style="info" %}
標準仕様でご提供する設定項目となります。
{% endhint %}

左メニューから`環境設定` > `請求書設定`  より、下記の設定ができます。

* 端数丸め処理：切り捨て、切り上げ、四捨五入\
  日本円に変換するタイミングでの小数点以下の扱いを設定できます。


# 毎月の請求書発行の手順

お客様が月初に、毎月行う必要のある作業を順にご紹介します。

{% content-ref url="/pages/-LaOzCeLI3GjrT6rZPvJ" %}
[1. 請求データ確定の連絡](/ripple/guide/routine/click-button)
{% endcontent-ref %}

{% content-ref url="/pages/-LaOzGCmvYGoGe2lTW\_H" %}
[2. 為替レートの登録](/ripple/guide/routine/set-conversion-rate)
{% endcontent-ref %}

{% content-ref url="/pages/-LaOzIHcJzxImkS2u3HU" %}
[3. ショットの費用を請求に含める](/ripple/guide/routine/add-fee)
{% endcontent-ref %}

{% content-ref url="/pages/-LaOzNMouaRca1badK8H" %}
[4. 請求書の作成](/ripple/guide/routine/issue-invoice)
{% endcontent-ref %}

{% content-ref url="/pages/-LaOzU-7KH2rFBbp5a3k" %}
[5. 発行した請求明細の確認とダウンロード](/ripple/guide/routine/download-csv)
{% endcontent-ref %}

{% content-ref url="/pages/-LaOzXzTmKs5SBt70wAD" %}
[6. エンドユーザーに請求明細を提示](/ripple/guide/routine/show-billing-statement)
{% endcontent-ref %}


# 1. 請求データ確定の連絡

毎月月初3\~7日頃に、AWSから請求書が届きます。

請求書が届きましたら、 Ripple ダッシュボードにございます`請求データ確定の連絡`ボタンをクリックします。

のち、2営業日以内に弊社サポート（<ripple_cs@alphaus.cloud>）より、  `【Ripple】XX月請求データ計算完了のご連絡` というタイトルでメールを送付します。届きましたら次のステップに進んでください。

{% hint style="info" %}
AWSのサポート料金、AWSから付与されたクレジット、返金、その他通常の請求書に載らない一時金を請求に含める場合、毎月7日以降に確定ボタンをクリックしてください。
{% endhint %}


# 2. 為替レートの登録

発行したい請求月の為替レートを設定しましょう。

1. 左メニューの`請求書` > `換算レート設定`から、右上の `為替レートの登録` をクリックし、換算レートを入力します。

レートを再設定すると当月分のレートが上書きされます。過去のデータを変更することはできません。




---

[Next Page](/llms-full.txt/1)

