[JAWS-UG CLI] IAM #46 IAMポリシーの作成 (CodePileline)

AWS CLIを利用して、CodePipeline用のIAMポリシを作成してみます。


前提条件
========


IAMへの権限
-----------

- IAMに対してフル権限があること。


AWS CLIのバージョン
-------------------

以下のバージョンで動作確認済

- AWS CLI 1.11.2

```bash:コマンド:
aws --version
```

```text:結果(例):
      aws-cli/1.11.2 Python/2.7.11 Darwin/15.6.0 botocore/1.4.60
```

バージョンが古い場合は最新版に更新しましょう。

```bash:コマンド:
sudo -H pip install -U awscli
```


0. 準備
=======


0.1. 変数の確認
---------------

プロファイルが想定のものになっていることを確認します。

```bash:コマンド:
aws configure list
```

```text:結果(例)
            Name                    Value             Type    Location
            ----                    -----             ----    --------
         profile         iamFull-prjZ-mbp13        env    AWS_DEFAULT_PROFILE
      access_key     ****************XXXX shared-credentials-file
      secret_key     ****************XXXX shared-credentials-file
          region                         ap-northeast-1  env    AWS_DEFAULT_REGION
```

AssumeRoleを利用している場合はprofileが '<not set>'と表示されます。 それ以外のときにprofileが '<not set>' と表示される場合は、以下を実行してください。

```bash:変数の設定:
export AWS_DEFAULT_PROFILE=<IAMユーザ名>
```


0.2. AWSアカウントIDの取得
--------------------------

```bash:コマンド:
AWS_ID=$( \
        aws iam get-user \
          --query 'User.Arn' \
          --output text |\
        sed 's/^.*:://' |\
        sed 's/:.*$//' \
) \
        && echo ${AWS_ID}
```

```text:結果(例):
      XXXXXXXXXXXX
```


1. 事前作業
===========


1.1. IAMポリシー名の決定
------------------------

ポリシー名を決めます。

```bash:変数の設定
IAM_POLICY_NAME='CodePipelineAccess'
```

同じ名前のポリシーが無いことを確認します。

```bash:コマンド:
aws iam get-policy \
        --policy-arn arn:aws:iam::${AWS_ID}:policy/${IAM_POLICY_NAME}
```

```text:結果(例)
      A client error (NoSuchEntity) occurred when calling the GetPolicy operation: Policy arn:aws:iam::XXXXXXXXXXXX:policy/CodePipelineAccessdoes not exist.
```


1.2. IAMポリシードキュメントの作成
----------------------------------

ポリシードキュメントのファイル名を決めます。

```bash:変数の設定
FILE_INPUT="${IAM_POLICY_NAME}.json" \
          && echo ${FILE_INPUT}
```

```bash:コマンド:
cat << EOF > ${FILE_INPUT}
{
          "Version": "2012-10-17",
          "Statement": [
              {
                  "Action": [
                      "s3:GetObject",
                      "s3:GetObjectVersion",
                      "s3:GetBucketVersioning"
                  ],
                  "Resource": "*",
                  "Effect": "Allow"
              },
              {
                  "Action": [
                      "s3:PutObject"
                  ],
                  "Resource": [
                      "arn:aws:s3:::codepipeline*",
                      "arn:aws:s3:::elasticbeanstalk*"
                  ],
                  "Effect": "Allow"
              },
              {
                  "Action": [
                      "codecommit:CancelUploadArchive",
                      "codecommit:GetBranch",
                      "codecommit:GetCommit",
                      "codecommit:GetUploadArchiveStatus",
                      "codecommit:UploadArchive"
                  ],
                  "Resource": "*",
                  "Effect": "Allow"
              },
              {
                  "Action": [
                      "codedeploy:CreateDeployment",
                      "codedeploy:GetApplicationRevision",
                      "codedeploy:GetDeployment",
                      "codedeploy:GetDeploymentConfig",
                      "codedeploy:RegisterApplicationRevision"
                  ],
                  "Resource": "*",
                  "Effect": "Allow"
              },
              {
                  "Action": [
                      "elasticbeanstalk:*",
                      "ec2:*",
                      "elasticloadbalancing:*",
                      "autoscaling:*",
                      "cloudwatch:*",
                      "s3:*",
                      "sns:*",
                      "cloudformation:*",
                      "rds:*",
                      "sqs:*",
                      "ecs:*",
                      "iam:PassRole"
                  ],
                  "Resource": "*",
                  "Effect": "Allow"
              },
              {
                  "Action": [
                      "lambda:InvokeFunction",
                      "lambda:ListFunctions"
                  ],
                  "Resource": "*",
                  "Effect": "Allow"
              },
              {
                  "Action": [
                      "opsworks:CreateDeployment",
                      "opsworks:DescribeApps",
                      "opsworks:DescribeCommands",
                      "opsworks:DescribeDeployments",
                      "opsworks:DescribeInstances",
                      "opsworks:DescribeStacks",
                      "opsworks:UpdateApp",
                      "opsworks:UpdateStack"
                  ],
                  "Resource": "*",
                  "Effect": "Allow"
              }
          ]
}
EOF

cat ${FILE_INPUT}
```

JSONファイルを作成したら、フォーマットが壊れてないか必ず確認します。

```bash:コマンド:
jsonlint -q ${FILE_INPUT}
```

エラーが出力されなければOKです。


2. 本作業
=========


IAMポリシーの作成
-----------------

```bash:変数の確認
cat << ETX

        IAM_POLICY_NAME: ${IAM_POLICY_NAME}
        FILE_INPUT:      ${FILE_INPUT}

ETX
```

```bash:コマンド:
aws iam create-policy \
        --policy-name ${IAM_POLICY_NAME} \
        --policy-document file://${FILE_INPUT}
```

```json:結果(例):
      {
        "Policy": {
          "PolicyName": "CodePipelineAccess",
          "CreateDate": "10月 09, 2016T01:23:45.678Z",
          "AttachmentCount": 0,
          "IsAttachable": true,
          "PolicyId": "ANPAXXXXXXXXXXXXXXXXX",
          "DefaultVersionId": "v1",
          "Path": "/",
          "Arn": "arn:aws:iam:::XXXXXXXXXXXXpolicy/CodePipelineAccess",
          "UpdateDate": "10月 09, 2016T01:23:45.678Z"
        }
      }
```


3. 事後作業
===========


IAMポリシーの確認
-----------------

ARNを取得します。

```bash:変数の設定
IAM_POLICY_ARN=$( \
        aws iam list-policies \
          --max-items 1000 \
          --query "Policies[?PolicyName==\`${IAM_POLICY_NAME}\`].Arn" \
          --output text \
) \
        && echo "${IAM_POLICY_ARN}"
```

```json:結果(例):
      arn:aws:iam::XXXXXXXXXXXX:policy/CodePipelineAccess
```

ポリシのバージョンを取得します。

```bash:コマンド:
IAM_POLICY_VERSION=$( \
        aws iam list-policies \
          --max-items 1000 \
          --query "Policies[?PolicyName==\`${IAM_POLICY_NAME}\`].DefaultVersionId" \
          --output text \
) \
        && echo ${IAM_POLICY_VERSION}
```

```text:結果(例)
      v1
```

ポリシの内容を見てみましょう。

```bash:コマンド:
aws iam get-policy-version \
        --policy-arn ${IAM_POLICY_ARN} \
        --version-id ${IAM_POLICY_VERSION}
```

```json:結果(例):
      {
        "PolicyVersion": {
          "CreateDate": "\ |today|\ T01:23:45Z",
          "VersionId": "v1",
          "Document": {
              "Version": "2012-10-17",
              "Statement": [
                  {
                      "Action": [
                          "s3:GetObject",
                          "s3:GetObjectVersion",
                          "s3:GetBucketVersioning"
                      ],
                      "Resource": "*",
                      "Effect": "Allow"
                  },
                  {
                      "Action": [
                          "s3:PutObject"
                      ],
                      "Resource": [
                          "arn:aws:s3:::codepipeline*",
                          "arn:aws:s3:::elasticbeanstalk*"
                      ],
                      "Effect": "Allow"
                  },
                  {
                      "Action": [
                          "codecommit:CancelUploadArchive",
                          "codecommit:GetBranch",
                          "codecommit:GetCommit",
                          "codecommit:GetUploadArchiveStatus",
                          "codecommit:UploadArchive"
                      ],
                      "Resource": "*",
                      "Effect": "Allow"
                  },
                  {
                      "Action": [
                          "codedeploy:CreateDeployment",
                          "codedeploy:GetApplicationRevision",
                          "codedeploy:GetDeployment",
                          "codedeploy:GetDeploymentConfig",
                          "codedeploy:RegisterApplicationRevision"
                      ],
                      "Resource": "*",
                      "Effect": "Allow"
                  },
                  {
                      "Action": [
                          "elasticbeanstalk:*",
                          "ec2:*",
                          "elasticloadbalancing:*",
                          "autoscaling:*",
                          "cloudwatch:*",
                          "s3:*",
                          "sns:*",
                          "cloudformation:*",
                          "rds:*",
                          "sqs:*",
                          "ecs:*",
                          "iam:PassRole"
                      ],
                      "Resource": "*",
                      "Effect": "Allow"
                  },
                  {
                      "Action": [
                          "lambda:InvokeFunction",
                          "lambda:ListFunctions"
                      ],
                      "Resource": "*",
                      "Effect": "Allow"
                  },
                  {
                      "Action": [
                          "opsworks:CreateDeployment",
                          "opsworks:DescribeApps",
                          "opsworks:DescribeCommands",
                          "opsworks:DescribeDeployments",
                          "opsworks:DescribeInstances",
                          "opsworks:DescribeStacks",
                          "opsworks:UpdateApp",
                          "opsworks:UpdateStack"
                      ],
                      "Resource": "*",
                      "Effect": "Allow"
                  }
              ]
          },
          "IsDefaultVersion": true
        }
      }
```


完了
====