Warning対応

[DEPRECATION WARNING]: Invoking "dnf" only once while using a loop via squash_actions is deprecated. Instead of using a loop to supply multiple items and specifying `name: "{{ item }}"`, please use `name: ['bind', 'bind-utils']` and remove the loop. This feature will be removed in version 2.11. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.

ループ除去

- name: install bind
  dnf:
    name={{ item }} state=latest
  with_items:
    - bind
    - bind-utils
- name: install bind
  dnf:
    name:
      - bind
      - bind-utils
    state:
      latest

改善

  1. yum から dkfへ
  2. S3から使ってないarchive除去
  3. mavenが手動ダウンロード前提なのでなんとかする
  4. geo_ipもなんとかしたい

自作Ansible対応状況

aws graviton2

通信量計測 202005

setup400M
apps180Mjdkがでかい
myapps java500他が無視できるほどjava関連の容量と時間食う。350M+chrome/nodeで170M

CentOS8

KagoyaPostgresでエラー
Conoha
自宅vmwareminimalだとpythonすらないのでsecureで

VPS

Sakura VPS 2G
KAGOYA VPS KVMPyYAMLがバージョン競合(インストールするほうが新しい)。あったらパスするロジック
お名前.com VPS 2G
awshostcentos7限定のところを見直し(python-selinux),dnfがない

自宅

Ansible完全読本

最新版はつかわないこと

2.0への移行

2.0が2016/01にリリースされたが随所で変更が必要。

Block

複数の処理をまとめることができる。さらにrescue,alwaysを組み合わせるときり戻しに近いことができる。

インベントリなどのsudo

ansible_sudoansible_become

playbookのsudo

sudobecome
sudo_userbecome_user

playbookの変数

[DEPRECATION WARNING]: Using bare variables is deprecated. Update your playbooks so that the environment value uses the full variable syntax ('{{yum_basic_items}}').This feature will be removed in a future release. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
with_items:
  yum_epel_items → '{{ yum_epel_items }}'に変更

定義済み変数の確認

ansible -m setup localhost
ansible -m setup -i hoset HOSTNAME

インストール前に

コントロールされる側に以下のパッケージが必要。

python-simplejson

Install

sudo apt update
sudo apt install software-properties-common
sudo apt-add-repository --yes --update ppa:ansible/ansible
sudo apt install ansible
yum install python27-devel
pip-2.7 install ansible
yum install ansible --enablerepo=epel

CentOS 6.x

yum install python-pip.noarch
yum install python-devel.x86_64
pip install PyCrypto==2.3
pip install ansible

yumかaptかの判定

when: ansible_pkg_mgr == 'apt' or 'yum'

Windows/CygwinでAnsible

  1. gcc-core
  2. openssh
  3. python
  4. python-setuptools
easy_install-2.7 pip
pip2.7 install ansible

 http://server-setting.info/blog/sshpass-cygwin-autologin.html#sshpass_1

設定ファイル

ansible.cfgファイルの探す順番は以下の通り。

  1. カレントディレクトリ
  2. 環境変数の ANSIBLE_CONFIG or ~/ansible.cfg
  3. /etc/ansible/ansible.cfg

カレントにおいておけばそこが一番に読み込まれる。以下のように記載しておけば-iでインベントリを指定しなくてよい。

[defaults]
hostfile       = hosts

インベントリ(操作対象ホスト)

# local
localhost ansible_connection=local
# SSHポート 10022でユーザーはremote_user
remote.example.com  ansible_ssh_port=10022  ansible_ssh_user=remote_user ansible_ssh_private_key_file=~/.ssh/KEY_FILE  ansible_ssh_host=192.168.1.50

クラウド向けにはDynamic Inventoryという概念がある。詳細は公式HPで収集せよ。

パラメータ

ansible_ssh_hostホスト名に対しての実IP
ansible_ssh_portSSHポート
ansible_ssh_userSSHユーザ
ansible_ssh_passSSHパスワード。べた書きは非推奨なので--ask-passオプションを付けて実施するか公開鍵認証推奨
ansible_sudosudoを使うかどうか。デフォルトはfalse
ansible_sudo_passsudo のパスワード。危険なので--ask-sudo-passオプションを推奨)
ansible_sudo_exe (new in version 1.8)sudo コマンドへのパス
ansible_connectionlocal, ssh or paramiko.
ansible_ssh_private_key_file秘密鍵ファイルの場所
ansible_shell_typeシェル
ansible_python_interpreterログイン側のpython
ansible\_\*\_interpreteransibleのインタープリタの場所

変数定義

hoge: value
hogearray:
  - one
  - two
  - three

ワンラインで簡易実行

ansible web03 -a "ls" -i hostsls
ansible web03 -a "ls" -i hosts --ask-passls
ansible web03 -m copy -a "src=/etc/hosts dest=/tmp/hosts" -i host操作元ホストからリモートホストへファイルコピー

文法チェックと空実行(dry run)

ansible-playbook -i hosts simple-playbook.yml --syntax-check
ansible-playbook -i hosts simple-playbook.yml --list-tasks
ansible-playbook -i hosts simple-playbook.yml -C

推奨ディレクトリ構成

TOP
  -vars
  -roles
  hosts

Role

Playbook

- hosts: all
  user: hoge
  tasks:
    - script: /home/hoge/test.sh

インクルード(条件分岐あり)

---
- include: setup-web.yml
  when: type == "WEB"
- include: setup-db.yml
  when: type== "DB"

yum まとめてインスコ

- name: yum install
  yum:
    name={{ item }}
  with_items:
   - httpd
   - php

httpd,openjdkインストール(分割推奨)

- hosts: web03
  user: ec2-user
  tasks:
    - name: Install httpd
      yum: name=httpd state=latest
      sudo: yes
    - name: apacheが起動していることを確認
      action: service name=httpd state=started
      sudo: yes
    - name: "設定の修正(1)"
      lineinfile: >-
        dest='/etc/httpd/conf/httpd.conf'
        state=present
        backrefs=yes
        regexp='^#?\s*ServerTokens'
        line='ServerTokens Prod'
      sudo: yes
      notify: apache restart
    - name: Install openJDK
      yum: name=java-1.8.0-openjdk-devel state=latest
      sudo: yes
  handlers:
    - name: apache restart
      service:
        name=httpd
        state=restarted
      sudo: yes
ansible-playbook -i hosts tcp_wrapper.yml --tags "security"
- hosts: web03
  user: ec2-user
  tasks:
    - name: deny all service
      lineinfile: >-
        dest='/etc/hosts.deny'
        state=present
        line='ALL: ALL'
      sudo: yes
      tags:
        - security
    - name: enable ssh for limited ip
      lineinfile: >-
        dest='/etc/hosts.allow'
        state=present
        line='sshd: 172.20.128.'
      tags:
        - security
        - othertag
      sudo: yes
- hosts: web03
  user: ec2-user
  vars:
    user_name: normaluser
    user_pass: '$6$P0ky3YE5$JNFD0EuY52rXeVtNVypSMkB3chjHWu9z3o.8KMANeblkEe8p7ZOD0HSuPGT0pbzgHW2kP.xo4zE17tM6wy.1Y1'
  tasks:
    - name: Add a new user
      user: name={{user_name}} password={{user_pass}} groups=wheel state=present
      sudo: yes
- hosts: web03
  user: ec2-user
  tasks:
    - name: touch
      shell: touch /var/tmp/{{ item.path }}
      with_items:
        - { path: 'hoge' }
        - { path: 'fuga' }
    - name: result test
      shell: echo "hoge"
      register: result
      failed_when: result.rc not in [0, 1]
    - name: catしたものをcontents変数に入れる
      shell: cat /etc/passwd
      register: contents
    - name: contents変数の標準出力にrootが含まれるときは実施
      shell: ls
      when: contents.stdout.find('root') != -1
    - name: 日付変数を作成してそのファイルを作る
      shell: date +'%Y%M%d%I%M%S'
      register: datestring
    - name: 日付のフォルダ作成
      shell: touch /var/tmp/{{ datestring.stdout }}
    - name: symlink作成
      file: src=/var/tmp/{{ datestring.stdout }} dest=/var/tmp/latest state=link
- name: setup authorized_key
  authorized_key: user=user1 key="{{ item }}"
  with_file:
    - id_rsa.pub
   - name: 古いディレクトリを特定する。
     shell: ls -t1 | tail -n +5
     args:
       chdir: /var/tmp
     register: old_dirs
   - name: 古いディレクトリ削除
     file: path={{ item }}
     with_items: old_dirs.stdout_lines
- name: jenkins exists check
  stat: path=/var/cache/ansible/jenkins.war
  register: jenkins
- name: Jenkinsをダウンロードする
  get_url:
    url: http://mirrors.jenkins-ci.org/war/latest/jenkins.war
    dest: /var/cache/ansible/
  when: jenkins.stat.exists == False

Taskモジュール

一覧

ec2Amazon ec2boto required for this moduleとでたら、pip install boto
s3Amazon s3
shellシェルを実行だが、コマンドも実行できる

変数の出力

-name: debug
 debug: var=p

MySQL操作

リモート側にMySQL-pythonモジュールが必要。場合によってはyumではなくpipで入れないと認識しないので注意。

- name: MySQL DB 設定
  mysql_db: name=DB_NAME state=present
- name: MySQL user hoge 追加(ローカル限定のユーザ)
  mysql_user: name=hoge password=hoge priv=DB_NAME.*:ALL state=present
- name: MySQL user hoge 追加(どこからでもOKユーザー)
  mysql_user: name=hoge host=% password=hoge priv=DB_NAME.*:ALL state=present

EC2作成

- name: ec2インスタンスを作成する
  ec2:
    aws_access_key: アクセスキー
    aws_secret_key: シークレットキー
    region: ap-northeast-1
    instance_type: t2.micro
    keypair: キーペア名称
    group: セキュリティグループ(複数ある場合はカンマ区切り)
    image: AMIイメージID
    vpc_subnet_id: サブネットID
    assign_public_ip: yes
    wait: yes
    instance_tags:
     Name: 名前
    volumes:
      - device_name: /dev/xvda
        snapshot: snap-07b5593c→AMIが利用しているsnapshot IP
        volume_size: 100
  register: ec2_status
  tags: create

EC2作成後.ssh/configにIP記載

- name: .ssh/configに追記
  shell: >-
    echo Host awshost >> ~/.ssh/config;
    echo User ec2-user >> ~/.ssh/config;
    echo HostName {{ ec2_status.instances[0].public_ip }} >> ~/.ssh/config;
    echo IdentityFile ~/.ssh/YOUR_KEY.pem >> ~/.ssh/config;
  tags: ssh_config
インスタンスIDec2_status.instances[0].ID
private_ipec2_status.instances[0].private_ip
public_ipec2_status.instances[0].public_ip

s3アップロード/ダウンロード

- name: S3からMasterのIPをダウンロードする
  s3:
    aws_access_key: 
    aws_secret_key: 
    region: ap-northeast-1
    bucket: バケット名
    dest: /var/tmp/任意のパス
    object: /バケット名以下のパス/ファイル名
    mode: get

lineinfile

置換に便利なモジュール

- name: tomcat memory setting
  lineinfile:
    dest: /etc/tomcat8/tomcat8.conf
    line: JAVA_OPTS="-server"

Command Module

リモートでOSコマンドを実施する。

# Example from Ansible Playbooks.
- command: /sbin/shutdown -t now

# createsに指定されたファイルがない場合はcommandの処理を実行
- command: /usr/bin/make_database.sh arg1 arg2 creates=/path/to/database
# somedir以下に移動し、かつ
# createsに指定されたファイルがない場合はcommandの処理を実行
- command: /usr/bin/make_database.sh arg1 arg2
  args:
    chdir: somedir/
    creates: /path/to/database
#繰り返し処理のサンプル。変数定義済みであればwith_items:{{users}}でもOK
- name: add several users
  user: name={{ item }} state=present groups=wheel
  with_items:
     - testuser1
     - testuser2
#コンパイルのタスクだが、実際にはシェルが実行できるのでなんでもOK
- name: Apacheコンパイル
  shell:
    make
      chdir=/usr/local/src/httpd-2.4.12
      creates=/usr/local/apache/2.4.12/bin/httpd

Script Module

操作先にShellを送り込んで実行。操作先にpythonが必要ないのもメリット

Shell Module

Ansibleの実行サーバー先にあるshファイルをリモートに送り込んで実行できる。

Tips

Dry-run

チェックモードと実行ログにチェックモードであることを表示する。

--check
ansible.cfgに以下の記述を追加
[defaults]
check_mode_markers = yes

実行後の差分を表示するdiffオプション。checkと併用可能

--diff

途中から実施

一ステップずつ確認

外部変数(extra_vars)

http://d.hatena.ne.jp/akishin999/20130818/1376824640

ansible-playbook -i hosts setup.yml --extra-vars "admintool_seup=true" --tags=admintool

SSH接続時のキーチェック無効化

実行時の環境変数で設定export ANSIBLE_HOST_KEY_CHECKING=False

Playbookがまったく実行されない

- name: OK
-name: NG

謎のエラー

ローカルのパーミッションがNGだと内部モジュールでエラーがでてわかりづらい。コピー元はtemplateディレクトリに入れておくべき!

roleの条件の変数を勝手に書き換えたらroleの残りがスキップされた

考えてみりゃそりゃーそうだ。というわけで条件に使っている変数はグローバルなので変に共有しないこと!

条件

変数は{{}}で囲まないので注意

- user: root
  hosts: all
  tasks:
    - name: install mlocate
      yum: name=mlocate state=installed
      when: install == "y"

初接続時の注意

公開鍵が保持されていないとエラー。以下の記事を参考に自動化できぬものか!

http://qiita.com/kawaz/items/20983ec286088a1ae5c7

SSHパスワード接続時の注意

--ask-passオプションをつけるとSSHパスワード接続で実行できるが、sshpass.x86_64をyumインストールしておく必要がある。パスワードだとキーチェックが入るので一回接続しておくか、下記で無効にしておく。
export ANSIBLE_HOST_KEY_CHECKING=False

Selinux有効だとエラー

target uses selinux but python bindings (libselinux-python) aren't installed!

無効にしてしまう!

MysqlDB作成できない

the python mysqldb module is required

マルチバイトのファイル名をunarchiveするとエラー。

マルチバイトがあるのが残念なので、以下のコマンドで見つけて治す。

find . | grep \[^\ a-zA-Z0-9_:/@,%\\=\;\'\&\\\[\\+\\\(\\\)\\!\\.\\\-\]

proxy利用

接続先がproxy必須の場合、Linuxの設定としてproxyをセットするのがよいかも!

ansible完全読本メモ


トップ   編集 凍結 差分 履歴 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2022-10-20 (木) 08:17:28