はじめに
Ansible でターゲットのシステムに対して Python コマンドでスクリプトを実行する時、複数のバージョンの Python がインストールされていて、意図した通りに処理が実行されない場合があります。今回は Ansible が参照する Python とその Python でスクリプトを実行する方法を紹介します。
Ansible が利用する Python のパスを取得する
Ansible が取得する Python のパスを 取得します。
リモートホストに対して実行する場合
- name: Gather facts from remote host
ansible.builtin.setup:
register: results
- name: Execute selenium on remote host
ansible.builtin.command:
cmd: "{{ results.ansible_facts.ansible_python.executable }} script.py"
ローカルに対して実行する場合
- name: Gather facts
ansible.builtin.setup:
register: results
delegate_to: localhost
- name: Execute selenium
ansible.builtin.command:
cmd: "{{ results.ansible_facts.ansible_python.executable }} script.py"
delegate_to: localhost
この方法で利用する Python を限定することができます。
実践例 Ansible から Selenium を実行する
Ansible から Selenium を実行するサンプルです。動作確認は Ubuntu 22.04 lts で行っています。事前に Ubuntu に Docker をインストールし pip で ansible ・docker・selenium をインストールしておきます。
selenium.yml
---
- name: Create
hosts: localhost
connection: local
tasks:
- name: Setup Selenium container
community.docker.docker_container:
name: selenium
image: selenium/standalone-firefox:latest
ports:
- '4444:4444'
state: started
- name: Gather facts
ansible.builtin.setup:
register: results
- name: Execute selenium
ansible.builtin.command:
cmd: "{{ results.ansible_facts.ansible_python.executable }} selenium.py"
args:
chdir: files
changed_when: false
selenium.py
import os
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
# Setting up headless Firefox options
options = Options()
driver = webdriver.Remote(
command_executor='http://localhost:4444/wd/hub',
options=options
)
driver.get(target_url)
w = driver.execute_script("return document.body.scrollWidth;")
h = driver.execute_script("return document.body.scrollHeight;")
driver.set_window_rect(width=w, height=h)
filename = os.path.join(os.path.dirname(os.path.abspath(__file__)), "./screenshot.png")
driver.save_screenshot(filename)
driver.quit()
Selenium は Remote Container から実行されます。対象のサーバーの定期的なスクリーンショットが必要な場面、Ansible playbook 実行時の UIテストが必要な場面などで役に立つでしょう。
参考サイト
- ansible-playbooks-mamono210/wordpress_install | GitHub これらの処理を実際に導入しているAnsible playbook のコードサンプル