Can't use ansible inventory file because it is executable

后端 未结 2 1643
旧时难觅i
旧时难觅i 2021-01-13 00:06

I am trying to run an Ansible inventory file ansible -i hosts-prod all -u root -m ping and it is failing with this message:

ERROR: The file host         


        
相关标签:
2条回答
  • 2021-01-13 00:16

    Executable inventories are parsed as JSON instead of ini files, so you can convert it to a script that outputs JSON. On top of that, Ansible passes some arguments to them to a simple 'cat' isn't enough:

    #!/bin/bash
    cat <<EOF
    {
     "_meta": {
       "hostvars": {
         "host1": { "some_var": "value" }
       }
     },
     "hostgroup1": [
       "host1",
       "host2"
     ]
     ...
    }
    EOF
    

    Not as elegant as a simple 'cat', but should work.

    0 讨论(0)
  • 2021-01-13 00:23

    @hkariti's answer is first and closest to the original question. I ended up re-writing the config file entirely into a Ruby script and that is working fine. I thought I'd share that code here since finding complete examples for Ansible dynamic inventory files wasn't super easy for me. The file is different from a static file in how you associate variables with machine listings in the inventory (using the _meta tag)..

    #!/usr/bin/env ruby
    # this file must be executable (chmod +x) in order for ansible to use it
    require 'json'
    module LT
      module Ansible
        def self.staging_inventory
          {
            local: {
              hosts:["127.0.0.1"],
              vars: { 
                ansible_connection: "local"
              }
            },
            common: {
              hosts: [],
              children: ["web", "db"],
              vars: {
                ansible_connection: "ssh",
              }
            },
            web: {
              hosts: [],
              children: ["web_staging"]
            },
            db: {
              hosts: [],
              children: ["db_staging"]
            },
            web_staging: {
              hosts: ["webdb01-ci"],
              vars: {
                # server specific vars here
              }
            },
            db_staging: {
              hosts: ["webdb01-ci"]
            }
          }
        end
      end
    end
    # ansible will pass "--list" to this file when run from command line
    # testing for --list should let us require this file in code libraries as well
    if ARGV.find_index("--list") then
      puts LT::Ansible::staging_inventory.to_json
    end
    
    0 讨论(0)
提交回复
热议问题