<style>
/* basic design */
.reveal h1, .reveal h2, .reveal h3, .reveal h4, .reveal h5, .reveal h6,
.reveal section, .reveal table, .reveal li, .reveal blockquote, .reveal th, .reveal td, .reveal p {
font-family: 'Meiryo UI', 'Source Sans Pro', Helvetica, sans-serif, 'Helvetica Neue', 'Helvetica', 'Arial', 'Hiragino Sans', 'ヒラギノ角ゴシック', YuGothic, 'Yu Gothic';
text-align: left;
line-height: 1.8;
letter-spacing: normal;
text-shadow: none;
word-wrap: break-word;
color: #444;
}
.reveal h1, .reveal h2, .reveal h3, .reveal h4, .reveal h5, .reveal h6 {font-weight: bold;}
.reveal h1, .reveal h2, .reveal h3 {color: #2980b9;}
.reveal th {background: #DDD;}
.reveal section img {background:none; border:none; box-shadow:none; max-width: 95%; max-height: 95%;}
.reveal blockquote {width: 90%; padding: 0.5vw 3.0vw;}
.reveal table {margin: 1.0vw auto;}
.reveal code {line-height: 1.2;}
.reveal p, .reveal li {padding: 0vw; margin: 0vw;}
.reveal .box {margin: -0.5vw 1.5vw 2.0vw -1.5vw; padding: 0.5vw 1.5vw 0.5vw 1.5vw; background: #EEE; border-radius: 1.5vw;}
/* table design */
.reveal table {background: #f5f5f5;}
.reveal th {background: #444; color: #fff;}
.reveal td {position: relative; transition: all 300ms;}
.reveal tbody:hover td { color: transparent; text-shadow: 0 0 3px #aaa;}
.reveal tbody:hover tr:hover td {color: #444; text-shadow: 0 1px 0 #fff;}
/* blockquote design */
.reveal blockquote {
width: 90%;
padding: 0.5vw 0 0.5vw 6.0vw;
font-style: italic;
background: #f5f5f5;
}
.reveal blockquote:before{
position: absolute;
top: 0.1vw;
left: 1vw;
content: "\f10d";
font-family: FontAwesome;
color: #2980b9;
font-size: 3.0vw;
}
/* font size */
.reveal h1 {font-size: 5.0vw;}
.reveal h2 {font-size: 4.0vw;}
.reveal h3 {font-size: 2.8vw;}
.reveal h4 {font-size: 2.6vw;}
.reveal h5 {font-size: 2.4vw;}
.reveal h6 {font-size: 2.2vw;}
.reveal section, .reveal table, .reveal li, .reveal blockquote, .reveal th, .reveal td, .reveal p {font-size: 2.2vw;}
.reveal code {font-size: 1.6vw;}
/* new color */
.red {color: #EE6557;}
.blue {color: #16A6B6;}
/* split slide */
#right {left: -18.33%; text-align: left; float: left; width: 50%; z-index: -10;}
#left {left: 31.25%; text-align: left; float: left; width: 50%; z-index: -10;}
</style>
<style>
/* specific design */
.reveal h1 {
margin: 0% -100%;
padding: 2% 100% 4% 100%;
color: #fff;
background: #c2e59c; /* fallback for old browsers */
background: linear-gradient(-45deg, #EE7752, #E73C7E, #23A6D5, #23D5AB);
background-size: 200% 200%;
animation: Gradient 60s ease infinite;
}
@keyframes Gradient {
0% {background-position: 0% 50%}
50% {background-position: 100% 50%}
100% {background-position: 0% 50%}
}
.reveal h2 {
text-align: center;
margin: -5% -50% 2% -50%;
padding: 4% 10% 1% 10%;
color: #fff;
background: #c2e59c; /* fallback for old browsers */
background: -webkit-linear-gradient(to right, #64b3f4, #c2e59c); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to right, #64b3f4, #c2e59c); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}
</style>
<!-- --------------------------------------------------------------------------------------- -->
# AWS CLIをSSMからPlaybookで実行してみた
#### 2020.04.27
#### wakasa
<!-- Put the link to this slide here so people can follow -->
slide: https://hackmd.io/@gIlxDULmQfWyjBDSnDJQAg/r1-B_GhOU
[TOC]
---
## 自己紹介
- 某SIer
- 品質とか効率向上とか考えることが多いです
- AWS-CLI歴:2年弱(業務では少なめ。もっぱらJAWS-CLI)
- 楽するために頑張りたい派
---
## 本日の動機
- AWS CLIの豊富なナレッジを公開して頂いてる
- 「なるべくそのまま」自動化や手順書へ乗せてみたい
- 「やってみたらできるんじゃない?」なことを試して見ました
<br>
:heavy_check_mark: AWS-CLI以外は深掘りしない範疇で
---
## きっかけ
**「S3 or Github上のzip またはディレクトリ構造のPlaybookを実行できる」**
<br>
AnsibleのBest Practices構成のまま使えそう - これはすごい
<br>
<br>
<br>
<div class="box">
「Ansible使いの人はちょっと見逃せない。AWS Systems Managerで複雑な構成のAnsible-Playbookの実行が可能になりました」(2019.09.30)
https://dev.classmethod.jp/articles/systems-manager-to-execute-complex-ansible-playbooks/
</div>
---
## (ちょっと補足)Ansible / Playboookとは?
- オープンソースの構成管理ツールの製品名
- RedHatさんが開発・有償版を販売
- Playbook と呼ばれる可読性の高い設定ファイル(YAML形式)から
- モジュール と呼ばれる機能群を実行する(Pythonベース)
テスト用のplaybook集
https://github.com/ansible/test-playbooks
---
## Best Practicesなディレクトリ構成とは?
このようにzip化すると、そのまま読み込んでくれます
```directory
[フォルダ名]
|
site.yml # 各roleを呼び出す目次
+-roles
+-001_role # ロール名:章,段落,機能毎に合わせて分割
| +tasks # おまじない:Ansibleがこのディレクトリ内を自動的に探索
| +main.yml # 実際のコマンドを記載
+-002_role
+tasks
+main.yml # 実際のコマンドを記載
```
- site.ymlに書いたrole順に呼び出して実行されます
- 階層構造なので、処理を小分けに作成・修正しやすいです
- role名は任意。連番でなくとも良いです
https://docs.ansible.com/ansible/latest/user_guide/playbooks_best_practices.html
---
## 使うもの
- Cloud9:ここではAWS-CLIが有効なEC2として
- SSM(Systems Manager):
- Run Command から
- AWS-ApplyAnsiblePlaybooks を実行する(shellの集合体)
- S3,GitHub:設定ファイル置き場
---
## 概要図
```graphviz
digraph {
compound=true
rankdir=LR
graph [ fontname="Source Sans Pro", fontsize=20 ];
node [ fontname="Source Sans Pro", fontsize=14];
edge [ fontname="Source Sans Pro", fontsize=10 ];
subgraph Cloud9 {
c9c [label="Cloud9\nConsole"] [shape=box]
}
subgraph Contents {
concentrate=true
zip [label="[3]S3,GitHub\n(zipfile)"] [shape=box]
log [label="S3\n(log)"] [shape=box]
}
subgraph cluster_EC2 {
concentrate=true
ansbl [label="[2]Ansible/Playbook\n(shellモジュール他)"]
cli [label="[4]AWS-CLI\nsh,bash"]
label="EC2"
}
subgraph cluster_AWS {
concentrate=true
ssm [label="[1]SSM"] [shape=box]
api [label="[5]AWS_API"]
label="AWS"
}
aaa [label="AWS-ApplyAnsiblePlaybooks" shape=plaintext]
zip -> ansbl
c9c -> cli
ssm -> aaa -> ansbl
ansbl -> cli
log -> ansbl [dir="back"]
cli -> api [dir="both"]
}
}
```
[1]SSMから``AWS-ApplyAnsiblePlaybooks``を介して実行
[2][3]対象のEC2上でAnsibleが起動(最初時にinstallされます)
[4]あえてAWS-CLIを実行(できる限り活用したい)
[5]AWS_APIを操作
---
## 主に使う(使いたい)機能
**shellモジュール**
**Ansibleの``shell``モジュール の引数とする形で、AWS-CLIを実行させる**
- shell: aws ...
- 利点: 環境変数を利用できる...ということを期待
```
その他のシェルを実行するコマンド
- command : Execute commands on targets (環境変数を利用できない)
- raw : Executes a low-down and dirty command (あまり推奨されない)
- script : Runs a local script on a remote node after transferring it
- win_shell : Execute shell commands on target hosts
```
https://docs.ansible.com/ansible/latest/modules/shell_module.html
https://github.com/ansible/test-playbooks/blob/master/run_shell.yml
---
## 実際のPlaybook設定例
```yaml:
site.yml
---
- hosts: all
gather_facts: false
become: yes
become_user: ec2-user
vars:
ansible_python_interpreter: "/usr/bin/python"
ORG_NAME: "ssm-playbook"
ID_NAME: "●"
DATE_NAME: "20200427"
S3_BUCKET_NAME: "{{ ORG_NAME }}-{{ ID_NAME }}-{{ DATE_NAME }}"
roles:
- 000_whoami
- 001_ping
- 002_sts_get
- 100_echo_vars
```
[github](https://github.com/wakasak/20200427_jaws-cli_LT-2_sample_playboook/blob/master/20200427_jaws-cli_LT-2_sample_playboook.zip?raw=true)
---
## 実際のPlaybook設定例
```yaml
002_sts_get
---
- shell: aws sts get-caller-identity
- raw: aws sts get-caller-identity --query "Account" --output text
register: MyAccount
- shell: aws sts get-caller-identity --query "Account" --output text
register: MyAccount2
ignore_errors: True
```
ということで、
---
## やってみました
<br>
<br>
<br>
<br>
<br>
<br>
<br>
結構大変です
---
## Playbookの実行自体は簡単
すごく良くできてます
一度やってみます
```
AWS Systems Manager > Run Command > コマンドの実行
> AWS-ApplyAnsiblePlaybooks (一番上に表示されてます)
> Run command
> パラメータを記入して 実行
```
今回は履歴から実行します
---
## 必須な項目
- zip位置:
- Source Type: S3,GitHub
- Source Info: "path": "https://【バケット名】/【zip名】.zip
- Playbook File:
- 【解凍後】/site.yml
- ターゲット: EC2を指定
- タグ
- 手動(Inctance-ID)
- リソースグループ
- 出力オプション: バケット名(ログ保存先)
---
## 実行結果は画面とS3のログで確認できます
```
結果画面の インスタンス ID をクリック
- ステップ1 - 出力 : Ansible環境の確認
- ステップ2 - 出力 : zip/Playbook実行結果の確認
```
このとき、コマンド ID: xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx と同じ名前で、
指定したS3内にログが出力されてます
---
## 悩ましいこと
- ---queryしたフィルタ結果以外も変数に取り込まれてしまう
```yaml
},
"rc": 0,
"start": "2020-04-27 08:53:16.400689",
"stderr": "",
"stderr_lines": [],
"stdout": "098822336020",
"stdout_lines": [
"098822336020"
]
}
```
```yaml
echoしてみると...他の結果も入ってくる
"stdout_lines": [
"{rc: 0, stdout: 098822336020\\n, stdout_lines: [098822336020], stderr: , stderr_lines: [], changed: True, failed: False}"
]
}
-v オプションまで減らしても同様
無しを選択できるようにSSMブックを編集できればあるいは
```
- シェルの環境変数を利用しにくい
- shell上で設定した変数を ``$HOGEで`` 呼べない
- exportで固定してしまうのもなんか辛い
---
## 本日まとめ
- CLIの全部乗せという点で、変数の扱いは悩ましい
- shell仕様深掘り
- Ansible仕様で設定
- CLIでパラメータストア活用
- ファイル化
- いざとなればなんとかCLI対応もできそう
- Ansibleモジュールに未実装な機能へ対応する手段
- できるところから導入していけそう
- 階層化の利点として、Ansible仕様と混在可能
- CloudFormationの呼び出しなども?
---
## その他 ご参考
設定や参考情報など
---
### 実際の事前準備
1. EC2(Cloud9)をSSMの管理下に置く
cloud9 の EC2 roleに3種追加+見えなければ再起動(簡略手順)
- CloudWatchAgentServerPolicy
- AmazonSSMManagedInstanceCore
- AmazonSSMDirectoryServiceAccess
1. S3バケットを作成
- zip保管
- ログ結果
1. sudo visudo : /usr/local/bin追記
- 任意:sudo した時にpipのパスが変わる場合
1. SSMメニューの選択
- Run Command
- (ステートマネージャー)
4. まず動かして見る
- ansibleがインストールされます
---
### AWS-CLIからもSSM実行できます
```bash
aws ssm send-command --document-name "AWS-ApplyAnsiblePlaybooks" --document-version "1" --targets '[{"Key":"InstanceIds","Values":["i-0c836b8e69e611864"]}]' --parameters '{"SourceType":["S3"],"SourceInfo":["{\n \"path\": \"https://ssm-playbook-●-20200427.s3-ap-northeast-1.amazonaws.com/20200427_jaws-cli_LT-2_sample_playboook.zip\"\n}"],"InstallDependencies":["True"],"PlaybookFile":["20200427_jaws-cli_LT-2_sample_playboook/site.yml"],"ExtraVariables":["SSM=True"],"Check":["False"],"Verbose":["-vvvv"]}' --comment "-vvvv 20200427 ansible_python_interpreter: "usr/bin/python"" --timeout-seconds 300 --max-concurrency "50" --max-errors "0" --output-s3-bucket-name "ssm-playbook-●-20200427" --region ap-northeast-1
```
---
### GitHub に保管する時の設定
{
"owner":"user_name",
"repository":"name",
"path":"path_to_directory_or_playbook_to_download",
"getOptions":"branch:branch_name",
"tokenInfo":"{{(Optional)_token_information}}"
}
https://docs.aws.amazon.com/ja_jp/systems-manager/latest/userguide/systems-manager-state-manager-ansible.html
---
### AWS-ApplyAnsiblePlaybooks
このドキュメントを使用して、Systems Manager が管理するインスタンスで Ansible Playbooks を実行します。詳細については、以下をご覧ください。
<br>
Use this document to run Ansible Playbooks on Systems Manager managed instances. For more information, see
<br>
https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-state-manager-ansible.html.
---
### Tips
#### MacでDS_Storeファイルの削除
```shell
zip --delete ansible-ssm-test.zip "*__MACOSX*" "*.DS_Store"
```
---
#### sudo pip のパスへのパスを通す
``sudo pip install --upgrade pip``を実行すると、
``/usr/bin``から ``/usr/local/bin``へ変更されてしまいますが、sudo時にはパスが通っていません
いくつか方策はあるようですが、簡単に``sudo visudo``で追加してます
```bash
Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin
↓
Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin
```
---
#### pythonへのpath警告
Ansible設定とEC2で異なるために発生
(自動検索してくれるので実行は可能)
```bash
[WARNING]: Platform linux on host localhost is using the discovered Python
interpreter at /usr/bin/python, but future installation of another Python
interpreter could change this. See https://docs.ansible.com/ansible/2.9/referen
ce_appendices/interpreter_discovery.html for more information.
```
ansible_python_interpreter 不整合の警告は、最上位のsite.yml にvars指定で良い
```yaml
vars:
ansible_python_interpreter: "/usr/bin/python"
```
---
#### ansible shell でsudoを実行すると警告が発生する
```bash
[ec2-user@ip-10-0-0-78%]$ ansible all -i localhost, -m shell -a "sudo ls" -c local
[WARNING]: Consider using 'become', 'become_method', and 'become_user' rather than running sudo
[WARNING]: Platform linux on host localhost is using the discovered Python interpreter at /usr/bin/python, but future installation of another Python
interpreter could change this. See https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.
localhost | CHANGED | rc=0 >>
environment
node_modules
package-lock.json
```
---
#### 実行ユーザがrootになる
最上位のsite.yml で実行ユーザを指定すると全roleへ反映可能
(sudo実行を可能にすることとセット)
```yaml
become: yes
become_user: ec2-user
```
---
#### 本日ドキュメントはこちらのCSSをお借りしてます
sample2
https://qiita.com/suzuki_/items/08cbd75599bd78dcaca2
---
## ありがとうございました! :sheep:
---
{"metaMigratedAt":"2023-06-15T06:57:56.239Z","metaMigratedFrom":"YAML","title":"AWS CLIをSSMからPlaybookで実行してみた","breaks":"true","description":"View the slide with \"Slide Mode\".","lang":"ja-JP","dir":"ltr","slideOptions":"{\"theme\":\"white\",\"slideNumber\":\"c/t\",\"center\":false,\"trasition\":\"none\",\"keyboard\":true,\"width\":\"93%\",\"height\":\"100%\"}","contributors":"[{\"id\":\"8089710d-42e6-41f5-b28c-10d29c325002\",\"add\":25582,\"del\":12636}]"}