LoginSignup
30
26

More than 5 years have passed since last update.

Ansibleでタスク実行中に「y/n」などの回答を求められた際に自動返答する方法

Last updated at Posted at 2016-07-06

概要

ansibleから自動返答するためにはpexpectモジュールが必要。

pexpectはexpect - Executes a command and responds to promptsを見ると「pexpect >= 3.3」なのでpipからインストールする必要がある。

yum info pexpectでインストール出来るpexpectを調べたがバージョン2.3だったため、pipで導入した。

キモとなるのは下記の部分でPlease enter ~の問いかけに対して自動で"{{ input_file_path }}""test"を自動返答している。「y」や「n」を求められる場合はこの返答部分を"y"などにすれば良い。

      expect:
        command: /bin/bash -lc "ansible-playbook -i hosts playbook2.yml"
        responses:
          'Please enter input_file_path': "{{ playbook_dir }}"
          'Please enter input_file_body': "test"

pipからpexpectモジュールを導入する

  • sudo yum install -y python-pip
  • sudo pip install pexpect

実際に「playbook.yml」から「playbook2.yml」を起動し、自動返答を試してみる

  • 下記の内容の「hosts」ファイルを作成
    ※IPは適宜変更ください
[targets]
192.168.33.11
  • 下記の内容の「playbook.yml」ファイルを作成
- hosts: targets
  user: vagrant

  tasks:
    - name: "playbook2.ymlを実行"
      expect:
        command: /bin/bash -lc "ansible-playbook -i hosts playbook2.yml"
        responses:
          'Please enter input_file_path': "{{ playbook_dir }}"
          'Please enter input_file_body': "test"
      args:
        # {{ playbook_dir }}でこのplaybookが走っているカレントディレクトリを参照(ex./home/vagrant/nas_vagrant/ansible/expect_test)
        chdir: "{{ playbook_dir }}"
  • 下記の内容の「playbook2.yml」ファイルを作成
- hosts: targets
  user: vagrant
  vars_prompt:
    - name: "input_file_path"
      prompt: "Please enter input_file_path"
      private: no

    - name: "input_file_body"
      prompt: "Please enter input_file_body"
      private: no

  tasks:
    - name: "空のinput_fileファイル作成"
      file:
        path: "{{ input_file_path }}/test_file"
        state: touch

    - name: "input_fileファイルに追記"
      lineinfile:
        dest: "{{ input_file_path }}/test_file"
        state: present
        insertafter: EOF
        line: "{{  input_file_body  }}"
  • ansible-playbook -i hosts playbook.ymlで実行すると「playbook.yml」と同じフォルダ内に「test_file」というファイルが生成される

変更履歴

  • 2016/07/07:サンプルスクリプトを分かりやすく修正した

参考

30
26
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
30
26