Create a Windows AMI with packer and ansible on AWS - windows

I want to create an aws windows AMI with packer and ansible.
I have tried many configuration, but I have still a problem of connection to the instance.
Here is my packer conf :
{
"builders": [{
"type": "amazon-ebs",
"access_key": "{{user `aws_access_key`}}",
"secret_key": "{{user `aws_secret_key`}}",
"region": "eu-west-1",
"source_ami": "ami-58a1a73e",
"instance_type": "m3.medium",
"ami_name": "aaa-windows-ami {{timestamp}}",
"user_data_file":"./test.ps",
"communicator": "winrm",
"winrm_username": "Administrator",
"winrm_use_ssl": true,
"winrm_insecure": true
}],
"provisioners": [
{
"type": "ansible",
"playbook_file": "./playbook.yml",
"extra_arguments": [
"--extra-vars", "ansible_user=Administrator ansible_connection=winrm ansible_ssh_port=5986 ansible_winrm_server_cert_validation=ignore ansible_shell_type=powershell ansible_shell_executable=None"
]
},
{
"type": "powershell",
"script": "./init.ps1"
}
]
}
The User data script is activating winrm on the AWS instance.
<powershell>
write-output "Running User Data Script"
write-host "(host) Running User Data Script"
Set-ExecutionPolicy Unrestricted -Scope LocalMachine -Force -ErrorAction Ignore
# Don't set this before Set-ExecutionPolicy as it throws an error
$ErrorActionPreference = "stop"
# Remove HTTP listener
Remove-Item -Path WSMan:\Localhost\listener\listener* -Recurse
Set-Item WSMan:\localhost\MaxTimeoutms 1800000
Set-Item WSMan:\localhost\Service\Auth\Basic $true
$Cert = New-SelfSignedCertificate -CertstoreLocation Cert:\LocalMachine\My -DnsName "packer"
New-Item -Path WSMan:\LocalHost\Listener -Transport HTTPS -Address * -CertificateThumbPrint $Cert.Thumbprint -Force
# WinRM
write-output "Setting up WinRM"
write-host "(host) setting up WinRM"
cmd.exe /c winrm quickconfig -q
cmd.exe /c winrm set "winrm/config" '#{MaxTimeoutms="1800000"}'
cmd.exe /c winrm set "winrm/config/winrs" '#{MaxMemoryPerShellMB="1024"}'
cmd.exe /c winrm set "winrm/config/service" '#{AllowUnencrypted="true"}'
cmd.exe /c winrm set "winrm/config/client" '#{AllowUnencrypted="true"}'
cmd.exe /c winrm set "winrm/config/service/auth" '#{Basic="true"}'
cmd.exe /c winrm set "winrm/config/client/auth" '#{Basic="true"}'
cmd.exe /c winrm set "winrm/config/service/auth" '#{CredSSP="true"}'
cmd.exe /c winrm set "winrm/config/listener?Address=*+Transport=HTTPS" "#{Port=`"5986`";Hostname=`"packer`";CertificateThumbprint=`"$($Cert.Thumbprint)`"}"
cmd.exe /c netsh advfirewall firewall set rule group="remote administration" new enable=yes
cmd.exe /c netsh firewall add portopening TCP 5986 "Port 5986"
cmd.exe /c net stop winrm
cmd.exe /c sc config winrm start= auto
cmd.exe /c net start winrm
</powershell>
The error is.
==> amazon-ebs: Provisioning with Ansible...
amazon-ebs:
amazon-ebs: PLAY [all] *********************************************************************
amazon-ebs:
amazon-ebs: TASK [setup] *******************************************************************
amazon-ebs: fatal: [default]: UNREACHABLE! => {"changed": false, "msg": "ssl: auth method ssl requires a password", "unreachable": true}
amazon-ebs: to retry, use: --limit #/home/elhostis/repo/vagrant/playbook.retry
amazon-ebs:
amazon-ebs: PLAY RECAP *********************************************************************
amazon-ebs: default : ok=0 changed=0 unreachable=1 failed=0
amazon-ebs:
==> amazon-ebs: Terminating the source AWS instance...
==> amazon-ebs: Cleaning up any extra volumes...
==> amazon-ebs: No volumes to clean up, skipping
==> amazon-ebs: Deleting temporary security group...
==> amazon-ebs: Deleting temporary keypair...
I have also tried to create manually an AMI with a known username/password. Then, I have configured ansible with theses credentials, but I have this error.
==> amazon-ebs: Timeout waiting for password.
==> amazon-ebs: Terminating the source AWS instance...
==> amazon-ebs: Cleaning up any extra volumes...
==> amazon-ebs: No volumes to clean up, skipping
==> amazon-ebs: Deleting temporary security group...
==> amazon-ebs: Deleting temporary keypair...
Build 'amazon-ebs' errored: Timeout waiting for password.
Someone have an example to do that ?
Thanks a lot.
Eric

You need follow the instructions in the documentation for using the ansible provisioner with WinRM.
This is a working example running Windows 2016 Server Base:
{
"builders": [
{
"type": "amazon-ebs",
"region": "eu-west-1",
"instance_type": "m3.medium",
"source_ami": "ami-0983b56f",
"ami_name": "packer-demo-{{timestamp}}",
"user_data_file": "windows-userdata.txt",
"communicator": "winrm",
"winrm_username": "Administrator"
}],
"provisioners": [
{
"type": "ansible",
"playbook_file": "./win-playbook.yml",
"extra_arguments": [
"--connection", "packer", "-vvv",
"--extra-vars", "ansible_shell_type=powershell ansible_shell_executable=None"
]
}]
}
windows-userdata.txt
<powershell>
winrm quickconfig -q
winrm set winrm/config/winrs '#{MaxMemoryPerShellMB="300"}'
winrm set winrm/config '#{MaxTimeoutms="1800000"}'
winrm set winrm/config/service '#{AllowUnencrypted="true"}'
winrm set winrm/config/service/auth '#{Basic="true"}'
netsh advfirewall firewall add rule name="WinRM 5985" protocol=TCP dir=in localport=5985 action=allow
netsh advfirewall firewall add rule name="WinRM 5986" protocol=TCP dir=in localport=5986 action=allow
net stop winrm
sc config winrm start=auto
net start winrm
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope LocalMachine
</powershell>
win-playbook.yml
---
- hosts: all
tasks:
- win_ping:
#- ping:
connection_plugins/packer.py
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.connection.ssh import Connection as SSHConnection
class Connection(SSHConnection):
''' ssh based connections for powershell via packer'''
transport = 'packer'
has_pipelining = True
become_methods = []
allow_executable = False
module_implementation_preferences = ('.ps1', '')
def __init__(self, *args, **kwargs):
super(Connection, self).__init__(*args, **kwargs)
Unfortunatley there seems to be a problem with the latest (2.3.0) version Ansible and Packer, see #4904

I don't find solution.
So, I don't use packer in my stack. I'm using only ansible. Here an example of code for other people.
#
# First, create a new instance
#
- hosts: localhost
tasks:
# Create a new instance with an AMI
- name: Create a new instance
ec2:
aws_access_key: "xxx"
aws_secret_key: "xxx"
region: "xxx"
key_name: "xxx"
instance_type: "t2.small"
image: "xxx"
assign_public_ip: yes
wait: yes
count: 1
register: ec2_created
# Wait a few minutes for windows starting
- name: Wait for windows is starting
pause:
minutes: 5
# Subscribe the new instance to ansible
- name: Subscribe host to Ansible
add_host:
name: "{{ec2_created.instances[0].dns_name}}"
groups: win
ansible_ssh_pass: "xxx"
no_log: True
#
# Then, provision the instance
#
- hosts: win
roles:
- xxx
#
# Finally, create a new AMI with the instance
# and destroy it
#
- hosts: localhost
tasks:
- name: Create AMI
ec2_ami:
aws_access_key: "xxx"
aws_secret_key: "xxx"
region: "xxx"
instance_id: "{{ec2_created.instance_ids[0]}}"
wait: yes
name: "xxx"
register: ami_created
- name: Destroy instance
ec2:
aws_access_key: "xxx"
aws_secret_key: "xxx"
region: "xxx"
state: 'absent'
instance_ids: "{{ec2_created.instance_ids[0]}}"

Related

Use ODBC connection to managed Azure SQL Database

I need to run a SQL query on Azure SQL Database from an Ansible playbook.
My task is:
- name: Sql server - rights
vars:
sql_groups:
- { group_name: "{{ reader_group }}", db_access: "db_datareader" }
- { group_name: "{{ contributer_group }}", db_access: "db_datawriter" }
- { group_name: "{{ owner_group }}", db_access: "db_owner" }
community.general.odbc:
dsn: "Driver={ODBC Driver 13 for SQL Server};Server=tcp:{{ sql_server_host }},1433;Database={{ sql_server_db }};Uid={{ mssql_login_user }};Pwd={{ mssql_login_password }};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;Authentication=ActiveDirectoryPassword"
query: |
CREATE USER ["{{ group_name }}"] FROM EXTERNAL PROVIDER
EXEC sp_addrolemember '{{ db_access }}', '{{ group_name }}'
loop: "{{ sql_groups }}"
When I run the playbook with the following command, Ansible tries to communicate via SSH.
ansible-playbook -i inventory.yml playbook.yml --check
The error is :
[WARNING]: Unhandled error in Python interpreter discovery for host XXXXXX: Failed to connect to the host via ssh: ssh: Could not resolve hostname XXXXXX: Name
or service not known
fatal: [XXXXXX]: UNREACHABLE! => {"changed": false, "msg": "Data could not be sent to remote host \"XXXXXX\". Make sure this host can be reached over ssh: ssh: Could not resolve hostname XXXXXX: Name or service not known\r\n", "unreachable": true}
I think I need to force the use of an ODBC connection with something like below (example is for Windows server) :
ansible_connection: winrm
ansible_port: 5986
ansible_winrm_transport: credssp
ansible_winrm_server_cert_validation: ignore
What should I do ?
ansible_port: 1433 ? And what other parameters ?
I don't see how to communicate via ODBC.

Ansible: Importing GPG-keys from RPM Fusion not working

I'm trying to create a task to download and import the GPG-keys from the official RPM Fusion site but it fails.
- hosts: localhost
connection: local
name: DOWNLOADING AND IMPORTING SECURITY KEYS
tasks:
- name: Downloading the security key for RPM Fusion (free) repo
get_url:
url: https://rpmfusion.org/keys?action=AttachFile&do=get&target=RPM-GPG-KEY-rpmfusion-free-fedora-2020
dest: ~/Downloads/free_keys.txt
- name: Importing (free) key
ansible.builtin.rpm_key:
state: present
key: ~/Downloads/free_keys.txt
- name: Deleting security key file (free)
ansible.builtin.file:
path: ~/Downloads/free_keys.txt
state: absent
- name: Downloading the security key for RPM Fusion (non-free) repo
get_url:
url: https://rpmfusion.org/keys?action=AttachFile&do=get&target=RPM-GPG-KEY-rpmfusion-nonfree-fedora-2020
dest: ~/Downloads/nonfree_keys.txt
- name: Importing (non-free) key
ansible.builtin.rpm_key:
state: present
key: ~/Downloads/nonfree_keys.txt
- name: Deleting security key file (non-free)
ansible.builtin.file:
path: ~/Downloads/nonfree_keys.txt
state: absent
This is the output:
TASK [Gathering Facts] *********************************************************
ok: [localhost]
TASK [Downloading the security key for RPM Fusion (free) repo] *****************
changed: [localhost] => {"changed": true, "checksum_dest": null, "checksum_src": "554f50b16f9cf421f7caf02ce83c9069fd399b0e", "dest": "/home/[REDACTED]/Downloads/free_keys.txt", "elapsed": 0, "gid": 1000, "group": "[REDACTED]", "md5sum": "7206830528e4e9fb61d52dafc4e32ed1", "mode": "0664", "msg": "OK (1704 bytes)", "owner": "[REDACTED]", "secontext": "unconfined_u:object_r:user_home_t:s0", "size": 1704, "src": "/home/[REDACTED]/.ansible/tmp/ansible-tmp-1623521488.9204922-9892-237385967611488/tmp38djamsm", "state": "file", "status_code": 200, "uid": 1000, "url": "https://rpmfusion.org/keys?action=AttachFile&do=get&target=RPM-GPG-KEY-rpmfusion-free-fedora-2020"}
TASK [Importing (free) key] ****************************************************
fatal: [localhost]: FAILED! => {"changed": false, "msg": "Not a valid key ~/Downloads/free_keys.txt"}
PLAY RECAP *********************************************************************
localhost : ok=2 changed=1 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
So far I've tried to download the keys to .txt and .gpg format but none of these methods work. Any suggestion is greatly appreciated.
EDIT: To answer your questions:
1.
TASK [Importing (free) key] ****************************************************
task path: /home/[REDACTED]/Documents/ansible-playbooks/for_laptops/dell_e7270/import_keys.yml:11
<127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: [REDACTED]
<127.0.0.1> EXEC /bin/sh -c 'echo ~[REDACTED] && sleep 0'
<127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/[REDACTED]/.ansible/tmp `"&& mkdir "` echo /home/[REDACTED]/.ansible/tmp/ansible-tmp-1623533463.7691412-3758-92960382692038 `" && echo ansible-tmp-1623533463.7691412-3758-92960382692038="` echo /home/[REDACTED]/.ansible/tmp/ansible-tmp-1623533463.7691412-3758-92960382692038 `" ) && sleep 0'
Using module file /usr/lib/python3.9/site-packages/ansible/modules/packaging/os/rpm_key.py
<127.0.0.1> PUT /home/[REDACTED]/.ansible/tmp/ansible-local-3682vs8hkmey/tmpjamn9upp TO /home/[REDACTED]/.ansible/tmp/ansible-tmp-1623533463.7691412-3758-92960382692038/AnsiballZ_rpm_key.py
<127.0.0.1> EXEC /bin/sh -c 'chmod u+x /home/[REDACTED]/.ansible/tmp/ansible-tmp-1623533463.7691412-3758-92960382692038/ /home/[REDACTED]/.ansible/tmp/ansible-tmp-1623533463.7691412-3758-92960382692038/AnsiballZ_rpm_key.py && sleep 0'
<127.0.0.1> EXEC /bin/sh -c '/usr/bin/python3 /home/[REDACTED]/.ansible/tmp/ansible-tmp-1623533463.7691412-3758-92960382692038/AnsiballZ_rpm_key.py && sleep 0'
<127.0.0.1> EXEC /bin/sh -c 'rm -f -r /home/[REDACTED]/.ansible/tmp/ansible-tmp-1623533463.7691412-3758-92960382692038/ > /dev/null 2>&1 && sleep 0'
fatal: [localhost]: FAILED! => {
"changed": false,
"invocation": {
"module_args": {
"fingerprint": null,
"key": "~/Downloads/free_keys",
"state": "present",
"validate_certs": true
}
},
"msg": "Not a valid key ~/Downloads/free_keys"
}
The keys are the ones under 'Fedora 34' in this link.
Yes, the keys downloaded look like that.
Unfortunately, changing the permissions did not work.
Looks like a solution could be to download the distribution-gpg-keys from the official repos before installing the RPM Fusion.
Try to start ansible with very verbose logging
/bin/ansible-playbook import_gpg.yml -vvvv
As far as i know, its 2021 year now, and judging by URL (https://rpmfusion.org/keys?action=AttachFile&do=get&target=RPM-GPG-KEY-rpmfusion-nonfree-fedora-2020), key seems to be issued for 2020 year.
I think you have downloaded and tried to import expired key.
Can you verify you downloaded file that looks like GPG key?
Something, that looks like this:
-----BEGIN PGP PUBLIC KEY BLOCK-----
mQINBF2tvGQBEAC5Q2ePLZZafOkFhYHpGZdRRBCcCd+aiLATofFV8+FjPuPLL/3R
......
kgQgWZ6F2RZm5/R28DHdAetji50XbnmXgAk/u9u2Hw2bVVJfJ0WpEVcPvA1L86SE
8i8p1fmzljwRazZAksk5Zh2QfaM0jlMYHWbKpbXQcX19Uerm7D9IkciZvDAmgBYV
S6Y=
=rOqq
-----END PGP PUBLIC KEY BLOCK-----
Probably, they use cloudflare, that blocks default ansible user agent - https://docs.ansible.com/ansible/latest/collections/ansible/builtin/get_url_module.html#parameter-http_agent). You can set user agent to browser one.
Or, you can set proper permissions for file being saved to disk
- name: Downloading the security key for RPM Fusion (non-free) repo
get_url:
url: https://rpmfusion.org/keys?action=AttachFile&do=get&target=RPM-GPG-KEY-rpmfusion-nonfree-fedora-2020
dest: ~/Downloads/nonfree_keys.txt
mode: 0600
Because RPM cannot import keys from world writeable files.
After some digging I found the solution and it's simpler than I thought:
---
- hosts: localhost
connection: local
name: IMPORTING SECURITY KEYS
tasks:
- name: Importing (free) key
ansible.builtin.rpm_key:
state: present
key: https://rpmfusion.org/keys?action=AttachFile&do=get&target=RPM-GPG-KEY-rpmfusion-free-fedora-2020
- name: Importing (non-free) key
ansible.builtin.rpm_key:
state: present
key: https://rpmfusion.org/keys?action=AttachFile&do=get&target=RPM-GPG-KEY-rpmfusion-nonfree-fedora-2020
Following the official documentation, I thought you had to download the keys to your PC and then install them. Instead, you can directly enter the URL into the key section.

basic telnet script to copy to flash drive

I am trying to use ansible to telnet into cisco switches and apply a copy startup-config disk0 command.
Ansible seems to never be able to pass
(?i)"Destination filename": "work please" through the expect command
---
- hosts: all
gather_facts: false
connection: local
tasks:
- name: telnet,login and execute command
ignore_errors: true
expect:
command: telnet "{{ inventory_hostname }}"
responses:
(?i)password: "{{ password}}"
(?i)#: copy startup-config disk0
(?i)"Destination filename": "{{ lookup('pipe','date') }"
echo: yes
register: telnet_output
What i am getting as an output
ansible-playbook 2.7.6
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible-playbook
python version = 2.7.5 (default, Oct 30 2018, 23:45:53) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
Using /etc/ansible/ansible.cfg as config file
/var/lib/awx/projects/6500/hosts did not meet host_list requirements, check plugin documentation if this is unexpected
/var/lib/awx/projects/6500/hosts did not meet script requirements, check plugin documentation if this is unexpected
PLAYBOOK: copy-startup.yml *************************************************************************************************************************************************************************************************************
1 plays in copy-startup.yml
PLAY [all] *****************************************************************************************************************************************************************************************************************************
META: ran handlers
TASK [telnet,login and execute command] ************************************************************************************************************************************************************************************************
task path: /var/lib/awx/projects/6500/copy-startup.yml:6
fatal: [66.90.19.18]: FAILED! => {"changed": true, "cmd": "telnet \"66.90.19.18\"", "delta": "0:00:30.370396", "end": "2019-02-12 10:09:41.473716", "msg": "command exceeded timeout", "rc": null, "start": "2019-02-12 10:09:11.103320", "stdout": "Trying 66.90.19.18...\r\r\nConnected to 66.90.19.18.\r\r\nEscape character is '^]'.\r\r\n\r\n\r\nUser Access Verification\r\n\r\nPassword: \r\nLAB-6500-SUP2T#copy startup-config disk0\r\nDestination filename [disk0]? ", "stdout_lines": ["Trying 66.90.19.18...", "", "Connected to 66.90.19.18.", "", "Escape character is '^]'.", "", "", "", "User Access Verification", "", "Password: ", "LAB-6500-SUP2T#copy startup-config disk0", "Destination filename [disk0]? "]}
...ignoring
PLAY RECAP *****************************************************************************************************************************************************************************************************************************
66.90.19.18 : ok=2 changed=1 unreachable=0 failed=0
It seems to never want to write the Destination Filename[disk0]?
Any ideas
(?i)"Destination filename" matches for string with double quotes.
You need:
responses:
'(?i)password': "{{ password}}"
'(?i)#': copy startup-config disk0
'(?i)Destination filename': "{{ lookup('pipe','date') }"
---
- hosts: '6500'
gather_facts: true
connection: local
tasks:
- name: telnet,login and execute command
ignore_errors: true
expect:
command: telnet "{{ inventory_hostname }}"
responses:
(?i)Password: {{ password }}
(?i)Destination filename [disk0]? : "{{ lookup('pipe','date +%Y-%m-%d-%H-%M') }} {{ inventory_hostname }}"
(?i)#: copy startup-config disk0
(?i){{COMMAND}}: exit
echo: yes
register: telnet_output
This seems to be the best solution to what I need. I changed the order of operations and it was rocking,

Unable to stop and disable firewalld using Ansible

This is my playbook to stop and disable firewalld :
---
- hosts : openstack
connection : ssh
remote_user : ec2-user
become_method : sudo
become : yes
gather_facts : no
tasks :
- command: "{{ item }}"
with_items:
- systemctl stop firewalld
- systemctl disable firewalld
Error :
failed: [ec2-52-87-240-155.compute-1.amazonaws.com] (item=systemctl stop firewalld) => {"changed": true, "cmd": ["systemctl", "stop", "firewalld"], "delta": "0:00:00.009282", "end": "2016-10-27 13:37:20.620051", "failed": true, "item": "systemctl stop firewalld", "rc": 5, "start": "2016-10-27 13:37:20.610769", "stderr": "Failed to stop firewalld.service: Unit firewalld.service not loaded.", "stdout": "", "stdout_lines": [], "warnings": []}
failed: [ec2-52-87-240-155.compute-1.amazonaws.com] (item=systemctl disable firewalld) => {"changed": true, "cmd": ["systemctl", "disable", "firewalld"], "delta": "0:00:00.004876", "end": "2016-10-27 13:37:20.816710", "failed": true, "item": "systemctl disable firewalld", "rc": 1, "start": "2016-10-27 13:37:20.811834", "stderr": "Failed to execute operation: Access denied", "stdout": "", "stdout_lines": [], "warnings": []}
Could anyone help me out with this?
There a few things wrong with this playbook:
don't set a space character between parameter and :
use service module instead of command module
This should work:
---
- hosts: openstack
connection: ssh
remote_user: ec2-user
become: True
gather_facts: False
tasks:
- name: Stop and disable firewalld.
service:
name: firewalld
state: stopped
enabled: False
if firewalld not installed/not running you can simply ignore error message using "failed_when:"
To avoid Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg
- name: 'Disable firewalld Services'
service:
name: "{{item}}"
state: stopped
enabled: no
loop:
- firewalld
register: firewalld_service_disable
failed_when: "firewalld_service_disable|failed and ('Could not find the requested service' not in firewalld_service_disable.msg)"
ignore_errors: yes
tags: test
Below is the anisble playbook execution output
# ansible-playbook main.yml --tags test
PLAY [all] **********************************************************
TASK [Gathering Facts] **********************************************
ok: [ANSIBLECLIENTNODE]
TASK [hardening : Disable firewalld Services] ***********************
changed: [ANSIBLECLIENTNODE] => (item=firewalld)
PLAY RECAP **********************************************************
ANSIBLECLIENTNODE : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
If your ansible version 2.9 and later , follow below "service_facts" method
- name: 'Populate service facts'
service_facts:
- name: 'Disable firewalld Services'
service:
name: "{{item}}"
state: stopped
enabled: no
loop:
- firewalld
when: ansible_facts.services[item] is defined
ignore_errors: yes

Create EC2 Instance by Ansible Failed with ec2: error: unrecognized arguments:

I am newbie to Ansible and follow this tutorial to create a security group and an ec2 instance. The security group is created successfully, but creating ec2 instance is failed by ec2:
error: unrecognized arguments:
/home/ec2-user/.ansible/tmp/ansible-tmp-14244....
I did set up aws credentials and asnsible variables properly as below
# AWS Credentials
export AWS_ACCESS_KEY_ID=xxx
export AWS_SECRET_ACCESS_KEY=xxx
# EC2 Environment Variables
export ANSIBLE_HOSTS=/etc/ansible/ec2.py
export EC2_INI_PATH=/etc/ansible/ec2.ini
The files and output are showed as follow. Any ideas for this issue? Thanks for your Help!
$ cat group_vars/all
# Variables listed here are applicable to all host groups
key_name: sobrr-staging.pem
aws_region: cn-north-1
ami_id: ami-9e0c9ea7
instance_type: m1.small
$ cat basic-create.yml
# Basic provisioning example
- name: Create AWS resources
hosts: localhost
connection: local
gather_facts: False
tasks:
- name: Create security group
ec2_group:
name: my-security-group
description: "A Security group"
region: "{{aws_region}}"
rules:
- proto: tcp
type: ssh
from_port: 22
to_port: 22
cidr_ip: 0.0.0.0/0
rules_egress:
- proto: all
type: all
cidr_ip: 0.0.0.0/0
register: basic_firewall
- name: debug basic_firewall
debug: 'msg="{{ basic_firewall }}"'
- name: create an EC2 instance
local_action:
module: ec2
key_name: "{{key_name}}"
region: "{{aws_region}}"
group_id: "{{basic_firewall.group_id}}"
instance_type: "{{instance_type}}"
image: "{{ami_id}}"
count: 1
wait: yes
register: basic_ec2
- name: debug instance start
debug: 'msg="{{ basic_ec2 }}"'
OUTPUT
ansible-playbook -i /etc/ansible/hosts -vvvv basic-create.yml
/usr/lib64/python2.6/site-packages/Crypto/Util/number.py:57: PowmInsecureWarning: Not using mpz_powm_sec. You should rebuild using libgmp >= 5 to avoid timing attack vulnerability.
_warn("Not using mpz_powm_sec. You should rebuild using libgmp >= 5 to avoid timing attack vulnerability.", PowmInsecureWarning)
PLAY [Create AWS resources] ***************************************************
TASK: [Create security group] *************************************************
<localhost> region=cn-north-1 description=A Security group name=my-security-group
<localhost>
<localhost>
<localhost> u'LANG=en_US.UTF-8 LC_CTYPE=en_US.UTF-8 /usr/bin/python /home/ec2-user/.ansible/tmp/ansible-tmp-1424461765.15-98406246607462/ec2_group; rm -rf /home/ec2-user/.ansible/tmp/ansible-tmp-1424461765.15-98406246607462/ >/dev/null 2>&1']
ok: [localhost] => {"changed": false, "group_id": "sg-63fae101"}
TASK: [debug basic_firewall] **************************************************
ok: [localhost] => {
"msg": "{'invocation': {'module_name': u'ec2_group', 'module_args': ''}, 'changed': False, 'group_id': 'sg-63fae101'}"
}
TASK: [create an EC2 instance] ************************************************
<127.0.0.1> instance_type=m1.small image=ami-9e0c9ea7 group_id=sg-63fae101 region=cn-north-1 key_name=sobrr-staging.pem
<127.0.0.1>
<127.0.0.1>
<127.0.0.1>
<127.0.0.1> u'LANG=en_US.UTF-8 LC_CTYPE=en_US.UTF-8 /usr/bin/env python /home/ec2-user/.ansible/tmp/ansible-tmp-1424461765.54-184834253412898/ec2 /home/ec2-user/.ansible/tmp/ansible-tmp-1424461765.54-184834253412898/arguments; rm -rf /home/ec2-user/.ansible/tmp/ansible-tmp-1424461765.54-184834253412898/ >/dev/null 2>&1']
failed: [localhost -> 127.0.0.1] => {"failed": true, "parsed": false}
usage: ec2 [-h] [--list] [--host HOST] [--refresh-cache]
ec2: error: unrecognized arguments: /home/ec2-user/.ansible/tmp/ansible-tmp-1424461765.54-184834253412898/arguments
FATAL: all hosts have already failed -- aborting
PLAY RECAP ********************************************************************
to retry, use: --limit #/home/ec2-user/basic-create.retry
localhost : ok=2 changed=0 unreachable=0 failed=1
The key_name parameter in Ansible ec2 module refers to the ssh public key you uploaded or created(if you want to reuse the previous key) in your AWS account. You may want to verify it matches the name you specified in the AWS account.
My guess is that the key name in you AWS account is sobrr-staging, not sobrr-staging.pem
Try use sobrr-staging and see how that goes.

Resources