てくなべ (tekunabe)

ansible / network automation / 学習メモ

[Ansible] ansible-navigator 2.0.0 新機能ピックアップ Part 2: その他編

はじめに

先日、ansible-navigator 2.0.0 がリリースされました。

Release v2.0.0 · ansible/ansible-navigator · GitHub

前回の記事で、追加されたサブコマンドを取り上げました。

tekunabe.hatenablog.jp

今回はそれ以外の気になったものを取り上げます。

(詳細、一覧はリリースノートchangelogを参照してください)

アーティファクトファイル名に含む日時のタイムゾーンを指定可能に

ansible-navigator は Playbook を実行すると、アーティファクトというログをJSON形式で出力できます。

これまではアーティファクトのファイル名の規則として、Playbookのディレクトリ、Playbook名、UTCの時刻を利用できました。

ansible-navigator.yml では以下のように {キー名} で、指定できます。

# ansible-navigator 1.x での設定例
---
ansible-navigator:
  playbook-artifact:
    save-as: "{playbook_dir}/{playbook_name}-artifact-{ts_utc}.json"

時刻は UTC しか指定できませんでしが、ansible-navigator 2.0.0 ではタイムゾーンを指定できるようになりました。

指定できるタイムゾーンの形式は IANA time zone とのことです。この形式の詳細はお恥ずかしながらわかっていませんでしたが、身近なところでは JapanAsia/Tokyo が指定できました。デフォルトは UTC です。

コードを追っていくと、Python 3.9 以上では zoneinfo.ZoneInfo() の引数に渡っていました。

ほか、便利なのがlocal と指定すると、ansible-navigator 自体を実行しているOS側(コンテナの観点ではコンテナホスト)のタイムゾーンに合わせられます。実際はこの指定の仕方が一番多いのではないかと思います。

また、タイムゾーンの指定機能の導入にあわせて、時刻のキー名が ts_utc から time_stamp に変更されました。もし ts_utc のまま実行すると、書き換えるステップをはさみます(後述の設定ファイルの書式変更でも触れます)。

changelog より

タイムゾーン指定の件

Enabled the use of the time_zone settings entry for playbook artifact file name creation.

キー名変更の件

Renamed the ts_utc variable in the playbook artifact file name to time_stamp.

以下は、ansible-navigator.yml で、アーティファクトファイル名にタイムスタンプを含め、OS 側のタイムゾーンに合わせる設定例です。

---
ansible-navigator:
  playbook-artifact:
    enable: true    # デフォルト
    save-as: "{playbook_dir}/{playbook_name}-artifact-{time_stamp}.json"  # デフォルト
  time-zone: local  # OS設定に合わせる

OS側のタイムゾーンAsia/Tokyo の場合、playbook-artifact-2022-04-19T20:58:29.302037+09:00.json のようなアーティファクトが生成されます。+09:00 になります。

なお、この機能は私が issue を書いてご対応いただきました。 @cidrblock Thank you!



images サブコマンドが stdout モードでも利用可能に

images サブコマンドは、実行環境内の OS、Ansible バージョン、コレクション、Python パッケージのの情報を表示できる機能です。機能自体は以前からありましたが、 interactive モードのみのサポートでした。今回、stdout モードにも対応しました。

changelogから

Added basic support for mode stdout for the images subcommand.

その場でちょっと確認するだけでしたら interactive モードが便利かもしれません。

一方、出力結果をファイルに保存したり、抽出、加工する場合は stdout モードが適していそうです。

コマンドで stdout モードを指定する場合は、--mode stdout を指定します。詳細情報を特に指定しない場合は、実行環境の概要情報が表示されます。

ansible-navigator.yml がない状態で実行したら、以下の3つの環境が表示されました。

$ ansible-navigator images --mode stdout
---
- created: 2 days ago
  execution_environment: true
  full_name: quay.io/ansible/ansible-runner:latest
  image_id: 84f0acda4cea
  inspect:
# ...(略)...
- created: 4 months ago
  execution_environment: true
  full_name: quay.io/ansible/ansible-runner:stable-2.12-devel
  image_id: 8eb88c5bd9fb
  inspect:
# ...(略)...
- created: 2 weeks ago
  execution_environment: true
  full_name: quay.io/ansible/creator-ee:v0.4.2
  image_id: 12571ac947cf
  inspect:
# ...(略)...

詳細情報の表示

-d または --details をプションを指定すると、更に詳細情報を表示できます。詳細情報は以下の種類種類をさらに指定できます。デフォルトは everything です。

  • ansible_collections
  • ansible_version
  • everything
  • os_release
  • python_packages
  • python_version
  • redhat_release
  • system_packages

例えば、ansible_versionansible_collections に絞って表示したい場合は以下のように指定します。

$ ansible-navigator images -d ansible_version -d ansible_collections
---
ansible_collections:
  details:
    amazon.aws: 3.1.1
    ansible.posix: 1.3.0
    ansible.windows: 1.9.0
    awx.awx: 20.1.0
    azure.azcollection: 1.12.0
    community.docker: 2.3.0
    community.vmware: 2.2.0
    containers.podman: 1.9.3
    google.cloud: 1.0.2
    kubernetes.core: 2.3.0
    openstack.cloud: 1.7.2
    ovirt.ovirt: 1.6.6
    redhatinsights.insights: 1.0.7
    theforeman.foreman: 3.2.0
ansible_version:
  details: ansible [core 2.12.4.post0]
image_name: quay.io/ansible/creator-ee:v0.4.2

イメージを指定したい場合は、--eei オプションも指定します。

$ ansible-navigator images --eei イメージ名 -d ansible_version -d ansible_collections 

他、collections サブコマンドも、stdout モードでも利用可能になりました。

参考: images サブコマンドのヘルプ

ansible-navigator images -h の結果(クリックして開く)

$ ansible-navigator images -h
Usage: ansible-navigator images [options]

images: Explore execution environment images

Options (global):
 -h     --help                                   Show this help message and exit
 --version                                       Show the application version and
                                                 exit
 --rad  --ansible-runner-artifact-dir            The directory path to store
                                                 artifacts generated by ansible-
                                                 runner
 --rac  --ansible-runner-rotate-artifacts-count  Keep ansible-runner artifact
                                                 directories, for last n runs, if set
                                                 to 0 artifact directories won't be
                                                 deleted
 --rt   --ansible-runner-timeout                 The timeout value after which
                                                 ansible-runner will forcefully stop
                                                 the execution
 --cdcp --collection-doc-cache-path              The path to collection doc cache
                                                 (default:
                                                 /home/admin/.cache/ansible-
                                                 navigator/collection_doc_cache.db)
 --ce   --container-engine                       Specify the container engine
                                                 (auto=podman then docker)
                                                 (auto|podman|docker) (default: auto)
 --co   --container-options                      Extra parameters passed to the
                                                 container engine command
 --dc   --display-color                          Enable the use of color for mode
                                                 interactive and stdout (true|false)
                                                 (default: true)
 --ecmd --editor-command                         Specify the editor command (default:
                                                 vi +{line_number} {filename})
 --econ --editor-console                         Specify if the editor is console
                                                 based (true|false) (default: true)
 --ee   --execution-environment                  Enable or disable the use of an
                                                 execution environment (true|false)
                                                 (default: true)
 --eei  --execution-environment-image            Specify the name of the execution
                                                 environment image (default:
                                                 quay.io/ansible/creator-ee:v0.4.2)
 --eev  --execution-environment-volume-mounts    Specify volume to be bind mounted
                                                 within an execution environment
                                                 (--eev
                                                 /home/user/test:/home/user/test:Z)
 --la   --log-append                             Specify if log messages should be
                                                 appended to an existing log file,
                                                 otherwise a new log file will be
                                                 created per session (true|false)
                                                 (default: true)
 --lf   --log-file                               Specify the full path for the
                                                 ansible-navigator log file (default:
                                                 /home/admin/git/general/vagrant/nwla
                                                 b/ee/ansible-navigator.log)
 --ll   --log-level                              Specify the ansible-navigator log
                                                 level
                                                 (debug|info|warning|error|critical)
                                                 (default: warning)
 -m     --mode                                   Specify the user-interface mode
                                                 (stdout|interactive) (default:
                                                 interactive)
 --osc4 --osc4                                   Enable or disable terminal color
                                                 changing support with OSC 4
                                                 (true|false) (default: true)
 --penv --pass-environment-variable              Specify an existing environment
                                                 variable to be passed through to and
                                                 set within the execution environment
                                                 (--penv MY_VAR)
 --pa   --pull-arguments                         Specify any additional parameters
                                                 that should be added to the pull
                                                 command when pulling an execution
                                                 environment from a container
                                                 registry. e.g. --pa='--tls-
                                                 verify=false'
 --pp   --pull-policy                            Specify the image pull policy
                                                 always:Always pull the image,
                                                 missing:Pull if not locally
                                                 available, never:Never pull the
                                                 image, tag:if the image tag is
                                                 'latest', always pull the image,
                                                 otherwise pull if not locally
                                                 available (always|missing|never|tag)
                                                 (default: tag)
 --senv --set-environment-variable               Specify an environment variable and
                                                 a value to be set within the
                                                 execution environment (--senv
                                                 MY_VAR=42)
 --tz   --time-zone                              Specify the IANA time zone to use or
                                                 'local' to use the system time zone
                                                 (default: utc)

Options (images subcommand):
 -d     --details                                Provide detailed information about
                                                 the selected execution environment
                                                 image (ansible_collections|ansible_v
                                                 ersion|everything|os_release|python_
                                                 packages|python_version|redhat_relea
                                                 se|system_packages) (default:
                                                 ['everything'])



■ 設定ファイルの JSON Schema によるチェック

ansible-navigator run などの各処理の実行前に、ansible-navigator.yml などの設定ファイルJSON Schema によるチェックが行われるようになりました。

changelogから

Added settings file validation against the settings file JSON Schema during application initialization.

これまでは、設定ファイルにスペルミスなどの不備があった場合は、無視して処理が続行されていました。事前にチェックが入ることにより、意図しない挙動を未然に防げそうです。

例えば、以下の ansible-navigator.yml では environment のスペルを間違えています。

---
ansible-navigator:
  execution-enviroment:     # environment がスペルミス
    enabled: true
    image: localhost/my-ee:latest 

この状態で、書式チェックするために単に ansible-navigator とだけ実行すると、以下のようなエラーが表示されます。

$ ansible-navigator
Warning: Issues were found while applying the settings.
   Hint: Command provided: ''

  Error: The following errors were found in the settings file (/home/admin/git/general/vagrant/nwlab/ee/ansible-navigator.yml):
         In 'ansible-navigator': Additional properties are not allowed ('execution-enviroment' was unexpected).
   Hint: Check the settings file and compare it to the current version.
         The current version can be found here:
         (https://ansible-navigator.readthedocs.io/en/latest/settings/#ansible-navigator-settings)
         The schema used for validation can be seen with 'ansible-navigator settings --schema'
         A sample settings file can be created with 'ansible-navigator settings --sample'

   Note: Configuration failed, using default log file location. (/home/admin/git/general/vagrant/nwlab/ee/ansible-navigator.log) Log
         level set to debug
   Hint: Review the hints and log file to see what went wrong.

'execution-enviroment' was unexpected とあるので、すぐに気づけます。もし問題なければ、この場合は Welcome 画面が開きます。

一方、以前の バージョンの ansible-navigator では、書式エラーは無視され、デフォルトの設定で処理を続行しようとしてしまいます。

書式エラーで早い段階で止まってくれるのは安心です。

参考: VSCode による書式チェック

書式チェックの方法としては、VS CodeYAML という拡張を利用するというアプローチもあります。

そうすると、ansible-navigator.yml 以下のように、書式エラーが表示されます。

スペルミスを検出

また、この拡張によって各設定項目の入力候補も表示されるため、とても便利です。

便利な補完機能



■ 設定ファイルの書式変更

設定ファイル(ansible-navigator.yml)の一部の書式が変更されました。

旧書式を新書式の対応を示したサンプルは以下のとおりです。コメントアウトした旧書式Nと新書式Nが対応しています。

---
ansible-navigator:
  execution-environment:
    # 旧書式1
    # pull-policy: missing

    # 新書式1
    pull:
      policy: missing

  # 旧書式2
  # documentation:
  #   plugin:
  #     name: service
  #     type: module

  ansible:
    # 新書式2
    doc:
      plugin:
        name: service
        type: module

    # 旧書式3
    # playbook: hoge.yml
    # config: ansible.cfg
    # inventories: 
    #   - inventory.yml

    # 新書式3
    playbook:
      path: hoge.yml
    config:
      path: ansible.cfg
    inventory:
      entries:
        - inventory.yml

新書式のほうが、きれいに階層化された印象があります。

他にも、ヘルプ系の設定項目も書式変更があります。詳細は changelog を参照してください。

Moved the help entries into their respective ansible command parent keys in settings file.

新書式への移行機能

ansible-navigator 実行時に、以前のままの書式が検出された場合、新しい書式に移行(書き換え)するかどうか選択できます。

$ ansible-navigator 

The following version migrations are required:
  - Version 1 to Version 2 settings file format migration
Do you want to run them all? (Y/n): Y       # 書き換えする場合は Y

Version 1 to Version 2 settings file format migration:
Migration of 'config path'..................................Not needed
Migration of 'documentation'................................Updated     # 書き換わった
Migration of 'playbook path'................................Not needed
Migration of 'help builder'.................................Not needed
Migration of 'help config'..................................Not needed
Migration of 'help doc'.....................................Not needed
Migration of 'help inventory'...............................Not needed
Migration of 'help playbook'................................Not needed
Migration of 'inventory paths'..............................Not needed
Migration of 'playbook artifact timestamp'..................Not needed
Migration of 'pull-policy'..................................Not needed
Migration of 'volume mount labels'..........................Not needed
Backup: /home/admin/git/general/vagrant/nwlab/ee/ansible-navigator.v1
Updated: /home/admin/git/general/vagrant/nwlab/ee/ansible-navigator.yml

Migration complete

Press Enter to continue:    # 処理を続けるには Enter

書き換え前のファイルは ansible-navigator.v1 としてバックアップされますので、不要であれば削除します。



Python 3.8 以上が要件に

Python 3.6 と 3.7 がサポートから外され、Python 3.8 以上が要件になりました。

changelogから

Set the minimum supported python version for ansible-navigator to 3.8.

関連PR

github.com



■ 実行環境イメージpull時のオプションを指定可能に

ansible-navigator コマンドに、実行環境イメージpull時のオプションを指定できる --pa--pull-arguments オプションが利用できるようになりました。

たとえば、--pa='--tls-verify=false' と指定することで、podman pull 時に証明書検証を無効にする指定もできるようです。

  • ansible-navigator -h から抜粋
 --pa   --pull-arguments                         Specify any additional parameters that should be added
                                                 to the pull command when pulling an execution
                                                 environment from a container registry. e.g. --pa='--
                                                 tls-verify=false'


■ デフォルトの実行イメージが変更

pip でインストールした ansible-navigator 1.1.0 では quay.io/ansible/ansible-navigator-demo-ee:0.6.0 でしたが quay.io/ansible/creator-ee:v0.4 に変更されました。

changelog より

Upgraded default execution environment image to creator-ee:v0.4.0


おわりに

前回に続いて、ansible-navigator 2.0.0 の機能で気になったポイントを取り上げました。

いろいろと機能が追加されて、これかの発展も楽しみなツールです。

参考

リリースノート

github.com

changelog

ansible-navigator.readthedocs.io

[Ansible] ansible-navigator 2.0.0 機能ピックアップ Part 1: 追加サブコマンド編

はじめに

先日、ansible-navigator 2.0.0 がリリースされました。

github.com

ansible-navigator は、Playbook 実行や実行環境の管理などの機能を持つ TUI ツールです。

2.0.0 では、実行環境のビルドや ansible-lint を呼び出す機能などの追加や、設定ファイル(ansible-navigator.yml)の書式変更、Python 3.6 と 3.7 のサポート停止がされました。

この記事ですが、追加されたサブコマンド(機能)について取り上げます。

(詳細はリリースノートchangelogを参照してください)

※その他の機能追加や、変更点については後日別の記事にする予定です。 [2022/04/19 追記] その他編として投稿しました。

[Ansible] ansible-navigator 2.0.0 新機能ピックアップ Part 2: その他編 - てくなべ (tekunabe)

■ 1. settings サブコマンド追加 (設定内容の確認)

ansible-navigator は ansible-navigator サブコマンド という形で実行します。サブコマンドによって挙動が大きく変わります(サブコマンド一覧はこちら)。

ansible-navigator 2.0.0 ではいくつかのサブコマンドが追加されました。stettings もその一つです。

settings サブコマンドは ansible-navigator 自身の設定の状態確認できます。

changelog より

Added new subcommand :settings to output all current ansible-navigator settings to the menu or to standard output.

設定は ansible-navigator.yml環境変数などによって決まります。

  • ansible-navigator settings 実行結果

ansible-navigator settings コマンドの実行結果

設定の状態確認だけでなく、設定項目の番号は 数字1桁 または :数字1桁以上 エンター で指定すると、各設定のヘルプドキュメントも確認できます。

Container engine の詳細

設定項目はそれなりの数があるため、覚えるのも難しいです。そのため、公式ドキュメントのページを参照しますが、ansible-navigator setting からターミナル上で各設定項目の意味や指定できる値を選択できるのは便利だと思います。

なお、setting サブコマンドは、interactive (TUI)モードだけでなく stdout モードでの表示にも対応しています。コマンドの引数で指定する場合、-m stdout を追加で指定します。

$ ansible-navigator settings -m stdout
---
- choices: []
  cli_parameters:
    long: --ansible-runner-artifact-dir
    short: --rad
  current_settings_file: None
  current_value: Not set
  default: true
  default_value: Not set
  description: The directory path to store artifacts generated by ansible-runner
  env_var: ANSIBLE_NAVIGATOR_ANSIBLE_RUNNER_ARTIFACT_DIR
  name: Ansible runner artifact dir
  settings_file_sample:
    ansible-navigator:
      ansible-runner:
        artifact-dir: <------
  source: Not set
  subcommands:
# ...(略)...

参考: settings サブコマンドのヘルプ

ansible-navigator settings --help の結果(クリックして開く)

$ ansible-navigator settings --help
Usage: ansible-navigator settings [options]

settings: Review the current ansible-navigator settings

Options (global):
 -h     --help                                   Show this help message and exit
 --version                                       Show the application version and exit
 --rad  --ansible-runner-artifact-dir            The directory path to store artifacts generated by ansible-runner
 --rac  --ansible-runner-rotate-artifacts-count  Keep ansible-runner artifact directories, for last n runs, if set to 0 artifact directories won't be deleted
 --rt   --ansible-runner-timeout                 The timeout value after which ansible-runner will forcefully stop the execution
 --cdcp --collection-doc-cache-path              The path to collection doc cache (default: /home/admin/.cache/ansible-navigator/collection_doc_cache.db)
 --ce   --container-engine                       Specify the container engine (auto=podman then docker) (auto|podman|docker) (default: auto)
 --co   --container-options                      Extra parameters passed to the container engine command
 --dc   --display-color                          Enable the use of color for mode interactive and stdout (true|false) (default: true)
 --ecmd --editor-command                         Specify the editor command (default: vi +{line_number} {filename})
 --econ --editor-console                         Specify if the editor is console based (true|false) (default: true)
 --ee   --execution-environment                  Enable or disable the use of an execution environment (true|false) (default: true)
 --eei  --execution-environment-image            Specify the name of the execution environment image (default: quay.io/ansible/creator-ee:v0.4.2)
 --eev  --execution-environment-volume-mounts    Specify volume to be bind mounted within an execution environment (--eev /home/user/test:/home/user/test:Z)
 --la   --log-append                             Specify if log messages should be appended to an existing log file, otherwise a new log file will be created per
                                                 session (true|false) (default: true)
 --lf   --log-file                               Specify the full path for the ansible-navigator log file (default: /home/admin/git/general/ansible-
                                                 navigator.log)
 --ll   --log-level                              Specify the ansible-navigator log level (debug|info|warning|error|critical) (default: warning)
 -m     --mode                                   Specify the user-interface mode (stdout|interactive) (default: interactive)
 --osc4 --osc4                                   Enable or disable terminal color changing support with OSC 4 (true|false) (default: true)
 --penv --pass-environment-variable              Specify an existing environment variable to be passed through to and set within the execution environment
                                                 (--penv MY_VAR)
 --pa   --pull-arguments                         Specify any additional parameters that should be added to the pull command when pulling an execution environment
                                                 from a container registry. e.g. --pa='--tls-verify=false'
 --pp   --pull-policy                            Specify the image pull policy always:Always pull the image, missing:Pull if not locally available, never:Never
                                                 pull the image, tag:if the image tag is 'latest', always pull the image, otherwise pull if not locally available
                                                 (always|missing|never|tag) (default: tag)
 --senv --set-environment-variable               Specify an environment variable and a value to be set within the execution environment (--senv MY_VAR=42)
 --tz   --time-zone                              Specify the IANA time zone to use or 'local' to use the system time zone (default: utc)

Options (settings subcommand):
 --se   --effective                              Show the effective settings. Defaults, CLI parameters, environment variables, and the settings file will be
                                                 combined
 --gs   --sample                                 Generate a sample settings file
 --ss   --schema                                 Generate a schema for the settings file ('json'= draft-07 JSON Schema) (json) (default: json)
 --so   --sources                                Show the source of each current settings entry



■ 2. builder サブコマンド追加 (ansible-builder 呼び出し)

実行環境のイメージをビルドするツールとして ansible-builder があります。

ansible-navigator builder コマンド経由で、ansible-builder を呼べるようになりました。ansible-navigator をインストールすると、ansible-builder も一緒にインストールされます。

例えば、ansible-builder build に相当するコマンドは ansible-navigator builder build です。

対応の一覧は以下の通りです。

ansible-builder 直のコマンド ansible-navigator 経由のコマンド
ansible-builder create オプション ansible-navigator builder create オプション
ansible-builder build オプション ansible-navigator builder build オプション
ansible-builder introspect オプション ansible-navigator builder introspect オプション

createbuildintrospec の意味は ansible-navigator builder コマンド用のヘルプで確認できます。

$ ansible-navigator builder --help-builder
usage: ansible-builder [-h] [--version] {create,build,introspect} ...

Tooling to help build container images for running Ansible content. Get started by looking at the help text for one of the subcommands.

positional arguments:
  {create,build,introspect}
                        The command to invoke.
    create              Creates a build context, which can be used by podman to build an image.
    build               Builds a container image.
    introspect          Introspects collections in folder.

optional arguments:
  -h, --help            show this help message and exit
  --version             Print ansible-builder version and exit.

参考: builder サブコマンドのヘルプ

指定できるオプションは ansible-navigator builder --help を実行するといろいろ確認できます。

ansible-navigator builder --help の結果(クリックして開く)

$ ansible-navigator builder --help
Usage: ansible-navigator builder [options]

builder: Build execution environment (container image)

Options (global):
 -h     --help                                   Show this help message and exit
 --version                                       Show the application version and exit
 --rad  --ansible-runner-artifact-dir            The directory path to store artifacts generated by ansible-runner
 --rac  --ansible-runner-rotate-artifacts-count  Keep ansible-runner artifact directories, for last n runs, if set to 0 artifact directories won't be deleted
 --rt   --ansible-runner-timeout                 The timeout value after which ansible-runner will forcefully stop the execution
 --cdcp --collection-doc-cache-path              The path to collection doc cache (default: /home/admin/.cache/ansible-navigator/collection_doc_cache.db)
 --ce   --container-engine                       Specify the container engine (auto=podman then docker) (auto|podman|docker) (default: auto)
 --co   --container-options                      Extra parameters passed to the container engine command
 --dc   --display-color                          Enable the use of color for mode interactive and stdout (true|false) (default: true)
 --ecmd --editor-command                         Specify the editor command (default: vi +{line_number} {filename})
 --econ --editor-console                         Specify if the editor is console based (true|false) (default: true)
 --ee   --execution-environment                  Enable or disable the use of an execution environment (true|false) (default: true)
 --eei  --execution-environment-image            Specify the name of the execution environment image (default: quay.io/ansible/creator-ee:v0.4.2)
 --eev  --execution-environment-volume-mounts    Specify volume to be bind mounted within an execution environment (--eev /home/user/test:/home/user/test:Z)
 --la   --log-append                             Specify if log messages should be appended to an existing log file, otherwise a new log file will be created per
                                                 session (true|false) (default: true)
 --lf   --log-file                               Specify the full path for the ansible-navigator log file (default: /home/admin/git/general/ansible-
                                                 navigator.log)
 --ll   --log-level                              Specify the ansible-navigator log level (debug|info|warning|error|critical) (default: warning)
 -m     --mode                                   Specify the user-interface mode (stdout|interactive) (default: interactive)
 --osc4 --osc4                                   Enable or disable terminal color changing support with OSC 4 (true|false) (default: true)
 --penv --pass-environment-variable              Specify an existing environment variable to be passed through to and set within the execution environment
                                                 (--penv MY_VAR)
 --pa   --pull-arguments                         Specify any additional parameters that should be added to the pull command when pulling an execution environment
                                                 from a container registry. e.g. --pa='--tls-verify=false'
 --pp   --pull-policy                            Specify the image pull policy always:Always pull the image, missing:Pull if not locally available, never:Never
                                                 pull the image, tag:if the image tag is 'latest', always pull the image, otherwise pull if not locally available
                                                 (always|missing|never|tag) (default: tag)
 --senv --set-environment-variable               Specify an environment variable and a value to be set within the execution environment (--senv MY_VAR=42)
 --tz   --time-zone                              Specify the IANA time zone to use or 'local' to use the system time zone (default: utc)

Options (builder subcommand):
 --hb   --help-builder                           Help options for ansible-builder command in stdout mode (true|false)
 --bwd  --workdir                                Specify the path that contains ansible-builder manifest files (default: /home/admin/git/general)

Note: 'ansible-navigator builder' additionally supports the same parameters as the 'ansible-builder' command. For more information about these, try 'ansible-
navigator builder --help-builder --mode stdout'

最後の行に、

Note: 'ansible-navigator builder' additionally supports the same parameters as the 'ansible-builder' command.

とあるように、ansible-builder で指定できるオプションはそのまま ansible-navigator builder でも指定できるようです。ansible-builder のオプションの詳細は ansible-builder 側の公式ドキュメントを参照してください。



■ 3. exec サブコマンド追加(実行環境コンテナ内のコマンド実行)

ansible-navigator exec 実行したいコマンド で、実行環境コンテナ内に対してコマンドを実行できるようになりました。ちょっとした調べごとなどに便利かも知れません。

exec の後に指定するコマンドのデフォルトは /bin/bash です。単に ansible-navigator exec を実行すると、シェルに入れます。

$ ansible-navigator exec
bash-4.4# uname -a   # 適当に実行してみる
Linux 6a66a85e44f7 4.18.0-305.el8.x86_64 #1 SMP Thu Apr 29 08:54:30 EDT 2021 x86_64 x86_64 x86_64 GNU/Linux
bash-4.4# whoami  
root
bash-4.4# ansible --version
ansible [core 2.12.4.post0]
...()...

実行したいコマンドも合わせて指定すると、そのコマンドの実行結果だけが返ってきます。

$ ansible-navigator exec whoami
root

コマンド書式上、コマンドにスペースを含む場合はクォーテーションで囲う必要があります。

$ ansible-navigator exec "ansible --version | grep core"
ansible [core 2.12.4.post0

別途、-- で区切る方法もあります。

$ ansible-navigator exec -- ansible --version | grep core
ansible [core 2.12.4.post0]

ただのラッパーではない

exec サブコマンドは、ただの podman rundocker run のラッパーというわけではないようで、ansible-navigator の仕様に基づいてマウントなどもしてくれます。

podman inspect で詳細を確認すると、Mounts 配下の情報からバインドマウントしてる様子が確認できました。(抜粋部分はSSH キーのマウントの仕様によるもの)

// ...(略)...
        "Mounts": [
            {
                "Type": "bind",
                "Source": "/home/admin/.ssh",
                "Destination": "/home/runner/.ssh",
                "Driver": "",
                "Mode": "",
                "Options": [
                    "rbind"
                ],
                "RW": true,
                "Propagation": "rprivate"
            },
            {
                "Type": "bind",
                "Source": "/home/admin/.ssh",
                "Destination": "/root/.ssh",
                "Driver": "",
                "Mode": "",
                "Options": [
                    "rbind"
                ],
                "RW": true,
                "Propagation": "rprivate"
            },
// ...(略)...

参考: exec サブコマンドのヘルプ

ansible-navigator exec --help 結果(クリックして開く)

$ ansible-navigator exec --help
Usage: ansible-navigator exec [options]

exec: Run a command within an execution environment

Options (global):
 -h     --help                                   Show this help message and exit
 --version                                       Show the application version and exit
 --rad  --ansible-runner-artifact-dir            The directory path to store artifacts generated by ansible-runner
 --rac  --ansible-runner-rotate-artifacts-count  Keep ansible-runner artifact directories, for last n runs, if set to 0 artifact directories won't be deleted
 --rt   --ansible-runner-timeout                 The timeout value after which ansible-runner will forcefully stop the execution
 --cdcp --collection-doc-cache-path              The path to collection doc cache (default: /home/admin/.cache/ansible-navigator/collection_doc_cache.db)
 --ce   --container-engine                       Specify the container engine (auto=podman then docker) (auto|podman|docker) (default: auto)
 --co   --container-options                      Extra parameters passed to the container engine command
 --dc   --display-color                          Enable the use of color for mode interactive and stdout (true|false) (default: true)
 --ecmd --editor-command                         Specify the editor command (default: vi +{line_number} {filename})
 --econ --editor-console                         Specify if the editor is console based (true|false) (default: true)
 --ee   --execution-environment                  Enable or disable the use of an execution environment (true|false) (default: true)
 --eei  --execution-environment-image            Specify the name of the execution environment image (default: quay.io/ansible/creator-ee:v0.4.2)
 --eev  --execution-environment-volume-mounts    Specify volume to be bind mounted within an execution environment (--eev /home/user/test:/home/user/test:Z)
 --la   --log-append                             Specify if log messages should be appended to an existing log file, otherwise a new log file will be created per
                                                 session (true|false) (default: true)
 --lf   --log-file                               Specify the full path for the ansible-navigator log file (default: /home/admin/git/general/ansible-
                                                 navigator.log)
 --ll   --log-level                              Specify the ansible-navigator log level (debug|info|warning|error|critical) (default: warning)
 -m     --mode                                   Specify the user-interface mode (stdout|interactive) (default: interactive)
 --osc4 --osc4                                   Enable or disable terminal color changing support with OSC 4 (true|false) (default: true)
 --penv --pass-environment-variable              Specify an existing environment variable to be passed through to and set within the execution environment
                                                 (--penv MY_VAR)
 --pa   --pull-arguments                         Specify any additional parameters that should be added to the pull command when pulling an execution environment
                                                 from a container registry. e.g. --pa='--tls-verify=false'
 --pp   --pull-policy                            Specify the image pull policy always:Always pull the image, missing:Pull if not locally available, never:Never
                                                 pull the image, tag:if the image tag is 'latest', always pull the image, otherwise pull if not locally available
                                                 (always|missing|never|tag) (default: tag)
 --senv --set-environment-variable               Specify an environment variable and a value to be set within the execution environment (--senv MY_VAR=42)
 --tz   --time-zone                              Specify the IANA time zone to use or 'local' to use the system time zone (default: utc)

Options (exec subcommand):
 exec_command                                    Specify the command to run within the execution environment (default: /bin/bash)
 --exshell --exec-shell                          Specify the exec command should be run in a shell (true|false) (default: true)

Note: During development, it may become necessary to interact directly with the execution environment to review and confirm its build and behavior. All navigator
settings will be applied when starting the execution environment.



■ 4. lint サブコマンド追加 (ansible-lintの呼び出し)

ansible-navigator lint で、ansible-lint を呼び出せるようになりました。

ansible-navigator lint で ansible-lint の呼び出し

行頭の番号を数字1桁 または :数字1桁以上 エンター で指定すると、詳細が表示されます。

エラーや警告類の詳細表示

実行環境の利用が有効(デフォルト)の場合は、実行環境内の ansible-lint が呼び出されます。今回の場合は、デフォルトの実行環境のイメージ quay.io/ansible/creator-ee:v0.4.2 内の ansible-lint 6.0.2 と yamllint 1.26.3 が利用されました。

逆に、実行環境の利用が無効(--ee false 等による指定)の場合は、ホスト側(ansible-navigator 自身を実行している側)の ansible-lint を呼び出します。ただし、ansible-navigator インストール時には ansible-lint はセットでインストールされないため、別途インストールする必要があります。

stdout モードによる実行にも対応しています。こちらのほうが馴染み深いでしょうか。

$ ansible-navigator lint -m stdout
WARNING: PATH altered to include /usr/bin
yaml: truthy value should be one of [false, true] (truthy)
playbook.yml:2

fqcn-builtins: Use FQCN for builtin actions.
playbook.yml:6 Task/Handler: debug msg=hello

unnamed-task: All tasks should be named.
playbook.yml:6 Task/Handler: debug msg=hello

yaml: no new line character at the end of file (new-line-at-end-of-file)
playbook.yml:7

参考: lint サブコマンドのヘルプ

ansible-navigator lint --help 結果(クリックして開く)

$ ansible-navigator lint --help
Usage: ansible-navigator lint [options]

lint: Lint a file or directory for common errors and issues

Options (global):
 -h     --help                                   Show this help message and exit
 --version                                       Show the application version and exit
 --rad  --ansible-runner-artifact-dir            The directory path to store artifacts generated by ansible-runner
 --rac  --ansible-runner-rotate-artifacts-count  Keep ansible-runner artifact directories, for last n runs, if set to 0 artifact directories won't be deleted
 --rt   --ansible-runner-timeout                 The timeout value after which ansible-runner will forcefully stop the execution
 --cdcp --collection-doc-cache-path              The path to collection doc cache (default: /home/admin/.cache/ansible-navigator/collection_doc_cache.db)
 --ce   --container-engine                       Specify the container engine (auto=podman then docker) (auto|podman|docker) (default: auto)
 --co   --container-options                      Extra parameters passed to the container engine command
 --dc   --display-color                          Enable the use of color for mode interactive and stdout (true|false) (default: true)
 --ecmd --editor-command                         Specify the editor command (default: vi +{line_number} {filename})
 --econ --editor-console                         Specify if the editor is console based (true|false) (default: true)
 --ee   --execution-environment                  Enable or disable the use of an execution environment (true|false) (default: true)
 --eei  --execution-environment-image            Specify the name of the execution environment image (default: quay.io/ansible/creator-ee:v0.4.2)
 --eev  --execution-environment-volume-mounts    Specify volume to be bind mounted within an execution environment (--eev /home/user/test:/home/user/test:Z)
 --la   --log-append                             Specify if log messages should be appended to an existing log file, otherwise a new log file will be created per session (true|false)
                                                 (default: true)
 --lf   --log-file                               Specify the full path for the ansible-navigator log file (default: /home/admin/git/general/ansible-navigator.log)
 --ll   --log-level                              Specify the ansible-navigator log level (debug|info|warning|error|critical) (default: warning)
 -m     --mode                                   Specify the user-interface mode (stdout|interactive) (default: interactive)
 --osc4 --osc4                                   Enable or disable terminal color changing support with OSC 4 (true|false) (default: true)
 --penv --pass-environment-variable              Specify an existing environment variable to be passed through to and set within the execution environment (--penv MY_VAR)
 --pa   --pull-arguments                         Specify any additional parameters that should be added to the pull command when pulling an execution environment from a container registry.
                                                 e.g. --pa='--tls-verify=false'
 --pp   --pull-policy                            Specify the image pull policy always:Always pull the image, missing:Pull if not locally available, never:Never pull the image, tag:if the
                                                 image tag is 'latest', always pull the image, otherwise pull if not locally available (always|missing|never|tag) (default: tag)
 --senv --set-environment-variable               Specify an environment variable and a value to be set within the execution environment (--senv MY_VAR=42)
 --tz   --time-zone                              Specify the IANA time zone to use or 'local' to use the system time zone (default: utc)

Options (lint subcommand):
 --lic  --lint-config                            Specify the path to the ansible-lint configuration file
 lintables                                       Path to files on which to run ansible-lint

Note: Defaults to the current working directory. If using an execution environment, ansible-lint must be installed in it. If not using an execution environment, ansible-lint must be installed
on your system.


おわりに

ansible-navigator 2.0.0 では、サブコマンドが追加されて、 ansible-lint も ansible-builder も ansible-navigator コマンド経由で呼べるようになりました。

もしかしたら手癖でとりあえず、ansible-navigator と入力するようになるかもしれません。

その他の機能追加や、仕様変更は別の記事にする予定です。 [2022/04/19 追記] その他編として投稿しました。

tekunabe.hatenablog.jp

参考

リリースノート

github.com

changelog

ansible-navigator.readthedocs.io

[Ansible] azure.azcollection.azure_rm インベントリプラグインで停止中のVMも対象にする

はじめに

Ansible から Azure の VM の情報を取得して動的にインベントリを生成できる azure.azcollection.azure_rm インベントリプラグインという便利なものがあります。

こちらの issueを見てなるほどと思ったのですが、デフォルトだと実行中(running)でない VM や、provisioning_statesucceeded でない VM は除外されます。何らかの事情で、状態に関わらずインベントリとして取得したい場合は、default_host_filters オプションで空リストを指定すればいいということなので、試してみました。

  • 環境
    • ansible-core 2.12.1
    • azure.azcollection 1.10.0

(比較用)デフォルトの default_host_filters の場合

比較のためまず、default_host_filters の指定なしで試します。サービスプリンシパル~/.azure/credentials に定義済みの状態です。

---
plugin: azure.azcollection.azure_rm
include_vm_resource_groups:
  - "*"
plain_host_names: true # インベントリ名を仮想マシン名にする(本件とは直接関係ない)

確認には、単純にインベントリの情報だけ確認したいので、ansible-inventory コマンドを利用します。

$ ansible-inventory -i inventory_azure_rm.yml --graph
@all:
  |--@ungrouped:
  |  |--ansible01

ポータルと見比べると起動中の VM だけが対象になりました。

停止中含め 全 VM を対象にする

次は、状態に関わらず全 VM を対象にする場合です。

---
plugin: azure.azcollection.azure_rm
include_vm_resource_groups:
  - "*"
plain_host_names: true # インベントリ名を仮想マシン名にする(本件とは直接関係ない)

default_host_filters:  []  # ポイント         

また ansible-inventory を実行して確認します。

$ ansible-inventory -i inventory_azure_rm.yml --graph
@all:
  |--@ungrouped:
  |  |--ansible01
  |  |--iwana01
  |  |--yamame01
  |  |--yokoyoko

無事実行中以外の VM も表示されました。

参考

[Ansible] Ansible から HashiCorp Vault のシークレットを取得する

はじめに

前回の記事で、HashiCorp Vault の kv シークレットエンジンを使ってシークレットの登録をしました。

今回は、そのシークレットを Ansible から取得して表示したり、機器への接続パスワードに利用することを試します。

Ansible の community.hashi_vault.hashi_vault ルックアッププラグインを利用します。

少し紛らわしいかもしれませんが、Ansible Vaultとは直接は関係ありません。

  • 環境
    • Vault v1.10.0
    • ansible 5.6.0 (ansible-core 2.12.4)
    • community.hashi_vault コレクション 2.4.0
      • hashi_vault ルックアッププラグインは、もともとは community.general コレクションにありましたが、2.0.0 で削除されました

Vault 側の準備

Ansible の前にまず Vault 側の準備です。

vault -dev でサーバーを起動済みの状態から始めます。今回は Vault サーバーもAnsible も同じサーバーという構成です。

シークレットの確認

前回からのおさらいになりますが secret/mypassword の中に password というキーで、パスワード p@ssw0rd が登録されています。これを後で Ansible から取得します。

$ vault kv get secret/mypassword
===== Secret Path =====
secret/data/mypassword

======= Metadata =======
Key                Value
---                -----
created_time       2022-04-07T13:34:41.03484313Z
custom_metadata    <nil>
deletion_time      n/a
destroyed          false
version            1

====== Data ======
Key         Value
---         -----
password    p@ssw0rd

ポリシーの追加

シークレットの読み込みだけできるポリシーを追加します。ここでは read-secret という名前にします。

$ vault policy write read-secret - << EOF
path "secret/data/*" {
  capabilities = ["read"]
}
EOF
Success! Uploaded policy: read-secret

ポリシーのリストを確認すると read-secret が表示されます。

$ vault policy list
default
read-secret
root

内容も確認します。意図通りになっています。

$ vault policy read read-secret
path "secret/data/*" {
  capabilities = ["read"]
}

参考 Policies | Vault | HashiCorp Developer

トークンの生成

先ほど作成したポリシー read-secret に対するトークンを生成します。

$ vault token create -policy=read-secret
Key                  Value
---                  -----
token                hvs.dummyyyyyyyyyy
token_duration       768h
token_renewable      true
token_policies       ["default" "read-secret"]
identity_policies    []
policies             ["default" "read-secret"]

ここではダミーの値に伏せていますが、token に表示された値を後で使います。

参考 Authentication | Vault | HashiCorp Developer

Vault 側の準備はここまでです。

Ansible 側の準備

今度は Ansible 側の準備です。

hvac のインストール

ドキュメントの Requirementsにあるとおり、HashiCorp Vault API クライアントのPython パッケージ hvac が必要です。コントロールノード(Ansibleをインストールしたノード)に pip でインストールします。

pip install hvac

お試し1: 取得したシークレットを表示する

実用性はありませんが、とりあえず確認のため、取得したシークレットを表示するだけの Playbook を作成します。

---
- hosts: localhost
  gather_facts: false 

  tasks:
    - name: debug vault secret
      debug:
        msg: "{{ lookup('community.hashi_vault.hashi_vault', 'secret=secret/data/mypassword:password') }}"

secret のところで、取得したいシークレットのパスを指定します。password の値がほしいので、 :password も含めて指定します。

この他の代表的な設定要素として Vault サーバーへの接続先URLとトークンがあります。これらをルックアッププラグイン呼び出しのオプションで指定すると、複数箇所で呼び出すとき場合に毎回指定が必要になり冗長です。そのため、今回はURLとトークンは環境変数で指定します。トークンには Vault 側の準備で read-secret ポリシーに対して生成したものを指定します。

$ export ANSIBLE_HASHI_VAULT_TOKEN=hvs.dummyyyyyyyyyy
$ export ANSIBLE_HASHI_VAULT_ADDR=http://localhost:8200

なお、環境変数以外にはファイルに記載しておく方法もあります。詳細は、community.hashi_vault.hashi_vault ルックアッププラグインのドキュメントの urltokenを参照してください。

Playbook 実行

Playbook を実行します。

$ ansible-playbook -i localhost, debug_vault.yml 

PLAY [localhost] ****************************************************************************************************

TASK [debug vault secret] *******************************************************************************************
ok: [localhost] => {
    "msg": "p@ssw0rd"
}

PLAY RECAP **********************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

p@ssw0rd が表示できたため、無事に Vault からシークレットを取得できたことが確認できました。

お試し2: 取得したシークレットを機器接続パスワードとして利用する。

今度は少し実用的な例です。(URLとトークンの環境変数は設定したままです)

Vault のシークレットから取得した値を、Cisco IOS への接続パスワードとして利用します。

インベントリファイルに ios というグループの定義がされている状態で、group_vars/ios.yml に以下のように定義します。

---
ansible_network_os: cisco.ios.ios
ansible_connection: ansible.netcommon.network_cli
ansible_user: admin
ansible_password: "{{ lookup('community.hashi_vault.hashi_vault', 'secret=secret/data/mypassword:password') }}"

ansible_password 変数に対して、Vault から取得した値を利用するように指定します。

Playbook 自体は以下のものを利用します。無事に接続、認証できたことを確認できればいいので、show コマンドを実行して表示するだけです。

---
- hosts: ios
  gather_facts: false

  tasks:
    - name: exec show commands
      cisco.ios.ios_command:
        commands:
          - show running-config
      register: res_show_commands

    - name: debug show commands
      ansible.builtin.debug:
        msg: "{{ res_show_commands.stdout_lines[0] }}"

Playbook を実行します。

$ ansible-playbook -i inventory ios_show.yml 

PLAY [ios] **********************************************************************************************************

TASK [exec show commands] *******************************************************************************************
ok: [ios01]

TASK [debug show commands] ******************************************************************************************
ok: [ios01] => {
    "msg": [
        "Building configuration...",
        "",
        "  ",
        "Current configuration : 4076 bytes",
        "!",
        "! Last configuration change at 10:07:41 UTC Wed Apr 6 2022",
        "!",
        "version 15.9",
...(略)...
PLAY RECAP **********************************************************************************************************
ios01                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

無事に Playbook を実行できます。

おわりに

お試しレベルですが、Ansible から HashiCorp Vault のシークレットの値を取得する動作を確認しました。

簡単に連携できたなと思いました。

HashiCorp Vault によるシークレットの登録と確認を気軽に試してみた

はじめに

Software Design 2022年4月号で始まった連載「HashiCorp Vaultではじめるシークレット管理」を読んで、HashiCorp Vault(以下 Vault)に興味を持ちました。

他、HashiCorp Learn の Vualt のコンテンツも参照してみました。

あくまでお試しレベルですが、インストールからシークレットの登録、確認までやってみたことをまとめます。

インストール

ドキュメントに掲載されていた、yum コマンドによるインストールを行いました。

$ sudo yum install -y yum-utils
$ sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
$ sudo yum -y install vault

インストールできたら、バージョンの確認をします。今回はこちらです。

$ vault --version
Vault v1.10.0 (7738ec5d0d6f5bf94a809ee0f6ff0142cfa525a6)

起動・接続準備

簡易的な、開発モードでサーバーを起動します。

$ vault server -dev
==> Vault server configuration:
...(略)...
WARNING! dev mode is enabled! In this mode, Vault runs entirely in-memory
and starts unsealed with a single unseal key. The root token is already
authenticated to the CLI, so you can immediately begin using Vault.

You may need to set the following environment variable:

    $ export VAULT_ADDR='http://127.0.0.1:8200'

The unseal key and root token are displayed below in case you want to
seal/unseal the Vault or re-authenticate.

Unseal Key: dummyxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Root Token: hvs.dummyxxxxxxxxx

Development mode should NOT be used in production installations!

サーバーを起動したターミナルはそのままにして、別のターミナルを開きます。

接続の準備として、サーバーへの接続先を環境変数に設定します。

export VAULT_ADDR='http://127.0.0.1:8200'

今回は、サーバーもクライアントも同じマシンの上です。

参考 Starting the Server | Vault | HashiCorp Developer

シークレットの追加

さっそく kv シークレットエンジンを使ってシークレットを登録します。

今回は secret/mypassword 内に password の値として p@ssw0rd を登録します。

$ vault kv put secret/mypassword password=p@ssw0rd
===== Secret Path =====
secret/data/mypassword

======= Metadata =======
Key                Value
---                -----
created_time       2022-04-07T13:34:41.03484313Z
custom_metadata    <nil>
deletion_time      n/a
destroyed          false
version            1

参考 Your First Secret | Vault | HashiCorp Developer

シークレットの確認

登録できたことを vault kv get で確認します。

$ vault kv get secret/mypassword
===== Secret Path =====
secret/data/mypassword

======= Metadata =======
Key                Value
---                -----
created_time       2022-04-07T13:34:41.03484313Z
custom_metadata    <nil>
deletion_time      n/a
destroyed          false
version            1

====== Data ======
Key         Value
---         -----
password    p@ssw0rd

password の値として p@ssw0rd が登録されていることが確認できました。

参考 Your First Secret | Vault | HashiCorp Developer

おわりに

かんたんですが Vault で試したことをまとめました。おそらくまだ Vault が持っている機能のうちのほんの少しだけだと思います。

Software Design での連載の次の記事も楽しみです。

このブログととしては別途、Ansible からシークレットを呼び出す方法を書きたいと思います。

[追記]

tekunabe.hatenablog.jp

[Ansible] Ansible 3 以降のモジュール一覧のページ

はじめに

Ansible のモジュールの一覧を確認したいときは、よく公式ドキュメントを参照します。Ansible 2.9 までは、Module Indexというページがあり、さらにカテゴリごとのページに飛べます。また、All modules というページでは全モジュールの一覧が表示されます。

Ansible-base 2.10 / Ansible 3 からは、本体と一緒に管理されていたモジュールの多くがコレクションに移行した関係で、ドキュメントの構造も変わりました。

「前にあった All modules みたいにモジュール一覧のページどっかないのかな」と思ってたら、ちゃんとあることに最近気が付きました。

モジュール一覧のページ

f:id:akira6592:20220407204101p:plain:w200
Indexes of all modules and plugins > Index of all Modules
こちらです。

左メニューの [Indexes of all modules and plugins] 内の [Index of all Modules] です。 

docs.ansible.com

ここに、ansible.builtin コレクション内のモジュールの他、Ansible Community Package に同梱される様々なコレクションのモジュールがリストになっています。

2.9 までにあったカテゴリごとではなく、コレクションごとに並んでいます。

なお、ansible-core 側のドキュメントの同じページには、ansible.builtin コレクションのみ掲載されています。

docs.ansible.com

(参考) コレクションのリスト

先程はコレクション串刺しのモジュールのリストでしたが、コレクションのリストは以下のページです。この切り口のリストは 2.9 は無かったものです。

docs.ansible.com

[Ansible] スキップされたタスクの結果は is skipped でもあり is succeeded でもある

はじめに

Ansible では、タスクの実行結果を変数に保存し、その結果を後続のタスクで確認する機能があります。

docs.ansible.com

そういえばどうなんだろうシリーズといいますか、「スキップされたタスクって succeeded 扱いだっけ?」と思ったことがありました。

結果としては、is skipped でもあり is succeeded でもありました。

試した結果をまとめます。

  • 検証環境
    • ansible 5.4.0
    • ansible-core 2.12.3

Playbook

こんな Playbook で試します。

---
- hosts: localhost
  gather_facts: false

  tasks:
    # (1) 必ずスキップされるタスク
    - name: skipped task
      ansible.builtin.debug:
        msg: this task is skipped
      register: resister_skipped
      when:
        - false

    # (2) 1が skipped 扱いの場合に実行されるタスク
    - name: debug result skipped
      ansible.builtin.debug:
        msg: resister_skipped is skipped
      when:
        - resister_skipped is skipped

    # (3) 1が succeeded 扱いの場合に実行されるタスク
    - name: debug result succeeded
      ansible.builtin.debug:
        msg: resister_skipped is succeeded
      when:
        - resister_skipped is succeeded

一番確かめたいたいのは (3) のタスクです。

結果

実行結果は以下のとおりです。 is succeeded を条件にしたタスク3も実行されました。

$ ansible-playbook -i localhost, success.yml     

PLAY [localhost] ***************************************************************************************

TASK [skipped task] ************************************************************************************
skipping: [localhost]

TASK [debug result skipped] ****************************************************************************
ok: [localhost] => {
    "msg": "resister_skipped is skipped"
}

TASK [debug result succeeded] **************************************************************************
ok: [localhost] => {
    "msg": "resister_skipped is succeeded"
}

PLAY RECAP *********************************************************************************************
localhost      : ok=2    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0  

なお resister_skipped 変数をデバッグ表示すると以下のとおりです。

    "resister_skipped": {
        "changed": false,
        "failed": false,
        "msg": "this task is skipped"
    }

私の解釈

コードでいうとこのあたりでしょうか。

github.com

failed でない場合は succeededまたは successsuccessful )のようです。

今回の場合は「正常に判断処理がされた結果、スキップできた」ことをもって succeeded なのかなと捉えています。

一方たとえば、(1) のタスクで、when に未定義の変数をした場合(確認のためにignore_errors: true も併用)はさすがに succeeded にはなりませんでした。

---
- hosts: localhost
  gather_facts: false

  tasks:
    # (1) when が異常
    - name: skipped task
      ansible.builtin.debug:
        msg: this task is skipped
      register: resister_skipped
      when:
        - hogehoge_undefined_variable
      ignore_errors: true
        
    # (2) 1が skipped 扱いの場合に実行されるタスク
    - name: debug result skipped
      ansible.builtin.debug:
        msg: resister_skipped is skipped
      when:
        - resister_skipped is skipped

    #  (3) 1がsucceeded 扱いの場合に実行されるタスク
    - name: debug result succeeded
      ansible.builtin.debug:
        msg: resister_skipped is succeeded
      when:
        - resister_skipped is succeeded

実行結果

PLAY [localhost] ***************************************************************************************************

TASK [skipped task] ************************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "The conditional check 'hogehoge_undefined_variable' failed. The error was: error while evaluating conditional (hogehoge_undefined_variable): 'hogehoge_undefined_variable' is undefined\n\nThe error appears to be in '/Users/akira/Documents/git/general/vagrant/nwlab/qa/success.yml': line 7, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n    # (1) when が異常\n    - name: skipped task\n      ^ here\n"}
...ignoring

TASK [debug result skipped] ****************************************************************************************
skipping: [localhost]

TASK [debug result succeeded] **************************************************************************************
skipping: [localhost]

PLAY RECAP *********************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=2    rescued=0    ignored=1