LoginSignup
0
0

Ansibleを使ってサーバを操作する。

Posted at

はじめに

Ansibleとは構成管理ツールです。
簡単に言うと手順書を書いておけば自動でサーバにsshで接続して色々構築してくれるツールです。
一度に複数サーバに対して同時に命令を実行させることもできるそうです。
今回は、PC(mac)からサーバ(cent os)にshellを実行させるまでをゴールにしようと思います。

準備するもの

ひとまず、必要なファイルだけ用意しておきましょう。

hosts
xx.xxx.xxx.xxx

hostsファイルにはipアドレスを記載してください。
sshで上記のアドレスに接続します。

packages.yml
- hosts: xx.xxx.xxx.xxx
  connection: ssh

  tasks:
   - name: test
     shell: cd /var/hoge && mkdir test

shellに実行したいコマンドを記載します。
こちらのymlファイルに色々と命令を書くことができるらしいです。
hostsとpackages.ymlは適当なディレクトリに格納しておいてください。

構築手順

  • Homebrewをインストールする 
     ※既にインストール済みであればスキップしてください。
  • brew install ansibleでansibleをインストールする
    以下のようなエラーが出る場合
Error: Your Command Line Tools are too outdated.
Update them from Software Update in System Preferences.

If that doesn't show you any updates, run:
  sudo rm -rf /Library/Developer/CommandLineTools
  sudo xcode-select --install

Alternatively, manually download them from:
  https://developer.apple.com/download/all/.
You should download the Command Line Tools for Xcode 14.2.

以下のコマンドを順に実行してください。
sudo rm -rf /Library/Developer/CommandLineTools
sudo xcode-select --install

  • 以下のコマンドでansibleからサーバに接続できるかテストする。
    ansible-console --inventory xx.xxx.xxx.xxx, --user xxxxx
    lsコマンドを実行する。
xx.xxx.xxx.xxx | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: xxx@xx.xxx.xxx.xxx: Permission denied (publickey,password).",
    "unreachable": true
}

⇨上記のようなエラーが発生した場合は、以下のコマンドを試す。
ansible-console --inventory xx.xxx.xxx.xxx, --user xxx --ask-pass
そしてサーバのパスワードを入力し、lsコマンドを実行する。
※userはサーバのuseridのことです。

xx.xxx.xxx.xxx | FAILED | rc=-1 >>
to use the 'ssh' connection type with passwords or pkcs11_provider, you must install the sshpass program

それでも上記のようなエラーが発生したら、、
brew install hudochenkov/sshpass/sshpassを実行してください。
インストールが完了したら、もう一度以下のコマンドを実行します。
ansible-console --inventory xx.xxx.xxx.xxx, --user xxx --ask-pass
そしてサーバのパスワードを入力し、lsコマンドを実行する。

xx.xxx.xxx.xxx | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

上記のように「SUCCESS」となっていればOKです。

  • hosts、packages.ymlがあるディレクトリに移動して、以下のコマンドを実行します。
    ansible-playbook -i hosts packages.yml --user xxx --ask-pass
    パスワードを聞かれると思うので、サーバのパスワードを入力します。
    あとは、実際にサーバに接続してみて「test」というフォルダが作成されていることを確認してください。
    作成されていれば正常にpackages.yml(playbook)が正常に実行されています。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0