3

I have created an Ansible playbook to launch 5 AWS EC2 instances. I want to run this playbook using the Python API but I am confused as to how to do this.

Here is my playbook:

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

And here is the code to run the playbook:

ansible-playbook -i hosts ec2_launch.yml

How can I run the playbook using this code from within a Python project file?

ydaetskcoR
  • 53,225
  • 8
  • 158
  • 177
Haldamir
  • 115
  • 2
  • 10

1 Answers1

3

If you just want to run a complete playbook that is runnable via Ansible normally then why not just use subprocess to shell out and run it?

This should be as simple as something like:

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

As long as the playbook and inventory are in the same relative path as your Python project.

If you want to interact with Ansible's Python API to a more granular level then you will probably want to read the docs.

ydaetskcoR
  • 53,225
  • 8
  • 158
  • 177