2016-05-08 10 views
1

Ich habe ein Ansible-Playbook erstellt, um 5 AWS EC2-Instanzen zu starten. Ich möchte dieses Playbook mit der Python-API ausführen, aber ich bin verwirrt, wie das geht.Ausführen von Ansible-Playbook mit der Python-API

Hier ist mein Textbuch:

--- 
- name: Provision an EC2 Instance 
hosts: local 
connection: local 
gather_facts: False 
tags: provisioning 
# Necessary Variables for creating/provisioning the EC2 Instance 
vars: 
    instance_type: t2.micro 
    security_group: webserver 
    image: ami-f95ef58a 
    region: eu-west-1c 
    keypair: Daniel 
    count: 5 

# Task that will be used to Launch/Create an EC2 Instance 
tasks: 

    - name: Create a security group 
    local_action: 
     module: ec2_group 
     name: "{{ security_group }}" 
     description: Security Group for webserver Servers 
     region: "{{ region }}" 
     rules: 
     - proto: tcp 
      type: ssh 
      from_port: 22 
      to_port: 22 
      cidr_ip: 0.0.0.0/0 
     - proto: tcp 
      from_port: 80 
      to_port: 80 
      cidr_ip: 0.0.0.0/0 
     rules_egress: 
     - proto: all 
      type: all 
      cidr_ip: 0.0.0.0/0 


    - name: Launch the new EC2 Instance 
    local_action: ec2 
        group={{ security_group }} 
        instance_type={{ instance_type}} 
        image={{ image }} 
        wait=true 
        region={{ region }} 
        keypair={{ keypair }} 
        count={{count}} 
    register: ec2 

    - name: Add the newly created EC2 instance(s) to the local host group (located inside the directory) 
    local_action: lineinfile 
        dest="./hosts" 
        regexp={{ item.public_ip }} 
        insertafter="[webserver]" line={{ item.public_ip }} 
    with_items: ec2.instances 


    - name: Wait for SSH to come up 
    local_action: wait_for 
        host={{ item.public_ip }} 
        port=22 
        state=started 
    with_items: ec2.instances 

    - name: Add tag to Instance(s) 
    local_action: ec2_tag resource={{ item.id }} region={{ region }} state=present 
    with_items: ec2.instances 
    args: 
     tags: 
     Name: webserver 

Und hier ist der Code das Textbuch auszuführen:

ansible-playbook -i hosts ec2_launch.yml 

Wie kann ich das Textbuch mit diesem Code aus einer Python-Projekt-Datei ausführen?

+0

https://serversforhackers.com/running-ansible-programmatisch Google ist dein Freund –

Antwort

1

Wenn Sie nur ein komplettes Playbook ausführen möchten, das normal über Ansible ausgeführt werden kann, dann verwenden Sie einfach subprocess, um es auszupacken und auszuführen?

als so etwas wie dies sollte so einfach sein:

from subprocess import call 
call(["ansible-playbook", "-i", "hosts", "ec2_launch.yml"]) 

Solange das Textbuch und Inventar in dem gleichen relativen Pfad wie Python-Projekt ist.

Wenn Sie mit der Python-API von Ansible auf einer detaillierteren Ebene interagieren möchten, sollten Sie wahrscheinlich read the docs.

Verwandte Themen