status
stringclasses 1
value | repo_name
stringclasses 31
values | repo_url
stringclasses 31
values | issue_id
int64 1
104k
| title
stringlengths 4
369
| body
stringlengths 0
254k
⌀ | issue_url
stringlengths 37
56
| pull_url
stringlengths 37
54
| before_fix_sha
stringlengths 40
40
| after_fix_sha
stringlengths 40
40
| report_datetime
timestamp[us, tz=UTC] | language
stringclasses 5
values | commit_datetime
timestamp[us, tz=UTC] | updated_file
stringlengths 4
188
| file_content
stringlengths 0
5.12M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
closed
|
electron/electron
|
https://github.com/electron/electron
| 39,658 |
[Bug]: protocol.handle unexpected behavior when request.body is a ReadableStream
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
26.1.0
### What operating system are you using?
Windows
### Operating System Version
Windows 11 22H2
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Iterating on a `ReadableStream` inside `protocol.handle` should not output anything except what is fed into the stream.
### Actual Behavior
Currently, doing this outputs a bunch of `undefined` entries when it shouldn't
```ts
protocol.handle(SCHEME, async (request) => {
console.log("starting stream");
for await (const p of request.body) {
console.log(p);
}
console.log("ending stream");
});
```
For some reason, the first few logs are correct outputting `Uint8Array` as expected but it eventually starts outputting `undefined`:
```
starting stream
Uint8Array(5) [ 84, 104, 105, 115, 32 ]
Uint8Array(3) [ 105, 115, 32 ]
Uint8Array(2) [ 97, 32 ]
Uint8Array(5) [ 115, 108, 111, 119, 32 ]
Uint8Array(8) [
114, 101, 113,
117, 101, 115,
116, 46
]
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
ending stream
```
The main problem is that such a `ReadableStream` is not accepted by `net.fetch` or `fetch` and they crash with the following error:
```
node:52760) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received undefined
at new NodeError (node:internal/errors:399:5)
at _write (node:internal/streams/writable:315:13)
at ClientRequest.write (node:internal/streams/writable:337:10)
at Object.write (node:internal/webstreams/adapters:179:63)
at ensureIsPromise (node:internal/webstreams/util:192:19)
at writableStreamDefaultControllerProcessWrite (node:internal/webstreams/writablestream:1115:5)
at writableStreamDefaultControllerAdvanceQueueIfNeeded (node:internal/webstreams/writablestream:1230:5)
at writableStreamDefaultControllerWrite (node:internal/webstreams/writablestream:1104:3)
at writableStreamDefaultWriterWrite (node:internal/webstreams/writablestream:994:3)
at [kChunk] (node:internal/webstreams/readablestream:1399:28)
(Use `Notesnook --trace-warnings ...` to show where the warning was created)
(node:52760) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 9)
```
On the browser side, I am doing a simple fetch like so:
```ts
function wait(milliseconds: number) {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
const stream = new ReadableStream({
async start(controller) {
await wait(1000);
controller.enqueue("This ");
await wait(1000);
controller.enqueue("is ");
await wait(1000);
controller.enqueue("a ");
await wait(1000);
controller.enqueue("slow ");
await wait(1000);
controller.enqueue("request.");
controller.close();
}
}).pipeThrough(new TextEncoderStream());
const response = await fetch(uploadUrl, {
method: "PUT",
body: stream,
signal,
duplex: "half"
});
```
### Testcase Gist URL
https://gist.github.com/thecodrr/ddabb97be1e93435f9e25dcfab76876e
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/39658
|
https://github.com/electron/electron/pull/41052
|
d4413a8e53590b43d622ad9dce4259be89acbb8c
|
80906c0adb1e1b8103dcdfb8340c4b660b330c25
| 2023-08-25T12:58:59Z |
c++
| 2024-02-16T19:29:29Z |
lib/browser/api/protocol.ts
|
import { ProtocolRequest, session } from 'electron/main';
import { createReadStream } from 'fs';
import { Readable } from 'stream';
import { ReadableStream } from 'stream/web';
// Global protocol APIs.
const { registerSchemesAsPrivileged, getStandardSchemes, Protocol } = process._linkedBinding('electron_browser_protocol');
const ERR_FAILED = -2;
const ERR_UNEXPECTED = -9;
const isBuiltInScheme = (scheme: string) => ['http', 'https', 'file'].includes(scheme);
function makeStreamFromPipe (pipe: any): ReadableStream {
const buf = new Uint8Array(1024 * 1024 /* 1 MB */);
return new ReadableStream({
async pull (controller) {
try {
const rv = await pipe.read(buf);
if (rv > 0) {
controller.enqueue(buf.subarray(0, rv));
} else {
controller.close();
}
} catch (e) {
controller.error(e);
}
}
});
}
function convertToRequestBody (uploadData: ProtocolRequest['uploadData']): RequestInit['body'] {
if (!uploadData) return null;
// Optimization: skip creating a stream if the request is just a single buffer.
if (uploadData.length === 1 && (uploadData[0] as any).type === 'rawData') return uploadData[0].bytes;
const chunks = [...uploadData] as any[]; // TODO: types are wrong
let current: ReadableStreamDefaultReader | null = null;
return new ReadableStream({
pull (controller) {
if (current) {
current.read().then(({ done, value }) => {
controller.enqueue(value);
if (done) current = null;
}, (err) => {
controller.error(err);
});
} else {
if (!chunks.length) { return controller.close(); }
const chunk = chunks.shift()!;
if (chunk.type === 'rawData') { controller.enqueue(chunk.bytes); } else if (chunk.type === 'file') {
current = Readable.toWeb(createReadStream(chunk.filePath, { start: chunk.offset ?? 0, end: chunk.length >= 0 ? chunk.offset + chunk.length : undefined })).getReader();
this.pull!(controller);
} else if (chunk.type === 'stream') {
current = makeStreamFromPipe(chunk.body).getReader();
this.pull!(controller);
}
}
}
}) as RequestInit['body'];
}
// TODO(codebytere): Use Object.hasOwn() once we update to ECMAScript 2022.
function validateResponse (res: Response) {
if (!res || typeof res !== 'object') return false;
if (res.type === 'error') return true;
const exists = (key: string) => Object.hasOwn(res, key);
if (exists('status') && typeof res.status !== 'number') return false;
if (exists('statusText') && typeof res.statusText !== 'string') return false;
if (exists('headers') && typeof res.headers !== 'object') return false;
if (exists('body')) {
if (typeof res.body !== 'object') return false;
if (res.body !== null && !(res.body instanceof ReadableStream)) return false;
}
return true;
}
Protocol.prototype.handle = function (this: Electron.Protocol, scheme: string, handler: (req: Request) => Response | Promise<Response>) {
const register = isBuiltInScheme(scheme) ? this.interceptProtocol : this.registerProtocol;
const success = register.call(this, scheme, async (preq: ProtocolRequest, cb: any) => {
try {
const body = convertToRequestBody(preq.uploadData);
const req = new Request(preq.url, {
headers: preq.headers,
method: preq.method,
referrer: preq.referrer,
body,
duplex: body instanceof ReadableStream ? 'half' : undefined
} as any);
const res = await handler(req);
if (!validateResponse(res)) {
return cb({ error: ERR_UNEXPECTED });
} else if (res.type === 'error') {
cb({ error: ERR_FAILED });
} else {
cb({
data: res.body ? Readable.fromWeb(res.body as ReadableStream<ArrayBufferView>) : null,
headers: res.headers ? Object.fromEntries(res.headers) : {},
statusCode: res.status,
statusText: res.statusText,
mimeType: (res as any).__original_resp?._responseHead?.mimeType
});
}
} catch (e) {
console.error(e);
cb({ error: ERR_UNEXPECTED });
}
});
if (!success) throw new Error(`Failed to register protocol: ${scheme}`);
};
Protocol.prototype.unhandle = function (this: Electron.Protocol, scheme: string) {
const unregister = isBuiltInScheme(scheme) ? this.uninterceptProtocol : this.unregisterProtocol;
if (!unregister.call(this, scheme)) { throw new Error(`Failed to unhandle protocol: ${scheme}`); }
};
Protocol.prototype.isProtocolHandled = function (this: Electron.Protocol, scheme: string) {
const isRegistered = isBuiltInScheme(scheme) ? this.isProtocolIntercepted : this.isProtocolRegistered;
return isRegistered.call(this, scheme);
};
const protocol = {
registerSchemesAsPrivileged,
getStandardSchemes,
registerStringProtocol: (...args) => session.defaultSession.protocol.registerStringProtocol(...args),
registerBufferProtocol: (...args) => session.defaultSession.protocol.registerBufferProtocol(...args),
registerStreamProtocol: (...args) => session.defaultSession.protocol.registerStreamProtocol(...args),
registerFileProtocol: (...args) => session.defaultSession.protocol.registerFileProtocol(...args),
registerHttpProtocol: (...args) => session.defaultSession.protocol.registerHttpProtocol(...args),
registerProtocol: (...args) => session.defaultSession.protocol.registerProtocol(...args),
unregisterProtocol: (...args) => session.defaultSession.protocol.unregisterProtocol(...args),
isProtocolRegistered: (...args) => session.defaultSession.protocol.isProtocolRegistered(...args),
interceptStringProtocol: (...args) => session.defaultSession.protocol.interceptStringProtocol(...args),
interceptBufferProtocol: (...args) => session.defaultSession.protocol.interceptBufferProtocol(...args),
interceptStreamProtocol: (...args) => session.defaultSession.protocol.interceptStreamProtocol(...args),
interceptFileProtocol: (...args) => session.defaultSession.protocol.interceptFileProtocol(...args),
interceptHttpProtocol: (...args) => session.defaultSession.protocol.interceptHttpProtocol(...args),
interceptProtocol: (...args) => session.defaultSession.protocol.interceptProtocol(...args),
uninterceptProtocol: (...args) => session.defaultSession.protocol.uninterceptProtocol(...args),
isProtocolIntercepted: (...args) => session.defaultSession.protocol.isProtocolIntercepted(...args),
handle: (...args) => session.defaultSession.protocol.handle(...args),
unhandle: (...args) => session.defaultSession.protocol.unhandle(...args),
isProtocolHandled: (...args) => session.defaultSession.protocol.isProtocolHandled(...args)
} as typeof Electron.protocol;
export default protocol;
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 39,658 |
[Bug]: protocol.handle unexpected behavior when request.body is a ReadableStream
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
26.1.0
### What operating system are you using?
Windows
### Operating System Version
Windows 11 22H2
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Iterating on a `ReadableStream` inside `protocol.handle` should not output anything except what is fed into the stream.
### Actual Behavior
Currently, doing this outputs a bunch of `undefined` entries when it shouldn't
```ts
protocol.handle(SCHEME, async (request) => {
console.log("starting stream");
for await (const p of request.body) {
console.log(p);
}
console.log("ending stream");
});
```
For some reason, the first few logs are correct outputting `Uint8Array` as expected but it eventually starts outputting `undefined`:
```
starting stream
Uint8Array(5) [ 84, 104, 105, 115, 32 ]
Uint8Array(3) [ 105, 115, 32 ]
Uint8Array(2) [ 97, 32 ]
Uint8Array(5) [ 115, 108, 111, 119, 32 ]
Uint8Array(8) [
114, 101, 113,
117, 101, 115,
116, 46
]
undefined
undefined
undefined
undefined
undefined
undefined
undefined
undefined
ending stream
```
The main problem is that such a `ReadableStream` is not accepted by `net.fetch` or `fetch` and they crash with the following error:
```
node:52760) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received undefined
at new NodeError (node:internal/errors:399:5)
at _write (node:internal/streams/writable:315:13)
at ClientRequest.write (node:internal/streams/writable:337:10)
at Object.write (node:internal/webstreams/adapters:179:63)
at ensureIsPromise (node:internal/webstreams/util:192:19)
at writableStreamDefaultControllerProcessWrite (node:internal/webstreams/writablestream:1115:5)
at writableStreamDefaultControllerAdvanceQueueIfNeeded (node:internal/webstreams/writablestream:1230:5)
at writableStreamDefaultControllerWrite (node:internal/webstreams/writablestream:1104:3)
at writableStreamDefaultWriterWrite (node:internal/webstreams/writablestream:994:3)
at [kChunk] (node:internal/webstreams/readablestream:1399:28)
(Use `Notesnook --trace-warnings ...` to show where the warning was created)
(node:52760) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 9)
```
On the browser side, I am doing a simple fetch like so:
```ts
function wait(milliseconds: number) {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
const stream = new ReadableStream({
async start(controller) {
await wait(1000);
controller.enqueue("This ");
await wait(1000);
controller.enqueue("is ");
await wait(1000);
controller.enqueue("a ");
await wait(1000);
controller.enqueue("slow ");
await wait(1000);
controller.enqueue("request.");
controller.close();
}
}).pipeThrough(new TextEncoderStream());
const response = await fetch(uploadUrl, {
method: "PUT",
body: stream,
signal,
duplex: "half"
});
```
### Testcase Gist URL
https://gist.github.com/thecodrr/ddabb97be1e93435f9e25dcfab76876e
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/39658
|
https://github.com/electron/electron/pull/41052
|
d4413a8e53590b43d622ad9dce4259be89acbb8c
|
80906c0adb1e1b8103dcdfb8340c4b660b330c25
| 2023-08-25T12:58:59Z |
c++
| 2024-02-16T19:29:29Z |
spec/api-protocol-spec.ts
|
import { expect } from 'chai';
import { v4 } from 'uuid';
import { protocol, webContents, WebContents, session, BrowserWindow, ipcMain, net } from 'electron/main';
import * as ChildProcess from 'node:child_process';
import * as path from 'node:path';
import * as url from 'node:url';
import * as http from 'node:http';
import * as fs from 'node:fs';
import * as qs from 'node:querystring';
import * as stream from 'node:stream';
import { EventEmitter, once } from 'node:events';
import { closeAllWindows, closeWindow } from './lib/window-helpers';
import { WebmGenerator } from './lib/video-helpers';
import { listen, defer, ifit } from './lib/spec-helpers';
import { setTimeout } from 'node:timers/promises';
const fixturesPath = path.resolve(__dirname, 'fixtures');
const registerStringProtocol = protocol.registerStringProtocol;
const registerBufferProtocol = protocol.registerBufferProtocol;
const registerFileProtocol = protocol.registerFileProtocol;
const registerStreamProtocol = protocol.registerStreamProtocol;
const interceptStringProtocol = protocol.interceptStringProtocol;
const interceptBufferProtocol = protocol.interceptBufferProtocol;
const interceptHttpProtocol = protocol.interceptHttpProtocol;
const interceptStreamProtocol = protocol.interceptStreamProtocol;
const unregisterProtocol = protocol.unregisterProtocol;
const uninterceptProtocol = protocol.uninterceptProtocol;
const text = 'valar morghulis';
const protocolName = 'no-cors';
const postData = {
name: 'post test',
type: 'string'
};
function getStream (chunkSize = text.length, data: Buffer | string = text) {
// allowHalfOpen required, otherwise Readable.toWeb gets confused and thinks
// the stream isn't done when the readable half ends.
const body = new stream.PassThrough({ allowHalfOpen: false });
async function sendChunks () {
await setTimeout(0); // the stream protocol API breaks if you send data immediately.
let buf = Buffer.from(data as any); // nodejs typings are wrong, Buffer.from can take a Buffer
for (;;) {
body.push(buf.slice(0, chunkSize));
buf = buf.slice(chunkSize);
if (!buf.length) {
break;
}
// emulate some network delay
await setTimeout(10);
}
body.push(null);
}
sendChunks();
return body;
}
function getWebStream (chunkSize = text.length, data: Buffer | string = text): ReadableStream<ArrayBufferView> {
return stream.Readable.toWeb(getStream(chunkSize, data)) as ReadableStream<ArrayBufferView>;
}
// A promise that can be resolved externally.
function deferPromise (): Promise<any> & {resolve: Function, reject: Function} {
let promiseResolve: Function = null as unknown as Function;
let promiseReject: Function = null as unknown as Function;
const promise: any = new Promise((resolve, reject) => {
promiseResolve = resolve;
promiseReject = reject;
});
promise.resolve = promiseResolve;
promise.reject = promiseReject;
return promise;
}
describe('protocol module', () => {
let contents: WebContents;
// NB. sandbox: true is used because it makes navigations much (~8x) faster.
before(() => { contents = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true }); });
after(() => contents.destroy());
async function ajax (url: string, options = {}) {
// Note that we need to do navigation every time after a protocol is
// registered or unregistered, otherwise the new protocol won't be
// recognized by current page when NetworkService is used.
await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html'));
return contents.executeJavaScript(`ajax("${url}", ${JSON.stringify(options)})`);
}
afterEach(() => {
protocol.unregisterProtocol(protocolName);
protocol.uninterceptProtocol('http');
});
describe('protocol.register(Any)Protocol', () => {
it('fails when scheme is already registered', () => {
expect(registerStringProtocol(protocolName, (req, cb) => cb(''))).to.equal(true);
expect(registerBufferProtocol(protocolName, (req, cb) => cb(Buffer.from('')))).to.equal(false);
});
it('does not crash when handler is called twice', async () => {
registerStringProtocol(protocolName, (request, callback) => {
try {
callback(text);
callback('');
} catch {
// Ignore error
}
});
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
it('sends error when callback is called with nothing', async () => {
registerBufferProtocol(protocolName, (req, cb: any) => cb());
await expect(ajax(protocolName + '://fake-host')).to.eventually.be.rejected();
});
it('does not crash when callback is called in next tick', async () => {
registerStringProtocol(protocolName, (request, callback) => {
setImmediate(() => callback(text));
});
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
it('can redirect to the same scheme', async () => {
registerStringProtocol(protocolName, (request, callback) => {
if (request.url === `${protocolName}://fake-host/redirect`) {
callback({
statusCode: 302,
headers: {
Location: `${protocolName}://fake-host`
}
});
} else {
expect(request.url).to.equal(`${protocolName}://fake-host`);
callback('redirected');
}
});
const r = await ajax(`${protocolName}://fake-host/redirect`);
expect(r.data).to.equal('redirected');
});
});
describe('protocol.unregisterProtocol', () => {
it('returns false when scheme does not exist', () => {
expect(unregisterProtocol('not-exist')).to.equal(false);
});
});
for (const [registerStringProtocol, name] of [
[protocol.registerStringProtocol, 'protocol.registerStringProtocol'] as const,
[(protocol as any).registerProtocol as typeof protocol.registerStringProtocol, 'protocol.registerProtocol'] as const
]) {
describe(name, () => {
it('sends string as response', async () => {
registerStringProtocol(protocolName, (request, callback) => callback(text));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
it('sets Access-Control-Allow-Origin', async () => {
registerStringProtocol(protocolName, (request, callback) => callback(text));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
expect(r.headers).to.have.property('access-control-allow-origin', '*');
});
it('sends object as response', async () => {
registerStringProtocol(protocolName, (request, callback) => {
callback({
data: text,
mimeType: 'text/html'
});
});
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
it('fails when sending object other than string', async () => {
const notAString = () => {};
registerStringProtocol(protocolName, (request, callback) => callback(notAString as any));
await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
});
});
}
for (const [registerBufferProtocol, name] of [
[protocol.registerBufferProtocol, 'protocol.registerBufferProtocol'] as const,
[(protocol as any).registerProtocol as typeof protocol.registerBufferProtocol, 'protocol.registerProtocol'] as const
]) {
describe(name, () => {
const buffer = Buffer.from(text);
it('sends Buffer as response', async () => {
registerBufferProtocol(protocolName, (request, callback) => callback(buffer));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
it('sets Access-Control-Allow-Origin', async () => {
registerBufferProtocol(protocolName, (request, callback) => callback(buffer));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
expect(r.headers).to.have.property('access-control-allow-origin', '*');
});
it('sends object as response', async () => {
registerBufferProtocol(protocolName, (request, callback) => {
callback({
data: buffer,
mimeType: 'text/html'
});
});
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
if (name !== 'protocol.registerProtocol') {
it('fails when sending string', async () => {
registerBufferProtocol(protocolName, (request, callback) => callback(text as any));
await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
});
}
});
}
for (const [registerFileProtocol, name] of [
[protocol.registerFileProtocol, 'protocol.registerFileProtocol'] as const,
[(protocol as any).registerProtocol as typeof protocol.registerFileProtocol, 'protocol.registerProtocol'] as const
]) {
describe(name, () => {
const filePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'file1');
const fileContent = fs.readFileSync(filePath);
const normalPath = path.join(fixturesPath, 'pages', 'a.html');
const normalContent = fs.readFileSync(normalPath);
afterEach(closeAllWindows);
if (name === 'protocol.registerFileProtocol') {
it('sends file path as response', async () => {
registerFileProtocol(protocolName, (request, callback) => callback(filePath));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(String(fileContent));
});
}
it('sets Access-Control-Allow-Origin', async () => {
registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath }));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(String(fileContent));
expect(r.headers).to.have.property('access-control-allow-origin', '*');
});
it('sets custom headers', async () => {
registerFileProtocol(protocolName, (request, callback) => callback({
path: filePath,
headers: { 'X-Great-Header': 'sogreat' }
}));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(String(fileContent));
expect(r.headers).to.have.property('x-great-header', 'sogreat');
});
it('can load iframes with custom protocols', async () => {
registerFileProtocol('custom', (request, callback) => {
const filename = request.url.substring(9);
const p = path.join(__dirname, 'fixtures', 'pages', filename);
callback({ path: p });
});
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
const loaded = once(ipcMain, 'loaded-iframe-custom-protocol');
w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'iframe-protocol.html'));
await loaded;
});
it('sends object as response', async () => {
registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath }));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(String(fileContent));
});
it('can send normal file', async () => {
registerFileProtocol(protocolName, (request, callback) => callback({ path: normalPath }));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(String(normalContent));
});
it('fails when sending unexist-file', async () => {
const fakeFilePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'not-exist');
registerFileProtocol(protocolName, (request, callback) => callback({ path: fakeFilePath }));
await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
});
it('fails when sending unsupported content', async () => {
registerFileProtocol(protocolName, (request, callback) => callback(new Date() as any));
await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
});
});
}
for (const [registerHttpProtocol, name] of [
[protocol.registerHttpProtocol, 'protocol.registerHttpProtocol'] as const,
[(protocol as any).registerProtocol as typeof protocol.registerHttpProtocol, 'protocol.registerProtocol'] as const
]) {
describe(name, () => {
it('sends url as response', async () => {
const server = http.createServer((req, res) => {
expect(req.headers.accept).to.not.equal('');
res.end(text);
server.close();
});
const { url } = await listen(server);
registerHttpProtocol(protocolName, (request, callback) => callback({ url }));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
it('fails when sending invalid url', async () => {
registerHttpProtocol(protocolName, (request, callback) => callback({ url: 'url' }));
await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
});
it('fails when sending unsupported content', async () => {
registerHttpProtocol(protocolName, (request, callback) => callback(new Date() as any));
await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
});
it('works when target URL redirects', async () => {
const server = http.createServer((req, res) => {
if (req.url === '/serverRedirect') {
res.statusCode = 301;
res.setHeader('Location', `http://${req.rawHeaders[1]}`);
res.end();
} else {
res.end(text);
}
});
after(() => server.close());
const { port } = await listen(server);
const url = `${protocolName}://fake-host`;
const redirectURL = `http://127.0.0.1:${port}/serverRedirect`;
registerHttpProtocol(protocolName, (request, callback) => callback({ url: redirectURL }));
const r = await ajax(url);
expect(r.data).to.equal(text);
});
it('can access request headers', (done) => {
protocol.registerHttpProtocol(protocolName, (request) => {
try {
expect(request).to.have.property('headers');
done();
} catch (e) {
done(e);
}
});
ajax(protocolName + '://fake-host').catch(() => {});
});
});
}
for (const [registerStreamProtocol, name] of [
[protocol.registerStreamProtocol, 'protocol.registerStreamProtocol'] as const,
[(protocol as any).registerProtocol as typeof protocol.registerStreamProtocol, 'protocol.registerProtocol'] as const
]) {
describe(name, () => {
it('sends Stream as response', async () => {
registerStreamProtocol(protocolName, (request, callback) => callback(getStream()));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
it('sends object as response', async () => {
registerStreamProtocol(protocolName, (request, callback) => callback({ data: getStream() }));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
expect(r.status).to.equal(200);
});
it('sends custom response headers', async () => {
registerStreamProtocol(protocolName, (request, callback) => callback({
data: getStream(3),
headers: {
'x-electron': ['a', 'b']
}
}));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
expect(r.status).to.equal(200);
expect(r.headers).to.have.property('x-electron', 'a, b');
});
it('sends custom status code', async () => {
registerStreamProtocol(protocolName, (request, callback) => callback({
statusCode: 204,
data: null as any
}));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.be.empty('data');
expect(r.status).to.equal(204);
});
it('receives request headers', async () => {
registerStreamProtocol(protocolName, (request, callback) => {
callback({
headers: {
'content-type': 'application/json'
},
data: getStream(5, JSON.stringify(Object.assign({}, request.headers)))
});
});
const r = await ajax(protocolName + '://fake-host', { headers: { 'x-return-headers': 'yes' } });
expect(JSON.parse(r.data)['x-return-headers']).to.equal('yes');
});
it('returns response multiple response headers with the same name', async () => {
registerStreamProtocol(protocolName, (request, callback) => {
callback({
headers: {
header1: ['value1', 'value2'],
header2: 'value3'
},
data: getStream()
});
});
const r = await ajax(protocolName + '://fake-host');
// SUBTLE: when the response headers have multiple values it
// separates values by ", ". When the response headers are incorrectly
// converting an array to a string it separates values by ",".
expect(r.headers).to.have.property('header1', 'value1, value2');
expect(r.headers).to.have.property('header2', 'value3');
});
it('can handle large responses', async () => {
const data = Buffer.alloc(128 * 1024);
registerStreamProtocol(protocolName, (request, callback) => {
callback(getStream(data.length, data));
});
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.have.lengthOf(data.length);
});
it('can handle a stream completing while writing', async () => {
function dumbPassthrough () {
return new stream.Transform({
async transform (chunk, encoding, cb) {
cb(null, chunk);
}
});
}
registerStreamProtocol(protocolName, (request, callback) => {
callback({
statusCode: 200,
headers: { 'Content-Type': 'text/plain' },
data: getStream(1024 * 1024, Buffer.alloc(1024 * 1024 * 2)).pipe(dumbPassthrough())
});
});
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.have.lengthOf(1024 * 1024 * 2);
});
it('can handle next-tick scheduling during read calls', async () => {
const events = new EventEmitter();
function createStream () {
const buffers = [
Buffer.alloc(65536),
Buffer.alloc(65537),
Buffer.alloc(39156)
];
const e = new stream.Readable({ highWaterMark: 0 });
e.push(buffers.shift());
e._read = function () {
process.nextTick(() => this.push(buffers.shift() || null));
};
e.on('end', function () {
events.emit('end');
});
return e;
}
registerStreamProtocol(protocolName, (request, callback) => {
callback({
statusCode: 200,
headers: { 'Content-Type': 'text/plain' },
data: createStream()
});
});
const hasEndedPromise = once(events, 'end');
ajax(protocolName + '://fake-host').catch(() => {});
await hasEndedPromise;
});
it('destroys response streams when aborted before completion', async () => {
const events = new EventEmitter();
registerStreamProtocol(protocolName, (request, callback) => {
const responseStream = new stream.PassThrough();
responseStream.push('data\r\n');
responseStream.on('close', () => {
events.emit('close');
});
callback({
statusCode: 200,
headers: { 'Content-Type': 'text/plain' },
data: responseStream
});
events.emit('respond');
});
const hasRespondedPromise = once(events, 'respond');
const hasClosedPromise = once(events, 'close');
ajax(protocolName + '://fake-host').catch(() => {});
await hasRespondedPromise;
await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html'));
await hasClosedPromise;
});
});
}
describe('protocol.isProtocolRegistered', () => {
it('returns false when scheme is not registered', () => {
const result = protocol.isProtocolRegistered('no-exist');
expect(result).to.be.false('no-exist: is handled');
});
it('returns true for custom protocol', () => {
registerStringProtocol(protocolName, (request, callback) => callback(''));
const result = protocol.isProtocolRegistered(protocolName);
expect(result).to.be.true('custom protocol is handled');
});
});
describe('protocol.isProtocolIntercepted', () => {
it('returns true for intercepted protocol', () => {
interceptStringProtocol('http', (request, callback) => callback(''));
const result = protocol.isProtocolIntercepted('http');
expect(result).to.be.true('intercepted protocol is handled');
});
});
describe('protocol.intercept(Any)Protocol', () => {
it('returns false when scheme is already intercepted', () => {
expect(protocol.interceptStringProtocol('http', (request, callback) => callback(''))).to.equal(true);
expect(protocol.interceptBufferProtocol('http', (request, callback) => callback(Buffer.from('')))).to.equal(false);
});
it('does not crash when handler is called twice', async () => {
interceptStringProtocol('http', (request, callback) => {
try {
callback(text);
callback('');
} catch {
// Ignore error
}
});
const r = await ajax('http://fake-host');
expect(r.data).to.be.equal(text);
});
it('sends error when callback is called with nothing', async () => {
interceptStringProtocol('http', (request, callback: any) => callback());
await expect(ajax('http://fake-host')).to.be.eventually.rejected();
});
});
describe('protocol.interceptStringProtocol', () => {
it('can intercept http protocol', async () => {
interceptStringProtocol('http', (request, callback) => callback(text));
const r = await ajax('http://fake-host');
expect(r.data).to.equal(text);
});
it('can set content-type', async () => {
interceptStringProtocol('http', (request, callback) => {
callback({
mimeType: 'application/json',
data: '{"value": 1}'
});
});
const r = await ajax('http://fake-host');
expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1);
});
it('can set content-type with charset', async () => {
interceptStringProtocol('http', (request, callback) => {
callback({
mimeType: 'application/json; charset=UTF-8',
data: '{"value": 1}'
});
});
const r = await ajax('http://fake-host');
expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1);
});
it('can receive post data', async () => {
interceptStringProtocol('http', (request, callback) => {
const uploadData = request.uploadData![0].bytes.toString();
callback({ data: uploadData });
});
const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) });
expect({ ...qs.parse(r.data) }).to.deep.equal(postData);
});
});
describe('protocol.interceptBufferProtocol', () => {
it('can intercept http protocol', async () => {
interceptBufferProtocol('http', (request, callback) => callback(Buffer.from(text)));
const r = await ajax('http://fake-host');
expect(r.data).to.equal(text);
});
it('can receive post data', async () => {
interceptBufferProtocol('http', (request, callback) => {
const uploadData = request.uploadData![0].bytes;
callback(uploadData);
});
const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) });
expect(qs.parse(r.data)).to.deep.equal({ name: 'post test', type: 'string' });
});
});
describe('protocol.interceptHttpProtocol', () => {
// FIXME(zcbenz): This test was passing because the test itself was wrong,
// I don't know whether it ever passed before and we should take a look at
// it in future.
xit('can send POST request', async () => {
const server = http.createServer((req, res) => {
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
res.end(body);
});
server.close();
});
after(() => server.close());
const { url } = await listen(server);
interceptHttpProtocol('http', (request, callback) => {
const data: Electron.ProtocolResponse = {
url: url,
method: 'POST',
uploadData: {
contentType: 'application/x-www-form-urlencoded',
data: request.uploadData![0].bytes
},
session: undefined
};
callback(data);
});
const r = await ajax('http://fake-host', { type: 'POST', data: postData });
expect({ ...qs.parse(r.data) }).to.deep.equal(postData);
});
it('can use custom session', async () => {
const customSession = session.fromPartition('custom-ses', { cache: false });
customSession.webRequest.onBeforeRequest((details, callback) => {
expect(details.url).to.equal('http://fake-host/');
callback({ cancel: true });
});
after(() => customSession.webRequest.onBeforeRequest(null));
interceptHttpProtocol('http', (request, callback) => {
callback({
url: request.url,
session: customSession
});
});
await expect(ajax('http://fake-host')).to.be.eventually.rejectedWith(Error);
});
it('can access request headers', (done) => {
protocol.interceptHttpProtocol('http', (request) => {
try {
expect(request).to.have.property('headers');
done();
} catch (e) {
done(e);
}
});
ajax('http://fake-host').catch(() => {});
});
});
describe('protocol.interceptStreamProtocol', () => {
it('can intercept http protocol', async () => {
interceptStreamProtocol('http', (request, callback) => callback(getStream()));
const r = await ajax('http://fake-host');
expect(r.data).to.equal(text);
});
it('can receive post data', async () => {
interceptStreamProtocol('http', (request, callback) => {
callback(getStream(3, request.uploadData![0].bytes.toString()));
});
const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) });
expect({ ...qs.parse(r.data) }).to.deep.equal(postData);
});
it('can execute redirects', async () => {
interceptStreamProtocol('http', (request, callback) => {
if (request.url.indexOf('http://fake-host') === 0) {
setTimeout(300).then(() => {
callback({
data: '',
statusCode: 302,
headers: {
Location: 'http://fake-redirect'
}
});
});
} else {
expect(request.url.indexOf('http://fake-redirect')).to.equal(0);
callback(getStream(1, 'redirect'));
}
});
const r = await ajax('http://fake-host');
expect(r.data).to.equal('redirect');
});
it('should discard post data after redirection', async () => {
interceptStreamProtocol('http', (request, callback) => {
if (request.url.indexOf('http://fake-host') === 0) {
setTimeout(300).then(() => {
callback({
statusCode: 302,
headers: {
Location: 'http://fake-redirect'
}
});
});
} else {
expect(request.url.indexOf('http://fake-redirect')).to.equal(0);
callback(getStream(3, request.method));
}
});
const r = await ajax('http://fake-host', { type: 'POST', data: postData });
expect(r.data).to.equal('GET');
});
});
describe('protocol.uninterceptProtocol', () => {
it('returns false when scheme does not exist', () => {
expect(uninterceptProtocol('not-exist')).to.equal(false);
});
it('returns false when scheme is not intercepted', () => {
expect(uninterceptProtocol('http')).to.equal(false);
});
});
describe('protocol.registerSchemeAsPrivileged', () => {
it('does not crash on exit', async () => {
const appPath = path.join(__dirname, 'fixtures', 'api', 'custom-protocol-shutdown.js');
const appProcess = ChildProcess.spawn(process.execPath, ['--enable-logging', appPath]);
let stdout = '';
let stderr = '';
appProcess.stdout.on('data', data => { process.stdout.write(data); stdout += data; });
appProcess.stderr.on('data', data => { process.stderr.write(data); stderr += data; });
const [code] = await once(appProcess, 'exit');
if (code !== 0) {
console.log('Exit code : ', code);
console.log('stdout : ', stdout);
console.log('stderr : ', stderr);
}
expect(code).to.equal(0);
expect(stdout).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED');
expect(stderr).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED');
});
});
describe('protocol.registerSchemesAsPrivileged allowServiceWorkers', () => {
protocol.registerStringProtocol(serviceWorkerScheme, (request, cb) => {
if (request.url.endsWith('.js')) {
cb({
mimeType: 'text/javascript',
charset: 'utf-8',
data: 'console.log("Loaded")'
});
} else {
cb({
mimeType: 'text/html',
charset: 'utf-8',
data: '<!DOCTYPE html>'
});
}
});
after(() => protocol.unregisterProtocol(serviceWorkerScheme));
it('should fail when registering invalid service worker', async () => {
await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`);
await expect(contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.notjs', {scope: './'})`)).to.be.rejected();
});
it('should be able to register service worker for custom scheme', async () => {
await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`);
await contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.js', {scope: './'})`);
});
});
describe('protocol.registerSchemesAsPrivileged standard', () => {
const origin = `${standardScheme}://fake-host`;
const imageURL = `${origin}/test.png`;
const filePath = path.join(fixturesPath, 'pages', 'b.html');
const fileContent = '<img src="/test.png" />';
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
});
afterEach(async () => {
await closeWindow(w);
unregisterProtocol(standardScheme);
w = null as unknown as BrowserWindow;
});
it('resolves relative resources', async () => {
registerFileProtocol(standardScheme, (request, callback) => {
if (request.url === imageURL) {
callback('');
} else {
callback(filePath);
}
});
await w.loadURL(origin);
});
it('resolves absolute resources', async () => {
registerStringProtocol(standardScheme, (request, callback) => {
if (request.url === imageURL) {
callback('');
} else {
callback({
data: fileContent,
mimeType: 'text/html'
});
}
});
await w.loadURL(origin);
});
it('can have fetch working in it', async () => {
const requestReceived = deferPromise();
const server = http.createServer((req, res) => {
res.end();
server.close();
requestReceived.resolve();
});
const { url } = await listen(server);
const content = `<script>fetch(${JSON.stringify(url)})</script>`;
registerStringProtocol(standardScheme, (request, callback) => callback({ data: content, mimeType: 'text/html' }));
await w.loadURL(origin);
await requestReceived;
});
it('can access files through the FileSystem API', (done) => {
const filePath = path.join(fixturesPath, 'pages', 'filesystem.html');
protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath }));
w.loadURL(origin);
ipcMain.once('file-system-error', (event, err) => done(err));
ipcMain.once('file-system-write-end', () => done());
});
it('registers secure, when {secure: true}', (done) => {
const filePath = path.join(fixturesPath, 'pages', 'cache-storage.html');
ipcMain.once('success', () => done());
ipcMain.once('failure', (event, err) => done(err));
protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath }));
w.loadURL(origin);
});
});
describe('protocol.registerSchemesAsPrivileged cors-fetch', function () {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
for (const scheme of [standardScheme, 'cors', 'no-cors', 'no-fetch']) {
protocol.unregisterProtocol(scheme);
}
});
it('supports fetch api by default', async () => {
const url = `file://${fixturesPath}/assets/logo.png`;
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const ok = await w.webContents.executeJavaScript(`fetch(${JSON.stringify(url)}).then(r => r.ok)`);
expect(ok).to.be.true('response ok');
});
it('allows CORS requests by default', async () => {
await allowsCORSRequests('cors', 200, new RegExp(''), () => {
const { ipcRenderer } = require('electron');
fetch('cors://myhost').then(function (response) {
ipcRenderer.send('response', response.status);
}).catch(function () {
ipcRenderer.send('response', 'failed');
});
});
});
// DISABLED-FIXME: Figure out why this test is failing
it('disallows CORS and fetch requests when only supportFetchAPI is specified', async () => {
await allowsCORSRequests('no-cors', ['failed xhr', 'failed fetch'], /has been blocked by CORS policy/, () => {
const { ipcRenderer } = require('electron');
Promise.all([
new Promise(resolve => {
const req = new XMLHttpRequest();
req.onload = () => resolve('loaded xhr');
req.onerror = () => resolve('failed xhr');
req.open('GET', 'no-cors://myhost');
req.send();
}),
fetch('no-cors://myhost')
.then(() => 'loaded fetch')
.catch(() => 'failed fetch')
]).then(([xhr, fetch]) => {
ipcRenderer.send('response', [xhr, fetch]);
});
});
});
it('allows CORS, but disallows fetch requests, when specified', async () => {
await allowsCORSRequests('no-fetch', ['loaded xhr', 'failed fetch'], /Fetch API cannot load/, () => {
const { ipcRenderer } = require('electron');
Promise.all([
new Promise(resolve => {
const req = new XMLHttpRequest();
req.onload = () => resolve('loaded xhr');
req.onerror = () => resolve('failed xhr');
req.open('GET', 'no-fetch://myhost');
req.send();
}),
fetch('no-fetch://myhost')
.then(() => 'loaded fetch')
.catch(() => 'failed fetch')
]).then(([xhr, fetch]) => {
ipcRenderer.send('response', [xhr, fetch]);
});
});
});
async function allowsCORSRequests (corsScheme: string, expected: any, expectedConsole: RegExp, content: Function) {
registerStringProtocol(standardScheme, (request, callback) => {
callback({ data: `<script>(${content})()</script>`, mimeType: 'text/html' });
});
registerStringProtocol(corsScheme, (request, callback) => {
callback('');
});
const newContents = (webContents as typeof ElectronInternal.WebContents).create({
nodeIntegration: true,
contextIsolation: false
});
const consoleMessages: string[] = [];
newContents.on('console-message', (e, level, message) => consoleMessages.push(message));
try {
newContents.loadURL(standardScheme + '://fake-host');
const [, response] = await once(ipcMain, 'response');
expect(response).to.deep.equal(expected);
expect(consoleMessages.join('\n')).to.match(expectedConsole);
} finally {
// This is called in a timeout to avoid a crash that happens when
// calling destroy() in a microtask.
setTimeout().then(() => {
newContents.destroy();
});
}
}
});
describe('protocol.registerSchemesAsPrivileged stream', async function () {
const pagePath = path.join(fixturesPath, 'pages', 'video.html');
const videoSourceImagePath = path.join(fixturesPath, 'video-source-image.webp');
const videoPath = path.join(fixturesPath, 'video.webm');
let w: BrowserWindow;
before(async () => {
// generate test video
const imageBase64 = await fs.promises.readFile(videoSourceImagePath, 'base64');
const imageDataUrl = `data:image/webp;base64,${imageBase64}`;
const encoder = new WebmGenerator(15);
for (let i = 0; i < 30; i++) {
encoder.add(imageDataUrl);
}
await new Promise((resolve, reject) => {
encoder.compile((output:Uint8Array) => {
fs.promises.writeFile(videoPath, output).then(resolve, reject);
});
});
});
after(async () => {
await fs.promises.unlink(videoPath);
});
beforeEach(async function () {
w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
if (!await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')')) {
this.skip();
}
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
await protocol.unregisterProtocol(standardScheme);
await protocol.unregisterProtocol('stream');
});
it('successfully plays videos when content is buffered (stream: false)', async () => {
await streamsResponses(standardScheme, 'play');
});
it('successfully plays videos when streaming content (stream: true)', async () => {
await streamsResponses('stream', 'play');
});
async function streamsResponses (testingScheme: string, expected: any) {
const protocolHandler = (request: any, callback: Function) => {
if (request.url.includes('/video.webm')) {
const stat = fs.statSync(videoPath);
const fileSize = stat.size;
const range = request.headers.Range;
if (range) {
const parts = range.replace(/bytes=/, '').split('-');
const start = parseInt(parts[0], 10);
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
const chunksize = (end - start) + 1;
const headers = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': String(chunksize),
'Content-Type': 'video/webm'
};
callback({ statusCode: 206, headers, data: fs.createReadStream(videoPath, { start, end }) });
} else {
callback({
statusCode: 200,
headers: {
'Content-Length': String(fileSize),
'Content-Type': 'video/webm'
},
data: fs.createReadStream(videoPath)
});
}
} else {
callback({ data: fs.createReadStream(pagePath), headers: { 'Content-Type': 'text/html' }, statusCode: 200 });
}
};
await registerStreamProtocol(standardScheme, protocolHandler);
await registerStreamProtocol('stream', protocolHandler);
const newContents = (webContents as typeof ElectronInternal.WebContents).create({
nodeIntegration: true,
contextIsolation: false
});
try {
newContents.loadURL(testingScheme + '://fake-host');
const [, response] = await once(ipcMain, 'result');
expect(response).to.deep.equal(expected);
} finally {
// This is called in a timeout to avoid a crash that happens when
// calling destroy() in a microtask.
setTimeout().then(() => {
newContents.destroy();
});
}
}
});
describe('protocol.registerSchemesAsPrivileged codeCache', function () {
const temp = require('temp').track();
const appPath = path.join(fixturesPath, 'apps', 'refresh-page');
let w: BrowserWindow;
let codeCachePath: string;
beforeEach(async () => {
w = new BrowserWindow({ show: false });
codeCachePath = temp.path();
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('code cache in custom protocol is disabled by default', async () => {
ChildProcess.spawnSync(process.execPath, [appPath, 'false', codeCachePath]);
expect(fs.readdirSync(path.join(codeCachePath, 'js')).length).to.equal(2);
});
it('codeCache:true enables codeCache in custom protocol', async () => {
ChildProcess.spawnSync(process.execPath, [appPath, 'true', codeCachePath]);
expect(fs.readdirSync(path.join(codeCachePath, 'js')).length).to.above(2);
});
});
describe('handle', () => {
afterEach(closeAllWindows);
it('receives requests to a custom scheme', async () => {
protocol.handle('test-scheme', (req) => new Response('hello ' + req.url));
defer(() => { protocol.unhandle('test-scheme'); });
const resp = await net.fetch('test-scheme://foo');
expect(resp.status).to.equal(200);
});
it('can be unhandled', async () => {
protocol.handle('test-scheme', (req) => new Response('hello ' + req.url));
defer(() => {
try {
// In case of failure, make sure we unhandle. But we should succeed
// :)
protocol.unhandle('test-scheme');
} catch { /* ignore */ }
});
const resp1 = await net.fetch('test-scheme://foo');
expect(resp1.status).to.equal(200);
protocol.unhandle('test-scheme');
await expect(net.fetch('test-scheme://foo')).to.eventually.be.rejectedWith(/ERR_UNKNOWN_URL_SCHEME/);
});
it('receives requests to the existing https scheme', async () => {
protocol.handle('https', (req) => new Response('hello ' + req.url));
defer(() => { protocol.unhandle('https'); });
const body = await net.fetch('https://foo').then(r => r.text());
expect(body).to.equal('hello https://foo/');
});
it('receives requests to the existing file scheme', (done) => {
const filePath = path.join(__dirname, 'fixtures', 'pages', 'a.html');
protocol.handle('file', (req) => {
let file;
if (process.platform === 'win32') {
file = `file:///${filePath.replaceAll('\\', '/')}`;
} else {
file = `file://${filePath}`;
}
if (req.url === file) done();
return new Response(req.url);
});
defer(() => { protocol.unhandle('file'); });
const w = new BrowserWindow();
w.loadFile(filePath);
});
it('receives requests to an existing scheme when navigating', async () => {
protocol.handle('https', (req) => new Response('hello ' + req.url));
defer(() => { protocol.unhandle('https'); });
const w = new BrowserWindow({ show: false });
await w.loadURL('https://localhost');
expect(await w.webContents.executeJavaScript('document.body.textContent')).to.equal('hello https://localhost/');
});
it('can send buffer body', async () => {
protocol.handle('test-scheme', (req) => new Response(Buffer.from('hello ' + req.url)));
defer(() => { protocol.unhandle('test-scheme'); });
const body = await net.fetch('test-scheme://foo').then(r => r.text());
expect(body).to.equal('hello test-scheme://foo');
});
it('can send stream body', async () => {
protocol.handle('test-scheme', () => new Response(getWebStream()));
defer(() => { protocol.unhandle('test-scheme'); });
const body = await net.fetch('test-scheme://foo').then(r => r.text());
expect(body).to.equal(text);
});
it('accepts urls with no hostname in non-standard schemes', async () => {
protocol.handle('test-scheme', (req) => new Response(req.url));
defer(() => { protocol.unhandle('test-scheme'); });
{
const body = await net.fetch('test-scheme://foo').then(r => r.text());
expect(body).to.equal('test-scheme://foo');
}
{
const body = await net.fetch('test-scheme:///foo').then(r => r.text());
expect(body).to.equal('test-scheme:///foo');
}
{
const body = await net.fetch('test-scheme://').then(r => r.text());
expect(body).to.equal('test-scheme://');
}
});
it('accepts urls with a port-like component in non-standard schemes', async () => {
protocol.handle('test-scheme', (req) => new Response(req.url));
defer(() => { protocol.unhandle('test-scheme'); });
{
const body = await net.fetch('test-scheme://foo:30').then(r => r.text());
expect(body).to.equal('test-scheme://foo:30');
}
});
it('normalizes urls in standard schemes', async () => {
// NB. 'app' is registered as a standard scheme in test setup.
protocol.handle('app', (req) => new Response(req.url));
defer(() => { protocol.unhandle('app'); });
{
const body = await net.fetch('app://foo').then(r => r.text());
expect(body).to.equal('app://foo/');
}
{
const body = await net.fetch('app:///foo').then(r => r.text());
expect(body).to.equal('app://foo/');
}
// NB. 'app' is registered with the default scheme type of 'host'.
{
const body = await net.fetch('app://foo:1234').then(r => r.text());
expect(body).to.equal('app://foo/');
}
await expect(net.fetch('app://')).to.be.rejectedWith('Invalid URL');
});
it('fails on URLs with a username', async () => {
// NB. 'app' is registered as a standard scheme in test setup.
protocol.handle('http', (req) => new Response(req.url));
defer(() => { protocol.unhandle('http'); });
await expect(contents.loadURL('http://x@foo:1234')).to.be.rejectedWith(/ERR_UNEXPECTED/);
});
it('normalizes http urls', async () => {
protocol.handle('http', (req) => new Response(req.url));
defer(() => { protocol.unhandle('http'); });
{
const body = await net.fetch('http://foo').then(r => r.text());
expect(body).to.equal('http://foo/');
}
});
it('can send errors', async () => {
protocol.handle('test-scheme', () => Response.error());
defer(() => { protocol.unhandle('test-scheme'); });
await expect(net.fetch('test-scheme://foo')).to.eventually.be.rejectedWith('net::ERR_FAILED');
});
it('handles invalid protocol response status', async () => {
protocol.handle('test-scheme', () => {
return { status: [] } as any;
});
defer(() => { protocol.unhandle('test-scheme'); });
await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED');
});
it('handles invalid protocol response statusText', async () => {
protocol.handle('test-scheme', () => {
return { statusText: false } as any;
});
defer(() => { protocol.unhandle('test-scheme'); });
await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED');
});
it('handles invalid protocol response header parameters', async () => {
protocol.handle('test-scheme', () => {
return { headers: false } as any;
});
defer(() => { protocol.unhandle('test-scheme'); });
await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED');
});
it('handles invalid protocol response body parameters', async () => {
protocol.handle('test-scheme', () => {
return { body: false } as any;
});
defer(() => { protocol.unhandle('test-scheme'); });
await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED');
});
it('handles a synchronous error in the handler', async () => {
protocol.handle('test-scheme', () => { throw new Error('test'); });
defer(() => { protocol.unhandle('test-scheme'); });
await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED');
});
it('handles an asynchronous error in the handler', async () => {
protocol.handle('test-scheme', () => Promise.reject(new Error('rejected promise')));
defer(() => { protocol.unhandle('test-scheme'); });
await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED');
});
it('correctly sets statusCode', async () => {
protocol.handle('test-scheme', () => new Response(null, { status: 201 }));
defer(() => { protocol.unhandle('test-scheme'); });
const resp = await net.fetch('test-scheme://foo');
expect(resp.status).to.equal(201);
});
it('correctly sets content-type and charset', async () => {
protocol.handle('test-scheme', () => new Response(null, { headers: { 'content-type': 'text/html; charset=testcharset' } }));
defer(() => { protocol.unhandle('test-scheme'); });
const resp = await net.fetch('test-scheme://foo');
expect(resp.headers.get('content-type')).to.equal('text/html; charset=testcharset');
});
it('can forward to http', async () => {
const server = http.createServer((req, res) => {
res.end(text);
});
defer(() => { server.close(); });
const { url } = await listen(server);
protocol.handle('test-scheme', () => net.fetch(url));
defer(() => { protocol.unhandle('test-scheme'); });
const body = await net.fetch('test-scheme://foo').then(r => r.text());
expect(body).to.equal(text);
});
it('can forward an http request with headers', async () => {
const server = http.createServer((req, res) => {
res.setHeader('foo', 'bar');
res.end(text);
});
defer(() => { server.close(); });
const { url } = await listen(server);
protocol.handle('test-scheme', (req) => net.fetch(url, { headers: req.headers }));
defer(() => { protocol.unhandle('test-scheme'); });
const resp = await net.fetch('test-scheme://foo');
expect(resp.headers.get('foo')).to.equal('bar');
});
it('can forward to file', async () => {
protocol.handle('test-scheme', () => net.fetch(url.pathToFileURL(path.join(__dirname, 'fixtures', 'hello.txt')).toString()));
defer(() => { protocol.unhandle('test-scheme'); });
const body = await net.fetch('test-scheme://foo').then(r => r.text());
expect(body.trimEnd()).to.equal('hello world');
});
it('can receive simple request body', async () => {
protocol.handle('test-scheme', (req) => new Response(req.body));
defer(() => { protocol.unhandle('test-scheme'); });
const body = await net.fetch('test-scheme://foo', {
method: 'POST',
body: 'foobar'
}).then(r => r.text());
expect(body).to.equal('foobar');
});
it('can receive stream request body', async () => {
protocol.handle('test-scheme', (req) => new Response(req.body));
defer(() => { protocol.unhandle('test-scheme'); });
const body = await net.fetch('test-scheme://foo', {
method: 'POST',
body: getWebStream(),
duplex: 'half' // https://github.com/microsoft/TypeScript/issues/53157
} as any).then(r => r.text());
expect(body).to.equal(text);
});
it('can receive multi-part postData from loadURL', async () => {
protocol.handle('test-scheme', (req) => new Response(req.body));
defer(() => { protocol.unhandle('test-scheme'); });
await contents.loadURL('test-scheme://foo', { postData: [{ type: 'rawData', bytes: Buffer.from('a') }, { type: 'rawData', bytes: Buffer.from('b') }] });
expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('ab');
});
it('can receive file postData from loadURL', async () => {
protocol.handle('test-scheme', (req) => new Response(req.body));
defer(() => { protocol.unhandle('test-scheme'); });
await contents.loadURL('test-scheme://foo', { postData: [{ type: 'file', filePath: path.join(fixturesPath, 'hello.txt'), length: 'hello world\n'.length, offset: 0, modificationTime: 0 }] });
expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('hello world\n');
});
it('can receive file postData from a form', async () => {
protocol.handle('test-scheme', (req) => new Response(req.body));
defer(() => { protocol.unhandle('test-scheme'); });
await contents.loadURL('data:text/html,<form action="test-scheme://foo" method=POST enctype="multipart/form-data"><input name=foo type=file>');
const { debugger: dbg } = contents;
dbg.attach();
const { root } = await dbg.sendCommand('DOM.getDocument');
const { nodeId: fileInputNodeId } = await dbg.sendCommand('DOM.querySelector', { nodeId: root.nodeId, selector: 'input' });
await dbg.sendCommand('DOM.setFileInputFiles', {
nodeId: fileInputNodeId,
files: [
path.join(fixturesPath, 'hello.txt')
]
});
const navigated = once(contents, 'did-finish-load');
await contents.executeJavaScript('document.querySelector("form").submit()');
await navigated;
expect(await contents.executeJavaScript('document.documentElement.textContent')).to.match(/------WebKitFormBoundary.*\nContent-Disposition: form-data; name="foo"; filename="hello.txt"\nContent-Type: text\/plain\n\nhello world\n\n------WebKitFormBoundary.*--\n/);
});
it('can receive streaming fetch upload', async () => {
protocol.handle('no-cors', (req) => new Response(req.body));
defer(() => { protocol.unhandle('no-cors'); });
await contents.loadURL('no-cors://foo');
const fetchBodyResult = await contents.executeJavaScript(`
const stream = new ReadableStream({
async start(controller) {
controller.enqueue('hello world');
controller.close();
},
}).pipeThrough(new TextEncoderStream());
fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text())
`);
expect(fetchBodyResult).to.equal('hello world');
});
it('can receive streaming fetch upload when a webRequest handler is present', async () => {
session.defaultSession.webRequest.onBeforeRequest((details, cb) => {
console.log('webRequest', details.url, details.method);
cb({});
});
defer(() => {
session.defaultSession.webRequest.onBeforeRequest(null);
});
protocol.handle('no-cors', (req) => {
console.log('handle', req.url, req.method);
return new Response(req.body);
});
defer(() => { protocol.unhandle('no-cors'); });
await contents.loadURL('no-cors://foo');
const fetchBodyResult = await contents.executeJavaScript(`
const stream = new ReadableStream({
async start(controller) {
controller.enqueue('hello world');
controller.close();
},
}).pipeThrough(new TextEncoderStream());
fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text())
`);
expect(fetchBodyResult).to.equal('hello world');
});
it('can receive an error from streaming fetch upload', async () => {
protocol.handle('no-cors', (req) => new Response(req.body));
defer(() => { protocol.unhandle('no-cors'); });
await contents.loadURL('no-cors://foo');
const fetchBodyResult = await contents.executeJavaScript(`
const stream = new ReadableStream({
async start(controller) {
controller.error('test')
},
});
fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()).catch(err => err)
`);
expect(fetchBodyResult).to.be.an.instanceOf(Error);
});
it('gets an error from streaming fetch upload when the renderer dies', async () => {
let gotRequest: Function;
const receivedRequest = new Promise<Request>(resolve => { gotRequest = resolve; });
protocol.handle('no-cors', (req) => {
if (/fetch/.test(req.url)) gotRequest(req);
return new Response();
});
defer(() => { protocol.unhandle('no-cors'); });
await contents.loadURL('no-cors://foo');
contents.executeJavaScript(`
const stream = new ReadableStream({
async start(controller) {
window.controller = controller // no GC
},
});
fetch(location.href + '/fetch', {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()).catch(err => err)
`);
const req = await receivedRequest;
contents.destroy();
// Undo .destroy() for the next test
contents = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true });
await expect(req.body!.getReader().read()).to.eventually.be.rejectedWith('net::ERR_FAILED');
});
it('can bypass intercepeted protocol handlers', async () => {
protocol.handle('http', () => new Response('custom'));
defer(() => { protocol.unhandle('http'); });
const server = http.createServer((req, res) => {
res.end('default');
});
defer(() => server.close());
const { url } = await listen(server);
expect(await net.fetch(url, { bypassCustomProtocolHandlers: true }).then(r => r.text())).to.equal('default');
});
it('bypassing custom protocol handlers also bypasses new protocols', async () => {
protocol.handle('app', () => new Response('custom'));
defer(() => { protocol.unhandle('app'); });
await expect(net.fetch('app://foo', { bypassCustomProtocolHandlers: true })).to.be.rejectedWith('net::ERR_UNKNOWN_URL_SCHEME');
});
it('can forward to the original handler', async () => {
protocol.handle('http', (req) => net.fetch(req, { bypassCustomProtocolHandlers: true }));
defer(() => { protocol.unhandle('http'); });
const server = http.createServer((req, res) => {
res.end('hello');
server.close();
});
const { url } = await listen(server);
await contents.loadURL(url);
expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('hello');
});
it('supports sniffing mime type', async () => {
protocol.handle('http', async (req) => {
return net.fetch(req, { bypassCustomProtocolHandlers: true });
});
defer(() => { protocol.unhandle('http'); });
const server = http.createServer((req, res) => {
if (/html/.test(req.url ?? '')) { res.end('<!doctype html><body>hi'); } else { res.end('hi'); }
});
const { url } = await listen(server);
defer(() => server.close());
{
await contents.loadURL(url);
const doc = await contents.executeJavaScript('document.documentElement.outerHTML');
expect(doc).to.match(/white-space: pre-wrap/);
}
{
await contents.loadURL(url + '?html');
const doc = await contents.executeJavaScript('document.documentElement.outerHTML');
expect(doc).to.equal('<html><head></head><body>hi</body></html>');
}
});
// TODO(nornagon): this test doesn't pass on Linux currently, investigate.
ifit(process.platform !== 'linux')('is fast', async () => {
// 128 MB of spaces.
const chunk = new Uint8Array(128 * 1024 * 1024);
chunk.fill(' '.charCodeAt(0));
const server = http.createServer((req, res) => {
// The sniffed mime type for the space-filled chunk will be
// text/plain, which chews up all its performance in the renderer
// trying to wrap lines. Setting content-type to text/html measures
// something closer to just the raw cost of getting the bytes over
// the wire.
res.setHeader('content-type', 'text/html');
res.end(chunk);
});
defer(() => server.close());
const { url } = await listen(server);
const rawTime = await (async () => {
await contents.loadURL(url); // warm
const begin = Date.now();
await contents.loadURL(url);
const end = Date.now();
return end - begin;
})();
// Fetching through an intercepted handler should not be too much slower
// than it would be if the protocol hadn't been intercepted.
protocol.handle('http', async (req) => {
return net.fetch(req, { bypassCustomProtocolHandlers: true });
});
defer(() => { protocol.unhandle('http'); });
const interceptedTime = await (async () => {
const begin = Date.now();
await contents.loadURL(url);
const end = Date.now();
return end - begin;
})();
expect(interceptedTime).to.be.lessThan(rawTime * 1.5);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 41,212 |
[Bug]: `-webkit-app-region: drag` still doesn't works after #41030
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
29.0.0-beta.4
### What operating system are you using?
Windows
### Operating System Version
Windows 11 23H2 (22631)
### What arch are you using?
x64
### Last Known Working Electron version
29.0.0-alpha.7
### Expected Behavior
If `-webkit-app-region: drag` was used, it should be possible to click on the region and drag the `Window`.
### Actual Behavior
It will behave as if the property is not applied.
### Testcase Gist URL
https://gist.github.com/JellyBrick/ec1ef4b79d55bc8a46fcdcd289259996
### Additional Information
In this case (gist), `YouTube` internally overrides the browser's events (like `MouseEvent`, `Event`, etc), which seems to cause `-webkit-app-region: drag` to be ignored. (Until `29.0.0-alpha.7`, `-webkit-app-region: drag` was not ignored and worked fine)
- Related to #40985
|
https://github.com/electron/electron/issues/41212
|
https://github.com/electron/electron/pull/41377
|
7cd23a4900642c5f2eb83c1fd5af42da20e05102
|
136d7e7e6ab1d62ceb1c390ceccf7ddf0225b912
| 2024-02-01T13:01:25Z |
c++
| 2024-02-21T03:10:43Z |
shell/renderer/electron_render_frame_observer.cc
|
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/renderer/electron_render_frame_observer.h"
#include <utility>
#include <vector>
#include "base/command_line.h"
#include "base/memory/ref_counted_memory.h"
#include "base/trace_event/trace_event.h"
#include "content/public/renderer/render_frame.h"
#include "electron/buildflags/buildflags.h"
#include "electron/shell/common/api/api.mojom.h"
#include "ipc/ipc_message_macros.h"
#include "net/base/net_module.h"
#include "net/grit/net_resources.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "shell/common/gin_helper/microtasks_scope.h"
#include "shell/common/options_switches.h"
#include "shell/common/world_ids.h"
#include "shell/renderer/renderer_client_base.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/web_preferences/web_preferences.h"
#include "third_party/blink/public/platform/scheduler/web_agent_group_scheduler.h"
#include "third_party/blink/public/platform/web_isolated_world_info.h"
#include "third_party/blink/public/web/blink.h"
#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_draggable_region.h"
#include "third_party/blink/public/web/web_element.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/public/web/web_script_source.h"
#include "third_party/blink/public/web/web_view.h"
#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h" // nogncheck
#include "ui/base/resource/resource_bundle.h"
namespace electron {
namespace {
scoped_refptr<base::RefCountedMemory> NetResourceProvider(int key) {
if (key == IDR_DIR_HEADER_HTML) {
return ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytes(
IDR_DIR_HEADER_HTML);
}
return nullptr;
}
[[nodiscard]] constexpr bool is_main_world(int world_id) {
return world_id == WorldIDs::MAIN_WORLD_ID;
}
[[nodiscard]] constexpr bool is_isolated_world(int world_id) {
return world_id == WorldIDs::ISOLATED_WORLD_ID;
}
} // namespace
ElectronRenderFrameObserver::ElectronRenderFrameObserver(
content::RenderFrame* frame,
RendererClientBase* renderer_client)
: content::RenderFrameObserver(frame),
render_frame_(frame),
renderer_client_(renderer_client) {
// Initialise resource for directory listing.
net::NetModule::SetResourceProvider(NetResourceProvider);
// App regions are only supported in the main frame.
auto* main_frame = frame->GetMainRenderFrame();
if (main_frame && main_frame == frame)
render_frame_->GetWebView()->SetSupportsAppRegion(true);
}
void ElectronRenderFrameObserver::DidClearWindowObject() {
// Do a delayed Node.js initialization for child window.
// Check DidInstallConditionalFeatures below for the background.
auto* web_frame =
static_cast<blink::WebLocalFrameImpl*>(render_frame_->GetWebFrame());
if (has_delayed_node_initialization_ &&
!web_frame->IsOnInitialEmptyDocument()) {
v8::Isolate* isolate = web_frame->GetAgentGroupScheduler()->Isolate();
v8::HandleScope handle_scope{isolate};
v8::Handle<v8::Context> context = web_frame->MainWorldScriptContext();
v8::MicrotasksScope microtasks_scope(
isolate, context->GetMicrotaskQueue(),
v8::MicrotasksScope::kDoNotRunMicrotasks);
v8::Context::Scope context_scope(context);
// DidClearWindowObject only emits for the main world.
DidInstallConditionalFeatures(context, MAIN_WORLD_ID);
}
renderer_client_->DidClearWindowObject(render_frame_);
}
void ElectronRenderFrameObserver::DidInstallConditionalFeatures(
v8::Handle<v8::Context> context,
int world_id) {
// When a child window is created with window.open, its WebPreferences will
// be copied from its parent, and Chromium will initialize JS context in it
// immediately.
// Normally the WebPreferences is overridden in browser before navigation,
// but this behavior bypasses the browser side navigation and the child
// window will get wrong WebPreferences in the initialization.
// This will end up initializing Node.js in the child window with wrong
// WebPreferences, leads to problem that child window having node integration
// while "nodeIntegration=no" is passed.
// We work around this issue by delaying the child window's initialization of
// Node.js if this is the initial empty document, and only do it when the
// actual page has started to load.
auto* web_frame =
static_cast<blink::WebLocalFrameImpl*>(render_frame_->GetWebFrame());
if (web_frame->Opener() && web_frame->IsOnInitialEmptyDocument()) {
// FIXME(zcbenz): Chromium does not do any browser side navigation for
// window.open('about:blank'), so there is no way to override WebPreferences
// of it. We should not delay Node.js initialization as there will be no
// further loadings.
// Please check http://crbug.com/1215096 for updates which may help remove
// this hack.
GURL url = web_frame->GetDocument().Url();
if (!url.IsAboutBlank()) {
has_delayed_node_initialization_ = true;
return;
}
}
has_delayed_node_initialization_ = false;
auto* isolate = context->GetIsolate();
v8::MicrotasksScope microtasks_scope(
isolate, context->GetMicrotaskQueue(),
v8::MicrotasksScope::kDoNotRunMicrotasks);
if (ShouldNotifyClient(world_id))
renderer_client_->DidCreateScriptContext(context, render_frame_);
auto prefs = render_frame_->GetBlinkPreferences();
bool use_context_isolation = prefs.context_isolation;
// This logic matches the EXPLAINED logic in electron_renderer_client.cc
// to avoid explaining it twice go check that implementation in
// DidCreateScriptContext();
bool is_main_world = electron::is_main_world(world_id);
bool is_main_frame = render_frame_->IsMainFrame();
bool allow_node_in_sub_frames = prefs.node_integration_in_sub_frames;
bool should_create_isolated_context =
use_context_isolation && is_main_world &&
(is_main_frame || allow_node_in_sub_frames);
if (should_create_isolated_context) {
CreateIsolatedWorldContext();
if (!renderer_client_->IsWebViewFrame(context, render_frame_))
renderer_client_->SetupMainWorldOverrides(context, render_frame_);
}
}
void ElectronRenderFrameObserver::DraggableRegionsChanged() {
blink::WebVector<blink::WebDraggableRegion> webregions =
render_frame_->GetWebFrame()->GetDocument().DraggableRegions();
std::vector<mojom::DraggableRegionPtr> regions;
for (auto& webregion : webregions) {
auto region = mojom::DraggableRegion::New();
render_frame_->ConvertViewportToWindow(&webregion.bounds);
region->bounds = webregion.bounds;
region->draggable = webregion.draggable;
regions.push_back(std::move(region));
}
mojo::AssociatedRemote<mojom::ElectronWebContentsUtility>
web_contents_utility_remote;
render_frame_->GetRemoteAssociatedInterfaces()->GetInterface(
&web_contents_utility_remote);
web_contents_utility_remote->UpdateDraggableRegions(std::move(regions));
}
void ElectronRenderFrameObserver::WillReleaseScriptContext(
v8::Local<v8::Context> context,
int world_id) {
if (ShouldNotifyClient(world_id))
renderer_client_->WillReleaseScriptContext(context, render_frame_);
}
void ElectronRenderFrameObserver::OnDestruct() {
delete this;
}
void ElectronRenderFrameObserver::DidMeaningfulLayout(
blink::WebMeaningfulLayout layout_type) {
if (layout_type == blink::WebMeaningfulLayout::kVisuallyNonEmpty) {
mojo::AssociatedRemote<mojom::ElectronWebContentsUtility>
web_contents_utility_remote;
render_frame_->GetRemoteAssociatedInterfaces()->GetInterface(
&web_contents_utility_remote);
web_contents_utility_remote->OnFirstNonEmptyLayout();
}
}
void ElectronRenderFrameObserver::CreateIsolatedWorldContext() {
auto* frame = render_frame_->GetWebFrame();
blink::WebIsolatedWorldInfo info;
// This maps to the name shown in the context combo box in the Console tab
// of the dev tools.
info.human_readable_name =
blink::WebString::FromUTF8("Electron Isolated Context");
// Setup document's origin policy in isolated world
info.security_origin = frame->GetDocument().GetSecurityOrigin();
blink::SetIsolatedWorldInfo(WorldIDs::ISOLATED_WORLD_ID, info);
// Create initial script context in isolated world
blink::WebScriptSource source("void 0");
frame->ExecuteScriptInIsolatedWorld(
WorldIDs::ISOLATED_WORLD_ID, source,
blink::BackForwardCacheAware::kPossiblyDisallow);
}
bool ElectronRenderFrameObserver::ShouldNotifyClient(int world_id) const {
const auto& prefs = render_frame_->GetBlinkPreferences();
// This is necessary because if an iframe is created and a source is not
// set, the iframe loads about:blank and creates a script context for the
// same. We don't want to create a Node.js environment here because if the src
// is later set, the JS necessary to do that triggers illegal access errors
// when the initial about:blank Node.js environment is cleaned up. See:
// https://source.chromium.org/chromium/chromium/src/+/main:content/renderer/render_frame_impl.h;l=870-892;drc=4b6001440a18740b76a1c63fa2a002cc941db394
const bool allow_node_in_sub_frames = prefs.node_integration_in_sub_frames;
if (allow_node_in_sub_frames && !render_frame_->IsMainFrame()) {
if (GURL{render_frame_->GetWebFrame()->GetDocument().Url()}.IsAboutBlank())
return false;
}
if (prefs.context_isolation &&
(render_frame_->IsMainFrame() || allow_node_in_sub_frames))
return is_isolated_world(world_id);
return is_main_world(world_id);
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 41,212 |
[Bug]: `-webkit-app-region: drag` still doesn't works after #41030
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
29.0.0-beta.4
### What operating system are you using?
Windows
### Operating System Version
Windows 11 23H2 (22631)
### What arch are you using?
x64
### Last Known Working Electron version
29.0.0-alpha.7
### Expected Behavior
If `-webkit-app-region: drag` was used, it should be possible to click on the region and drag the `Window`.
### Actual Behavior
It will behave as if the property is not applied.
### Testcase Gist URL
https://gist.github.com/JellyBrick/ec1ef4b79d55bc8a46fcdcd289259996
### Additional Information
In this case (gist), `YouTube` internally overrides the browser's events (like `MouseEvent`, `Event`, etc), which seems to cause `-webkit-app-region: drag` to be ignored. (Until `29.0.0-alpha.7`, `-webkit-app-region: drag` was not ignored and worked fine)
- Related to #40985
|
https://github.com/electron/electron/issues/41212
|
https://github.com/electron/electron/pull/41377
|
7cd23a4900642c5f2eb83c1fd5af42da20e05102
|
136d7e7e6ab1d62ceb1c390ceccf7ddf0225b912
| 2024-02-01T13:01:25Z |
c++
| 2024-02-21T03:10:43Z |
spec/api-browser-window-spec.ts
|
import { expect } from 'chai';
import * as childProcess from 'node:child_process';
import * as path from 'node:path';
import * as fs from 'node:fs';
import * as qs from 'node:querystring';
import * as http from 'node:http';
import * as os from 'node:os';
import { AddressInfo } from 'node:net';
import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main';
import { emittedUntil, emittedNTimes } from './lib/events-helpers';
import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers';
import { closeWindow, closeAllWindows } from './lib/window-helpers';
import { areColorsSimilar, captureScreen, HexColors, getPixelColor, hasCapturableScreen } from './lib/screen-helpers';
import { once } from 'node:events';
import { setTimeout } from 'node:timers/promises';
import { setTimeout as syncSetTimeout } from 'node:timers';
const fixtures = path.resolve(__dirname, 'fixtures');
const mainFixtures = path.resolve(__dirname, 'fixtures');
// Is the display's scale factor possibly causing rounding of pixel coordinate
// values?
const isScaleFactorRounding = () => {
const { scaleFactor } = screen.getPrimaryDisplay();
// Return true if scale factor is non-integer value
if (Math.round(scaleFactor) !== scaleFactor) return true;
// Return true if scale factor is odd number above 2
return scaleFactor > 2 && scaleFactor % 2 === 1;
};
const expectBoundsEqual = (actual: any, expected: any) => {
if (!isScaleFactorRounding()) {
expect(expected).to.deep.equal(actual);
} else if (Array.isArray(actual)) {
expect(actual[0]).to.be.closeTo(expected[0], 1);
expect(actual[1]).to.be.closeTo(expected[1], 1);
} else {
expect(actual.x).to.be.closeTo(expected.x, 1);
expect(actual.y).to.be.closeTo(expected.y, 1);
expect(actual.width).to.be.closeTo(expected.width, 1);
expect(actual.height).to.be.closeTo(expected.height, 1);
}
};
const isBeforeUnload = (event: Event, level: number, message: string) => {
return (message === 'beforeunload');
};
describe('BrowserWindow module', () => {
it('sets the correct class name on the prototype', () => {
expect(BrowserWindow.prototype.constructor.name).to.equal('BrowserWindow');
});
describe('BrowserWindow constructor', () => {
it('allows passing void 0 as the webContents', async () => {
expect(() => {
const w = new BrowserWindow({
show: false,
// apparently void 0 had different behaviour from undefined in the
// issue that this test is supposed to catch.
webContents: void 0 // eslint-disable-line no-void
} as any);
w.destroy();
}).not.to.throw();
});
ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => {
const appPath = path.join(fixtures, 'apps', 'xwindow-icon');
const appProcess = childProcess.spawn(process.execPath, [appPath]);
await once(appProcess, 'exit');
});
it('does not crash or throw when passed an invalid icon', async () => {
expect(() => {
const w = new BrowserWindow({
icon: undefined
} as any);
w.destroy();
}).not.to.throw();
});
});
describe('garbage collection', () => {
const v8Util = process._linkedBinding('electron_common_v8_util');
afterEach(closeAllWindows);
it('window does not get garbage collected when opened', async () => {
const w = new BrowserWindow({ show: false });
// Keep a weak reference to the window.
const wr = new WeakRef(w);
await setTimeout();
// Do garbage collection, since |w| is not referenced in this closure
// it would be gone after next call if there is no other reference.
v8Util.requestGarbageCollectionForTesting();
await setTimeout();
expect(wr.deref()).to.not.be.undefined();
});
});
describe('BrowserWindow.close()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('should work if called when a messageBox is showing', async () => {
const closed = once(w, 'closed');
dialog.showMessageBox(w, { message: 'Hello Error' });
w.close();
await closed;
});
it('closes window without rounded corners', async () => {
await closeWindow(w);
w = new BrowserWindow({ show: false, frame: false, roundedCorners: false });
const closed = once(w, 'closed');
w.close();
await closed;
});
it('should not crash if called after webContents is destroyed', () => {
w.webContents.destroy();
w.webContents.on('destroyed', () => w.close());
});
it('should allow access to id after destruction', async () => {
const closed = once(w, 'closed');
w.destroy();
await closed;
expect(w.id).to.be.a('number');
});
it('should emit unload handler', async () => {
await w.loadFile(path.join(fixtures, 'api', 'unload.html'));
const closed = once(w, 'closed');
w.close();
await closed;
const test = path.join(fixtures, 'api', 'unload');
const content = fs.readFileSync(test);
fs.unlinkSync(test);
expect(String(content)).to.equal('unload');
});
it('should emit beforeunload handler', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.close();
await once(w.webContents, '-before-unload-fired');
});
it('should not crash when keyboard event is sent before closing', async () => {
await w.loadURL('data:text/html,pls no crash');
const closed = once(w, 'closed');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
w.close();
await closed;
});
describe('when invoked synchronously inside navigation observer', () => {
let server: http.Server;
let url: string;
before(async () => {
server = http.createServer((request, response) => {
switch (request.url) {
case '/net-error':
response.destroy();
break;
case '/301':
response.statusCode = 301;
response.setHeader('Location', '/200');
response.end();
break;
case '/200':
response.statusCode = 200;
response.end('hello');
break;
case '/title':
response.statusCode = 200;
response.end('<title>Hello</title>');
break;
default:
throw new Error(`unsupported endpoint: ${request.url}`);
}
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
const events = [
{ name: 'did-start-loading', path: '/200' },
{ name: 'dom-ready', path: '/200' },
{ name: 'page-title-updated', path: '/title' },
{ name: 'did-stop-loading', path: '/200' },
{ name: 'did-finish-load', path: '/200' },
{ name: 'did-frame-finish-load', path: '/200' },
{ name: 'did-fail-load', path: '/net-error' }
];
for (const { name, path } of events) {
it(`should not crash when closed during ${name}`, async () => {
const w = new BrowserWindow({ show: false });
w.webContents.once((name as any), () => {
w.close();
});
const destroyed = once(w.webContents, 'destroyed');
w.webContents.loadURL(url + path);
await destroyed;
});
}
});
});
describe('window.close()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('should emit unload event', async () => {
w.loadFile(path.join(fixtures, 'api', 'close.html'));
await once(w, 'closed');
const test = path.join(fixtures, 'api', 'close');
const content = fs.readFileSync(test).toString();
fs.unlinkSync(test);
expect(content).to.equal('close');
});
it('should emit beforeunload event', async function () {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.webContents.executeJavaScript('window.close()', true);
await once(w.webContents, '-before-unload-fired');
});
});
describe('BrowserWindow.destroy()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('prevents users to access methods of webContents', async () => {
const contents = w.webContents;
w.destroy();
await new Promise(setImmediate);
expect(() => {
contents.getProcessId();
}).to.throw('Object has been destroyed');
});
it('should not crash when destroying windows with pending events', () => {
const focusListener = () => { };
app.on('browser-window-focus', focusListener);
const windowCount = 3;
const windowOptions = {
show: false,
width: 400,
height: 400,
webPreferences: {
backgroundThrottling: false
}
};
const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions));
for (const win of windows) win.show();
for (const win of windows) win.focus();
for (const win of windows) win.destroy();
app.removeListener('browser-window-focus', focusListener);
});
});
describe('BrowserWindow.loadURL(url)', () => {
let w: BrowserWindow;
const scheme = 'other';
const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js');
before(() => {
protocol.registerFileProtocol(scheme, (request, callback) => {
callback(srcPath);
});
});
after(() => {
protocol.unregisterProtocol(scheme);
});
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
let server: http.Server;
let url: string;
let postData = null as any;
before(async () => {
const filePath = path.join(fixtures, 'pages', 'a.html');
const fileStats = fs.statSync(filePath);
postData = [
{
type: 'rawData',
bytes: Buffer.from('username=test&file=')
},
{
type: 'file',
filePath: filePath,
offset: 0,
length: fileStats.size,
modificationTime: fileStats.mtime.getTime() / 1000
}
];
server = http.createServer((req, res) => {
function respond () {
if (req.method === 'POST') {
let body = '';
req.on('data', (data) => {
if (data) body += data;
});
req.on('end', () => {
const parsedData = qs.parse(body);
fs.readFile(filePath, (err, data) => {
if (err) return;
if (parsedData.username === 'test' &&
parsedData.file === data.toString()) {
res.end();
}
});
});
} else if (req.url === '/302') {
res.setHeader('Location', '/200');
res.statusCode = 302;
res.end();
} else {
res.end();
}
}
setTimeout(req.url && req.url.includes('slow') ? 200 : 0).then(respond);
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
it('should emit did-start-loading event', async () => {
const didStartLoading = once(w.webContents, 'did-start-loading');
w.loadURL('about:blank');
await didStartLoading;
});
it('should emit ready-to-show event', async () => {
const readyToShow = once(w, 'ready-to-show');
w.loadURL('about:blank');
await readyToShow;
});
// DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what
// changed and adjust the test.
it('should emit did-fail-load event for files that do not exist', async () => {
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadURL('file://a.txt');
const [, code, desc,, isMainFrame] = await didFailLoad;
expect(code).to.equal(-6);
expect(desc).to.equal('ERR_FILE_NOT_FOUND');
expect(isMainFrame).to.equal(true);
});
it('should emit did-fail-load event for invalid URL', async () => {
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadURL('http://example:port');
const [, code, desc,, isMainFrame] = await didFailLoad;
expect(desc).to.equal('ERR_INVALID_URL');
expect(code).to.equal(-300);
expect(isMainFrame).to.equal(true);
});
it('should not emit did-fail-load for a successfully loaded media file', async () => {
w.webContents.on('did-fail-load', () => {
expect.fail('did-fail-load should not emit on media file loads');
});
const mediaStarted = once(w.webContents, 'media-started-playing');
w.loadFile(path.join(fixtures, 'cat-spin.mp4'));
await mediaStarted;
});
it('should set `mainFrame = false` on did-fail-load events in iframes', async () => {
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html'));
const [,,,, isMainFrame] = await didFailLoad;
expect(isMainFrame).to.equal(false);
});
it('does not crash in did-fail-provisional-load handler', (done) => {
w.webContents.once('did-fail-provisional-load', () => {
w.loadURL('http://127.0.0.1:11111');
done();
});
w.loadURL('http://127.0.0.1:11111');
});
it('should emit did-fail-load event for URL exceeding character limit', async () => {
const data = Buffer.alloc(2 * 1024 * 1024).toString('base64');
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadURL(`data:image/png;base64,${data}`);
const [, code, desc,, isMainFrame] = await didFailLoad;
expect(desc).to.equal('ERR_INVALID_URL');
expect(code).to.equal(-300);
expect(isMainFrame).to.equal(true);
});
it('should return a promise', () => {
const p = w.loadURL('about:blank');
expect(p).to.have.property('then');
});
it('should return a promise that resolves', async () => {
await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled();
});
it('should return a promise that rejects on a load failure', async () => {
const data = Buffer.alloc(2 * 1024 * 1024).toString('base64');
const p = w.loadURL(`data:image/png;base64,${data}`);
await expect(p).to.eventually.be.rejected;
});
it('should return a promise that resolves even if pushState occurs during navigation', async () => {
const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>');
await expect(p).to.eventually.be.fulfilled;
});
describe('POST navigations', () => {
afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); });
it('supports specifying POST data', async () => {
await w.loadURL(url, { postData });
});
it('sets the content type header on URL encoded forms', async () => {
await w.loadURL(url);
const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => {
w.webContents.session.webRequest.onBeforeSendHeaders((details) => {
resolve(details);
});
});
w.webContents.executeJavaScript(`
form = document.createElement('form')
document.body.appendChild(form)
form.method = 'POST'
form.submit()
`);
const details = await requestDetails;
expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded');
});
it('sets the content type header on multi part forms', async () => {
await w.loadURL(url);
const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => {
w.webContents.session.webRequest.onBeforeSendHeaders((details) => {
resolve(details);
});
});
w.webContents.executeJavaScript(`
form = document.createElement('form')
document.body.appendChild(form)
form.method = 'POST'
form.enctype = 'multipart/form-data'
file = document.createElement('input')
file.type = 'file'
file.name = 'file'
form.appendChild(file)
form.submit()
`);
const details = await requestDetails;
expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true);
});
});
it('should support base url for data urls', async () => {
await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` });
expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong');
});
});
for (const sandbox of [false, true]) {
describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('will-navigate event', () => {
let server: http.Server;
let url: string;
before(async () => {
server = http.createServer((req, res) => {
if (req.url === '/navigate-top') {
res.end('<a target=_top href="/">navigate _top</a>');
} else {
res.end('');
}
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
it('allows the window to be closed from the event listener', async () => {
const event = once(w.webContents, 'will-navigate');
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
await event;
w.close();
});
it('can be prevented', (done) => {
let willNavigate = false;
w.webContents.once('will-navigate', (e) => {
willNavigate = true;
e.preventDefault();
});
w.webContents.on('did-stop-loading', () => {
if (willNavigate) {
// i.e. it shouldn't have had '?navigated' appended to it.
try {
expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true();
done();
} catch (e) {
done(e);
}
}
});
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
});
it('is triggered when navigating from file: to http:', async () => {
await w.loadFile(path.join(fixtures, 'api', 'blank.html'));
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-navigate', (e, url) => {
e.preventDefault();
resolve(url);
});
});
expect(navigatedTo).to.equal(url + '/');
expect(w.webContents.getURL()).to.match(/^file:/);
});
it('is triggered when navigating from about:blank to http:', async () => {
await w.loadURL('about:blank');
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-navigate', (e, url) => {
e.preventDefault();
resolve(url);
});
});
expect(navigatedTo).to.equal(url + '/');
expect(w.webContents.getURL()).to.equal('about:blank');
});
it('is triggered when a cross-origin iframe navigates _top', async () => {
w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`);
await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame);
let initiator: WebFrameMain | undefined;
w.webContents.on('will-navigate', (e) => {
initiator = e.initiator;
});
const subframe = w.webContents.mainFrame.frames[0];
subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true);
await once(w.webContents, 'did-navigate');
expect(initiator).not.to.be.undefined();
expect(initiator).to.equal(subframe);
});
it('is triggered when navigating from chrome: to http:', async () => {
let hasEmittedWillNavigate = false;
const willNavigatePromise = new Promise((resolve) => {
w.webContents.once('will-navigate', e => {
e.preventDefault();
hasEmittedWillNavigate = true;
resolve(e.url);
});
});
await w.loadURL('chrome://gpu');
// shouldn't emit for browser-initiated request via loadURL
expect(hasEmittedWillNavigate).to.equal(false);
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await willNavigatePromise;
expect(navigatedTo).to.equal(url + '/');
expect(w.webContents.getURL()).to.equal('chrome://gpu/');
});
});
describe('will-frame-navigate event', () => {
let server = null as unknown as http.Server;
let url = null as unknown as string;
before(async () => {
server = http.createServer((req, res) => {
if (req.url === '/navigate-top') {
res.end('<a target=_top href="/">navigate _top</a>');
} else if (req.url === '/navigate-iframe') {
res.end('<a href="/test">navigate iframe</a>');
} else if (req.url === '/navigate-iframe?navigated') {
res.end('Successfully navigated');
} else if (req.url === '/navigate-iframe-immediately') {
res.end(`
<script type="text/javascript" charset="utf-8">
location.href += '?navigated'
</script>
`);
} else if (req.url === '/navigate-iframe-immediately?navigated') {
res.end('Successfully navigated');
} else {
res.end('');
}
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
it('allows the window to be closed from the event listener', (done) => {
w.webContents.once('will-frame-navigate', () => {
w.close();
done();
});
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
});
it('can be prevented', (done) => {
let willNavigate = false;
w.webContents.once('will-frame-navigate', (e) => {
willNavigate = true;
e.preventDefault();
});
w.webContents.on('did-stop-loading', () => {
if (willNavigate) {
// i.e. it shouldn't have had '?navigated' appended to it.
try {
expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true();
done();
} catch (e) {
done(e);
}
}
});
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
});
it('can be prevented when navigating subframe', (done) => {
let willNavigate = false;
w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => {
if (isMainFrame) return;
w.webContents.once('will-frame-navigate', (e) => {
willNavigate = true;
e.preventDefault();
});
w.webContents.on('did-stop-loading', () => {
const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
expect(frame).to.not.be.undefined();
if (willNavigate) {
// i.e. it shouldn't have had '?navigated' appended to it.
try {
expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true();
done();
} catch (e) {
done(e);
}
}
});
});
w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`);
});
it('is triggered when navigating from file: to http:', async () => {
await w.loadFile(path.join(fixtures, 'api', 'blank.html'));
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-frame-navigate', (e) => {
e.preventDefault();
resolve(e.url);
});
});
expect(navigatedTo).to.equal(url + '/');
expect(w.webContents.getURL()).to.match(/^file:/);
});
it('is triggered when navigating from about:blank to http:', async () => {
await w.loadURL('about:blank');
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-frame-navigate', (e) => {
e.preventDefault();
resolve(e.url);
});
});
expect(navigatedTo).to.equal(url + '/');
expect(w.webContents.getURL()).to.equal('about:blank');
});
it('is triggered when a cross-origin iframe navigates _top', async () => {
await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`);
await setTimeout(1000);
let willFrameNavigateEmitted = false;
let isMainFrameValue;
w.webContents.on('will-frame-navigate', (event) => {
willFrameNavigateEmitted = true;
isMainFrameValue = event.isMainFrame;
});
const didNavigatePromise = once(w.webContents, 'did-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: iframeTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await didNavigatePromise;
expect(willFrameNavigateEmitted).to.be.true();
expect(isMainFrameValue).to.be.true();
});
it('is triggered when a cross-origin iframe navigates itself', async () => {
await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`);
await setTimeout(1000);
let willNavigateEmitted = false;
let isMainFrameValue;
w.webContents.on('will-frame-navigate', (event) => {
willNavigateEmitted = true;
isMainFrameValue = event.isMainFrame;
});
const didNavigatePromise = once(w.webContents, 'did-frame-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: iframeTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await didNavigatePromise;
expect(willNavigateEmitted).to.be.true();
expect(isMainFrameValue).to.be.false();
});
it('can cancel when a cross-origin iframe navigates itself', async () => {
});
});
describe('will-redirect event', () => {
let server: http.Server;
let url: string;
before(async () => {
server = http.createServer((req, res) => {
if (req.url === '/302') {
res.setHeader('Location', '/200');
res.statusCode = 302;
res.end();
} else if (req.url === '/navigate-302') {
res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`);
} else {
res.end();
}
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
it('is emitted on redirects', async () => {
const willRedirect = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/302`);
await willRedirect;
});
it('is emitted after will-navigate on redirects', async () => {
let navigateCalled = false;
w.webContents.on('will-navigate', () => {
navigateCalled = true;
});
const willRedirect = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/navigate-302`);
await willRedirect;
expect(navigateCalled).to.equal(true, 'should have called will-navigate first');
});
it('is emitted before did-stop-loading on redirects', async () => {
let stopCalled = false;
w.webContents.on('did-stop-loading', () => {
stopCalled = true;
});
const willRedirect = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/302`);
await willRedirect;
expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first');
});
it('allows the window to be closed from the event listener', async () => {
const event = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/302`);
await event;
w.close();
});
it('can be prevented', (done) => {
w.webContents.once('will-redirect', (event) => {
event.preventDefault();
});
w.webContents.on('will-navigate', (e, u) => {
expect(u).to.equal(`${url}/302`);
});
w.webContents.on('did-stop-loading', () => {
try {
expect(w.webContents.getURL()).to.equal(
`${url}/navigate-302`,
'url should not have changed after navigation event'
);
done();
} catch (e) {
done(e);
}
});
w.webContents.on('will-redirect', (e, u) => {
try {
expect(u).to.equal(`${url}/200`);
} catch (e) {
done(e);
}
});
w.loadURL(`${url}/navigate-302`);
});
});
describe('ordering', () => {
let server = null as unknown as http.Server;
let url = null as unknown as string;
const navigationEvents = [
'did-start-navigation',
'did-navigate-in-page',
'will-frame-navigate',
'will-navigate',
'will-redirect',
'did-redirect-navigation',
'did-frame-navigate',
'did-navigate'
];
before(async () => {
server = http.createServer((req, res) => {
if (req.url === '/navigate') {
res.end('<a href="/">navigate</a>');
} else if (req.url === '/redirect') {
res.end('<a href="/redirect2">redirect</a>');
} else if (req.url === '/redirect2') {
res.statusCode = 302;
res.setHeader('location', url);
res.end();
} else if (req.url === '/in-page') {
res.end('<a href="#in-page">redirect</a><div id="in-page"></div>');
} else {
res.end('');
}
});
url = (await listen(server)).url;
});
it('for initial navigation, event order is consistent', async () => {
const firedEvents: string[] = [];
const expectedEventOrder = [
'did-start-navigation',
'did-frame-navigate',
'did-navigate'
];
const allEvents = Promise.all(navigationEvents.map(event =>
once(w.webContents, event).then(() => firedEvents.push(event))
));
const timeout = setTimeout(1000);
w.loadURL(url);
await Promise.race([allEvents, timeout]);
expect(firedEvents).to.deep.equal(expectedEventOrder);
});
it('for second navigation, event order is consistent', async () => {
const firedEvents: string[] = [];
const expectedEventOrder = [
'did-start-navigation',
'will-frame-navigate',
'will-navigate',
'did-frame-navigate',
'did-navigate'
];
w.loadURL(url + '/navigate');
await once(w.webContents, 'did-navigate');
await setTimeout(2000);
Promise.all(navigationEvents.map(event =>
once(w.webContents, event).then(() => firedEvents.push(event))
));
const navigationFinished = once(w.webContents, 'did-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: pageTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await navigationFinished;
expect(firedEvents).to.deep.equal(expectedEventOrder);
});
it('when navigating with redirection, event order is consistent', async () => {
const firedEvents: string[] = [];
const expectedEventOrder = [
'did-start-navigation',
'will-frame-navigate',
'will-navigate',
'will-redirect',
'did-redirect-navigation',
'did-frame-navigate',
'did-navigate'
];
w.loadURL(url + '/redirect');
await once(w.webContents, 'did-navigate');
await setTimeout(2000);
Promise.all(navigationEvents.map(event =>
once(w.webContents, event).then(() => firedEvents.push(event))
));
const navigationFinished = once(w.webContents, 'did-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: pageTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await navigationFinished;
expect(firedEvents).to.deep.equal(expectedEventOrder);
});
it('when navigating in-page, event order is consistent', async () => {
const firedEvents: string[] = [];
const expectedEventOrder = [
'did-start-navigation',
'did-navigate-in-page'
];
w.loadURL(url + '/in-page');
await once(w.webContents, 'did-navigate');
await setTimeout(2000);
Promise.all(navigationEvents.map(event =>
once(w.webContents, event).then(() => firedEvents.push(event))
));
const navigationFinished = once(w.webContents, 'did-navigate-in-page');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: pageTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await navigationFinished;
expect(firedEvents).to.deep.equal(expectedEventOrder);
});
});
});
}
describe('focus and visibility', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('BrowserWindow.show()', () => {
it('should focus on window', async () => {
const p = once(w, 'focus');
w.show();
await p;
expect(w.isFocused()).to.equal(true);
});
it('should make the window visible', async () => {
const p = once(w, 'focus');
w.show();
await p;
expect(w.isVisible()).to.equal(true);
});
it('emits when window is shown', async () => {
const show = once(w, 'show');
w.show();
await show;
expect(w.isVisible()).to.equal(true);
});
});
describe('BrowserWindow.hide()', () => {
it('should defocus on window', () => {
w.hide();
expect(w.isFocused()).to.equal(false);
});
it('should make the window not visible', () => {
w.show();
w.hide();
expect(w.isVisible()).to.equal(false);
});
it('emits when window is hidden', async () => {
const shown = once(w, 'show');
w.show();
await shown;
const hidden = once(w, 'hide');
w.hide();
await hidden;
expect(w.isVisible()).to.equal(false);
});
});
describe('BrowserWindow.minimize()', () => {
// TODO(codebytere): Enable for Linux once maximize/minimize events work in CI.
ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => {
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
expect(w.isMinimized()).to.equal(true);
expect(w.isVisible()).to.equal(false);
});
});
describe('BrowserWindow.showInactive()', () => {
it('should not focus on window', () => {
w.showInactive();
expect(w.isFocused()).to.equal(false);
});
// TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests
ifit(process.platform !== 'linux')('should not restore maximized windows', async () => {
const maximize = once(w, 'maximize');
const shown = once(w, 'show');
w.maximize();
// TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden
if (process.platform !== 'darwin') {
await maximize;
} else {
await setTimeout(1000);
}
w.showInactive();
await shown;
expect(w.isMaximized()).to.equal(true);
});
ifit(process.platform === 'darwin')('should attach child window to parent', async () => {
const wShow = once(w, 'show');
w.show();
await wShow;
const c = new BrowserWindow({ show: false, parent: w });
const cShow = once(c, 'show');
c.showInactive();
await cShow;
// verifying by checking that the child tracks the parent's visibility
const minimized = once(w, 'minimize');
w.minimize();
await minimized;
expect(w.isVisible()).to.be.false('parent is visible');
expect(c.isVisible()).to.be.false('child is visible');
const restored = once(w, 'restore');
w.restore();
await restored;
expect(w.isVisible()).to.be.true('parent is visible');
expect(c.isVisible()).to.be.true('child is visible');
closeWindow(c);
});
});
describe('BrowserWindow.focus()', () => {
it('does not make the window become visible', () => {
expect(w.isVisible()).to.equal(false);
w.focus();
expect(w.isVisible()).to.equal(false);
});
ifit(process.platform !== 'win32')('focuses a blurred window', async () => {
{
const isBlurred = once(w, 'blur');
const isShown = once(w, 'show');
w.show();
w.blur();
await isShown;
await isBlurred;
}
expect(w.isFocused()).to.equal(false);
w.focus();
expect(w.isFocused()).to.equal(true);
});
ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => {
const w1 = new BrowserWindow({ show: false });
const w2 = new BrowserWindow({ show: false });
const w3 = new BrowserWindow({ show: false });
{
const isFocused3 = once(w3, 'focus');
const isShown1 = once(w1, 'show');
const isShown2 = once(w2, 'show');
const isShown3 = once(w3, 'show');
w1.show();
w2.show();
w3.show();
await isShown1;
await isShown2;
await isShown3;
await isFocused3;
}
// TODO(RaisinTen): Investigate why this assertion fails only on Linux.
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(true);
w1.focus();
expect(w1.isFocused()).to.equal(true);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(false);
w2.focus();
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(true);
expect(w3.isFocused()).to.equal(false);
w3.focus();
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(true);
{
const isClosed1 = once(w1, 'closed');
const isClosed2 = once(w2, 'closed');
const isClosed3 = once(w3, 'closed');
w1.destroy();
w2.destroy();
w3.destroy();
await isClosed1;
await isClosed2;
await isClosed3;
}
});
ifit(process.platform === 'darwin')('it does not activate the app if focusing an inactive panel', async () => {
// Show to focus app, then remove existing window
w.show();
w.destroy();
// We first need to resign app focus for this test to work
const isInactive = once(app, 'did-resign-active');
childProcess.execSync('osascript -e \'tell application "Finder" to activate\'');
await isInactive;
// Create new window
w = new BrowserWindow({
type: 'panel',
height: 200,
width: 200,
center: true,
show: false
});
const isShow = once(w, 'show');
const isFocus = once(w, 'focus');
w.showInactive();
w.focus();
await isShow;
await isFocus;
const getActiveAppOsa = 'tell application "System Events" to get the name of the first process whose frontmost is true';
const activeApp = childProcess.execSync(`osascript -e '${getActiveAppOsa}'`).toString().trim();
expect(activeApp).to.equal('Finder');
});
});
// TODO(RaisinTen): Make this work on Windows too.
// Refs: https://github.com/electron/electron/issues/20464.
ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => {
it('removes focus from window', async () => {
{
const isFocused = once(w, 'focus');
const isShown = once(w, 'show');
w.show();
await isShown;
await isFocused;
}
expect(w.isFocused()).to.equal(true);
w.blur();
expect(w.isFocused()).to.equal(false);
});
ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => {
const w1 = new BrowserWindow({ show: false });
const w2 = new BrowserWindow({ show: false });
const w3 = new BrowserWindow({ show: false });
{
const isFocused3 = once(w3, 'focus');
const isShown1 = once(w1, 'show');
const isShown2 = once(w2, 'show');
const isShown3 = once(w3, 'show');
w1.show();
w2.show();
w3.show();
await isShown1;
await isShown2;
await isShown3;
await isFocused3;
}
// TODO(RaisinTen): Investigate why this assertion fails only on Linux.
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(true);
w3.blur();
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(true);
expect(w3.isFocused()).to.equal(false);
w2.blur();
expect(w1.isFocused()).to.equal(true);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(false);
w1.blur();
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(true);
{
const isClosed1 = once(w1, 'closed');
const isClosed2 = once(w2, 'closed');
const isClosed3 = once(w3, 'closed');
w1.destroy();
w2.destroy();
w3.destroy();
await isClosed1;
await isClosed2;
await isClosed3;
}
});
});
describe('BrowserWindow.getFocusedWindow()', () => {
it('returns the opener window when dev tools window is focused', async () => {
const p = once(w, 'focus');
w.show();
await p;
w.webContents.openDevTools({ mode: 'undocked' });
await once(w.webContents, 'devtools-focused');
expect(BrowserWindow.getFocusedWindow()).to.equal(w);
});
});
describe('BrowserWindow.moveTop()', () => {
afterEach(closeAllWindows);
it('should not steal focus', async () => {
const posDelta = 50;
const wShownInactive = once(w, 'show');
w.showInactive();
await wShownInactive;
expect(w.isFocused()).to.equal(false);
const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' });
const otherWindowShown = once(otherWindow, 'show');
const otherWindowFocused = once(otherWindow, 'focus');
otherWindow.show();
await otherWindowShown;
await otherWindowFocused;
expect(otherWindow.isFocused()).to.equal(true);
w.moveTop();
const wPos = w.getPosition();
const wMoving = once(w, 'move');
w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta);
await wMoving;
expect(w.isFocused()).to.equal(false);
expect(otherWindow.isFocused()).to.equal(true);
const wFocused = once(w, 'focus');
const otherWindowBlurred = once(otherWindow, 'blur');
w.focus();
await wFocused;
await otherWindowBlurred;
expect(w.isFocused()).to.equal(true);
otherWindow.moveTop();
const otherWindowPos = otherWindow.getPosition();
const otherWindowMoving = once(otherWindow, 'move');
otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta);
await otherWindowMoving;
expect(otherWindow.isFocused()).to.equal(false);
expect(w.isFocused()).to.equal(true);
await closeWindow(otherWindow, { assertNotWindows: false });
expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1);
});
it('should not crash when called on a modal child window', async () => {
const shown = once(w, 'show');
w.show();
await shown;
const child = new BrowserWindow({ modal: true, parent: w });
expect(() => { child.moveTop(); }).to.not.throw();
});
});
describe('BrowserWindow.moveAbove(mediaSourceId)', () => {
it('should throw an exception if wrong formatting', async () => {
const fakeSourceIds = [
'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2'
];
for (const sourceId of fakeSourceIds) {
expect(() => {
w.moveAbove(sourceId);
}).to.throw(/Invalid media source id/);
}
});
it('should throw an exception if wrong type', async () => {
const fakeSourceIds = [null as any, 123 as any];
for (const sourceId of fakeSourceIds) {
expect(() => {
w.moveAbove(sourceId);
}).to.throw(/Error processing argument at index 0 */);
}
});
it('should throw an exception if invalid window', async () => {
// It is very unlikely that these window id exist.
const fakeSourceIds = ['window:99999999:0', 'window:123456:1',
'window:123456:9'];
for (const sourceId of fakeSourceIds) {
expect(() => {
w.moveAbove(sourceId);
}).to.throw(/Invalid media source id/);
}
});
it('should not throw an exception', async () => {
const w2 = new BrowserWindow({ show: false, title: 'window2' });
const w2Shown = once(w2, 'show');
w2.show();
await w2Shown;
expect(() => {
w.moveAbove(w2.getMediaSourceId());
}).to.not.throw();
await closeWindow(w2, { assertNotWindows: false });
});
});
describe('BrowserWindow.setFocusable()', () => {
it('can set unfocusable window to focusable', async () => {
const w2 = new BrowserWindow({ focusable: false });
const w2Focused = once(w2, 'focus');
w2.setFocusable(true);
w2.focus();
await w2Focused;
await closeWindow(w2, { assertNotWindows: false });
});
});
describe('BrowserWindow.isFocusable()', () => {
it('correctly returns whether a window is focusable', async () => {
const w2 = new BrowserWindow({ focusable: false });
expect(w2.isFocusable()).to.be.false();
w2.setFocusable(true);
expect(w2.isFocusable()).to.be.true();
await closeWindow(w2, { assertNotWindows: false });
});
});
});
describe('sizing', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, width: 400, height: 400 });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('BrowserWindow.setBounds(bounds[, animate])', () => {
it('sets the window bounds with full bounds', () => {
const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
w.setBounds(fullBounds);
expectBoundsEqual(w.getBounds(), fullBounds);
});
it('sets the window bounds with partial bounds', () => {
const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
w.setBounds(fullBounds);
const boundsUpdate = { width: 200 };
w.setBounds(boundsUpdate as any);
const expectedBounds = { ...fullBounds, ...boundsUpdate };
expectBoundsEqual(w.getBounds(), expectedBounds);
});
ifit(process.platform === 'darwin')('on macOS', () => {
it('emits \'resized\' event after animating', async () => {
const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
w.setBounds(fullBounds, true);
await expect(once(w, 'resized')).to.eventually.be.fulfilled();
});
});
});
describe('BrowserWindow.setSize(width, height)', () => {
it('sets the window size', async () => {
const size = [300, 400];
const resized = once(w, 'resize');
w.setSize(size[0], size[1]);
await resized;
expectBoundsEqual(w.getSize(), size);
});
ifit(process.platform === 'darwin')('on macOS', () => {
it('emits \'resized\' event after animating', async () => {
const size = [300, 400];
w.setSize(size[0], size[1], true);
await expect(once(w, 'resized')).to.eventually.be.fulfilled();
});
});
});
describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => {
it('sets the maximum and minimum size of the window', () => {
expect(w.getMinimumSize()).to.deep.equal([0, 0]);
expect(w.getMaximumSize()).to.deep.equal([0, 0]);
w.setMinimumSize(100, 100);
expectBoundsEqual(w.getMinimumSize(), [100, 100]);
expectBoundsEqual(w.getMaximumSize(), [0, 0]);
w.setMaximumSize(900, 600);
expectBoundsEqual(w.getMinimumSize(), [100, 100]);
expectBoundsEqual(w.getMaximumSize(), [900, 600]);
});
});
describe('BrowserWindow.setAspectRatio(ratio)', () => {
it('resets the behaviour when passing in 0', async () => {
const size = [300, 400];
w.setAspectRatio(1 / 2);
w.setAspectRatio(0);
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
expectBoundsEqual(w.getSize(), size);
});
it('doesn\'t change bounds when maximum size is set', () => {
w.setMenu(null);
w.setMaximumSize(400, 400);
// Without https://github.com/electron/electron/pull/29101
// following call would shrink the window to 384x361.
// There would be also DCHECK in resize_utils.cc on
// debug build.
w.setAspectRatio(1.0);
expectBoundsEqual(w.getSize(), [400, 400]);
});
});
describe('BrowserWindow.setPosition(x, y)', () => {
it('sets the window position', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
expect(w.getPosition()).to.deep.equal(pos);
});
});
describe('BrowserWindow.setContentSize(width, height)', () => {
it('sets the content size', async () => {
// NB. The CI server has a very small screen. Attempting to size the window
// larger than the screen will limit the window's size to the screen and
// cause the test to fail.
const size = [456, 567];
w.setContentSize(size[0], size[1]);
await new Promise(setImmediate);
const after = w.getContentSize();
expect(after).to.deep.equal(size);
});
it('works for a frameless window', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
frame: false,
width: 400,
height: 400
});
const size = [456, 567];
w.setContentSize(size[0], size[1]);
await new Promise(setImmediate);
const after = w.getContentSize();
expect(after).to.deep.equal(size);
});
});
describe('BrowserWindow.setContentBounds(bounds)', () => {
it('sets the content size and position', async () => {
const bounds = { x: 10, y: 10, width: 250, height: 250 };
const resize = once(w, 'resize');
w.setContentBounds(bounds);
await resize;
await setTimeout();
expectBoundsEqual(w.getContentBounds(), bounds);
});
it('works for a frameless window', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
frame: false,
width: 300,
height: 300
});
const bounds = { x: 10, y: 10, width: 250, height: 250 };
const resize = once(w, 'resize');
w.setContentBounds(bounds);
await resize;
await setTimeout();
expectBoundsEqual(w.getContentBounds(), bounds);
});
});
describe('BrowserWindow.getBackgroundColor()', () => {
it('returns default value if no backgroundColor is set', () => {
w.destroy();
w = new BrowserWindow({});
expect(w.getBackgroundColor()).to.equal('#FFFFFF');
});
it('returns correct value if backgroundColor is set', () => {
const backgroundColor = '#BBAAFF';
w.destroy();
w = new BrowserWindow({
backgroundColor: backgroundColor
});
expect(w.getBackgroundColor()).to.equal(backgroundColor);
});
it('returns correct value from setBackgroundColor()', () => {
const backgroundColor = '#AABBFF';
w.destroy();
w = new BrowserWindow({});
w.setBackgroundColor(backgroundColor);
expect(w.getBackgroundColor()).to.equal(backgroundColor);
});
it('returns correct color with multiple passed formats', () => {
w.destroy();
w = new BrowserWindow({});
w.setBackgroundColor('#AABBFF');
expect(w.getBackgroundColor()).to.equal('#AABBFF');
w.setBackgroundColor('blueviolet');
expect(w.getBackgroundColor()).to.equal('#8A2BE2');
w.setBackgroundColor('rgb(255, 0, 185)');
expect(w.getBackgroundColor()).to.equal('#FF00B9');
w.setBackgroundColor('rgba(245, 40, 145, 0.8)');
expect(w.getBackgroundColor()).to.equal('#F52891');
w.setBackgroundColor('hsl(155, 100%, 50%)');
expect(w.getBackgroundColor()).to.equal('#00FF95');
});
});
describe('BrowserWindow.getNormalBounds()', () => {
describe('Normal state', () => {
it('checks normal bounds after resize', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
expectBoundsEqual(w.getNormalBounds(), w.getBounds());
});
it('checks normal bounds after move', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
expectBoundsEqual(w.getNormalBounds(), w.getBounds());
});
});
ifdescribe(process.platform !== 'linux')('Maximized state', () => {
it('checks normal bounds when maximized', async () => {
const bounds = w.getBounds();
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('updates normal bounds after resize and maximize', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
const original = w.getBounds();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('updates normal bounds after move and maximize', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
const original = w.getBounds();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('checks normal bounds when unmaximized', async () => {
const bounds = w.getBounds();
w.once('maximize', () => {
w.unmaximize();
});
const unmaximize = once(w, 'unmaximize');
w.show();
w.maximize();
await unmaximize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('correctly reports maximized state after maximizing then minimizing', async () => {
w.destroy();
w = new BrowserWindow({ show: false });
w.show();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
expect(w.isMaximized()).to.equal(false);
expect(w.isMinimized()).to.equal(true);
});
it('correctly reports maximized state after maximizing then fullscreening', async () => {
w.destroy();
w = new BrowserWindow({ show: false });
w.show();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const enterFS = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFS;
expect(w.isMaximized()).to.equal(false);
expect(w.isFullScreen()).to.equal(true);
});
it('does not crash if maximized, minimized, then restored to maximized state', (done) => {
w.destroy();
w = new BrowserWindow({ show: false });
w.show();
let count = 0;
w.on('maximize', () => {
if (count === 0) syncSetTimeout(() => { w.minimize(); });
count++;
});
w.on('minimize', () => {
if (count === 1) syncSetTimeout(() => { w.restore(); });
count++;
});
w.on('restore', () => {
try {
throw new Error('hey!');
} catch (e: any) {
expect(e.message).to.equal('hey!');
done();
}
});
w.maximize();
});
it('checks normal bounds for maximized transparent window', async () => {
w.destroy();
w = new BrowserWindow({
transparent: true,
show: false
});
w.show();
const bounds = w.getNormalBounds();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('does not change size for a frameless window with min size', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
frame: false,
width: 300,
height: 300,
minWidth: 300,
minHeight: 300
});
const bounds = w.getBounds();
w.once('maximize', () => {
w.unmaximize();
});
const unmaximize = once(w, 'unmaximize');
w.show();
w.maximize();
await unmaximize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('correctly checks transparent window maximization state', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
width: 300,
height: 300,
transparent: true
});
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
expect(w.isMaximized()).to.equal(true);
const unmaximize = once(w, 'unmaximize');
w.unmaximize();
await unmaximize;
expect(w.isMaximized()).to.equal(false);
});
it('returns the correct value for windows with an aspect ratio', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
fullscreenable: false
});
w.setAspectRatio(16 / 11);
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
expect(w.isMaximized()).to.equal(true);
w.resizable = false;
expect(w.isMaximized()).to.equal(true);
});
});
ifdescribe(process.platform !== 'linux')('Minimized state', () => {
it('checks normal bounds when minimized', async () => {
const bounds = w.getBounds();
const minimize = once(w, 'minimize');
w.show();
w.minimize();
await minimize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('updates normal bounds after move and minimize', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
const original = w.getBounds();
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
const normal = w.getNormalBounds();
expect(original).to.deep.equal(normal);
expectBoundsEqual(normal, w.getBounds());
});
it('updates normal bounds after resize and minimize', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
const original = w.getBounds();
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
const normal = w.getNormalBounds();
expect(original).to.deep.equal(normal);
expectBoundsEqual(normal, w.getBounds());
});
it('checks normal bounds when restored', async () => {
const bounds = w.getBounds();
w.once('minimize', () => {
w.restore();
});
const restore = once(w, 'restore');
w.show();
w.minimize();
await restore;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('does not change size for a frameless window with min size', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
frame: false,
width: 300,
height: 300,
minWidth: 300,
minHeight: 300
});
const bounds = w.getBounds();
w.once('minimize', () => {
w.restore();
});
const restore = once(w, 'restore');
w.show();
w.minimize();
await restore;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
});
ifdescribe(process.platform === 'win32')('Fullscreen state', () => {
it('with properties', () => {
it('can be set with the fullscreen constructor option', () => {
w = new BrowserWindow({ fullscreen: true });
expect(w.fullScreen).to.be.true();
});
it('does not go fullscreen if roundedCorners are enabled', async () => {
w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true });
expect(w.fullScreen).to.be.false();
});
it('can be changed', () => {
w.fullScreen = false;
expect(w.fullScreen).to.be.false();
w.fullScreen = true;
expect(w.fullScreen).to.be.true();
});
it('checks normal bounds when fullscreen\'ed', async () => {
const bounds = w.getBounds();
const enterFullScreen = once(w, 'enter-full-screen');
w.show();
w.fullScreen = true;
await enterFullScreen;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('updates normal bounds after resize and fullscreen', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
const original = w.getBounds();
const fsc = once(w, 'enter-full-screen');
w.fullScreen = true;
await fsc;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('updates normal bounds after move and fullscreen', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
const original = w.getBounds();
const fsc = once(w, 'enter-full-screen');
w.fullScreen = true;
await fsc;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('checks normal bounds when unfullscreen\'ed', async () => {
const bounds = w.getBounds();
w.once('enter-full-screen', () => {
w.fullScreen = false;
});
const leaveFullScreen = once(w, 'leave-full-screen');
w.show();
w.fullScreen = true;
await leaveFullScreen;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
});
it('with functions', () => {
it('can be set with the fullscreen constructor option', () => {
w = new BrowserWindow({ fullscreen: true });
expect(w.isFullScreen()).to.be.true();
});
it('can be changed', () => {
w.setFullScreen(false);
expect(w.isFullScreen()).to.be.false();
w.setFullScreen(true);
expect(w.isFullScreen()).to.be.true();
});
it('checks normal bounds when fullscreen\'ed', async () => {
const bounds = w.getBounds();
w.show();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('updates normal bounds after resize and fullscreen', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
const original = w.getBounds();
const fsc = once(w, 'enter-full-screen');
w.setFullScreen(true);
await fsc;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('updates normal bounds after move and fullscreen', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
const original = w.getBounds();
const fsc = once(w, 'enter-full-screen');
w.setFullScreen(true);
await fsc;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('checks normal bounds when unfullscreen\'ed', async () => {
const bounds = w.getBounds();
w.show();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
});
});
});
});
ifdescribe(process.platform === 'darwin')('tabbed windows', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(closeAllWindows);
describe('BrowserWindow.selectPreviousTab()', () => {
it('does not throw', () => {
expect(() => {
w.selectPreviousTab();
}).to.not.throw();
});
});
describe('BrowserWindow.selectNextTab()', () => {
it('does not throw', () => {
expect(() => {
w.selectNextTab();
}).to.not.throw();
});
});
describe('BrowserWindow.showAllTabs()', () => {
it('does not throw', () => {
expect(() => {
w.showAllTabs();
}).to.not.throw();
});
});
describe('BrowserWindow.mergeAllWindows()', () => {
it('does not throw', () => {
expect(() => {
w.mergeAllWindows();
}).to.not.throw();
});
});
describe('BrowserWindow.moveTabToNewWindow()', () => {
it('does not throw', () => {
expect(() => {
w.moveTabToNewWindow();
}).to.not.throw();
});
});
describe('BrowserWindow.toggleTabBar()', () => {
it('does not throw', () => {
expect(() => {
w.toggleTabBar();
}).to.not.throw();
});
});
describe('BrowserWindow.addTabbedWindow()', () => {
it('does not throw', async () => {
const tabbedWindow = new BrowserWindow({});
expect(() => {
w.addTabbedWindow(tabbedWindow);
}).to.not.throw();
expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow
await closeWindow(tabbedWindow, { assertNotWindows: false });
expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w
});
it('throws when called on itself', () => {
expect(() => {
w.addTabbedWindow(w);
}).to.throw('AddTabbedWindow cannot be called by a window on itself.');
});
});
describe('BrowserWindow.tabbingIdentifier', () => {
it('is undefined if no tabbingIdentifier was set', () => {
const w = new BrowserWindow({ show: false });
expect(w.tabbingIdentifier).to.be.undefined('tabbingIdentifier');
});
it('returns the window tabbingIdentifier', () => {
const w = new BrowserWindow({ show: false, tabbingIdentifier: 'group1' });
expect(w.tabbingIdentifier).to.equal('group1');
});
});
});
describe('autoHideMenuBar state', () => {
afterEach(closeAllWindows);
it('for properties', () => {
it('can be set with autoHideMenuBar constructor option', () => {
const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
w.autoHideMenuBar = true;
expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
w.autoHideMenuBar = false;
expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
});
});
it('for functions', () => {
it('can be set with autoHideMenuBar constructor option', () => {
const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
w.setAutoHideMenuBar(true);
expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
w.setAutoHideMenuBar(false);
expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
});
});
});
describe('BrowserWindow.capturePage(rect)', () => {
afterEach(closeAllWindows);
it('returns a Promise with a Buffer', async () => {
const w = new BrowserWindow({ show: false });
const image = await w.capturePage({
x: 0,
y: 0,
width: 100,
height: 100
});
expect(image.isEmpty()).to.equal(true);
});
ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => {
const w = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
}
w.hide();
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('hidden');
expect(hidden).to.be.true('hidden');
}
await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true });
const visible = await w.webContents.executeJavaScript('document.visibilityState');
expect(visible).to.equal('hidden');
});
it('resolves when the window is occluded', async () => {
const w1 = new BrowserWindow({ show: false });
w1.loadFile(path.join(fixtures, 'pages', 'a.html'));
await once(w1, 'ready-to-show');
w1.show();
const w2 = new BrowserWindow({ show: false });
w2.loadFile(path.join(fixtures, 'pages', 'a.html'));
await once(w2, 'ready-to-show');
w2.show();
const visibleImage = await w1.capturePage();
expect(visibleImage.isEmpty()).to.equal(false);
});
it('resolves when the window is not visible', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixtures, 'pages', 'a.html'));
await once(w, 'ready-to-show');
w.show();
const visibleImage = await w.capturePage();
expect(visibleImage.isEmpty()).to.equal(false);
w.minimize();
const hiddenImage = await w.capturePage();
expect(hiddenImage.isEmpty()).to.equal(false);
});
it('preserves transparency', async () => {
const w = new BrowserWindow({ show: false, transparent: true });
w.loadFile(path.join(fixtures, 'pages', 'theme-color.html'));
await once(w, 'ready-to-show');
w.show();
const image = await w.capturePage();
const imgBuffer = image.toPNG();
// Check the 25th byte in the PNG.
// Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha
expect(imgBuffer[25]).to.equal(6);
});
});
describe('BrowserWindow.setProgressBar(progress)', () => {
let w: BrowserWindow;
before(() => {
w = new BrowserWindow({ show: false });
});
after(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('sets the progress', () => {
expect(() => {
if (process.platform === 'darwin') {
app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png'));
}
w.setProgressBar(0.5);
if (process.platform === 'darwin') {
app.dock.setIcon(null as any);
}
w.setProgressBar(-1);
}).to.not.throw();
});
it('sets the progress using "paused" mode', () => {
expect(() => {
w.setProgressBar(0.5, { mode: 'paused' });
}).to.not.throw();
});
it('sets the progress using "error" mode', () => {
expect(() => {
w.setProgressBar(0.5, { mode: 'error' });
}).to.not.throw();
});
it('sets the progress using "normal" mode', () => {
expect(() => {
w.setProgressBar(0.5, { mode: 'normal' });
}).to.not.throw();
});
});
describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => {
let w: BrowserWindow;
afterEach(closeAllWindows);
beforeEach(() => {
w = new BrowserWindow({ show: true });
});
it('sets the window as always on top', () => {
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true, 'screen-saver');
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
w.setAlwaysOnTop(false);
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true);
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
});
ifit(process.platform === 'darwin')('resets the windows level on minimize', async () => {
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true, 'screen-saver');
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
const minimized = once(w, 'minimize');
w.minimize();
await minimized;
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
const restored = once(w, 'restore');
w.restore();
await restored;
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
});
it('causes the right value to be emitted on `always-on-top-changed`', async () => {
const alwaysOnTopChanged = once(w, 'always-on-top-changed') as Promise<[any, boolean]>;
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true);
const [, alwaysOnTop] = await alwaysOnTopChanged;
expect(alwaysOnTop).to.be.true('is not alwaysOnTop');
});
ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => {
w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ parent: w });
c.setAlwaysOnTop(true, 'screen-saver');
expect(w.isAlwaysOnTop()).to.be.false();
expect(c.isAlwaysOnTop()).to.be.true('child is not always on top');
expect(c._getAlwaysOnTopLevel()).to.equal('screen-saver');
});
});
describe('preconnect feature', () => {
let w: BrowserWindow;
let server: http.Server;
let url: string;
let connections = 0;
beforeEach(async () => {
connections = 0;
server = http.createServer((req, res) => {
if (req.url === '/link') {
res.setHeader('Content-type', 'text/html');
res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>');
return;
}
res.end();
});
server.on('connection', () => { connections++; });
url = (await listen(server)).url;
});
afterEach(async () => {
server.close();
await closeWindow(w);
w = null as unknown as BrowserWindow;
server = null as unknown as http.Server;
});
it('calling preconnect() connects to the server', async () => {
w = new BrowserWindow({ show: false });
w.webContents.on('did-start-navigation', (event, url) => {
w.webContents.session.preconnect({ url, numSockets: 4 });
});
await w.loadURL(url);
expect(connections).to.equal(4);
});
it('does not preconnect unless requested', async () => {
w = new BrowserWindow({ show: false });
await w.loadURL(url);
expect(connections).to.equal(1);
});
it('parses <link rel=preconnect>', async () => {
w = new BrowserWindow({ show: true });
const p = once(w.webContents.session, 'preconnect');
w.loadURL(url + '/link');
const [, preconnectUrl, allowCredentials] = await p;
expect(preconnectUrl).to.equal('http://example.com/');
expect(allowCredentials).to.be.true('allowCredentials');
});
});
describe('BrowserWindow.setAutoHideCursor(autoHide)', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
ifit(process.platform === 'darwin')('on macOS', () => {
it('allows changing cursor auto-hiding', () => {
expect(() => {
w.setAutoHideCursor(false);
w.setAutoHideCursor(true);
}).to.not.throw();
});
});
ifit(process.platform !== 'darwin')('on non-macOS platforms', () => {
it('is not available', () => {
expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function');
});
});
});
ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => {
afterEach(closeAllWindows);
it('does not throw', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setWindowButtonVisibility(true);
w.setWindowButtonVisibility(false);
}).to.not.throw();
});
it('changes window button visibility for normal window', () => {
const w = new BrowserWindow({ show: false });
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
});
it('changes window button visibility for frameless window', () => {
const w = new BrowserWindow({ show: false, frame: false });
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
});
it('changes window button visibility for hiddenInset window', () => {
const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' });
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
});
// Buttons of customButtonsOnHover are always hidden unless hovered.
it('does not change window button visibility for customButtonsOnHover window', () => {
const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' });
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
});
it('correctly updates when entering/exiting fullscreen for hidden style', async () => {
const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' });
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
const enterFS = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFS;
const leaveFS = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFS;
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
});
it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => {
const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' });
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
const enterFS = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFS;
const leaveFS = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFS;
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
});
});
ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => {
afterEach(closeAllWindows);
it('allows setting, changing, and removing the vibrancy', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setVibrancy('titlebar');
w.setVibrancy('selection');
w.setVibrancy(null);
w.setVibrancy('menu');
w.setVibrancy('' as any);
}).to.not.throw();
});
it('does not crash if vibrancy is set to an invalid value', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any);
}).to.not.throw();
});
});
ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => {
const pos = { x: 10, y: 10 };
afterEach(closeAllWindows);
describe('BrowserWindow.getWindowButtonPosition(pos)', () => {
it('returns null when there is no custom position', () => {
const w = new BrowserWindow({ show: false });
expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition');
});
it('gets position property for "hidden" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
expect(w.getWindowButtonPosition()).to.deep.equal(pos);
});
it('gets position property for "customButtonsOnHover" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
expect(w.getWindowButtonPosition()).to.deep.equal(pos);
});
});
describe('BrowserWindow.setWindowButtonPosition(pos)', () => {
it('resets the position when null is passed', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
w.setWindowButtonPosition(null);
expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition');
});
it('sets position property for "hidden" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
const newPos = { x: 20, y: 20 };
w.setWindowButtonPosition(newPos);
expect(w.getWindowButtonPosition()).to.deep.equal(newPos);
});
it('sets position property for "customButtonsOnHover" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
const newPos = { x: 20, y: 20 };
w.setWindowButtonPosition(newPos);
expect(w.getWindowButtonPosition()).to.deep.equal(newPos);
});
});
});
ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => {
afterEach(closeAllWindows);
it('supports setting the app details', () => {
const w = new BrowserWindow({ show: false });
const iconPath = path.join(fixtures, 'assets', 'icon.ico');
expect(() => {
w.setAppDetails({ appId: 'my.app.id' });
w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 });
w.setAppDetails({ appIconPath: iconPath });
w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' });
w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' });
w.setAppDetails({ relaunchDisplayName: 'My app name' });
w.setAppDetails({
appId: 'my.app.id',
appIconPath: iconPath,
appIconIndex: 0,
relaunchCommand: 'my-app.exe arg1 arg2',
relaunchDisplayName: 'My app name'
});
w.setAppDetails({});
}).to.not.throw();
expect(() => {
(w.setAppDetails as any)();
}).to.throw('Insufficient number of arguments.');
});
});
describe('BrowserWindow.fromId(id)', () => {
afterEach(closeAllWindows);
it('returns the window with id', () => {
const w = new BrowserWindow({ show: false });
expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id);
});
});
describe('Opening a BrowserWindow from a link', () => {
let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined;
afterEach(() => {
if (appProcess && !appProcess.killed) {
appProcess.kill();
appProcess = undefined;
}
});
it('can properly open and load a new window from a link', async () => {
const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link');
appProcess = childProcess.spawn(process.execPath, [appPath]);
const [code] = await once(appProcess, 'exit');
expect(code).to.equal(0);
});
});
describe('BrowserWindow.fromWebContents(webContents)', () => {
afterEach(closeAllWindows);
it('returns the window with the webContents', () => {
const w = new BrowserWindow({ show: false });
const found = BrowserWindow.fromWebContents(w.webContents);
expect(found!.id).to.equal(w.id);
});
it('returns null for webContents without a BrowserWindow', () => {
const contents = (webContents as typeof ElectronInternal.WebContents).create();
try {
expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)');
} finally {
contents.destroy();
}
});
it('returns the correct window for a BrowserView webcontents', async () => {
const w = new BrowserWindow({ show: false });
const bv = new BrowserView();
w.setBrowserView(bv);
defer(() => {
w.removeBrowserView(bv);
bv.webContents.destroy();
});
await bv.webContents.loadURL('about:blank');
expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id);
});
it('returns the correct window for a WebView webcontents', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>');
// NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for
// https://github.com/electron/electron/issues/25413, and is not integral
// to the test.
const p = once(w.webContents, 'did-attach-webview');
const [, webviewContents] = await once(app, 'web-contents-created') as [any, WebContents];
expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id);
await p;
});
it('is usable immediately on browser-window-created', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('window.open(""); null');
const [win, winFromWebContents] = await new Promise<any>((resolve) => {
app.once('browser-window-created', (e, win) => {
resolve([win, BrowserWindow.fromWebContents(win.webContents)]);
});
});
expect(winFromWebContents).to.equal(win);
});
});
describe('BrowserWindow.openDevTools()', () => {
afterEach(closeAllWindows);
it('does not crash for frameless window', () => {
const w = new BrowserWindow({ show: false, frame: false });
w.webContents.openDevTools();
});
});
describe('BrowserWindow.fromBrowserView(browserView)', () => {
afterEach(closeAllWindows);
it('returns the window with the BrowserView', () => {
const w = new BrowserWindow({ show: false });
const bv = new BrowserView();
w.setBrowserView(bv);
defer(() => {
w.removeBrowserView(bv);
bv.webContents.destroy();
});
expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id);
});
it('returns the window when there are multiple BrowserViews', () => {
const w = new BrowserWindow({ show: false });
const bv1 = new BrowserView();
w.addBrowserView(bv1);
const bv2 = new BrowserView();
w.addBrowserView(bv2);
defer(() => {
w.removeBrowserView(bv1);
w.removeBrowserView(bv2);
bv1.webContents.destroy();
bv2.webContents.destroy();
});
expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id);
expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id);
});
it('returns undefined if not attached', () => {
const bv = new BrowserView();
defer(() => {
bv.webContents.destroy();
});
expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv');
});
});
describe('BrowserWindow.setOpacity(opacity)', () => {
afterEach(closeAllWindows);
ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => {
it('make window with initial opacity', () => {
const w = new BrowserWindow({ show: false, opacity: 0.5 });
expect(w.getOpacity()).to.equal(0.5);
});
it('allows setting the opacity', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setOpacity(0.0);
expect(w.getOpacity()).to.equal(0.0);
w.setOpacity(0.5);
expect(w.getOpacity()).to.equal(0.5);
w.setOpacity(1.0);
expect(w.getOpacity()).to.equal(1.0);
}).to.not.throw();
});
it('clamps opacity to [0.0...1.0]', () => {
const w = new BrowserWindow({ show: false, opacity: 0.5 });
w.setOpacity(100);
expect(w.getOpacity()).to.equal(1.0);
w.setOpacity(-100);
expect(w.getOpacity()).to.equal(0.0);
});
});
ifdescribe(process.platform === 'linux')(('Linux'), () => {
it('sets 1 regardless of parameter', () => {
const w = new BrowserWindow({ show: false });
w.setOpacity(0);
expect(w.getOpacity()).to.equal(1.0);
w.setOpacity(0.5);
expect(w.getOpacity()).to.equal(1.0);
});
});
});
describe('BrowserWindow.setShape(rects)', () => {
afterEach(closeAllWindows);
it('allows setting shape', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setShape([]);
w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]);
w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]);
w.setShape([]);
}).to.not.throw();
});
});
describe('"useContentSize" option', () => {
afterEach(closeAllWindows);
it('make window created with content size when used', () => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
useContentSize: true
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
});
it('make window created with window size when not used', () => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400
});
const size = w.getSize();
expect(size).to.deep.equal([400, 400]);
});
it('works for a frameless window', () => {
const w = new BrowserWindow({
show: false,
frame: false,
width: 400,
height: 400,
useContentSize: true
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
const size = w.getSize();
expect(size).to.deep.equal([400, 400]);
});
});
ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => {
const testWindowsOverlay = async (style: any) => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: style,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: true
});
const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
if (process.platform === 'darwin') {
await w.loadFile(overlayHTML);
} else {
const overlayReady = once(ipcMain, 'geometrychange');
await w.loadFile(overlayHTML);
await overlayReady;
}
const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
expect(overlayEnabled).to.be.true('overlayEnabled');
const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()');
expect(overlayRect.y).to.equal(0);
if (process.platform === 'darwin') {
expect(overlayRect.x).to.be.greaterThan(0);
} else {
expect(overlayRect.x).to.equal(0);
}
expect(overlayRect.width).to.be.greaterThan(0);
expect(overlayRect.height).to.be.greaterThan(0);
const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();');
expect(cssOverlayRect).to.deep.equal(overlayRect);
const geometryChange = once(ipcMain, 'geometrychange');
w.setBounds({ width: 800 });
const [, newOverlayRect] = await geometryChange;
expect(newOverlayRect.width).to.equal(overlayRect.width + 400);
};
afterEach(async () => {
await closeAllWindows();
ipcMain.removeAllListeners('geometrychange');
});
it('creates browser window with hidden title bar', () => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hidden'
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
});
ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hiddenInset'
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
});
it('sets Window Control Overlay with hidden title bar', async () => {
await testWindowsOverlay('hidden');
});
ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => {
await testWindowsOverlay('hiddenInset');
});
ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: {
color: '#0000f0',
symbolColor: '#ffffff'
},
titleBarStyle: 'hiddenInset'
});
});
afterEach(async () => {
await closeAllWindows();
});
it('does not crash changing minimizability ', () => {
expect(() => {
w.setMinimizable(false);
}).to.not.throw();
});
it('does not crash changing maximizability', () => {
expect(() => {
w.setMaximizable(false);
}).to.not.throw();
});
});
});
ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => {
const testWindowsOverlayHeight = async (size: any) => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hidden',
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: {
height: size
}
});
const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
if (process.platform === 'darwin') {
await w.loadFile(overlayHTML);
} else {
const overlayReady = once(ipcMain, 'geometrychange');
await w.loadFile(overlayHTML);
await overlayReady;
}
const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
expect(overlayEnabled).to.be.true('overlayEnabled');
const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()');
if (!w.isMaximized()) {
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
}
expect(w.isMaximized()).to.be.true('not maximized');
const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()');
expect(overlayRectPreMax.y).to.equal(0);
if (process.platform === 'darwin') {
expect(overlayRectPreMax.x).to.be.greaterThan(0);
} else {
expect(overlayRectPreMax.x).to.equal(0);
}
expect(overlayRectPreMax.width).to.be.greaterThan(0);
expect(overlayRectPreMax.height).to.equal(size);
// Confirm that maximization only affected the height of the buttons and not the title bar
expect(overlayRectPostMax.height).to.equal(size);
};
afterEach(async () => {
await closeAllWindows();
ipcMain.removeAllListeners('geometrychange');
});
it('sets Window Control Overlay with title bar height of 40', async () => {
await testWindowsOverlayHeight(40);
});
});
ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => {
afterEach(async () => {
await closeAllWindows();
ipcMain.removeAllListeners('geometrychange');
});
it('does not crash when an invalid titleBarStyle was initially set', () => {
const win = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: {
color: '#0000f0',
symbolColor: '#ffffff'
},
titleBarStyle: 'hiddenInset'
});
expect(() => {
win.setTitleBarOverlay({
color: '#000000'
});
}).to.not.throw();
});
it('correctly updates the height of the overlay', async () => {
const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => {
const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
const overlayReady = once(ipcMain, 'geometrychange');
await w.loadFile(overlayHTML);
if (firstRun) {
await overlayReady;
}
const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
expect(overlayEnabled).to.be.true('overlayEnabled');
const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()');
if (!w.isMaximized()) {
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
}
expect(w.isMaximized()).to.be.true('not maximized');
const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()');
expect(x).to.equal(0);
expect(y).to.equal(0);
expect(width).to.be.greaterThan(0);
expect(height).to.equal(size);
expect(preMaxHeight).to.equal(size);
};
const INITIAL_SIZE = 40;
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hidden',
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: {
height: INITIAL_SIZE
}
});
await testOverlay(w, INITIAL_SIZE, true);
w.setTitleBarOverlay({
height: INITIAL_SIZE + 10
});
await testOverlay(w, INITIAL_SIZE + 10, false);
});
});
ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => {
afterEach(closeAllWindows);
it('can move the window out of screen', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
w.setPosition(-10, 50);
const after = w.getPosition();
expect(after).to.deep.equal([-10, 50]);
});
it('cannot move the window behind menu bar', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
w.setPosition(-10, -10);
const after = w.getPosition();
expect(after[1]).to.be.at.least(0);
});
it('can move the window behind menu bar if it has no frame', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false });
w.setPosition(-10, -10);
const after = w.getPosition();
expect(after[0]).to.be.equal(-10);
expect(after[1]).to.be.equal(-10);
});
it('without it, cannot move the window out of screen', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
w.setPosition(-10, -10);
const after = w.getPosition();
expect(after[1]).to.be.at.least(0);
});
it('can set the window larger than screen', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
const size = screen.getPrimaryDisplay().size;
size.width += 100;
size.height += 100;
w.setSize(size.width, size.height);
expectBoundsEqual(w.getSize(), [size.width, size.height]);
});
it('without it, cannot set the window larger than screen', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
const size = screen.getPrimaryDisplay().size;
size.width += 100;
size.height += 100;
w.setSize(size.width, size.height);
expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height);
});
});
ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => {
afterEach(closeAllWindows);
it('sets the window width to the page width when used', () => {
const w = new BrowserWindow({
show: false,
width: 500,
height: 400,
zoomToPageWidth: true
});
w.maximize();
expect(w.getSize()[0]).to.equal(500);
});
});
describe('"tabbingIdentifier" option', () => {
afterEach(closeAllWindows);
it('can be set on a window', () => {
expect(() => {
/* eslint-disable-next-line no-new */
new BrowserWindow({
tabbingIdentifier: 'group1'
});
/* eslint-disable-next-line no-new */
new BrowserWindow({
tabbingIdentifier: 'group2',
frame: false
});
}).not.to.throw();
});
});
describe('"webPreferences" option', () => {
afterEach(() => { ipcMain.removeAllListeners('answer'); });
afterEach(closeAllWindows);
describe('"preload" option', () => {
const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => {
it(name, async () => {
const w = new BrowserWindow({
webPreferences: {
...webPrefs,
preload: path.resolve(fixtures, 'module', 'empty.js')
},
show: false
});
w.loadFile(path.join(fixtures, 'api', 'no-leak.html'));
const [, result] = await once(ipcMain, 'leak-result');
expect(result).to.have.property('require', 'undefined');
expect(result).to.have.property('exports', 'undefined');
expect(result).to.have.property('windowExports', 'undefined');
expect(result).to.have.property('windowPreload', 'undefined');
expect(result).to.have.property('windowRequire', 'undefined');
});
};
doesNotLeakSpec('does not leak require', {
nodeIntegration: false,
sandbox: false,
contextIsolation: false
});
doesNotLeakSpec('does not leak require when sandbox is enabled', {
nodeIntegration: false,
sandbox: true,
contextIsolation: false
});
doesNotLeakSpec('does not leak require when context isolation is enabled', {
nodeIntegration: false,
sandbox: false,
contextIsolation: true
});
doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', {
nodeIntegration: false,
sandbox: true,
contextIsolation: true
});
it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => {
let w = new BrowserWindow({
webPreferences: {
contextIsolation: false,
nodeIntegration: false,
preload: path.resolve(fixtures, 'module', 'empty.js')
},
show: false
});
w.loadFile(path.join(fixtures, 'api', 'globals.html'));
const [, notIsolated] = await once(ipcMain, 'leak-result');
expect(notIsolated).to.have.property('globals');
w.destroy();
w = new BrowserWindow({
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
preload: path.resolve(fixtures, 'module', 'empty.js')
},
show: false
});
w.loadFile(path.join(fixtures, 'api', 'globals.html'));
const [, isolated] = await once(ipcMain, 'leak-result');
expect(isolated).to.have.property('globals');
const notIsolatedGlobals = new Set(notIsolated.globals);
for (const isolatedGlobal of isolated.globals) {
notIsolatedGlobals.delete(isolatedGlobal);
}
expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals');
});
it('loads the script before other scripts in window', async () => {
const preload = path.join(fixtures, 'module', 'set-global.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
preload
}
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test).to.eql('preload');
});
it('has synchronous access to all eventual window APIs', async () => {
const preload = path.join(fixtures, 'module', 'access-blink-apis.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
preload
}
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test).to.be.an('object');
expect(test.atPreload).to.be.an('array');
expect(test.atLoad).to.be.an('array');
expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs');
});
});
describe('session preload scripts', function () {
const preloads = [
path.join(fixtures, 'module', 'set-global-preload-1.js'),
path.join(fixtures, 'module', 'set-global-preload-2.js'),
path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js'))
];
const defaultSession = session.defaultSession;
beforeEach(() => {
expect(defaultSession.getPreloads()).to.deep.equal([]);
defaultSession.setPreloads(preloads);
});
afterEach(() => {
defaultSession.setPreloads([]);
});
it('can set multiple session preload script', () => {
expect(defaultSession.getPreloads()).to.deep.equal(preloads);
});
const generateSpecs = (description: string, sandbox: boolean) => {
describe(description, () => {
it('loads the script before other scripts in window including normal preloads', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox,
preload: path.join(fixtures, 'module', 'get-global-preload.js'),
contextIsolation: false
}
});
w.loadURL('about:blank');
const [, preload1, preload2, preload3] = await once(ipcMain, 'vars');
expect(preload1).to.equal('preload-1');
expect(preload2).to.equal('preload-1-2');
expect(preload3).to.be.undefined('preload 3');
});
});
};
generateSpecs('without sandbox', false);
generateSpecs('with sandbox', true);
});
describe('"additionalArguments" option', () => {
it('adds extra args to process.argv in the renderer process', async () => {
const preload = path.join(fixtures, 'module', 'check-arguments.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
preload,
additionalArguments: ['--my-magic-arg']
}
});
w.loadFile(path.join(fixtures, 'api', 'blank.html'));
const [, argv] = await once(ipcMain, 'answer');
expect(argv).to.include('--my-magic-arg');
});
it('adds extra value args to process.argv in the renderer process', async () => {
const preload = path.join(fixtures, 'module', 'check-arguments.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
preload,
additionalArguments: ['--my-magic-arg=foo']
}
});
w.loadFile(path.join(fixtures, 'api', 'blank.html'));
const [, argv] = await once(ipcMain, 'answer');
expect(argv).to.include('--my-magic-arg=foo');
});
});
describe('"node-integration" option', () => {
it('disables node integration by default', async () => {
const preload = path.join(fixtures, 'module', 'send-later.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
preload,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'api', 'blank.html'));
const [, typeofProcess, typeofBuffer] = await once(ipcMain, 'answer');
expect(typeofProcess).to.equal('undefined');
expect(typeofBuffer).to.equal('undefined');
});
});
describe('"sandbox" option', () => {
const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js');
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((request, response) => {
switch (request.url) {
case '/cross-site':
response.end(`<html><body><h1>${request.url}</h1></body></html>`);
break;
default:
throw new Error(`unsupported endpoint: ${request.url}`);
}
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('exposes ipcRenderer to preload script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test).to.equal('preload');
});
it('exposes ipcRenderer to preload script (path has special chars)', async () => {
const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload: preloadSpecialChars,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test).to.equal('preload');
});
it('exposes "loaded" event to preload script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload
}
});
w.loadURL('about:blank');
await once(ipcMain, 'process-loaded');
});
it('exposes "exit" event to preload script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event');
const pageUrl = 'file://' + htmlPath;
w.loadURL(pageUrl);
const [, url] = await once(ipcMain, 'answer');
const expectedUrl = process.platform === 'win32'
? 'file:///' + htmlPath.replaceAll('\\', '/')
: pageUrl;
expect(url).to.equal(expectedUrl);
});
it('exposes full EventEmitter object to preload script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload: path.join(fixtures, 'module', 'preload-eventemitter.js')
}
});
w.loadURL('about:blank');
const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer');
const { EventEmitter } = require('node:events');
const emitter = new EventEmitter();
const browserEventEmitterProperties = [];
let currentObj = emitter;
do {
browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj));
} while ((currentObj = Object.getPrototypeOf(currentObj)));
expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties);
});
it('should open windows in same domain with cross-scripting enabled', async () => {
const w = new BrowserWindow({
show: true,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload
}
}
}));
const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open');
const pageUrl = 'file://' + htmlPath;
const answer = once(ipcMain, 'answer');
w.loadURL(pageUrl);
const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window') as [BrowserWindow, Electron.DidCreateWindowDetails];
const expectedUrl = process.platform === 'win32'
? 'file:///' + htmlPath.replaceAll('\\', '/')
: pageUrl;
expect(url).to.equal(expectedUrl);
expect(frameName).to.equal('popup!');
expect(options.width).to.equal(500);
expect(options.height).to.equal(600);
const [, html] = await answer;
expect(html).to.equal('<h1>scripting from opener</h1>');
});
it('should open windows in another domain with cross-scripting disabled', async () => {
const w = new BrowserWindow({
show: true,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload
}
}
}));
w.loadFile(
path.join(__dirname, 'fixtures', 'api', 'sandbox.html'),
{ search: 'window-open-external' }
);
// Wait for a message from the main window saying that it's ready.
await once(ipcMain, 'opener-loaded');
// Ask the opener to open a popup with window.opener.
const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html".
w.webContents.send('open-the-popup', expectedPopupUrl);
// The page is going to open a popup that it won't be able to close.
// We have to close it from here later.
const [, popupWindow] = await once(app, 'browser-window-created') as [any, BrowserWindow];
// Ask the popup window for details.
const detailsAnswer = once(ipcMain, 'child-loaded');
popupWindow.webContents.send('provide-details');
const [, openerIsNull, , locationHref] = await detailsAnswer;
expect(openerIsNull).to.be.false('window.opener is null');
expect(locationHref).to.equal(expectedPopupUrl);
// Ask the page to access the popup.
const touchPopupResult = once(ipcMain, 'answer');
w.webContents.send('touch-the-popup');
const [, popupAccessMessage] = await touchPopupResult;
// Ask the popup to access the opener.
const touchOpenerResult = once(ipcMain, 'answer');
popupWindow.webContents.send('touch-the-opener');
const [, openerAccessMessage] = await touchOpenerResult;
// We don't need the popup anymore, and its parent page can't close it,
// so let's close it from here before we run any checks.
await closeWindow(popupWindow, { assertNotWindows: false });
const errorPattern = /Failed to read a named property 'document' from 'Window': Blocked a frame with origin "(.*?)" from accessing a cross-origin frame./;
expect(popupAccessMessage).to.be.a('string',
'child\'s .document is accessible from its parent window');
expect(popupAccessMessage).to.match(errorPattern);
expect(openerAccessMessage).to.be.a('string',
'opener .document is accessible from a popup window');
expect(openerAccessMessage).to.match(errorPattern);
});
it('should inherit the sandbox setting in opened windows', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } }));
w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
const [, { argv }] = await once(ipcMain, 'answer');
expect(argv).to.include('--enable-sandbox');
});
it('should open windows with the options configured via setWindowOpenHandler handlers', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } }));
w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
const [[, childWebContents]] = await Promise.all([
once(app, 'web-contents-created') as Promise<[any, WebContents]>,
once(ipcMain, 'answer')
]);
const webPreferences = childWebContents.getLastWebPreferences();
expect(webPreferences!.contextIsolation).to.equal(false);
});
it('should set ipc event sender correctly', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
let childWc: WebContents | null = null;
w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } }));
w.webContents.on('did-create-window', (win) => {
childWc = win.webContents;
expect(w.webContents).to.not.equal(childWc);
});
ipcMain.once('parent-ready', function (event) {
expect(event.sender).to.equal(w.webContents, 'sender should be the parent');
event.sender.send('verified');
});
ipcMain.once('child-ready', function (event) {
expect(childWc).to.not.be.null('child webcontents should be available');
expect(event.sender).to.equal(childWc, 'sender should be the child');
event.sender.send('verified');
});
const done = Promise.all([
'parent-answer',
'child-answer'
].map(name => once(ipcMain, name)));
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' });
await done;
});
describe('event handling', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
});
it('works for window events', async () => {
const pageTitleUpdated = once(w, 'page-title-updated');
w.loadURL('data:text/html,<script>document.title = \'changed\'</script>');
await pageTitleUpdated;
});
it('works for stop events', async () => {
const done = Promise.all([
'did-navigate',
'did-fail-load',
'did-stop-loading'
].map(name => once(w.webContents, name)));
w.loadURL('data:text/html,<script>stop()</script>');
await done;
});
it('works for web contents events', async () => {
const done = Promise.all([
'did-finish-load',
'did-frame-finish-load',
'did-navigate-in-page',
'will-navigate',
'did-start-loading',
'did-stop-loading',
'did-frame-finish-load',
'dom-ready'
].map(name => once(w.webContents, name)));
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' });
await done;
});
});
it('validates process APIs access in sandboxed renderer', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
w.webContents.once('preload-error', (event, preloadPath, error) => {
throw error;
});
process.env.sandboxmain = 'foo';
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test.hasCrash).to.be.true('has crash');
expect(test.hasHang).to.be.true('has hang');
expect(test.heapStatistics).to.be.an('object');
expect(test.blinkMemoryInfo).to.be.an('object');
expect(test.processMemoryInfo).to.be.an('object');
expect(test.systemVersion).to.be.a('string');
expect(test.cpuUsage).to.be.an('object');
expect(test.ioCounters).to.be.an('object');
expect(test.uptime).to.be.a('number');
expect(test.arch).to.equal(process.arch);
expect(test.platform).to.equal(process.platform);
expect(test.env).to.deep.equal(process.env);
expect(test.execPath).to.equal(process.helperExecPath);
expect(test.sandboxed).to.be.true('sandboxed');
expect(test.contextIsolated).to.be.false('contextIsolated');
expect(test.type).to.equal('renderer');
expect(test.version).to.equal(process.version);
expect(test.versions).to.deep.equal(process.versions);
expect(test.contextId).to.be.a('string');
expect(test.nodeEvents).to.equal(true);
expect(test.nodeTimers).to.equal(true);
expect(test.nodeUrl).to.equal(true);
if (process.platform === 'linux' && test.osSandbox) {
expect(test.creationTime).to.be.null('creation time');
expect(test.systemMemoryInfo).to.be.null('system memory info');
} else {
expect(test.creationTime).to.be.a('number');
expect(test.systemMemoryInfo).to.be.an('object');
}
});
it('webview in sandbox renderer', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
webviewTag: true,
contextIsolation: false
}
});
const didAttachWebview = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>;
const webviewDomReady = once(ipcMain, 'webview-dom-ready');
w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html'));
const [, webContents] = await didAttachWebview;
const [, id] = await webviewDomReady;
expect(webContents.id).to.equal(id);
});
});
describe('child windows', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
// tests relies on preloads in opened windows
nodeIntegrationInSubFrames: true,
contextIsolation: false
}
});
});
it('opens window of about:blank with cross-scripting enabled', async () => {
const answer = once(ipcMain, 'answer');
w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html'));
const [, content] = await answer;
expect(content).to.equal('Hello');
});
it('opens window of same domain with cross-scripting enabled', async () => {
const answer = once(ipcMain, 'answer');
w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html'));
const [, content] = await answer;
expect(content).to.equal('Hello');
});
it('blocks accessing cross-origin frames', async () => {
const answer = once(ipcMain, 'answer');
w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html'));
const [, content] = await answer;
expect(content).to.equal('Failed to read a named property \'toString\' from \'Location\': Blocked a frame with origin "file://" from accessing a cross-origin frame.');
});
it('opens window from <iframe> tags', async () => {
const answer = once(ipcMain, 'answer');
w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html'));
const [, content] = await answer;
expect(content).to.equal('Hello');
});
it('opens window with cross-scripting enabled from isolated context', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js')
}
});
w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html'));
const [, content] = await once(ipcMain, 'answer');
expect(content).to.equal('Hello');
});
ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => {
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html'));
{
const [, content] = await once(ipcMain, 'answer');
expect(content).to.equal('function');
}
w.reload();
{
const [, content] = await once(ipcMain, 'answer');
expect(content).to.equal('function');
}
});
it('<webview> works in a scriptable popup', async () => {
const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegrationInSubFrames: true,
webviewTag: true,
contextIsolation: false,
preload
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
show: false,
webPreferences: {
contextIsolation: false,
webviewTag: true,
nodeIntegrationInSubFrames: true,
preload
}
}
}));
const webviewLoaded = once(ipcMain, 'webview-loaded');
w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html'));
await webviewLoaded;
});
it('should open windows with the options configured via setWindowOpenHandler handlers', async () => {
const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload: preloadPath,
contextIsolation: false
}
}
}));
w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
const [[, childWebContents]] = await Promise.all([
once(app, 'web-contents-created') as Promise<[any, WebContents]>,
once(ipcMain, 'answer')
]);
const webPreferences = childWebContents.getLastWebPreferences();
expect(webPreferences!.contextIsolation).to.equal(false);
});
describe('window.location', () => {
const protocols = [
['foo', path.join(fixtures, 'api', 'window-open-location-change.html')],
['bar', path.join(fixtures, 'api', 'window-open-location-final.html')]
];
beforeEach(() => {
for (const [scheme, path] of protocols) {
protocol.registerBufferProtocol(scheme, (request, callback) => {
callback({
mimeType: 'text/html',
data: fs.readFileSync(path)
});
});
}
});
afterEach(() => {
for (const [scheme] of protocols) {
protocol.unregisterProtocol(scheme);
}
});
it('retains the original web preferences when window.location is changed to a new origin', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
// test relies on preloads in opened window
nodeIntegrationInSubFrames: true,
contextIsolation: false
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload: path.join(mainFixtures, 'api', 'window-open-preload.js'),
contextIsolation: false,
nodeIntegrationInSubFrames: true
}
}
}));
w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
const [, { nodeIntegration, typeofProcess }] = await once(ipcMain, 'answer');
expect(nodeIntegration).to.be.false();
expect(typeofProcess).to.eql('undefined');
});
it('window.opener is not null when window.location is changed to a new origin', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
// test relies on preloads in opened window
nodeIntegrationInSubFrames: true
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload: path.join(mainFixtures, 'api', 'window-open-preload.js')
}
}
}));
w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
const [, { windowOpenerIsNull }] = await once(ipcMain, 'answer');
expect(windowOpenerIsNull).to.be.false('window.opener is null');
});
});
});
describe('"disableHtmlFullscreenWindowResize" option', () => {
it('prevents window from resizing when set', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
disableHtmlFullscreenWindowResize: true
}
});
await w.loadURL('about:blank');
const size = w.getSize();
const enterHtmlFullScreen = once(w.webContents, 'enter-html-full-screen');
w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
await enterHtmlFullScreen;
expect(w.getSize()).to.deep.equal(size);
});
});
describe('"defaultFontFamily" option', () => {
it('can change the standard font family', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
defaultFontFamily: {
standard: 'Impact'
}
}
});
await w.loadFile(path.join(fixtures, 'pages', 'content.html'));
const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true);
expect(fontFamily).to.equal('Impact');
});
});
});
describe('beforeunload handler', function () {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
});
afterEach(closeAllWindows);
it('returning undefined would not prevent close', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
const wait = once(w, 'closed');
w.close();
await wait;
});
it('returning false would prevent close', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.close();
const [, proceed] = await once(w.webContents, '-before-unload-fired');
expect(proceed).to.equal(false);
});
it('returning empty string would prevent close', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html'));
w.close();
const [, proceed] = await once(w.webContents, '-before-unload-fired');
expect(proceed).to.equal(false);
});
it('emits for each close attempt', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
const destroyListener = () => { expect.fail('Close was not prevented'); };
w.webContents.once('destroyed', destroyListener);
w.webContents.executeJavaScript('installBeforeUnload(2)', true);
// The renderer needs to report the status of beforeunload handler
// back to main process, so wait for next console message, which means
// the SuddenTerminationStatus message have been flushed.
await once(w.webContents, 'console-message');
w.close();
await once(w.webContents, '-before-unload-fired');
w.close();
await once(w.webContents, '-before-unload-fired');
w.webContents.removeListener('destroyed', destroyListener);
const wait = once(w, 'closed');
w.close();
await wait;
});
it('emits for each reload attempt', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
const navigationListener = () => { expect.fail('Reload was not prevented'); };
w.webContents.once('did-start-navigation', navigationListener);
w.webContents.executeJavaScript('installBeforeUnload(2)', true);
// The renderer needs to report the status of beforeunload handler
// back to main process, so wait for next console message, which means
// the SuddenTerminationStatus message have been flushed.
await once(w.webContents, 'console-message');
w.reload();
// Chromium does not emit '-before-unload-fired' on WebContents for
// navigations, so we have to use other ways to know if beforeunload
// is fired.
await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
w.reload();
await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
w.webContents.removeListener('did-start-navigation', navigationListener);
w.reload();
await once(w.webContents, 'did-finish-load');
});
it('emits for each navigation attempt', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
const navigationListener = () => { expect.fail('Reload was not prevented'); };
w.webContents.once('did-start-navigation', navigationListener);
w.webContents.executeJavaScript('installBeforeUnload(2)', true);
// The renderer needs to report the status of beforeunload handler
// back to main process, so wait for next console message, which means
// the SuddenTerminationStatus message have been flushed.
await once(w.webContents, 'console-message');
w.loadURL('about:blank');
// Chromium does not emit '-before-unload-fired' on WebContents for
// navigations, so we have to use other ways to know if beforeunload
// is fired.
await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
w.loadURL('about:blank');
await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
w.webContents.removeListener('did-start-navigation', navigationListener);
await w.loadURL('about:blank');
});
});
// TODO(codebytere): figure out how to make these pass in CI on Windows.
ifdescribe(process.platform !== 'win32')('document.visibilityState/hidden', () => {
afterEach(closeAllWindows);
it('visibilityState is initially visible despite window being hidden', async () => {
const w = new BrowserWindow({
show: false,
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
let readyToShow = false;
w.once('ready-to-show', () => {
readyToShow = true;
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(readyToShow).to.be.false('ready to show');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
});
it('visibilityState changes when window is hidden', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
}
w.hide();
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('hidden');
expect(hidden).to.be.true('hidden');
}
});
it('visibilityState changes when window is shown', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
if (process.platform === 'darwin') {
// See https://github.com/electron/electron/issues/8664
await once(w, 'show');
}
w.hide();
w.show();
const [, visibilityState] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
});
it('visibilityState changes when window is shown inactive', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
if (process.platform === 'darwin') {
// See https://github.com/electron/electron/issues/8664
await once(w, 'show');
}
w.hide();
w.showInactive();
const [, visibilityState] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
});
ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
}
w.minimize();
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('hidden');
expect(hidden).to.be.true('hidden');
}
});
it('visibilityState remains visible if backgroundThrottling is disabled', async () => {
const w = new BrowserWindow({
show: false,
width: 100,
height: 100,
webPreferences: {
backgroundThrottling: false,
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
}
ipcMain.once('pong', (event, visibilityState, hidden) => {
throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`);
});
try {
const shown1 = once(w, 'show');
w.show();
await shown1;
const hidden = once(w, 'hide');
w.hide();
await hidden;
const shown2 = once(w, 'show');
w.show();
await shown2;
} finally {
ipcMain.removeAllListeners('pong');
}
});
});
ifdescribe(process.platform !== 'linux')('max/minimize events', () => {
afterEach(closeAllWindows);
it('emits an event when window is maximized', async () => {
const w = new BrowserWindow({ show: false });
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
});
it('emits an event when a transparent window is maximized', async () => {
const w = new BrowserWindow({
show: false,
frame: false,
transparent: true
});
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
});
it('emits only one event when frameless window is maximized', () => {
const w = new BrowserWindow({ show: false, frame: false });
let emitted = 0;
w.on('maximize', () => emitted++);
w.show();
w.maximize();
expect(emitted).to.equal(1);
});
it('emits an event when window is unmaximized', async () => {
const w = new BrowserWindow({ show: false });
const unmaximize = once(w, 'unmaximize');
w.show();
w.maximize();
w.unmaximize();
await unmaximize;
});
it('emits an event when a transparent window is unmaximized', async () => {
const w = new BrowserWindow({
show: false,
frame: false,
transparent: true
});
const maximize = once(w, 'maximize');
const unmaximize = once(w, 'unmaximize');
w.show();
w.maximize();
await maximize;
w.unmaximize();
await unmaximize;
});
it('emits an event when window is minimized', async () => {
const w = new BrowserWindow({ show: false });
const minimize = once(w, 'minimize');
w.show();
w.minimize();
await minimize;
});
});
describe('beginFrameSubscription method', () => {
it('does not crash when callback returns nothing', (done) => {
const w = new BrowserWindow({ show: false });
let called = false;
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
w.webContents.on('dom-ready', () => {
w.webContents.beginFrameSubscription(function () {
// This callback might be called twice.
if (called) return;
called = true;
// Pending endFrameSubscription to next tick can reliably reproduce
// a crash which happens when nothing is returned in the callback.
setTimeout().then(() => {
w.webContents.endFrameSubscription();
done();
});
});
});
});
it('subscribes to frame updates', (done) => {
const w = new BrowserWindow({ show: false });
let called = false;
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
w.webContents.on('dom-ready', () => {
w.webContents.beginFrameSubscription(function (data) {
// This callback might be called twice.
if (called) return;
called = true;
try {
expect(data.constructor.name).to.equal('NativeImage');
expect(data.isEmpty()).to.be.false('data is empty');
done();
} catch (e) {
done(e);
} finally {
w.webContents.endFrameSubscription();
}
});
});
});
it('subscribes to frame updates (only dirty rectangle)', (done) => {
const w = new BrowserWindow({ show: false });
let called = false;
let gotInitialFullSizeFrame = false;
const [contentWidth, contentHeight] = w.getContentSize();
w.webContents.on('did-finish-load', () => {
w.webContents.beginFrameSubscription(true, (image, rect) => {
if (image.isEmpty()) {
// Chromium sometimes sends a 0x0 frame at the beginning of the
// page load.
return;
}
if (rect.height === contentHeight && rect.width === contentWidth &&
!gotInitialFullSizeFrame) {
// The initial frame is full-size, but we're looking for a call
// with just the dirty-rect. The next frame should be a smaller
// rect.
gotInitialFullSizeFrame = true;
return;
}
// This callback might be called twice.
if (called) return;
// We asked for just the dirty rectangle, so we expect to receive a
// rect smaller than the full size.
// TODO(jeremy): this is failing on windows currently; investigate.
// assert(rect.width < contentWidth || rect.height < contentHeight)
called = true;
try {
const expectedSize = rect.width * rect.height * 4;
expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize);
done();
} catch (e) {
done(e);
} finally {
w.webContents.endFrameSubscription();
}
});
});
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
});
it('throws error when subscriber is not well defined', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.webContents.beginFrameSubscription(true, true as any);
// TODO(zcbenz): gin is weak at guessing parameter types, we should
// upstream native_mate's implementation to gin.
}).to.throw('Error processing argument at index 1, conversion failure from ');
});
});
describe('savePage method', () => {
const savePageDir = path.join(fixtures, 'save_page');
const savePageHtmlPath = path.join(savePageDir, 'save_page.html');
const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js');
const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css');
afterEach(() => {
closeAllWindows();
try {
fs.unlinkSync(savePageCssPath);
fs.unlinkSync(savePageJsPath);
fs.unlinkSync(savePageHtmlPath);
fs.rmdirSync(path.join(savePageDir, 'save_page_files'));
fs.rmdirSync(savePageDir);
} catch {}
});
it('should throw when passing relative paths', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
await expect(
w.webContents.savePage('save_page.html', 'HTMLComplete')
).to.eventually.be.rejectedWith('Path must be absolute');
await expect(
w.webContents.savePage('save_page.html', 'HTMLOnly')
).to.eventually.be.rejectedWith('Path must be absolute');
await expect(
w.webContents.savePage('save_page.html', 'MHTML')
).to.eventually.be.rejectedWith('Path must be absolute');
});
it('should save page to disk with HTMLOnly', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly');
expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
expect(fs.existsSync(savePageJsPath)).to.be.false('js path');
expect(fs.existsSync(savePageCssPath)).to.be.false('css path');
});
it('should save page to disk with MHTML', async () => {
/* Use temp directory for saving MHTML file since the write handle
* gets passed to untrusted process and chromium will deny exec access to
* the path. To perform this task, chromium requires that the path is one
* of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416
*/
const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-'));
const savePageMHTMLPath = path.join(tmpDir, 'save_page.html');
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
await w.webContents.savePage(savePageMHTMLPath, 'MHTML');
expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path');
expect(fs.existsSync(savePageJsPath)).to.be.false('js path');
expect(fs.existsSync(savePageCssPath)).to.be.false('css path');
try {
await fs.promises.unlink(savePageMHTMLPath);
await fs.promises.rmdir(tmpDir);
} catch {}
});
it('should save page to disk with HTMLComplete', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete');
expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
expect(fs.existsSync(savePageJsPath)).to.be.true('js path');
expect(fs.existsSync(savePageCssPath)).to.be.true('css path');
});
});
describe('BrowserWindow options argument is optional', () => {
afterEach(closeAllWindows);
it('should create a window with default size (800x600)', () => {
const w = new BrowserWindow();
expect(w.getSize()).to.deep.equal([800, 600]);
});
});
describe('BrowserWindow.restore()', () => {
afterEach(closeAllWindows);
it('should restore the previous window size', () => {
const w = new BrowserWindow({
minWidth: 800,
width: 800
});
const initialSize = w.getSize();
w.minimize();
w.restore();
expectBoundsEqual(w.getSize(), initialSize);
});
it('does not crash when restoring hidden minimized window', () => {
const w = new BrowserWindow({});
w.minimize();
w.hide();
w.show();
});
// TODO(zcbenz):
// This test does not run on Linux CI. See:
// https://github.com/electron/electron/issues/28699
ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => {
const w = new BrowserWindow({});
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
expect(w.isMaximized()).to.equal(false);
const restore = once(w, 'restore');
w.restore();
await restore;
expect(w.isMaximized()).to.equal(true);
});
});
// TODO(dsanders11): Enable once maximize event works on Linux again on CI
ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => {
afterEach(closeAllWindows);
it('should show the window if it is not currently shown', async () => {
const w = new BrowserWindow({ show: false });
const hidden = once(w, 'hide');
let shown = once(w, 'show');
const maximize = once(w, 'maximize');
expect(w.isVisible()).to.be.false('visible');
w.maximize();
await maximize;
await shown;
expect(w.isMaximized()).to.be.true('maximized');
expect(w.isVisible()).to.be.true('visible');
// Even if the window is already maximized
w.hide();
await hidden;
expect(w.isVisible()).to.be.false('visible');
shown = once(w, 'show');
w.maximize();
await shown;
expect(w.isVisible()).to.be.true('visible');
});
});
describe('BrowserWindow.unmaximize()', () => {
afterEach(closeAllWindows);
it('should restore the previous window position', () => {
const w = new BrowserWindow();
const initialPosition = w.getPosition();
w.maximize();
w.unmaximize();
expectBoundsEqual(w.getPosition(), initialPosition);
});
// TODO(dsanders11): Enable once minimize event works on Linux again.
// See https://github.com/electron/electron/issues/28699
ifit(process.platform !== 'linux')('should not restore a minimized window', async () => {
const w = new BrowserWindow();
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
w.unmaximize();
await setTimeout(1000);
expect(w.isMinimized()).to.be.true();
});
it('should not change the size or position of a normal window', async () => {
const w = new BrowserWindow();
const initialSize = w.getSize();
const initialPosition = w.getPosition();
w.unmaximize();
await setTimeout(1000);
expectBoundsEqual(w.getSize(), initialSize);
expectBoundsEqual(w.getPosition(), initialPosition);
});
ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => {
const { workArea } = screen.getPrimaryDisplay();
const bounds = {
x: workArea.x,
y: workArea.y,
width: workArea.width,
height: workArea.height
};
const w = new BrowserWindow(bounds);
w.unmaximize();
await setTimeout(1000);
expectBoundsEqual(w.getBounds(), bounds);
});
});
describe('setFullScreen(false)', () => {
afterEach(closeAllWindows);
// only applicable to windows: https://github.com/electron/electron/issues/6036
ifdescribe(process.platform === 'win32')('on windows', () => {
it('should restore a normal visible window from a fullscreen startup state', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const shown = once(w, 'show');
// start fullscreen and hidden
w.setFullScreen(true);
w.show();
await shown;
const leftFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leftFullScreen;
expect(w.isVisible()).to.be.true('visible');
expect(w.isFullScreen()).to.be.false('fullscreen');
});
it('should keep window hidden if already in hidden state', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const leftFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leftFullScreen;
expect(w.isVisible()).to.be.false('visible');
expect(w.isFullScreen()).to.be.false('fullscreen');
});
});
ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => {
it('exits HTML fullscreen when window leaves fullscreen', async () => {
const w = new BrowserWindow();
await w.loadURL('about:blank');
await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
await once(w, 'enter-full-screen');
// Wait a tick for the full-screen state to 'stick'
await setTimeout();
w.setFullScreen(false);
await once(w, 'leave-html-full-screen');
});
});
});
describe('parent window', () => {
afterEach(closeAllWindows);
ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => {
const w = new BrowserWindow();
const sheetBegin = once(w, 'sheet-begin');
// eslint-disable-next-line no-new
new BrowserWindow({
modal: true,
parent: w
});
await sheetBegin;
});
ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => {
const w = new BrowserWindow();
const sheet = new BrowserWindow({
modal: true,
parent: w
});
const sheetEnd = once(w, 'sheet-end');
sheet.close();
await sheetEnd;
});
describe('parent option', () => {
it('sets parent window', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
expect(c.getParentWindow()).to.equal(w);
});
it('adds window to child windows of parent', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
expect(w.getChildWindows()).to.deep.equal([c]);
});
it('removes from child windows of parent when window is closed', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
const closed = once(c, 'closed');
c.close();
await closed;
// The child window list is not immediately cleared, so wait a tick until it's ready.
await setTimeout();
expect(w.getChildWindows().length).to.equal(0);
});
it('can handle child window close and reparent multiple times', async () => {
const w = new BrowserWindow({ show: false });
let c: BrowserWindow | null;
for (let i = 0; i < 5; i++) {
c = new BrowserWindow({ show: false, parent: w });
const closed = once(c, 'closed');
c.close();
await closed;
}
await setTimeout();
expect(w.getChildWindows().length).to.equal(0);
});
ifit(process.platform === 'darwin')('only shows the intended window when a child with siblings is shown', async () => {
const w = new BrowserWindow({ show: false });
const childOne = new BrowserWindow({ show: false, parent: w });
const childTwo = new BrowserWindow({ show: false, parent: w });
const parentShown = once(w, 'show');
w.show();
await parentShown;
expect(childOne.isVisible()).to.be.false('childOne is visible');
expect(childTwo.isVisible()).to.be.false('childTwo is visible');
const childOneShown = once(childOne, 'show');
childOne.show();
await childOneShown;
expect(childOne.isVisible()).to.be.true('childOne is not visible');
expect(childTwo.isVisible()).to.be.false('childTwo is visible');
});
ifit(process.platform === 'darwin')('child matches parent visibility when parent visibility changes', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
const wShow = once(w, 'show');
const cShow = once(c, 'show');
w.show();
c.show();
await Promise.all([wShow, cShow]);
const minimized = once(w, 'minimize');
w.minimize();
await minimized;
expect(w.isVisible()).to.be.false('parent is visible');
expect(c.isVisible()).to.be.false('child is visible');
const restored = once(w, 'restore');
w.restore();
await restored;
expect(w.isVisible()).to.be.true('parent is visible');
expect(c.isVisible()).to.be.true('child is visible');
});
ifit(process.platform === 'darwin')('parent matches child visibility when child visibility changes', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
const wShow = once(w, 'show');
const cShow = once(c, 'show');
w.show();
c.show();
await Promise.all([wShow, cShow]);
const minimized = once(c, 'minimize');
c.minimize();
await minimized;
expect(c.isVisible()).to.be.false('child is visible');
const restored = once(c, 'restore');
c.restore();
await restored;
expect(w.isVisible()).to.be.true('parent is visible');
expect(c.isVisible()).to.be.true('child is visible');
});
it('closes a grandchild window when a middle child window is destroyed', async () => {
const w = new BrowserWindow();
w.loadFile(path.join(fixtures, 'pages', 'base-page.html'));
w.webContents.executeJavaScript('window.open("")');
w.webContents.on('did-create-window', async (window) => {
const childWindow = new BrowserWindow({ parent: window });
await setTimeout();
const closed = once(childWindow, 'closed');
window.close();
await closed;
expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw();
});
});
it('should not affect the show option', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
expect(c.isVisible()).to.be.false('child is visible');
expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible');
});
});
describe('win.setParentWindow(parent)', () => {
it('sets parent window', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false });
expect(w.getParentWindow()).to.be.null('w.parent');
expect(c.getParentWindow()).to.be.null('c.parent');
c.setParentWindow(w);
expect(c.getParentWindow()).to.equal(w);
c.setParentWindow(null);
expect(c.getParentWindow()).to.be.null('c.parent');
});
it('adds window to child windows of parent', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false });
expect(w.getChildWindows()).to.deep.equal([]);
c.setParentWindow(w);
expect(w.getChildWindows()).to.deep.equal([c]);
c.setParentWindow(null);
expect(w.getChildWindows()).to.deep.equal([]);
});
it('removes from child windows of parent when window is closed', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false });
const closed = once(c, 'closed');
c.setParentWindow(w);
c.close();
await closed;
// The child window list is not immediately cleared, so wait a tick until it's ready.
await setTimeout();
expect(w.getChildWindows().length).to.equal(0);
});
ifit(process.platform === 'darwin')('can reparent when the first parent is destroyed', async () => {
const w1 = new BrowserWindow({ show: false });
const w2 = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false });
c.setParentWindow(w1);
expect(w1.getChildWindows().length).to.equal(1);
const closed = once(w1, 'closed');
w1.destroy();
await closed;
c.setParentWindow(w2);
await setTimeout();
const children = w2.getChildWindows();
expect(children[0]).to.equal(c);
});
});
describe('modal option', () => {
it('does not freeze or crash', async () => {
const parentWindow = new BrowserWindow();
const createTwo = async () => {
const two = new BrowserWindow({
width: 300,
height: 200,
parent: parentWindow,
modal: true,
show: false
});
const twoShown = once(two, 'show');
two.show();
await twoShown;
setTimeout(500).then(() => two.close());
await once(two, 'closed');
};
const one = new BrowserWindow({
width: 600,
height: 400,
parent: parentWindow,
modal: true,
show: false
});
const oneShown = once(one, 'show');
one.show();
await oneShown;
setTimeout(500).then(() => one.destroy());
await once(one, 'closed');
await createTwo();
});
ifit(process.platform !== 'darwin')('can disable and enable a window', () => {
const w = new BrowserWindow({ show: false });
w.setEnabled(false);
expect(w.isEnabled()).to.be.false('w.isEnabled()');
w.setEnabled(true);
expect(w.isEnabled()).to.be.true('!w.isEnabled()');
});
ifit(process.platform !== 'darwin')('disables parent window', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
expect(w.isEnabled()).to.be.true('w.isEnabled');
c.show();
expect(w.isEnabled()).to.be.false('w.isEnabled');
});
ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
const closed = once(c, 'closed');
c.show();
c.close();
await closed;
expect(w.isEnabled()).to.be.true('w.isEnabled');
});
ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
const closed = once(c, 'closed');
w.setEnabled(false);
c.show();
c.close();
await closed;
expect(w.isEnabled()).to.be.false('w.isEnabled');
});
ifit(process.platform !== 'darwin')('disables parent window recursively', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
const c2 = new BrowserWindow({ show: false, parent: w, modal: true });
c.show();
expect(w.isEnabled()).to.be.false('w.isEnabled');
c2.show();
expect(w.isEnabled()).to.be.false('w.isEnabled');
c.destroy();
expect(w.isEnabled()).to.be.false('w.isEnabled');
c2.destroy();
expect(w.isEnabled()).to.be.true('w.isEnabled');
});
});
});
describe('window states', () => {
afterEach(closeAllWindows);
it('does not resize frameless windows when states change', () => {
const w = new BrowserWindow({
frame: false,
width: 300,
height: 200,
show: false
});
w.minimizable = false;
w.minimizable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
w.resizable = false;
w.resizable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
w.maximizable = false;
w.maximizable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
w.fullScreenable = false;
w.fullScreenable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
w.closable = false;
w.closable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
});
describe('resizable state', () => {
it('with properties', () => {
it('can be set with resizable constructor option', () => {
const w = new BrowserWindow({ show: false, resizable: false });
expect(w.resizable).to.be.false('resizable');
if (process.platform === 'darwin') {
expect(w.maximizable).to.to.true('maximizable');
}
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.resizable).to.be.true('resizable');
w.resizable = false;
expect(w.resizable).to.be.false('resizable');
w.resizable = true;
expect(w.resizable).to.be.true('resizable');
});
});
it('with functions', () => {
it('can be set with resizable constructor option', () => {
const w = new BrowserWindow({ show: false, resizable: false });
expect(w.isResizable()).to.be.false('resizable');
if (process.platform === 'darwin') {
expect(w.isMaximizable()).to.to.true('maximizable');
}
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isResizable()).to.be.true('resizable');
w.setResizable(false);
expect(w.isResizable()).to.be.false('resizable');
w.setResizable(true);
expect(w.isResizable()).to.be.true('resizable');
});
});
it('works for a frameless window', () => {
const w = new BrowserWindow({ show: false, frame: false });
expect(w.resizable).to.be.true('resizable');
if (process.platform === 'win32') {
const w = new BrowserWindow({ show: false, thickFrame: false });
expect(w.resizable).to.be.false('resizable');
}
});
// On Linux there is no "resizable" property of a window.
ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => {
const w = new BrowserWindow({ show: false });
expect(w.resizable).to.be.true('resizable');
expect(w.maximizable).to.be.true('maximizable');
w.resizable = false;
expect(w.maximizable).to.be.false('not maximizable');
w.resizable = true;
expect(w.maximizable).to.be.true('maximizable');
});
ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => {
const w = new BrowserWindow({
show: false,
frame: false,
resizable: false,
transparent: true
});
w.setContentSize(60, 60);
expectBoundsEqual(w.getContentSize(), [60, 60]);
w.setContentSize(30, 30);
expectBoundsEqual(w.getContentSize(), [30, 30]);
w.setContentSize(10, 10);
expectBoundsEqual(w.getContentSize(), [10, 10]);
});
ifit(process.platform === 'win32')('do not change window with frame bounds when maximized', () => {
const w = new BrowserWindow({
show: true,
frame: true,
thickFrame: true
});
expect(w.isResizable()).to.be.true('resizable');
w.maximize();
expect(w.isMaximized()).to.be.true('maximized');
const bounds = w.getBounds();
w.setResizable(false);
expectBoundsEqual(w.getBounds(), bounds);
w.setResizable(true);
expectBoundsEqual(w.getBounds(), bounds);
});
ifit(process.platform === 'win32')('do not change window without frame bounds when maximized', () => {
const w = new BrowserWindow({
show: true,
frame: false,
thickFrame: true
});
expect(w.isResizable()).to.be.true('resizable');
w.maximize();
expect(w.isMaximized()).to.be.true('maximized');
const bounds = w.getBounds();
w.setResizable(false);
expectBoundsEqual(w.getBounds(), bounds);
w.setResizable(true);
expectBoundsEqual(w.getBounds(), bounds);
});
ifit(process.platform === 'win32')('do not change window transparent without frame bounds when maximized', () => {
const w = new BrowserWindow({
show: true,
frame: false,
thickFrame: true,
transparent: true
});
expect(w.isResizable()).to.be.true('resizable');
w.maximize();
expect(w.isMaximized()).to.be.true('maximized');
const bounds = w.getBounds();
w.setResizable(false);
expectBoundsEqual(w.getBounds(), bounds);
w.setResizable(true);
expectBoundsEqual(w.getBounds(), bounds);
});
});
describe('loading main frame state', () => {
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((request, response) => {
response.end();
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('is true when the main frame is loading', async () => {
const w = new BrowserWindow({ show: false });
const didStartLoading = once(w.webContents, 'did-start-loading');
w.webContents.loadURL(serverUrl);
await didStartLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
});
it('is false when only a subframe is loading', async () => {
const w = new BrowserWindow({ show: false });
const didStopLoading = once(w.webContents, 'did-stop-loading');
w.webContents.loadURL(serverUrl);
await didStopLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
const didStartLoading = once(w.webContents, 'did-start-loading');
w.webContents.executeJavaScript(`
var iframe = document.createElement('iframe')
iframe.src = '${serverUrl}/page2'
document.body.appendChild(iframe)
`);
await didStartLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
});
it('is true when navigating to pages from the same origin', async () => {
const w = new BrowserWindow({ show: false });
const didStopLoading = once(w.webContents, 'did-stop-loading');
w.webContents.loadURL(serverUrl);
await didStopLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
const didStartLoading = once(w.webContents, 'did-start-loading');
w.webContents.loadURL(`${serverUrl}/page2`);
await didStartLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
});
});
});
ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => {
// Not implemented on Linux.
afterEach(closeAllWindows);
describe('movable state', () => {
it('with properties', () => {
it('can be set with movable constructor option', () => {
const w = new BrowserWindow({ show: false, movable: false });
expect(w.movable).to.be.false('movable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.movable).to.be.true('movable');
w.movable = false;
expect(w.movable).to.be.false('movable');
w.movable = true;
expect(w.movable).to.be.true('movable');
});
});
it('with functions', () => {
it('can be set with movable constructor option', () => {
const w = new BrowserWindow({ show: false, movable: false });
expect(w.isMovable()).to.be.false('movable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMovable()).to.be.true('movable');
w.setMovable(false);
expect(w.isMovable()).to.be.false('movable');
w.setMovable(true);
expect(w.isMovable()).to.be.true('movable');
});
});
});
describe('visibleOnAllWorkspaces state', () => {
it('with properties', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.visibleOnAllWorkspaces).to.be.false();
w.visibleOnAllWorkspaces = true;
expect(w.visibleOnAllWorkspaces).to.be.true();
});
});
it('with functions', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isVisibleOnAllWorkspaces()).to.be.false();
w.setVisibleOnAllWorkspaces(true);
expect(w.isVisibleOnAllWorkspaces()).to.be.true();
});
});
});
ifdescribe(process.platform === 'darwin')('documentEdited state', () => {
it('with properties', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.documentEdited).to.be.false();
w.documentEdited = true;
expect(w.documentEdited).to.be.true();
});
});
it('with functions', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isDocumentEdited()).to.be.false();
w.setDocumentEdited(true);
expect(w.isDocumentEdited()).to.be.true();
});
});
});
ifdescribe(process.platform === 'darwin')('representedFilename', () => {
it('with properties', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.representedFilename).to.eql('');
w.representedFilename = 'a name';
expect(w.representedFilename).to.eql('a name');
});
});
it('with functions', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.getRepresentedFilename()).to.eql('');
w.setRepresentedFilename('a name');
expect(w.getRepresentedFilename()).to.eql('a name');
});
});
});
describe('native window title', () => {
it('with properties', () => {
it('can be set with title constructor option', () => {
const w = new BrowserWindow({ show: false, title: 'mYtItLe' });
expect(w.title).to.eql('mYtItLe');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.title).to.eql('Electron Test Main');
w.title = 'NEW TITLE';
expect(w.title).to.eql('NEW TITLE');
});
});
it('with functions', () => {
it('can be set with minimizable constructor option', () => {
const w = new BrowserWindow({ show: false, title: 'mYtItLe' });
expect(w.getTitle()).to.eql('mYtItLe');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.getTitle()).to.eql('Electron Test Main');
w.setTitle('NEW TITLE');
expect(w.getTitle()).to.eql('NEW TITLE');
});
});
});
describe('minimizable state', () => {
it('with properties', () => {
it('can be set with minimizable constructor option', () => {
const w = new BrowserWindow({ show: false, minimizable: false });
expect(w.minimizable).to.be.false('minimizable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.minimizable).to.be.true('minimizable');
w.minimizable = false;
expect(w.minimizable).to.be.false('minimizable');
w.minimizable = true;
expect(w.minimizable).to.be.true('minimizable');
});
});
it('with functions', () => {
it('can be set with minimizable constructor option', () => {
const w = new BrowserWindow({ show: false, minimizable: false });
expect(w.isMinimizable()).to.be.false('movable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMinimizable()).to.be.true('isMinimizable');
w.setMinimizable(false);
expect(w.isMinimizable()).to.be.false('isMinimizable');
w.setMinimizable(true);
expect(w.isMinimizable()).to.be.true('isMinimizable');
});
});
});
describe('maximizable state (property)', () => {
it('with properties', () => {
it('can be set with maximizable constructor option', () => {
const w = new BrowserWindow({ show: false, maximizable: false });
expect(w.maximizable).to.be.false('maximizable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.maximizable).to.be.true('maximizable');
w.maximizable = false;
expect(w.maximizable).to.be.false('maximizable');
w.maximizable = true;
expect(w.maximizable).to.be.true('maximizable');
});
it('is not affected when changing other states', () => {
const w = new BrowserWindow({ show: false });
w.maximizable = false;
expect(w.maximizable).to.be.false('maximizable');
w.minimizable = false;
expect(w.maximizable).to.be.false('maximizable');
w.closable = false;
expect(w.maximizable).to.be.false('maximizable');
w.maximizable = true;
expect(w.maximizable).to.be.true('maximizable');
w.closable = true;
expect(w.maximizable).to.be.true('maximizable');
w.fullScreenable = false;
expect(w.maximizable).to.be.true('maximizable');
});
});
it('with functions', () => {
it('can be set with maximizable constructor option', () => {
const w = new BrowserWindow({ show: false, maximizable: false });
expect(w.isMaximizable()).to.be.false('isMaximizable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMaximizable()).to.be.true('isMaximizable');
w.setMaximizable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMaximizable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
});
it('is not affected when changing other states', () => {
const w = new BrowserWindow({ show: false });
w.setMaximizable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMinimizable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setClosable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMaximizable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
w.setClosable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
w.setFullScreenable(false);
expect(w.isMaximizable()).to.be.true('isMaximizable');
});
});
});
ifdescribe(process.platform === 'win32')('maximizable state', () => {
it('with properties', () => {
it('is reset to its former state', () => {
const w = new BrowserWindow({ show: false });
w.maximizable = false;
w.resizable = false;
w.resizable = true;
expect(w.maximizable).to.be.false('maximizable');
w.maximizable = true;
w.resizable = false;
w.resizable = true;
expect(w.maximizable).to.be.true('maximizable');
});
});
it('with functions', () => {
it('is reset to its former state', () => {
const w = new BrowserWindow({ show: false });
w.setMaximizable(false);
w.setResizable(false);
w.setResizable(true);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMaximizable(true);
w.setResizable(false);
w.setResizable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
});
});
});
ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => {
describe('with properties', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.menuBarVisible).to.be.true();
w.menuBarVisible = false;
expect(w.menuBarVisible).to.be.false();
w.menuBarVisible = true;
expect(w.menuBarVisible).to.be.true();
});
});
describe('with functions', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
w.setMenuBarVisibility(false);
expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible');
w.setMenuBarVisibility(true);
expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
});
});
});
ifdescribe(process.platform !== 'darwin')('when fullscreen state is changed', () => {
it('correctly remembers state prior to fullscreen change', async () => {
const w = new BrowserWindow({ show: false });
expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
w.setMenuBarVisibility(false);
expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible');
const enterFS = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFS;
expect(w.fullScreen).to.be.true('not fullscreen');
const exitFS = once(w, 'leave-full-screen');
w.setFullScreen(false);
await exitFS;
expect(w.fullScreen).to.be.false('not fullscreen');
expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible');
});
it('correctly remembers state prior to fullscreen change with autoHide', async () => {
const w = new BrowserWindow({ show: false });
expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
w.autoHideMenuBar = true;
expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
w.setMenuBarVisibility(false);
expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible');
const enterFS = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFS;
expect(w.fullScreen).to.be.true('not fullscreen');
const exitFS = once(w, 'leave-full-screen');
w.setFullScreen(false);
await exitFS;
expect(w.fullScreen).to.be.false('not fullscreen');
expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible');
});
});
ifdescribe(process.platform === 'darwin')('fullscreenable state', () => {
it('with functions', () => {
it('can be set with fullscreenable constructor option', () => {
const w = new BrowserWindow({ show: false, fullscreenable: false });
expect(w.isFullScreenable()).to.be.false('isFullScreenable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isFullScreenable()).to.be.true('isFullScreenable');
w.setFullScreenable(false);
expect(w.isFullScreenable()).to.be.false('isFullScreenable');
w.setFullScreenable(true);
expect(w.isFullScreenable()).to.be.true('isFullScreenable');
});
});
it('does not open non-fullscreenable child windows in fullscreen if parent is fullscreen', async () => {
const w = new BrowserWindow();
const enterFS = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFS;
const child = new BrowserWindow({ parent: w, resizable: false, fullscreenable: false });
const shown = once(child, 'show');
await shown;
expect(child.resizable).to.be.false('resizable');
expect(child.fullScreen).to.be.false('fullscreen');
expect(child.fullScreenable).to.be.false('fullscreenable');
});
it('is set correctly with different resizable values', async () => {
const w1 = new BrowserWindow({
resizable: false,
fullscreenable: false
});
const w2 = new BrowserWindow({
resizable: true,
fullscreenable: false
});
const w3 = new BrowserWindow({
fullscreenable: false
});
expect(w1.isFullScreenable()).to.be.false('isFullScreenable');
expect(w2.isFullScreenable()).to.be.false('isFullScreenable');
expect(w3.isFullScreenable()).to.be.false('isFullScreenable');
});
it('does not disable maximize button if window is resizable', () => {
const w = new BrowserWindow({
resizable: true,
fullscreenable: false
});
expect(w.isMaximizable()).to.be.true('isMaximizable');
w.setResizable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
});
});
ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => {
it('with functions', () => {
it('can be set with ignoreMissionControl constructor option', () => {
const w = new BrowserWindow({ show: false, hiddenInMissionControl: true });
expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl');
w.setHiddenInMissionControl(true);
expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl');
w.setHiddenInMissionControl(false);
expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl');
});
});
});
// fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron
ifdescribe(process.platform === 'darwin')('kiosk state', () => {
it('with properties', () => {
it('can be set with a constructor property', () => {
const w = new BrowserWindow({ kiosk: true });
expect(w.kiosk).to.be.true();
});
it('can be changed ', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.kiosk = true;
expect(w.isKiosk()).to.be.true('isKiosk');
await enterFullScreen;
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.kiosk = false;
expect(w.isKiosk()).to.be.false('isKiosk');
await leaveFullScreen;
});
});
it('with functions', () => {
it('can be set with a constructor property', () => {
const w = new BrowserWindow({ kiosk: true });
expect(w.isKiosk()).to.be.true();
});
it('can be changed ', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setKiosk(true);
expect(w.isKiosk()).to.be.true('isKiosk');
await enterFullScreen;
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setKiosk(false);
expect(w.isKiosk()).to.be.false('isKiosk');
await leaveFullScreen;
});
});
});
ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => {
it('resizable flag should be set to false and restored', async () => {
const w = new BrowserWindow({ resizable: false });
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.resizable).to.be.false('resizable');
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expect(w.resizable).to.be.false('resizable');
});
it('default resizable flag should be restored after entering/exiting fullscreen', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.resizable).to.be.false('resizable');
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expect(w.resizable).to.be.true('resizable');
});
});
ifdescribe(process.platform === 'darwin')('fullscreen state', () => {
it('should not cause a crash if called when exiting fullscreen', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
});
it('should be able to load a URL while transitioning to fullscreen', async () => {
const w = new BrowserWindow({ fullscreen: true });
w.loadFile(path.join(fixtures, 'pages', 'c.html'));
const load = once(w.webContents, 'did-finish-load');
const enterFS = once(w, 'enter-full-screen');
await Promise.all([enterFS, load]);
expect(w.fullScreen).to.be.true();
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
});
it('can be changed with setFullScreen method', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('isFullScreen');
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('isFullScreen');
});
it('handles several transitions starting with fullscreen', async () => {
const w = new BrowserWindow({ fullscreen: true, show: true });
expect(w.isFullScreen()).to.be.true('not fullscreen');
w.setFullScreen(false);
w.setFullScreen(true);
const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('not fullscreen');
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('is fullscreen');
});
it('handles several HTML fullscreen transitions', async () => {
const w = new BrowserWindow();
await w.loadFile(path.join(fixtures, 'pages', 'a.html'));
expect(w.isFullScreen()).to.be.false('is fullscreen');
const enterFullScreen = once(w, 'enter-full-screen');
const leaveFullScreen = once(w, 'leave-full-screen');
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFullScreen;
await w.webContents.executeJavaScript('document.exitFullscreen()', true);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('is fullscreen');
await setTimeout();
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFullScreen;
await w.webContents.executeJavaScript('document.exitFullscreen()', true);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('is fullscreen');
});
it('handles several transitions in close proximity', async () => {
const w = new BrowserWindow();
expect(w.isFullScreen()).to.be.false('is fullscreen');
const enterFS = emittedNTimes(w, 'enter-full-screen', 2);
const leaveFS = emittedNTimes(w, 'leave-full-screen', 2);
w.setFullScreen(true);
w.setFullScreen(false);
w.setFullScreen(true);
w.setFullScreen(false);
await Promise.all([enterFS, leaveFS]);
expect(w.isFullScreen()).to.be.false('not fullscreen');
});
it('handles several chromium-initiated transitions in close proximity', async () => {
const w = new BrowserWindow();
await w.loadFile(path.join(fixtures, 'pages', 'a.html'));
expect(w.isFullScreen()).to.be.false('is fullscreen');
let enterCount = 0;
let exitCount = 0;
const done = new Promise<void>(resolve => {
const checkDone = () => {
if (enterCount === 2 && exitCount === 2) resolve();
};
w.webContents.on('enter-html-full-screen', () => {
enterCount++;
checkDone();
});
w.webContents.on('leave-html-full-screen', () => {
exitCount++;
checkDone();
});
});
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await w.webContents.executeJavaScript('document.exitFullscreen()');
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await w.webContents.executeJavaScript('document.exitFullscreen()');
await done;
});
it('handles HTML fullscreen transitions when fullscreenable is false', async () => {
const w = new BrowserWindow({ fullscreenable: false });
await w.loadFile(path.join(fixtures, 'pages', 'a.html'));
expect(w.isFullScreen()).to.be.false('is fullscreen');
let enterCount = 0;
let exitCount = 0;
const done = new Promise<void>((resolve, reject) => {
const checkDone = () => {
if (enterCount === 2 && exitCount === 2) resolve();
};
w.webContents.on('enter-html-full-screen', async () => {
enterCount++;
if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false'));
const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement');
if (!isFS) reject(new Error('Document should have fullscreen element'));
checkDone();
});
w.webContents.on('leave-html-full-screen', () => {
exitCount++;
if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false'));
checkDone();
});
});
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await w.webContents.executeJavaScript('document.exitFullscreen()');
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await w.webContents.executeJavaScript('document.exitFullscreen()');
await expect(done).to.eventually.be.fulfilled();
});
it('does not crash when exiting simpleFullScreen (properties)', async () => {
const w = new BrowserWindow();
w.setSimpleFullScreen(true);
await setTimeout(1000);
w.setFullScreen(!w.isFullScreen());
});
it('does not crash when exiting simpleFullScreen (functions)', async () => {
const w = new BrowserWindow();
w.simpleFullScreen = true;
await setTimeout(1000);
w.setFullScreen(!w.isFullScreen());
});
it('should not be changed by setKiosk method', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setKiosk(true);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('isFullScreen');
const leaveFullScreen = once(w, 'leave-full-screen');
w.setKiosk(false);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('isFullScreen');
});
it('should stay fullscreen if fullscreen before kiosk', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('isFullScreen');
w.setKiosk(true);
w.setKiosk(false);
// Wait enough time for a fullscreen change to take effect.
await setTimeout(2000);
expect(w.isFullScreen()).to.be.true('isFullScreen');
});
it('multiple windows inherit correct fullscreen state', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('isFullScreen');
await setTimeout(1000);
const w2 = new BrowserWindow({ show: false });
const enterFullScreen2 = once(w2, 'enter-full-screen');
w2.show();
await enterFullScreen2;
expect(w2.isFullScreen()).to.be.true('isFullScreen');
});
});
describe('closable state', () => {
it('with properties', () => {
it('can be set with closable constructor option', () => {
const w = new BrowserWindow({ show: false, closable: false });
expect(w.closable).to.be.false('closable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.closable).to.be.true('closable');
w.closable = false;
expect(w.closable).to.be.false('closable');
w.closable = true;
expect(w.closable).to.be.true('closable');
});
});
it('with functions', () => {
it('can be set with closable constructor option', () => {
const w = new BrowserWindow({ show: false, closable: false });
expect(w.isClosable()).to.be.false('isClosable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isClosable()).to.be.true('isClosable');
w.setClosable(false);
expect(w.isClosable()).to.be.false('isClosable');
w.setClosable(true);
expect(w.isClosable()).to.be.true('isClosable');
});
});
});
describe('hasShadow state', () => {
it('with properties', () => {
it('returns a boolean on all platforms', () => {
const w = new BrowserWindow({ show: false });
expect(w.shadow).to.be.a('boolean');
});
// On Windows there's no shadow by default & it can't be changed dynamically.
it('can be changed with hasShadow option', () => {
const hasShadow = process.platform !== 'darwin';
const w = new BrowserWindow({ show: false, hasShadow });
expect(w.shadow).to.equal(hasShadow);
});
it('can be changed with setHasShadow method', () => {
const w = new BrowserWindow({ show: false });
w.shadow = false;
expect(w.shadow).to.be.false('hasShadow');
w.shadow = true;
expect(w.shadow).to.be.true('hasShadow');
w.shadow = false;
expect(w.shadow).to.be.false('hasShadow');
});
});
describe('with functions', () => {
it('returns a boolean on all platforms', () => {
const w = new BrowserWindow({ show: false });
const hasShadow = w.hasShadow();
expect(hasShadow).to.be.a('boolean');
});
// On Windows there's no shadow by default & it can't be changed dynamically.
it('can be changed with hasShadow option', () => {
const hasShadow = process.platform !== 'darwin';
const w = new BrowserWindow({ show: false, hasShadow });
expect(w.hasShadow()).to.equal(hasShadow);
});
it('can be changed with setHasShadow method', () => {
const w = new BrowserWindow({ show: false });
w.setHasShadow(false);
expect(w.hasShadow()).to.be.false('hasShadow');
w.setHasShadow(true);
expect(w.hasShadow()).to.be.true('hasShadow');
w.setHasShadow(false);
expect(w.hasShadow()).to.be.false('hasShadow');
});
});
});
});
describe('window.getMediaSourceId()', () => {
afterEach(closeAllWindows);
it('returns valid source id', async () => {
const w = new BrowserWindow({ show: false });
const shown = once(w, 'show');
w.show();
await shown;
// Check format 'window:1234:0'.
const sourceId = w.getMediaSourceId();
expect(sourceId).to.match(/^window:\d+:\d+$/);
});
});
ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => {
afterEach(closeAllWindows);
it('returns valid handle', () => {
const w = new BrowserWindow({ show: false });
const isValidWindow = require('@electron-ci/is-valid-window');
expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window');
});
});
ifdescribe(process.platform === 'darwin')('previewFile', () => {
afterEach(closeAllWindows);
it('opens the path in Quick Look on macOS', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.previewFile(__filename);
w.closeFilePreview();
}).to.not.throw();
});
it('should not call BrowserWindow show event', async () => {
const w = new BrowserWindow({ show: false });
const shown = once(w, 'show');
w.show();
await shown;
let showCalled = false;
w.on('show', () => {
showCalled = true;
});
w.previewFile(__filename);
await setTimeout(500);
expect(showCalled).to.equal(false, 'should not have called show twice');
});
});
// TODO (jkleinsc) renable these tests on mas arm64
ifdescribe(!process.mas || process.arch !== 'arm64')('contextIsolation option with and without sandbox option', () => {
const expectedContextData = {
preloadContext: {
preloadProperty: 'number',
pageProperty: 'undefined',
typeofRequire: 'function',
typeofProcess: 'object',
typeofArrayPush: 'function',
typeofFunctionApply: 'function',
typeofPreloadExecuteJavaScriptProperty: 'undefined'
},
pageContext: {
preloadProperty: 'undefined',
pageProperty: 'string',
typeofRequire: 'undefined',
typeofProcess: 'undefined',
typeofArrayPush: 'number',
typeofFunctionApply: 'boolean',
typeofPreloadExecuteJavaScriptProperty: 'number',
typeofOpenedWindow: 'object'
}
};
afterEach(closeAllWindows);
it('separates the page context from the Electron/preload context', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
const p = once(ipcMain, 'isolated-world');
iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const [, data] = await p;
expect(data).to.deep.equal(expectedContextData);
});
it('recreates the contexts on reload', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
await iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const isolatedWorld = once(ipcMain, 'isolated-world');
iw.webContents.reload();
const [, data] = await isolatedWorld;
expect(data).to.deep.equal(expectedContextData);
});
it('enables context isolation on child windows', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
const browserWindowCreated = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>;
iw.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
const [, window] = await browserWindowCreated;
expect(window.webContents.getLastWebPreferences()!.contextIsolation).to.be.true('contextIsolation');
});
it('separates the page context from the Electron/preload context with sandbox on', async () => {
const ws = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
const p = once(ipcMain, 'isolated-world');
ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const [, data] = await p;
expect(data).to.deep.equal(expectedContextData);
});
it('recreates the contexts on reload with sandbox on', async () => {
const ws = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
await ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const isolatedWorld = once(ipcMain, 'isolated-world');
ws.webContents.reload();
const [, data] = await isolatedWorld;
expect(data).to.deep.equal(expectedContextData);
});
it('supports fetch api', async () => {
const fetchWindow = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js')
}
});
const p = once(ipcMain, 'isolated-fetch-error');
fetchWindow.loadURL('about:blank');
const [, error] = await p;
expect(error).to.equal('Failed to fetch');
});
it('doesn\'t break ipc serialization', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
const p = once(ipcMain, 'isolated-world');
iw.loadURL('about:blank');
iw.webContents.executeJavaScript(`
const opened = window.open()
openedLocation = opened.location.href
opened.close()
window.postMessage({openedLocation}, '*')
`);
const [, data] = await p;
expect(data.pageContext.openedLocation).to.equal('about:blank');
});
it('reports process.contextIsolated', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-process.js')
}
});
const p = once(ipcMain, 'context-isolation');
iw.loadURL('about:blank');
const [, contextIsolation] = await p;
expect(contextIsolation).to.be.true('contextIsolation');
});
});
it('reloading does not cause Node.js module API hangs after reload', (done) => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
let count = 0;
ipcMain.on('async-node-api-done', () => {
if (count === 3) {
ipcMain.removeAllListeners('async-node-api-done');
done();
} else {
count++;
w.reload();
}
});
w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html'));
});
describe('window.webContents.focus()', () => {
afterEach(closeAllWindows);
it('focuses window', async () => {
const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 });
w1.loadURL('about:blank');
const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 });
w2.loadURL('about:blank');
const w1Focused = once(w1, 'focus');
w1.webContents.focus();
await w1Focused;
expect(w1.webContents.isFocused()).to.be.true('focuses window');
});
});
describe('offscreen rendering', () => {
let w: BrowserWindow;
beforeEach(function () {
w = new BrowserWindow({
width: 100,
height: 100,
show: false,
webPreferences: {
backgroundThrottling: false,
offscreen: true
}
});
});
afterEach(closeAllWindows);
it('creates offscreen window with correct size', async () => {
const paint = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>;
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
const [,, data] = await paint;
expect(data.constructor.name).to.equal('NativeImage');
expect(data.isEmpty()).to.be.false('data is empty');
const size = data.getSize();
const { scaleFactor } = screen.getPrimaryDisplay();
expect(size.width).to.be.closeTo(100 * scaleFactor, 2);
expect(size.height).to.be.closeTo(100 * scaleFactor, 2);
});
it('does not crash after navigation', () => {
w.webContents.loadURL('about:blank');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
});
describe('window.webContents.isOffscreen()', () => {
it('is true for offscreen type', () => {
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
expect(w.webContents.isOffscreen()).to.be.true('isOffscreen');
});
it('is false for regular window', () => {
const c = new BrowserWindow({ show: false });
expect(c.webContents.isOffscreen()).to.be.false('isOffscreen');
c.destroy();
});
});
describe('window.webContents.isPainting()', () => {
it('returns whether is currently painting', async () => {
const paint = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>;
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await paint;
expect(w.webContents.isPainting()).to.be.true('isPainting');
});
});
describe('window.webContents.stopPainting()', () => {
it('stops painting', async () => {
const domReady = once(w.webContents, 'dom-ready');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await domReady;
w.webContents.stopPainting();
expect(w.webContents.isPainting()).to.be.false('isPainting');
});
});
describe('window.webContents.startPainting()', () => {
it('starts painting', async () => {
const domReady = once(w.webContents, 'dom-ready');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await domReady;
w.webContents.stopPainting();
w.webContents.startPainting();
await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage];
expect(w.webContents.isPainting()).to.be.true('isPainting');
});
});
describe('frameRate APIs', () => {
it('has default frame rate (function)', async () => {
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage];
expect(w.webContents.getFrameRate()).to.equal(60);
});
it('has default frame rate (property)', async () => {
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage];
expect(w.webContents.frameRate).to.equal(60);
});
it('sets custom frame rate (function)', async () => {
const domReady = once(w.webContents, 'dom-ready');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await domReady;
w.webContents.setFrameRate(30);
await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage];
expect(w.webContents.getFrameRate()).to.equal(30);
});
it('sets custom frame rate (property)', async () => {
const domReady = once(w.webContents, 'dom-ready');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await domReady;
w.webContents.frameRate = 30;
await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage];
expect(w.webContents.frameRate).to.equal(30);
});
});
});
describe('"transparent" option', () => {
afterEach(closeAllWindows);
ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => {
const w = new BrowserWindow({
frame: false,
transparent: true
});
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
expect(w.isMaximized()).to.be.false();
expect(w.isMinimized()).to.be.true();
});
// Only applicable on Windows where transparent windows can't be maximized.
ifit(process.platform === 'win32')('can show maximized frameless window', async () => {
const display = screen.getPrimaryDisplay();
const w = new BrowserWindow({
...display.bounds,
frame: false,
transparent: true,
show: true
});
w.loadURL('about:blank');
await once(w, 'ready-to-show');
expect(w.isMaximized()).to.be.true();
// Fails when the transparent HWND is in an invalid maximized state.
expect(w.getBounds()).to.deep.equal(display.workArea);
const newBounds = { width: 256, height: 256, x: 0, y: 0 };
w.setBounds(newBounds);
expect(w.getBounds()).to.deep.equal(newBounds);
});
// Linux and arm64 platforms (WOA and macOS) do not return any capture sources
ifit(process.platform === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => {
const display = screen.getPrimaryDisplay();
const backgroundWindow = new BrowserWindow({
...display.bounds,
frame: false,
backgroundColor: HexColors.GREEN,
hasShadow: false
});
await backgroundWindow.loadURL('about:blank');
const foregroundWindow = new BrowserWindow({
...display.bounds,
show: true,
transparent: true,
frame: false,
hasShadow: false
});
const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html');
await foregroundWindow.loadFile(colorFile);
await setTimeout(1000);
const screenCapture = await captureScreen();
const leftHalfColor = getPixelColor(screenCapture, {
x: display.size.width / 4,
y: display.size.height / 2
});
const rightHalfColor = getPixelColor(screenCapture, {
x: display.size.width - (display.size.width / 4),
y: display.size.height / 2
});
expect(areColorsSimilar(leftHalfColor, HexColors.GREEN)).to.be.true();
expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true();
});
ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => {
const display = screen.getPrimaryDisplay();
const backgroundWindow = new BrowserWindow({
...display.bounds,
frame: false,
backgroundColor: HexColors.PURPLE,
hasShadow: false
});
await backgroundWindow.loadURL('about:blank');
const foregroundWindow = new BrowserWindow({
...display.bounds,
frame: false,
transparent: true,
hasShadow: false,
webPreferences: {
contextIsolation: false,
nodeIntegration: true
}
});
foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html'));
await once(ipcMain, 'set-transparent');
await setTimeout(1000);
const screenCapture = await captureScreen();
const centerColor = getPixelColor(screenCapture, {
x: display.size.width / 2,
y: display.size.height / 2
});
expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true();
});
// Linux and arm64 platforms (WOA and macOS) do not return any capture sources
ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => {
const display = screen.getPrimaryDisplay();
for (const transparent of [false, undefined]) {
const window = new BrowserWindow({
...display.bounds,
transparent
});
await once(window, 'show');
await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>');
await setTimeout(1000);
const screenCapture = await captureScreen();
const centerColor = getPixelColor(screenCapture, {
x: display.size.width / 2,
y: display.size.height / 2
});
window.close();
// color-scheme is set to dark so background should not be white
expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false();
}
});
});
describe('"backgroundColor" option', () => {
afterEach(closeAllWindows);
// Linux/WOA doesn't return any capture sources.
ifit(process.platform === 'darwin')('should display the set color', async () => {
const display = screen.getPrimaryDisplay();
const w = new BrowserWindow({
...display.bounds,
show: true,
backgroundColor: HexColors.BLUE
});
w.loadURL('about:blank');
await once(w, 'ready-to-show');
await setTimeout(1000);
const screenCapture = await captureScreen();
const centerColor = getPixelColor(screenCapture, {
x: display.size.width / 2,
y: display.size.height / 2
});
expect(areColorsSimilar(centerColor, HexColors.BLUE)).to.be.true();
});
});
describe('draggable regions', () => {
afterEach(closeAllWindows);
ifit(hasCapturableScreen())('should allow the window to be dragged when enabled', async () => {
// WOA fails to load libnut so we're using require to defer loading only
// on supported platforms.
// "@nut-tree\libnut-win32\build\Release\libnut.node is not a valid Win32 application."
// @ts-ignore: nut-js is an optional dependency so it may not be installed
const { mouse, straightTo, centerOf, Region, Button } = require('@nut-tree/nut-js') as typeof import('@nut-tree/nut-js');
const display = screen.getPrimaryDisplay();
const w = new BrowserWindow({
x: 0,
y: 0,
width: display.bounds.width / 2,
height: display.bounds.height / 2,
frame: false,
titleBarStyle: 'hidden'
});
const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
w.loadFile(overlayHTML);
await once(w, 'ready-to-show');
const winBounds = w.getBounds();
const titleBarHeight = 30;
const titleBarRegion = new Region(winBounds.x, winBounds.y, winBounds.width, titleBarHeight);
const screenRegion = new Region(display.bounds.x, display.bounds.y, display.bounds.width, display.bounds.height);
const startPos = w.getPosition();
await mouse.setPosition(await centerOf(titleBarRegion));
await mouse.pressButton(Button.LEFT);
await mouse.drag(straightTo(centerOf(screenRegion)));
// Wait for move to complete
await Promise.race([
once(w, 'move'),
setTimeout(100) // fallback for possible race condition
]);
const endPos = w.getPosition();
expect(startPos).to.not.deep.equal(endPos);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 41,464 |
[Bug]: Docs - webContents.print() options aren't optional
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
28.2.4
### What operating system are you using?
Windows
### Operating System Version
Windows 11 23H2
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
```js
webContents.print(); // ok, without error
```
### Actual Behavior
```js
webContents.print(); // TypeError: webContents.print(): Invalid print settings specified.
webContents.print({}); // with empty object - ok
```
### Testcase Gist URL
_No response_
### Additional Information
Docs: https://www.electronjs.org/docs/latest/api/web-contents#contentsprintoptions-callback
|
https://github.com/electron/electron/issues/41464
|
https://github.com/electron/electron/pull/41467
|
a0dad83ded4661eb873cc62b75bb0f406ad7fecb
|
d5912fd05a1f998b347aa97a7b80951a453d1f4c
| 2024-02-28T07:51:22Z |
c++
| 2024-02-29T15:19:44Z |
lib/browser/api/web-contents.ts
|
import { app, ipcMain, session, webFrameMain, dialog } from 'electron/main';
import type { BrowserWindowConstructorOptions, LoadURLOptions, MessageBoxOptions, WebFrameMain } from 'electron/main';
import * as url from 'url';
import * as path from 'path';
import { openGuestWindow, makeWebPreferences, parseContentTypeFormat } from '@electron/internal/browser/guest-window-manager';
import { parseFeatures } from '@electron/internal/browser/parse-features-string';
import { ipcMainInternal } from '@electron/internal/browser/ipc-main-internal';
import * as ipcMainUtils from '@electron/internal/browser/ipc-main-internal-utils';
import { MessagePortMain } from '@electron/internal/browser/message-port-main';
import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages';
import { IpcMainImpl } from '@electron/internal/browser/ipc-main-impl';
import * as deprecate from '@electron/internal/common/deprecate';
// session is not used here, the purpose is to make sure session is initialized
// before the webContents module.
// eslint-disable-next-line no-unused-expressions
session;
const webFrameMainBinding = process._linkedBinding('electron_browser_web_frame_main');
let nextId = 0;
const getNextId = function () {
return ++nextId;
};
type PostData = LoadURLOptions['postData']
// Stock page sizes
const PDFPageSizes: Record<string, ElectronInternal.MediaSize> = {
Letter: {
custom_display_name: 'Letter',
height_microns: 279400,
name: 'NA_LETTER',
width_microns: 215900
},
Legal: {
custom_display_name: 'Legal',
height_microns: 355600,
name: 'NA_LEGAL',
width_microns: 215900
},
Tabloid: {
height_microns: 431800,
name: 'NA_LEDGER',
width_microns: 279400,
custom_display_name: 'Tabloid'
},
A0: {
custom_display_name: 'A0',
height_microns: 1189000,
name: 'ISO_A0',
width_microns: 841000
},
A1: {
custom_display_name: 'A1',
height_microns: 841000,
name: 'ISO_A1',
width_microns: 594000
},
A2: {
custom_display_name: 'A2',
height_microns: 594000,
name: 'ISO_A2',
width_microns: 420000
},
A3: {
custom_display_name: 'A3',
height_microns: 420000,
name: 'ISO_A3',
width_microns: 297000
},
A4: {
custom_display_name: 'A4',
height_microns: 297000,
name: 'ISO_A4',
is_default: 'true',
width_microns: 210000
},
A5: {
custom_display_name: 'A5',
height_microns: 210000,
name: 'ISO_A5',
width_microns: 148000
},
A6: {
custom_display_name: 'A6',
height_microns: 148000,
name: 'ISO_A6',
width_microns: 105000
}
} as const;
const paperFormats: Record<string, ElectronInternal.PageSize> = {
letter: { width: 8.5, height: 11 },
legal: { width: 8.5, height: 14 },
tabloid: { width: 11, height: 17 },
ledger: { width: 17, height: 11 },
a0: { width: 33.1, height: 46.8 },
a1: { width: 23.4, height: 33.1 },
a2: { width: 16.54, height: 23.4 },
a3: { width: 11.7, height: 16.54 },
a4: { width: 8.27, height: 11.7 },
a5: { width: 5.83, height: 8.27 },
a6: { width: 4.13, height: 5.83 }
} as const;
// The minimum micron size Chromium accepts is that where:
// Per printing/units.h:
// * kMicronsPerInch - Length of an inch in 0.001mm unit.
// * kPointsPerInch - Length of an inch in CSS's 1pt unit.
//
// Formula: (kPointsPerInch / kMicronsPerInch) * size >= 1
//
// Practically, this means microns need to be > 352 microns.
// We therefore need to verify this or it will silently fail.
const isValidCustomPageSize = (width: number, height: number) => {
return [width, height].every(x => x > 352);
};
// JavaScript implementations of WebContents.
const binding = process._linkedBinding('electron_browser_web_contents');
const printing = process._linkedBinding('electron_browser_printing');
const { WebContents } = binding as { WebContents: { prototype: Electron.WebContents } };
WebContents.prototype.postMessage = function (...args) {
return this.mainFrame.postMessage(...args);
};
WebContents.prototype.send = function (channel, ...args) {
return this.mainFrame.send(channel, ...args);
};
WebContents.prototype._sendInternal = function (channel, ...args) {
return this.mainFrame._sendInternal(channel, ...args);
};
function getWebFrame (contents: Electron.WebContents, frame: number | [number, number]) {
if (typeof frame === 'number') {
return webFrameMain.fromId(contents.mainFrame.processId, frame);
} else if (Array.isArray(frame) && frame.length === 2 && frame.every(value => typeof value === 'number')) {
return webFrameMain.fromId(frame[0], frame[1]);
} else {
throw new Error('Missing required frame argument (must be number or [processId, frameId])');
}
}
WebContents.prototype.sendToFrame = function (frameId, channel, ...args) {
const frame = getWebFrame(this, frameId);
if (!frame) return false;
frame.send(channel, ...args);
return true;
};
// Following methods are mapped to webFrame.
const webFrameMethods = [
'insertCSS',
'insertText',
'removeInsertedCSS',
'setVisualZoomLevelLimits'
] as ('insertCSS' | 'insertText' | 'removeInsertedCSS' | 'setVisualZoomLevelLimits')[];
for (const method of webFrameMethods) {
WebContents.prototype[method] = function (...args: any[]): Promise<any> {
return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, method, ...args);
};
}
const waitTillCanExecuteJavaScript = async (webContents: Electron.WebContents) => {
if (webContents.getURL() && !webContents.isLoadingMainFrame()) return;
return new Promise<void>((resolve) => {
webContents.once('did-stop-loading', () => {
resolve();
});
});
};
// Make sure WebContents::executeJavaScript would run the code only when the
// WebContents has been loaded.
WebContents.prototype.executeJavaScript = async function (code, hasUserGesture) {
await waitTillCanExecuteJavaScript(this);
return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, 'executeJavaScript', String(code), !!hasUserGesture);
};
WebContents.prototype.executeJavaScriptInIsolatedWorld = async function (worldId, code, hasUserGesture) {
await waitTillCanExecuteJavaScript(this);
return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, 'executeJavaScriptInIsolatedWorld', worldId, code, !!hasUserGesture);
};
function checkType<T> (value: T, type: 'number' | 'boolean' | 'string' | 'object', name: string): T {
// eslint-disable-next-line valid-typeof
if (typeof value !== type) {
throw new TypeError(`${name} must be a ${type}`);
}
return value;
}
function parsePageSize (pageSize: string | ElectronInternal.PageSize) {
if (typeof pageSize === 'string') {
const format = paperFormats[pageSize.toLowerCase()];
if (!format) {
throw new Error(`Invalid pageSize ${pageSize}`);
}
return { paperWidth: format.width, paperHeight: format.height };
} else if (typeof pageSize === 'object') {
if (typeof pageSize.width !== 'number' || typeof pageSize.height !== 'number') {
throw new TypeError('width and height properties are required for pageSize');
}
return { paperWidth: pageSize.width, paperHeight: pageSize.height };
} else {
throw new TypeError('pageSize must be a string or an object');
}
}
// Translate the options of printToPDF.
let pendingPromise: Promise<any> | undefined;
WebContents.prototype.printToPDF = async function (options) {
const margins = checkType(options.margins ?? {}, 'object', 'margins');
const pageSize = parsePageSize(options.pageSize ?? 'letter');
const { top, bottom, left, right } = margins;
const validHeight = [top, bottom].every(u => u === undefined || u <= pageSize.paperHeight);
const validWidth = [left, right].every(u => u === undefined || u <= pageSize.paperWidth);
if (!validHeight || !validWidth) {
throw new Error('margins must be less than or equal to pageSize');
}
const printSettings = {
requestID: getNextId(),
landscape: checkType(options.landscape ?? false, 'boolean', 'landscape'),
displayHeaderFooter: checkType(options.displayHeaderFooter ?? false, 'boolean', 'displayHeaderFooter'),
headerTemplate: checkType(options.headerTemplate ?? '', 'string', 'headerTemplate'),
footerTemplate: checkType(options.footerTemplate ?? '', 'string', 'footerTemplate'),
printBackground: checkType(options.printBackground ?? false, 'boolean', 'printBackground'),
scale: checkType(options.scale ?? 1.0, 'number', 'scale'),
marginTop: checkType(margins.top ?? 0.4, 'number', 'margins.top'),
marginBottom: checkType(margins.bottom ?? 0.4, 'number', 'margins.bottom'),
marginLeft: checkType(margins.left ?? 0.4, 'number', 'margins.left'),
marginRight: checkType(margins.right ?? 0.4, 'number', 'margins.right'),
pageRanges: checkType(options.pageRanges ?? '', 'string', 'pageRanges'),
preferCSSPageSize: checkType(options.preferCSSPageSize ?? false, 'boolean', 'preferCSSPageSize'),
generateTaggedPDF: checkType(options.generateTaggedPDF ?? false, 'boolean', 'generateTaggedPDF'),
generateDocumentOutline: checkType(options.generateDocumentOutline ?? false, 'boolean', 'generateDocumentOutline'),
...pageSize
};
if (this._printToPDF) {
if (pendingPromise) {
pendingPromise = pendingPromise.then(() => this._printToPDF(printSettings));
} else {
pendingPromise = this._printToPDF(printSettings);
}
return pendingPromise;
} else {
throw new Error('Printing feature is disabled');
}
};
// TODO(codebytere): deduplicate argument sanitization by moving rest of
// print param logic into new file shared between printToPDF and print
WebContents.prototype.print = function (options: ElectronInternal.WebContentsPrintOptions, callback) {
if (typeof options !== 'object') {
throw new TypeError('webContents.print(): Invalid print settings specified.');
}
const printSettings: Record<string, any> = { ...options };
const pageSize = options.pageSize ?? 'A4';
if (typeof pageSize === 'object') {
if (!pageSize.height || !pageSize.width) {
throw new Error('height and width properties are required for pageSize');
}
// Dimensions in Microns - 1 meter = 10^6 microns
const height = Math.ceil(pageSize.height);
const width = Math.ceil(pageSize.width);
if (!isValidCustomPageSize(width, height)) {
throw new RangeError('height and width properties must be minimum 352 microns.');
}
printSettings.mediaSize = {
name: 'CUSTOM',
custom_display_name: 'Custom',
height_microns: height,
width_microns: width,
imageable_area_left_microns: 0,
imageable_area_bottom_microns: 0,
imageable_area_right_microns: width,
imageable_area_top_microns: height
};
} else if (typeof pageSize === 'string' && PDFPageSizes[pageSize]) {
const mediaSize = PDFPageSizes[pageSize];
printSettings.mediaSize = {
...mediaSize,
imageable_area_left_microns: 0,
imageable_area_bottom_microns: 0,
imageable_area_right_microns: mediaSize.width_microns,
imageable_area_top_microns: mediaSize.height_microns
};
} else {
throw new Error(`Unsupported pageSize: ${pageSize}`);
}
if (this._print) {
if (callback) {
this._print(printSettings, callback);
} else {
this._print(printSettings);
}
} else {
console.error('Error: Printing feature is disabled.');
}
};
WebContents.prototype.getPrintersAsync = async function () {
// TODO(nornagon): this API has nothing to do with WebContents and should be
// moved.
if (printing.getPrinterListAsync) {
return printing.getPrinterListAsync();
} else {
console.error('Error: Printing feature is disabled.');
return [];
}
};
WebContents.prototype.loadFile = function (filePath, options = {}) {
if (typeof filePath !== 'string') {
throw new TypeError('Must pass filePath as a string');
}
const { query, search, hash } = options;
return this.loadURL(url.format({
protocol: 'file',
slashes: true,
pathname: path.resolve(app.getAppPath(), filePath),
query,
search,
hash
}));
};
type LoadError = { errorCode: number, errorDescription: string, url: string };
WebContents.prototype.loadURL = function (url, options) {
const p = new Promise<void>((resolve, reject) => {
const resolveAndCleanup = () => {
removeListeners();
resolve();
};
let error: LoadError | undefined;
const rejectAndCleanup = ({ errorCode, errorDescription, url }: LoadError) => {
const err = new Error(`${errorDescription} (${errorCode}) loading '${typeof url === 'string' ? url.substr(0, 2048) : url}'`);
Object.assign(err, { errno: errorCode, code: errorDescription, url });
removeListeners();
reject(err);
};
const finishListener = () => {
if (error) {
rejectAndCleanup(error);
} else {
resolveAndCleanup();
}
};
let navigationStarted = false;
let browserInitiatedInPageNavigation = false;
const navigationListener = (event: Electron.Event, url: string, isSameDocument: boolean, isMainFrame: boolean) => {
if (isMainFrame) {
if (navigationStarted && !isSameDocument) {
// the webcontents has started another unrelated navigation in the
// main frame (probably from the app calling `loadURL` again); reject
// the promise
// We should only consider the request aborted if the "navigation" is
// actually navigating and not simply transitioning URL state in the
// current context. E.g. pushState and `location.hash` changes are
// considered navigation events but are triggered with isSameDocument.
// We can ignore these to allow virtual routing on page load as long
// as the routing does not leave the document
return rejectAndCleanup({ errorCode: -3, errorDescription: 'ERR_ABORTED', url });
}
browserInitiatedInPageNavigation = navigationStarted && isSameDocument;
navigationStarted = true;
}
};
const failListener = (event: Electron.Event, errorCode: number, errorDescription: string, validatedURL: string, isMainFrame: boolean) => {
if (!error && isMainFrame) {
error = { errorCode, errorDescription, url: validatedURL };
}
if (!navigationStarted && isMainFrame) {
finishListener();
}
};
const stopLoadingListener = () => {
// By the time we get here, either 'finish' or 'fail' should have fired
// if the navigation occurred. However, in some situations (e.g. when
// attempting to load a page with a bad scheme), loading will stop
// without emitting finish or fail. In this case, we reject the promise
// with a generic failure.
// TODO(jeremy): enumerate all the cases in which this can happen. If
// the only one is with a bad scheme, perhaps ERR_INVALID_ARGUMENT
// would be more appropriate.
if (!error) {
error = { errorCode: -2, errorDescription: 'ERR_FAILED', url: url };
}
finishListener();
};
const finishListenerWhenUserInitiatedNavigation = () => {
if (!browserInitiatedInPageNavigation) {
finishListener();
}
};
const removeListeners = () => {
this.removeListener('did-finish-load', finishListener);
this.removeListener('did-fail-load', failListener);
this.removeListener('did-navigate-in-page', finishListenerWhenUserInitiatedNavigation);
this.removeListener('did-start-navigation', navigationListener);
this.removeListener('did-stop-loading', stopLoadingListener);
this.removeListener('destroyed', stopLoadingListener);
};
this.on('did-finish-load', finishListener);
this.on('did-fail-load', failListener);
this.on('did-navigate-in-page', finishListenerWhenUserInitiatedNavigation);
this.on('did-start-navigation', navigationListener);
this.on('did-stop-loading', stopLoadingListener);
this.on('destroyed', stopLoadingListener);
});
// Add a no-op rejection handler to silence the unhandled rejection error.
p.catch(() => {});
this._loadURL(url, options ?? {});
return p;
};
WebContents.prototype.setWindowOpenHandler = function (handler: (details: Electron.HandlerDetails) => Electron.WindowOpenHandlerResponse) {
this._windowOpenHandler = handler;
};
WebContents.prototype._callWindowOpenHandler = function (event: Electron.Event, details: Electron.HandlerDetails): {browserWindowConstructorOptions: BrowserWindowConstructorOptions | null, outlivesOpener: boolean, createWindow?: Electron.CreateWindowFunction} {
const defaultResponse = {
browserWindowConstructorOptions: null,
outlivesOpener: false,
createWindow: undefined
};
if (!this._windowOpenHandler) {
return defaultResponse;
}
const response = this._windowOpenHandler(details);
if (typeof response !== 'object') {
event.preventDefault();
console.error(`The window open handler response must be an object, but was instead of type '${typeof response}'.`);
return defaultResponse;
}
if (response === null) {
event.preventDefault();
console.error('The window open handler response must be an object, but was instead null.');
return defaultResponse;
}
if (response.action === 'deny') {
event.preventDefault();
return defaultResponse;
} else if (response.action === 'allow') {
return {
browserWindowConstructorOptions: typeof response.overrideBrowserWindowOptions === 'object' ? response.overrideBrowserWindowOptions : null,
outlivesOpener: typeof response.outlivesOpener === 'boolean' ? response.outlivesOpener : false,
createWindow: typeof response.createWindow === 'function' ? response.createWindow : undefined
};
} else {
event.preventDefault();
console.error('The window open handler response must be an object with an \'action\' property of \'allow\' or \'deny\'.');
return defaultResponse;
}
};
const addReplyToEvent = (event: Electron.IpcMainEvent) => {
const { processId, frameId } = event;
event.reply = (channel: string, ...args: any[]) => {
event.sender.sendToFrame([processId, frameId], channel, ...args);
};
};
const addSenderToEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent, sender: Electron.WebContents) => {
event.sender = sender;
const { processId, frameId } = event;
Object.defineProperty(event, 'senderFrame', {
get: () => webFrameMain.fromId(processId, frameId)
});
};
const addReturnValueToEvent = (event: Electron.IpcMainEvent) => {
Object.defineProperty(event, 'returnValue', {
set: (value) => event._replyChannel.sendReply(value),
get: () => {}
});
};
const getWebFrameForEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent) => {
if (!event.processId || !event.frameId) return null;
return webFrameMainBinding.fromIdOrNull(event.processId, event.frameId);
};
const commandLine = process._linkedBinding('electron_common_command_line');
const environment = process._linkedBinding('electron_common_environment');
const loggingEnabled = () => {
return environment.hasVar('ELECTRON_ENABLE_LOGGING') || commandLine.hasSwitch('enable-logging');
};
// Add JavaScript wrappers for WebContents class.
WebContents.prototype._init = function () {
const prefs = this.getLastWebPreferences() || {};
if (!prefs.nodeIntegration && prefs.preload != null && prefs.sandbox == null) {
deprecate.log('The default sandbox option for windows without nodeIntegration is changing. Presently, by default, when a window has a preload script, it defaults to being unsandboxed. In Electron 20, this default will be changing, and all windows that have nodeIntegration: false (which is the default) will be sandboxed by default. If your preload script doesn\'t use Node, no action is needed. If your preload script does use Node, either refactor it to move Node usage to the main process, or specify sandbox: false in your WebPreferences.');
}
// Read off the ID at construction time, so that it's accessible even after
// the underlying C++ WebContents is destroyed.
const id = this.id;
Object.defineProperty(this, 'id', {
value: id,
writable: false
});
this._windowOpenHandler = null;
const ipc = new IpcMainImpl();
Object.defineProperty(this, 'ipc', {
get () { return ipc; },
enumerable: true
});
// Dispatch IPC messages to the ipc module.
this.on('-ipc-message' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) {
addSenderToEvent(event, this);
if (internal) {
ipcMainInternal.emit(channel, event, ...args);
} else {
addReplyToEvent(event);
this.emit('ipc-message', event, channel, ...args);
const maybeWebFrame = getWebFrameForEvent(event);
maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, ...args);
ipc.emit(channel, event, ...args);
ipcMain.emit(channel, event, ...args);
}
});
this.on('-ipc-invoke' as any, async function (this: Electron.WebContents, event: Electron.IpcMainInvokeEvent, internal: boolean, channel: string, args: any[]) {
addSenderToEvent(event, this);
const replyWithResult = (result: any) => event._replyChannel.sendReply({ result });
const replyWithError = (error: Error) => {
console.error(`Error occurred in handler for '${channel}':`, error);
event._replyChannel.sendReply({ error: error.toString() });
};
const maybeWebFrame = getWebFrameForEvent(event);
const targets: (ElectronInternal.IpcMainInternal| undefined)[] = internal ? [ipcMainInternal] : [maybeWebFrame?.ipc, ipc, ipcMain];
const target = targets.find(target => target && (target as any)._invokeHandlers.has(channel));
if (target) {
const handler = (target as any)._invokeHandlers.get(channel);
try {
replyWithResult(await Promise.resolve(handler(event, ...args)));
} catch (err) {
replyWithError(err as Error);
}
} else {
replyWithError(new Error(`No handler registered for '${channel}'`));
}
});
this.on('-ipc-message-sync' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) {
addSenderToEvent(event, this);
addReturnValueToEvent(event);
if (internal) {
ipcMainInternal.emit(channel, event, ...args);
} else {
addReplyToEvent(event);
const maybeWebFrame = getWebFrameForEvent(event);
if (this.listenerCount('ipc-message-sync') === 0 && ipc.listenerCount(channel) === 0 && ipcMain.listenerCount(channel) === 0 && (!maybeWebFrame || maybeWebFrame.ipc.listenerCount(channel) === 0)) {
console.warn(`WebContents #${this.id} called ipcRenderer.sendSync() with '${channel}' channel without listeners.`);
}
this.emit('ipc-message-sync', event, channel, ...args);
maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, ...args);
ipc.emit(channel, event, ...args);
ipcMain.emit(channel, event, ...args);
}
});
this.on('-ipc-ports' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, message: any, ports: any[]) {
addSenderToEvent(event, this);
event.ports = ports.map(p => new MessagePortMain(p));
const maybeWebFrame = getWebFrameForEvent(event);
maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, message);
ipc.emit(channel, event, message);
ipcMain.emit(channel, event, message);
});
this.on('render-process-gone', (event, details) => {
app.emit('render-process-gone', event, this, details);
// Log out a hint to help users better debug renderer crashes.
if (loggingEnabled()) {
console.info(`Renderer process ${details.reason} - see https://www.electronjs.org/docs/tutorial/application-debugging for potential debugging information.`);
}
});
this.on('-before-unload-fired' as any, function (this: Electron.WebContents, event: Electron.Event, proceed: boolean) {
const type = this.getType();
// These are the "interactive" types, i.e. ones a user might be looking at.
// All other types should ignore the "proceed" signal and unload
// regardless.
if (type === 'window' || type === 'offscreen' || type === 'browserView') {
if (!proceed) { return event.preventDefault(); }
}
});
// The devtools requests the webContents to reload.
this.on('devtools-reload-page', function (this: Electron.WebContents) {
this.reload();
});
if (this.getType() !== 'remote') {
// Make new windows requested by links behave like "window.open".
this.on('-new-window' as any, (event: Electron.Event, url: string, frameName: string, disposition: Electron.HandlerDetails['disposition'],
rawFeatures: string, referrer: Electron.Referrer, postData: PostData) => {
const postBody = postData ? {
data: postData,
...parseContentTypeFormat(postData)
} : undefined;
const details: Electron.HandlerDetails = {
url,
frameName,
features: rawFeatures,
referrer,
postBody,
disposition
};
let result: ReturnType<typeof this._callWindowOpenHandler>;
try {
result = this._callWindowOpenHandler(event, details);
} catch (err) {
event.preventDefault();
throw err;
}
const options = result.browserWindowConstructorOptions;
if (!event.defaultPrevented) {
openGuestWindow({
embedder: this,
disposition,
referrer,
postData,
overrideBrowserWindowOptions: options || {},
windowOpenArgs: details,
outlivesOpener: result.outlivesOpener,
createWindow: result.createWindow
});
}
});
let windowOpenOverriddenOptions: BrowserWindowConstructorOptions | null = null;
let windowOpenOutlivesOpenerOption: boolean = false;
let createWindow: Electron.CreateWindowFunction | undefined;
this.on('-will-add-new-contents' as any, (event: Electron.Event, url: string, frameName: string, rawFeatures: string, disposition: Electron.HandlerDetails['disposition'], referrer: Electron.Referrer, postData: PostData) => {
const postBody = postData ? {
data: postData,
...parseContentTypeFormat(postData)
} : undefined;
const details: Electron.HandlerDetails = {
url,
frameName,
features: rawFeatures,
disposition,
referrer,
postBody
};
let result: ReturnType<typeof this._callWindowOpenHandler>;
try {
result = this._callWindowOpenHandler(event, details);
} catch (err) {
event.preventDefault();
throw err;
}
windowOpenOutlivesOpenerOption = result.outlivesOpener;
windowOpenOverriddenOptions = result.browserWindowConstructorOptions;
createWindow = result.createWindow;
if (!event.defaultPrevented) {
const secureOverrideWebPreferences = windowOpenOverriddenOptions ? {
// Allow setting of backgroundColor as a webPreference even though
// it's technically a BrowserWindowConstructorOptions option because
// we need to access it in the renderer at init time.
backgroundColor: windowOpenOverriddenOptions.backgroundColor,
transparent: windowOpenOverriddenOptions.transparent,
...windowOpenOverriddenOptions.webPreferences
} : undefined;
const { webPreferences: parsedWebPreferences } = parseFeatures(rawFeatures);
const webPreferences = makeWebPreferences({
embedder: this,
insecureParsedWebPreferences: parsedWebPreferences,
secureOverrideWebPreferences
});
windowOpenOverriddenOptions = {
...windowOpenOverriddenOptions,
webPreferences
};
this._setNextChildWebPreferences(webPreferences);
}
});
// Create a new browser window for "window.open"
this.on('-add-new-contents' as any, (event: Electron.Event, webContents: Electron.WebContents, disposition: string,
_userGesture: boolean, _left: number, _top: number, _width: number, _height: number, url: string, frameName: string,
referrer: Electron.Referrer, rawFeatures: string, postData: PostData) => {
const overriddenOptions = windowOpenOverriddenOptions || undefined;
const outlivesOpener = windowOpenOutlivesOpenerOption;
const windowOpenFunction = createWindow;
createWindow = undefined;
windowOpenOverriddenOptions = null;
// false is the default
windowOpenOutlivesOpenerOption = false;
if ((disposition !== 'foreground-tab' && disposition !== 'new-window' &&
disposition !== 'background-tab')) {
event.preventDefault();
return;
}
openGuestWindow({
embedder: this,
guest: webContents,
overrideBrowserWindowOptions: overriddenOptions,
disposition,
referrer,
postData,
windowOpenArgs: {
url,
frameName,
features: rawFeatures
},
outlivesOpener,
createWindow: windowOpenFunction
});
});
}
this.on('login', (event, ...args) => {
app.emit('login', event, this, ...args);
});
this.on('ready-to-show' as any, () => {
const owner = this.getOwnerBrowserWindow();
if (owner && !owner.isDestroyed()) {
process.nextTick(() => {
owner.emit('ready-to-show');
});
}
});
this.on('select-bluetooth-device', (event, devices, callback) => {
if (this.listenerCount('select-bluetooth-device') === 1) {
// Cancel it if there are no handlers
event.preventDefault();
callback('');
}
});
const originCounts = new Map<string, number>();
const openDialogs = new Set<AbortController>();
this.on('-run-dialog' as any, async (info: {frame: WebFrameMain, dialogType: 'prompt' | 'confirm' | 'alert', messageText: string, defaultPromptText: string}, callback: (success: boolean, user_input: string) => void) => {
const originUrl = new URL(info.frame.url);
const origin = originUrl.protocol === 'file:' ? originUrl.href : originUrl.origin;
if ((originCounts.get(origin) ?? 0) < 0) return callback(false, '');
const prefs = this.getLastWebPreferences();
if (!prefs || prefs.disableDialogs) return callback(false, '');
// We don't support prompt() for some reason :)
if (info.dialogType === 'prompt') return callback(false, '');
originCounts.set(origin, (originCounts.get(origin) ?? 0) + 1);
// TODO: translate?
const checkbox = originCounts.get(origin)! > 1 && prefs.safeDialogs ? prefs.safeDialogsMessage || 'Prevent this app from creating additional dialogs' : '';
const parent = this.getOwnerBrowserWindow();
const abortController = new AbortController();
const options: MessageBoxOptions = {
message: info.messageText,
checkboxLabel: checkbox,
signal: abortController.signal,
...(info.dialogType === 'confirm') ? {
buttons: ['OK', 'Cancel'],
defaultId: 0,
cancelId: 1
} : {
buttons: ['OK'],
defaultId: -1, // No default button
cancelId: 0
}
};
openDialogs.add(abortController);
const promise = parent && !prefs.offscreen ? dialog.showMessageBox(parent, options) : dialog.showMessageBox(options);
try {
const result = await promise;
if (abortController.signal.aborted || this.isDestroyed()) return;
if (result.checkboxChecked) originCounts.set(origin, -1);
return callback(result.response === 0, '');
} finally {
openDialogs.delete(abortController);
}
});
this.on('-cancel-dialogs' as any, () => {
for (const controller of openDialogs) { controller.abort(); }
openDialogs.clear();
});
app.emit('web-contents-created', { sender: this, preventDefault () {}, get defaultPrevented () { return false; } }, this);
// Properties
Object.defineProperty(this, 'audioMuted', {
get: () => this.isAudioMuted(),
set: (muted) => this.setAudioMuted(muted)
});
Object.defineProperty(this, 'userAgent', {
get: () => this.getUserAgent(),
set: (agent) => this.setUserAgent(agent)
});
Object.defineProperty(this, 'zoomLevel', {
get: () => this.getZoomLevel(),
set: (level) => this.setZoomLevel(level)
});
Object.defineProperty(this, 'zoomFactor', {
get: () => this.getZoomFactor(),
set: (factor) => this.setZoomFactor(factor)
});
Object.defineProperty(this, 'frameRate', {
get: () => this.getFrameRate(),
set: (rate) => this.setFrameRate(rate)
});
Object.defineProperty(this, 'backgroundThrottling', {
get: () => this.getBackgroundThrottling(),
set: (allowed) => this.setBackgroundThrottling(allowed)
});
};
// Public APIs.
export function create (options = {}): Electron.WebContents {
return new (WebContents as any)(options);
}
export function fromId (id: string) {
return binding.fromId(id);
}
export function fromFrame (frame: Electron.WebFrameMain) {
return binding.fromFrame(frame);
}
export function fromDevToolsTargetId (targetId: string) {
return binding.fromDevToolsTargetId(targetId);
}
export function getFocusedWebContents () {
let focused = null;
for (const contents of binding.getAllWebContents()) {
if (!contents.isFocused()) continue;
if (focused == null) focused = contents;
// Return webview web contents which may be embedded inside another
// web contents that is also reporting as focused
if (contents.getType() === 'webview') return contents;
}
return focused;
}
export function getAllWebContents () {
return binding.getAllWebContents();
}
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 41,464 |
[Bug]: Docs - webContents.print() options aren't optional
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
28.2.4
### What operating system are you using?
Windows
### Operating System Version
Windows 11 23H2
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
```js
webContents.print(); // ok, without error
```
### Actual Behavior
```js
webContents.print(); // TypeError: webContents.print(): Invalid print settings specified.
webContents.print({}); // with empty object - ok
```
### Testcase Gist URL
_No response_
### Additional Information
Docs: https://www.electronjs.org/docs/latest/api/web-contents#contentsprintoptions-callback
|
https://github.com/electron/electron/issues/41464
|
https://github.com/electron/electron/pull/41467
|
a0dad83ded4661eb873cc62b75bb0f406ad7fecb
|
d5912fd05a1f998b347aa97a7b80951a453d1f4c
| 2024-02-28T07:51:22Z |
c++
| 2024-02-29T15:19:44Z |
spec/api-web-contents-spec.ts
|
import { expect } from 'chai';
import { AddressInfo } from 'node:net';
import * as path from 'node:path';
import * as fs from 'node:fs';
import * as http from 'node:http';
import { BrowserWindow, ipcMain, webContents, session, app, BrowserView, WebContents } from 'electron/main';
import { closeAllWindows } from './lib/window-helpers';
import { ifdescribe, defer, waitUntil, listen, ifit } from './lib/spec-helpers';
import { once } from 'node:events';
import { setTimeout } from 'node:timers/promises';
const pdfjs = require('pdfjs-dist');
const fixturesPath = path.resolve(__dirname, 'fixtures');
const mainFixturesPath = path.resolve(__dirname, 'fixtures');
const features = process._linkedBinding('electron_common_features');
describe('webContents module', () => {
describe('getAllWebContents() API', () => {
afterEach(closeAllWindows);
it('returns an array of web contents', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { webviewTag: true }
});
w.loadFile(path.join(fixturesPath, 'pages', 'webview-zoom-factor.html'));
await once(w.webContents, 'did-attach-webview') as [any, WebContents];
w.webContents.openDevTools();
await once(w.webContents, 'devtools-opened');
const all = webContents.getAllWebContents().sort((a, b) => {
return a.id - b.id;
});
expect(all).to.have.length(3);
expect(all[0].getType()).to.equal('window');
expect(all[all.length - 2].getType()).to.equal('webview');
expect(all[all.length - 1].getType()).to.equal('remote');
});
});
describe('fromId()', () => {
it('returns undefined for an unknown id', () => {
expect(webContents.fromId(12345)).to.be.undefined();
});
});
describe('fromFrame()', () => {
it('returns WebContents for mainFrame', () => {
const contents = (webContents as typeof ElectronInternal.WebContents).create();
expect(webContents.fromFrame(contents.mainFrame)).to.equal(contents);
});
it('returns undefined for disposed frame', async () => {
const contents = (webContents as typeof ElectronInternal.WebContents).create();
const { mainFrame } = contents;
contents.destroy();
await waitUntil(() => typeof webContents.fromFrame(mainFrame) === 'undefined');
});
it('throws when passing invalid argument', async () => {
let errored = false;
try {
webContents.fromFrame({} as any);
} catch {
errored = true;
}
expect(errored).to.be.true();
});
});
describe('fromDevToolsTargetId()', () => {
it('returns WebContents for attached DevTools target', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
try {
await w.webContents.debugger.attach('1.3');
const { targetInfo } = await w.webContents.debugger.sendCommand('Target.getTargetInfo');
expect(webContents.fromDevToolsTargetId(targetInfo.targetId)).to.equal(w.webContents);
} finally {
await w.webContents.debugger.detach();
}
});
it('returns undefined for an unknown id', () => {
expect(webContents.fromDevToolsTargetId('nope')).to.be.undefined();
});
});
describe('will-prevent-unload event', function () {
afterEach(closeAllWindows);
it('does not emit if beforeunload returns undefined in a BrowserWindow', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.once('will-prevent-unload', () => {
expect.fail('should not have fired');
});
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
const wait = once(w, 'closed');
w.close();
await wait;
});
it('does not emit if beforeunload returns undefined in a BrowserView', async () => {
const w = new BrowserWindow({ show: false });
const view = new BrowserView();
w.setBrowserView(view);
view.setBounds(w.getBounds());
view.webContents.once('will-prevent-unload', () => {
expect.fail('should not have fired');
});
await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
const wait = once(w, 'closed');
w.close();
await wait;
});
it('emits if beforeunload returns false in a BrowserWindow', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.close();
await once(w.webContents, 'will-prevent-unload');
});
it('emits if beforeunload returns false in a BrowserView', async () => {
const w = new BrowserWindow({ show: false });
const view = new BrowserView();
w.setBrowserView(view);
view.setBounds(w.getBounds());
await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.close();
await once(view.webContents, 'will-prevent-unload');
});
it('supports calling preventDefault on will-prevent-unload events in a BrowserWindow', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.once('will-prevent-unload', event => event.preventDefault());
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
const wait = once(w, 'closed');
w.close();
await wait;
});
});
describe('webContents.send(channel, args...)', () => {
afterEach(closeAllWindows);
it('throws an error when the channel is missing', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
(w.webContents.send as any)();
}).to.throw('Missing required channel argument');
expect(() => {
w.webContents.send(null as any);
}).to.throw('Missing required channel argument');
});
it('does not block node async APIs when sent before document is ready', (done) => {
// Please reference https://github.com/electron/electron/issues/19368 if
// this test fails.
ipcMain.once('async-node-api-done', () => {
done();
});
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
sandbox: false,
contextIsolation: false
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'send-after-node.html'));
setTimeout(50).then(() => {
w.webContents.send('test');
});
});
});
ifdescribe(features.isPrintingEnabled())('webContents.print()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(closeAllWindows);
it('throws when invalid settings are passed', () => {
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print(true);
}).to.throw('webContents.print(): Invalid print settings specified.');
});
it('throws when an invalid pageSize is passed', () => {
const badSize = 5;
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print({ pageSize: badSize });
}).to.throw(`Unsupported pageSize: ${badSize}`);
});
it('throws when an invalid callback is passed', () => {
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print({}, true);
}).to.throw('webContents.print(): Invalid optional callback provided.');
});
it('fails when an invalid deviceName is passed', (done) => {
w.webContents.print({ deviceName: 'i-am-a-nonexistent-printer' }, (success, reason) => {
expect(success).to.equal(false);
expect(reason).to.match(/Invalid deviceName provided/);
done();
});
});
it('throws when an invalid pageSize is passed', () => {
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print({ pageSize: 'i-am-a-bad-pagesize' }, () => {});
}).to.throw('Unsupported pageSize: i-am-a-bad-pagesize');
});
it('throws when an invalid custom pageSize is passed', () => {
expect(() => {
w.webContents.print({
pageSize: {
width: 100,
height: 200
}
});
}).to.throw('height and width properties must be minimum 352 microns.');
});
it('does not crash with custom margins', () => {
expect(() => {
w.webContents.print({
silent: true,
margins: {
marginType: 'custom',
top: 1,
bottom: 1,
left: 1,
right: 1
}
});
}).to.not.throw();
});
});
describe('webContents.executeJavaScript', () => {
describe('in about:blank', () => {
const expected = 'hello, world!';
const expectedErrorMsg = 'woops!';
const code = `(() => "${expected}")()`;
const asyncCode = `(() => new Promise(r => setTimeout(() => r("${expected}"), 500)))()`;
const badAsyncCode = `(() => new Promise((r, e) => setTimeout(() => e("${expectedErrorMsg}"), 500)))()`;
const errorTypes = new Set([
Error,
ReferenceError,
EvalError,
RangeError,
SyntaxError,
TypeError,
URIError
]);
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: false } });
await w.loadURL('about:blank');
});
after(closeAllWindows);
it('resolves the returned promise with the result', async () => {
const result = await w.webContents.executeJavaScript(code);
expect(result).to.equal(expected);
});
it('resolves the returned promise with the result if the code returns an asynchronous promise', async () => {
const result = await w.webContents.executeJavaScript(asyncCode);
expect(result).to.equal(expected);
});
it('rejects the returned promise if an async error is thrown', async () => {
await expect(w.webContents.executeJavaScript(badAsyncCode)).to.eventually.be.rejectedWith(expectedErrorMsg);
});
it('rejects the returned promise with an error if an Error.prototype is thrown', async () => {
for (const error of errorTypes) {
await expect(w.webContents.executeJavaScript(`Promise.reject(new ${error.name}("Wamp-wamp"))`))
.to.eventually.be.rejectedWith(error);
}
});
});
describe('on a real page', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(closeAllWindows);
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((request, response) => {
response.end();
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('works after page load and during subframe load', async () => {
await w.loadURL(serverUrl);
// initiate a sub-frame load, then try and execute script during it
await w.webContents.executeJavaScript(`
var iframe = document.createElement('iframe')
iframe.src = '${serverUrl}/slow'
document.body.appendChild(iframe)
null // don't return the iframe
`);
await w.webContents.executeJavaScript('console.log(\'hello\')');
});
it('executes after page load', async () => {
const executeJavaScript = w.webContents.executeJavaScript('(() => "test")()');
w.loadURL(serverUrl);
const result = await executeJavaScript;
expect(result).to.equal('test');
});
});
});
describe('webContents.executeJavaScriptInIsolatedWorld', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } });
await w.loadURL('about:blank');
});
it('resolves the returned promise with the result', async () => {
await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X = 123' }]);
const isolatedResult = await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X' }]);
const mainWorldResult = await w.webContents.executeJavaScript('window.X');
expect(isolatedResult).to.equal(123);
expect(mainWorldResult).to.equal(undefined);
});
});
describe('loadURL() promise API', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false });
});
afterEach(closeAllWindows);
it('resolves when done loading', async () => {
await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled();
});
it('resolves when done loading a file URL', async () => {
await expect(w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'))).to.eventually.be.fulfilled();
});
it('resolves when navigating within the page', async () => {
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
await setTimeout();
await expect(w.loadURL(w.getURL() + '#foo')).to.eventually.be.fulfilled();
});
it('resolves after browser initiated navigation', async () => {
let finishedLoading = false;
w.webContents.on('did-finish-load', function () {
finishedLoading = true;
});
await w.loadFile(path.join(fixturesPath, 'pages', 'navigate_in_page_and_wait.html'));
expect(finishedLoading).to.be.true();
});
it('rejects when failing to load a file URL', async () => {
await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected()
.and.have.property('code', 'ERR_FILE_NOT_FOUND');
});
// FIXME: Temporarily disable on WOA until
// https://github.com/electron/electron/issues/20008 is resolved
ifit(!(process.platform === 'win32' && process.arch === 'arm64'))('rejects when loading fails due to DNS not resolved', async () => {
await expect(w.loadURL('https://err.name.not.resolved')).to.eventually.be.rejected()
.and.have.property('code', 'ERR_NAME_NOT_RESOLVED');
});
it('rejects when navigation is cancelled due to a bad scheme', async () => {
await expect(w.loadURL('bad-scheme://foo')).to.eventually.be.rejected()
.and.have.property('code', 'ERR_FAILED');
});
it('does not crash when loading a new URL with emulation settings set', async () => {
const setEmulation = async () => {
if (w.webContents) {
w.webContents.debugger.attach('1.3');
const deviceMetrics = {
width: 700,
height: 600,
deviceScaleFactor: 2,
mobile: true,
dontSetVisibleSize: true
};
await w.webContents.debugger.sendCommand(
'Emulation.setDeviceMetricsOverride',
deviceMetrics
);
}
};
try {
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
await setEmulation();
await w.loadURL('data:text/html,<h1>HELLO</h1>');
await setEmulation();
} catch (e) {
expect((e as Error).message).to.match(/Debugger is already attached to the target/);
}
});
it('fails if loadURL is called inside a non-reentrant critical section', (done) => {
w.webContents.once('did-fail-load', (_event, _errorCode, _errorDescription, validatedURL) => {
expect(validatedURL).to.contain('blank.html');
done();
});
w.webContents.once('did-start-loading', () => {
w.loadURL(`file://${fixturesPath}/pages/blank.html`);
});
w.loadURL('data:text/html,<h1>HELLO</h1>');
});
it('sets appropriate error information on rejection', async () => {
let err: any;
try {
await w.loadURL('file:non-existent');
} catch (e) {
err = e;
}
expect(err).not.to.be.null();
expect(err.code).to.eql('ERR_FILE_NOT_FOUND');
expect(err.errno).to.eql(-6);
expect(err.url).to.eql(process.platform === 'win32' ? 'file://non-existent/' : 'file:///non-existent');
});
it('rejects if the load is aborted', async () => {
const s = http.createServer(() => { /* never complete the request */ });
const { port } = await listen(s);
const p = expect(w.loadURL(`http://127.0.0.1:${port}`)).to.eventually.be.rejectedWith(Error, /ERR_ABORTED/);
// load a different file before the first load completes, causing the
// first load to be aborted.
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
await p;
s.close();
});
it("doesn't reject when a subframe fails to load", async () => {
let resp = null as unknown as http.ServerResponse;
const s = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<iframe src="http://err.name.not.resolved"></iframe>');
resp = res;
// don't end the response yet
});
const { port } = await listen(s);
const p = new Promise<void>(resolve => {
w.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL, isMainFrame) => {
if (!isMainFrame) {
resolve();
}
});
});
const main = w.loadURL(`http://127.0.0.1:${port}`);
await p;
resp.end();
await main;
s.close();
});
it("doesn't resolve when a subframe loads", async () => {
let resp = null as unknown as http.ServerResponse;
const s = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<iframe src="about:blank"></iframe>');
resp = res;
// don't end the response yet
});
const { port } = await listen(s);
const p = new Promise<void>(resolve => {
w.webContents.on('did-frame-finish-load', (event, isMainFrame) => {
if (!isMainFrame) {
resolve();
}
});
});
const main = w.loadURL(`http://127.0.0.1:${port}`);
await p;
resp.destroy(); // cause the main request to fail
await expect(main).to.eventually.be.rejected()
.and.have.property('errno', -355); // ERR_INCOMPLETE_CHUNKED_ENCODING
s.close();
});
it('subsequent load failures reject each time', async () => {
await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected();
await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected();
});
it('invalid URL load rejects', async () => {
await expect(w.loadURL('invalidURL')).to.eventually.be.rejected();
});
});
describe('getFocusedWebContents() API', () => {
afterEach(closeAllWindows);
// FIXME
ifit(!(process.platform === 'win32' && process.arch === 'arm64'))('returns the focused web contents', async () => {
const w = new BrowserWindow({ show: true });
await w.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.id);
const devToolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.openDevTools();
await devToolsOpened;
expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.devToolsWebContents!.id);
const devToolsClosed = once(w.webContents, 'devtools-closed');
w.webContents.closeDevTools();
await devToolsClosed;
expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.id);
});
it('does not crash when called on a detached dev tools window', async () => {
const w = new BrowserWindow({ show: true });
w.webContents.openDevTools({ mode: 'detach' });
w.webContents.inspectElement(100, 100);
// For some reason we have to wait for two focused events...?
await once(w.webContents, 'devtools-focused');
expect(() => { webContents.getFocusedWebContents(); }).to.not.throw();
// Work around https://github.com/electron/electron/issues/19985
await setTimeout();
const devToolsClosed = once(w.webContents, 'devtools-closed');
w.webContents.closeDevTools();
await devToolsClosed;
expect(() => { webContents.getFocusedWebContents(); }).to.not.throw();
});
});
describe('setDevToolsWebContents() API', () => {
afterEach(closeAllWindows);
it('sets arbitrary webContents as devtools', async () => {
const w = new BrowserWindow({ show: false });
const devtools = new BrowserWindow({ show: false });
const promise = once(devtools.webContents, 'dom-ready');
w.webContents.setDevToolsWebContents(devtools.webContents);
w.webContents.openDevTools();
await promise;
expect(devtools.webContents.getURL().startsWith('devtools://devtools')).to.be.true();
const result = await devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name');
expect(result).to.equal('InspectorFrontendHostImpl');
devtools.destroy();
});
});
describe('isFocused() API', () => {
it('returns false when the window is hidden', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(w.isVisible()).to.be.false();
expect(w.webContents.isFocused()).to.be.false();
});
});
describe('isCurrentlyAudible() API', () => {
afterEach(closeAllWindows);
it('returns whether audio is playing', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
await w.webContents.executeJavaScript(`
window.context = new AudioContext
// Start in suspended state, because of the
// new web audio api policy.
context.suspend()
window.oscillator = context.createOscillator()
oscillator.connect(context.destination)
oscillator.start()
`);
let p = once(w.webContents, 'audio-state-changed');
w.webContents.executeJavaScript('context.resume()');
await p;
expect(w.webContents.isCurrentlyAudible()).to.be.true();
p = once(w.webContents, 'audio-state-changed');
w.webContents.executeJavaScript('oscillator.stop()');
await p;
expect(w.webContents.isCurrentlyAudible()).to.be.false();
});
});
describe('openDevTools() API', () => {
afterEach(closeAllWindows);
it('can show window with activation', async () => {
const w = new BrowserWindow({ show: false });
const focused = once(w, 'focus');
w.show();
await focused;
expect(w.isFocused()).to.be.true();
const blurred = once(w, 'blur');
w.webContents.openDevTools({ mode: 'detach', activate: true });
await Promise.all([
once(w.webContents, 'devtools-opened'),
once(w.webContents, 'devtools-focused')
]);
await blurred;
expect(w.isFocused()).to.be.false();
});
it('can show window without activation', async () => {
const w = new BrowserWindow({ show: false });
const devtoolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.openDevTools({ mode: 'detach', activate: false });
await devtoolsOpened;
expect(w.webContents.isDevToolsOpened()).to.be.true();
});
it('can show a DevTools window with custom title', async () => {
const w = new BrowserWindow({ show: false });
const devtoolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.openDevTools({ mode: 'detach', activate: false, title: 'myTitle' });
await devtoolsOpened;
expect(w.webContents.getDevToolsTitle()).to.equal('myTitle');
});
it('can re-open devtools', async () => {
const w = new BrowserWindow({ show: false });
const devtoolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.openDevTools({ mode: 'detach', activate: true });
await devtoolsOpened;
expect(w.webContents.isDevToolsOpened()).to.be.true();
const devtoolsClosed = once(w.webContents, 'devtools-closed');
w.webContents.closeDevTools();
await devtoolsClosed;
expect(w.webContents.isDevToolsOpened()).to.be.false();
const devtoolsOpened2 = once(w.webContents, 'devtools-opened');
w.webContents.openDevTools({ mode: 'detach', activate: true });
await devtoolsOpened2;
expect(w.webContents.isDevToolsOpened()).to.be.true();
});
});
describe('setDevToolsTitle() API', () => {
afterEach(closeAllWindows);
it('can set devtools title with function', async () => {
const w = new BrowserWindow({ show: false });
const devtoolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.openDevTools({ mode: 'detach', activate: false });
await devtoolsOpened;
expect(w.webContents.isDevToolsOpened()).to.be.true();
w.webContents.setDevToolsTitle('newTitle');
expect(w.webContents.getDevToolsTitle()).to.equal('newTitle');
});
});
describe('before-input-event event', () => {
afterEach(closeAllWindows);
it('can prevent document keyboard events', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html'));
const keyDown = new Promise(resolve => {
ipcMain.once('keydown', (event, key) => resolve(key));
});
w.webContents.once('before-input-event', (event, input) => {
if (input.key === 'a') event.preventDefault();
});
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'a' });
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'b' });
expect(await keyDown).to.equal('b');
});
it('has the correct properties', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
const testBeforeInput = async (opts: any) => {
const modifiers = [];
if (opts.shift) modifiers.push('shift');
if (opts.control) modifiers.push('control');
if (opts.alt) modifiers.push('alt');
if (opts.meta) modifiers.push('meta');
if (opts.isAutoRepeat) modifiers.push('isAutoRepeat');
const p = once(w.webContents, 'before-input-event') as Promise<[any, Electron.Input]>;
w.webContents.sendInputEvent({
type: opts.type,
keyCode: opts.keyCode,
modifiers: modifiers as any
});
const [, input] = await p;
expect(input.type).to.equal(opts.type);
expect(input.key).to.equal(opts.key);
expect(input.code).to.equal(opts.code);
expect(input.isAutoRepeat).to.equal(opts.isAutoRepeat);
expect(input.shift).to.equal(opts.shift);
expect(input.control).to.equal(opts.control);
expect(input.alt).to.equal(opts.alt);
expect(input.meta).to.equal(opts.meta);
};
await testBeforeInput({
type: 'keyDown',
key: 'A',
code: 'KeyA',
keyCode: 'a',
shift: true,
control: true,
alt: true,
meta: true,
isAutoRepeat: true
});
await testBeforeInput({
type: 'keyUp',
key: '.',
code: 'Period',
keyCode: '.',
shift: false,
control: true,
alt: true,
meta: false,
isAutoRepeat: false
});
await testBeforeInput({
type: 'keyUp',
key: '!',
code: 'Digit1',
keyCode: '1',
shift: true,
control: false,
alt: false,
meta: true,
isAutoRepeat: false
});
await testBeforeInput({
type: 'keyUp',
key: 'Tab',
code: 'Tab',
keyCode: 'Tab',
shift: false,
control: true,
alt: false,
meta: false,
isAutoRepeat: true
});
});
});
// On Mac, zooming isn't done with the mouse wheel.
ifdescribe(process.platform !== 'darwin')('zoom-changed', () => {
afterEach(closeAllWindows);
it('is emitted with the correct zoom-in info', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
const testZoomChanged = async () => {
w.webContents.sendInputEvent({
type: 'mouseWheel',
x: 300,
y: 300,
deltaX: 0,
deltaY: 1,
wheelTicksX: 0,
wheelTicksY: 1,
modifiers: ['control', 'meta']
});
const [, zoomDirection] = await once(w.webContents, 'zoom-changed') as [any, string];
expect(zoomDirection).to.equal('in');
};
await testZoomChanged();
});
it('is emitted with the correct zoom-out info', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
const testZoomChanged = async () => {
w.webContents.sendInputEvent({
type: 'mouseWheel',
x: 300,
y: 300,
deltaX: 0,
deltaY: -1,
wheelTicksX: 0,
wheelTicksY: -1,
modifiers: ['control', 'meta']
});
const [, zoomDirection] = await once(w.webContents, 'zoom-changed') as [any, string];
expect(zoomDirection).to.equal('out');
};
await testZoomChanged();
});
});
describe('sendInputEvent(event)', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html'));
});
afterEach(closeAllWindows);
it('can send keydown events', async () => {
const keydown = once(ipcMain, 'keydown');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
expect(key).to.equal('a');
expect(code).to.equal('KeyA');
expect(keyCode).to.equal(65);
expect(shiftKey).to.be.false();
expect(ctrlKey).to.be.false();
expect(altKey).to.be.false();
});
it('can send keydown events with modifiers', async () => {
const keydown = once(ipcMain, 'keydown');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z', modifiers: ['shift', 'ctrl'] });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
expect(key).to.equal('Z');
expect(code).to.equal('KeyZ');
expect(keyCode).to.equal(90);
expect(shiftKey).to.be.true();
expect(ctrlKey).to.be.true();
expect(altKey).to.be.false();
});
it('can send keydown events with special keys', async () => {
const keydown = once(ipcMain, 'keydown');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Tab', modifiers: ['alt'] });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
expect(key).to.equal('Tab');
expect(code).to.equal('Tab');
expect(keyCode).to.equal(9);
expect(shiftKey).to.be.false();
expect(ctrlKey).to.be.false();
expect(altKey).to.be.true();
});
it('can send char events', async () => {
const keypress = once(ipcMain, 'keypress');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' });
w.webContents.sendInputEvent({ type: 'char', keyCode: 'A' });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress;
expect(key).to.equal('a');
expect(code).to.equal('KeyA');
expect(keyCode).to.equal(65);
expect(shiftKey).to.be.false();
expect(ctrlKey).to.be.false();
expect(altKey).to.be.false();
});
it('can correctly convert accelerators to key codes', async () => {
const keyup = once(ipcMain, 'keyup');
w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' });
w.webContents.sendInputEvent({ keyCode: 'Space', type: 'char' });
w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' });
w.webContents.sendInputEvent({ keyCode: 'Space', type: 'char' });
w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'char' });
w.webContents.sendInputEvent({ keyCode: 'Plus', type: 'keyUp' });
await keyup;
const inputText = await w.webContents.executeJavaScript('document.getElementById("input").value');
expect(inputText).to.equal('+ + +');
});
it('can send char events with modifiers', async () => {
const keypress = once(ipcMain, 'keypress');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z' });
w.webContents.sendInputEvent({ type: 'char', keyCode: 'Z', modifiers: ['shift', 'ctrl'] });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress;
expect(key).to.equal('Z');
expect(code).to.equal('KeyZ');
expect(keyCode).to.equal(90);
expect(shiftKey).to.be.true();
expect(ctrlKey).to.be.true();
expect(altKey).to.be.false();
});
});
describe('insertCSS', () => {
afterEach(closeAllWindows);
it('supports inserting CSS', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
await w.webContents.insertCSS('body { background-repeat: round; }');
const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")');
expect(result).to.equal('round');
});
it('supports removing inserted CSS', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
const key = await w.webContents.insertCSS('body { background-repeat: round; }');
await w.webContents.removeInsertedCSS(key);
const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")');
expect(result).to.equal('repeat');
});
});
describe('inspectElement()', () => {
afterEach(closeAllWindows);
it('supports inspecting an element in the devtools', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
const event = once(w.webContents, 'devtools-opened');
w.webContents.inspectElement(10, 10);
await event;
});
});
describe('startDrag({file, icon})', () => {
it('throws errors for a missing file or a missing/empty icon', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.webContents.startDrag({ icon: path.join(fixturesPath, 'assets', 'logo.png') } as any);
}).to.throw('Must specify either \'file\' or \'files\' option');
expect(() => {
w.webContents.startDrag({ file: __filename } as any);
}).to.throw('\'icon\' parameter is required');
expect(() => {
w.webContents.startDrag({ file: __filename, icon: path.join(mainFixturesPath, 'blank.png') });
}).to.throw(/Failed to load image from path (.+)/);
});
});
describe('focus APIs', () => {
describe('focus()', () => {
afterEach(closeAllWindows);
it('does not blur the focused window when the web contents is hidden', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
w.show();
await w.loadURL('about:blank');
w.focus();
const child = new BrowserWindow({ show: false });
child.loadURL('about:blank');
child.webContents.focus();
const currentFocused = w.isFocused();
const childFocused = child.isFocused();
child.close();
expect(currentFocused).to.be.true();
expect(childFocused).to.be.false();
});
});
const moveFocusToDevTools = async (win: BrowserWindow) => {
const devToolsOpened = once(win.webContents, 'devtools-opened');
win.webContents.openDevTools({ mode: 'right' });
await devToolsOpened;
win.webContents.devToolsWebContents!.focus();
};
describe('focus event', () => {
afterEach(closeAllWindows);
it('is triggered when web contents is focused', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
await moveFocusToDevTools(w);
const focusPromise = once(w.webContents, 'focus');
w.webContents.focus();
await expect(focusPromise).to.eventually.be.fulfilled();
});
});
describe('blur event', () => {
afterEach(closeAllWindows);
it('is triggered when web contents is blurred', async () => {
const w = new BrowserWindow({ show: true });
await w.loadURL('about:blank');
w.webContents.focus();
const blurPromise = once(w.webContents, 'blur');
await moveFocusToDevTools(w);
await expect(blurPromise).to.eventually.be.fulfilled();
});
});
});
describe('getOSProcessId()', () => {
afterEach(closeAllWindows);
it('returns a valid process id', async () => {
const w = new BrowserWindow({ show: false });
expect(w.webContents.getOSProcessId()).to.equal(0);
await w.loadURL('about:blank');
expect(w.webContents.getOSProcessId()).to.be.above(0);
});
});
describe('getMediaSourceId()', () => {
afterEach(closeAllWindows);
it('returns a valid stream id', () => {
const w = new BrowserWindow({ show: false });
expect(w.webContents.getMediaSourceId(w.webContents)).to.be.a('string').that.is.not.empty();
});
});
describe('userAgent APIs', () => {
it('is not empty by default', () => {
const w = new BrowserWindow({ show: false });
const userAgent = w.webContents.getUserAgent();
expect(userAgent).to.be.a('string').that.is.not.empty();
});
it('can set the user agent (functions)', () => {
const w = new BrowserWindow({ show: false });
const userAgent = w.webContents.getUserAgent();
w.webContents.setUserAgent('my-user-agent');
expect(w.webContents.getUserAgent()).to.equal('my-user-agent');
w.webContents.setUserAgent(userAgent);
expect(w.webContents.getUserAgent()).to.equal(userAgent);
});
it('can set the user agent (properties)', () => {
const w = new BrowserWindow({ show: false });
const userAgent = w.webContents.userAgent;
w.webContents.userAgent = 'my-user-agent';
expect(w.webContents.userAgent).to.equal('my-user-agent');
w.webContents.userAgent = userAgent;
expect(w.webContents.userAgent).to.equal(userAgent);
});
});
describe('audioMuted APIs', () => {
it('can set the audio mute level (functions)', () => {
const w = new BrowserWindow({ show: false });
w.webContents.setAudioMuted(true);
expect(w.webContents.isAudioMuted()).to.be.true();
w.webContents.setAudioMuted(false);
expect(w.webContents.isAudioMuted()).to.be.false();
});
it('can set the audio mute level (functions)', () => {
const w = new BrowserWindow({ show: false });
w.webContents.audioMuted = true;
expect(w.webContents.audioMuted).to.be.true();
w.webContents.audioMuted = false;
expect(w.webContents.audioMuted).to.be.false();
});
});
describe('zoom api', () => {
const hostZoomMap: Record<string, number> = {
host1: 0.3,
host2: 0.7,
host3: 0.2
};
before(() => {
const protocol = session.defaultSession.protocol;
protocol.registerStringProtocol(standardScheme, (request, callback) => {
const response = `<script>
const {ipcRenderer} = require('electron')
ipcRenderer.send('set-zoom', window.location.hostname)
ipcRenderer.on(window.location.hostname + '-zoom-set', () => {
ipcRenderer.send(window.location.hostname + '-zoom-level')
})
</script>`;
callback({ data: response, mimeType: 'text/html' });
});
});
after(() => {
const protocol = session.defaultSession.protocol;
protocol.unregisterProtocol(standardScheme);
});
afterEach(closeAllWindows);
it('throws on an invalid zoomFactor', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(() => {
w.webContents.setZoomFactor(0.0);
}).to.throw(/'zoomFactor' must be a double greater than 0.0/);
expect(() => {
w.webContents.setZoomFactor(-2.0);
}).to.throw(/'zoomFactor' must be a double greater than 0.0/);
});
it('can set the correct zoom level (functions)', async () => {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL('about:blank');
const zoomLevel = w.webContents.getZoomLevel();
expect(zoomLevel).to.eql(0.0);
w.webContents.setZoomLevel(0.5);
const newZoomLevel = w.webContents.getZoomLevel();
expect(newZoomLevel).to.eql(0.5);
} finally {
w.webContents.setZoomLevel(0);
}
});
it('can set the correct zoom level (properties)', async () => {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL('about:blank');
const zoomLevel = w.webContents.zoomLevel;
expect(zoomLevel).to.eql(0.0);
w.webContents.zoomLevel = 0.5;
const newZoomLevel = w.webContents.zoomLevel;
expect(newZoomLevel).to.eql(0.5);
} finally {
w.webContents.zoomLevel = 0;
}
});
it('can set the correct zoom factor (functions)', async () => {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL('about:blank');
const zoomFactor = w.webContents.getZoomFactor();
expect(zoomFactor).to.eql(1.0);
w.webContents.setZoomFactor(0.5);
const newZoomFactor = w.webContents.getZoomFactor();
expect(newZoomFactor).to.eql(0.5);
} finally {
w.webContents.setZoomFactor(1.0);
}
});
it('can set the correct zoom factor (properties)', async () => {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL('about:blank');
const zoomFactor = w.webContents.zoomFactor;
expect(zoomFactor).to.eql(1.0);
w.webContents.zoomFactor = 0.5;
const newZoomFactor = w.webContents.zoomFactor;
expect(newZoomFactor).to.eql(0.5);
} finally {
w.webContents.zoomFactor = 1.0;
}
});
it('can persist zoom level across navigation', (done) => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
let finalNavigation = false;
ipcMain.on('set-zoom', (e, host) => {
const zoomLevel = hostZoomMap[host];
if (!finalNavigation) w.webContents.zoomLevel = zoomLevel;
e.sender.send(`${host}-zoom-set`);
});
ipcMain.on('host1-zoom-level', (e) => {
try {
const zoomLevel = e.sender.getZoomLevel();
const expectedZoomLevel = hostZoomMap.host1;
expect(zoomLevel).to.equal(expectedZoomLevel);
if (finalNavigation) {
done();
} else {
w.loadURL(`${standardScheme}://host2`);
}
} catch (e) {
done(e);
}
});
ipcMain.once('host2-zoom-level', (e) => {
try {
const zoomLevel = e.sender.getZoomLevel();
const expectedZoomLevel = hostZoomMap.host2;
expect(zoomLevel).to.equal(expectedZoomLevel);
finalNavigation = true;
w.webContents.goBack();
} catch (e) {
done(e);
}
});
w.loadURL(`${standardScheme}://host1`);
});
it('can propagate zoom level across same session', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
const w2 = new BrowserWindow({ show: false });
defer(() => {
w2.setClosable(true);
w2.close();
});
await w.loadURL(`${standardScheme}://host3`);
w.webContents.zoomLevel = hostZoomMap.host3;
await w2.loadURL(`${standardScheme}://host3`);
const zoomLevel1 = w.webContents.zoomLevel;
expect(zoomLevel1).to.equal(hostZoomMap.host3);
const zoomLevel2 = w2.webContents.zoomLevel;
expect(zoomLevel1).to.equal(zoomLevel2);
});
it('cannot propagate zoom level across different session', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
const w2 = new BrowserWindow({
show: false,
webPreferences: {
partition: 'temp'
}
});
const protocol = w2.webContents.session.protocol;
protocol.registerStringProtocol(standardScheme, (request, callback) => {
callback('hello');
});
defer(() => {
w2.setClosable(true);
w2.close();
protocol.unregisterProtocol(standardScheme);
});
await w.loadURL(`${standardScheme}://host3`);
w.webContents.zoomLevel = hostZoomMap.host3;
await w2.loadURL(`${standardScheme}://host3`);
const zoomLevel1 = w.webContents.zoomLevel;
expect(zoomLevel1).to.equal(hostZoomMap.host3);
const zoomLevel2 = w2.webContents.zoomLevel;
expect(zoomLevel2).to.equal(0);
expect(zoomLevel1).to.not.equal(zoomLevel2);
});
it('can persist when it contains iframe', (done) => {
const w = new BrowserWindow({ show: false });
const server = http.createServer((req, res) => {
setTimeout(200).then(() => {
res.end();
});
});
listen(server).then(({ url }) => {
const content = `<iframe src=${url}></iframe>`;
w.webContents.on('did-frame-finish-load', (e, isMainFrame) => {
if (!isMainFrame) {
try {
const zoomLevel = w.webContents.zoomLevel;
expect(zoomLevel).to.equal(2.0);
w.webContents.zoomLevel = 0;
done();
} catch (e) {
done(e);
} finally {
server.close();
}
}
});
w.webContents.on('dom-ready', () => {
w.webContents.zoomLevel = 2.0;
});
w.loadURL(`data:text/html,${content}`);
});
});
it('cannot propagate when used with webframe', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
const w2 = new BrowserWindow({ show: false });
const temporaryZoomSet = once(ipcMain, 'temporary-zoom-set');
w.loadFile(path.join(fixturesPath, 'pages', 'webframe-zoom.html'));
await temporaryZoomSet;
const finalZoomLevel = w.webContents.getZoomLevel();
await w2.loadFile(path.join(fixturesPath, 'pages', 'c.html'));
const zoomLevel1 = w.webContents.zoomLevel;
const zoomLevel2 = w2.webContents.zoomLevel;
w2.setClosable(true);
w2.close();
expect(zoomLevel1).to.equal(finalZoomLevel);
expect(zoomLevel2).to.equal(0);
expect(zoomLevel1).to.not.equal(zoomLevel2);
});
describe('with unique domains', () => {
let server: http.Server;
let serverUrl: string;
let crossSiteUrl: string;
before(async () => {
server = http.createServer((req, res) => {
setTimeout().then(() => res.end('hey'));
});
serverUrl = (await listen(server)).url;
crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
});
after(() => {
server.close();
});
it('cannot persist zoom level after navigation with webFrame', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
const source = `
const {ipcRenderer, webFrame} = require('electron')
webFrame.setZoomLevel(0.6)
ipcRenderer.send('zoom-level-set', webFrame.getZoomLevel())
`;
const zoomLevelPromise = once(ipcMain, 'zoom-level-set');
await w.loadURL(serverUrl);
await w.webContents.executeJavaScript(source);
let [, zoomLevel] = await zoomLevelPromise;
expect(zoomLevel).to.equal(0.6);
const loadPromise = once(w.webContents, 'did-finish-load');
await w.loadURL(crossSiteUrl);
await loadPromise;
zoomLevel = w.webContents.zoomLevel;
expect(zoomLevel).to.equal(0);
});
});
});
describe('webrtc ip policy api', () => {
afterEach(closeAllWindows);
it('can set and get webrtc ip policies', () => {
const w = new BrowserWindow({ show: false });
const policies = [
'default',
'default_public_interface_only',
'default_public_and_private_interfaces',
'disable_non_proxied_udp'
] as const;
for (const policy of policies) {
w.webContents.setWebRTCIPHandlingPolicy(policy);
expect(w.webContents.getWebRTCIPHandlingPolicy()).to.equal(policy);
}
});
});
describe('webrtc udp port range policy api', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(closeAllWindows);
it('check default webrtc udp port range is { min: 0, max: 0 }', () => {
const settings = w.webContents.getWebRTCUDPPortRange();
expect(settings).to.deep.equal({ min: 0, max: 0 });
});
it('can set and get webrtc udp port range policy with correct arguments', () => {
w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65535 });
const settings = w.webContents.getWebRTCUDPPortRange();
expect(settings).to.deep.equal({ min: 1, max: 65535 });
});
it('can not set webrtc udp port range policy with invalid arguments', () => {
expect(() => {
w.webContents.setWebRTCUDPPortRange({ min: 0, max: 65535 });
}).to.throw("'min' and 'max' must be in the (0, 65535] range or [0, 0]");
expect(() => {
w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65536 });
}).to.throw("'min' and 'max' must be in the (0, 65535] range or [0, 0]");
expect(() => {
w.webContents.setWebRTCUDPPortRange({ min: 60000, max: 56789 });
}).to.throw("'max' must be greater than or equal to 'min'");
});
it('can reset webrtc udp port range policy to default with { min: 0, max: 0 }', () => {
w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65535 });
const settings = w.webContents.getWebRTCUDPPortRange();
expect(settings).to.deep.equal({ min: 1, max: 65535 });
w.webContents.setWebRTCUDPPortRange({ min: 0, max: 0 });
const defaultSetting = w.webContents.getWebRTCUDPPortRange();
expect(defaultSetting).to.deep.equal({ min: 0, max: 0 });
});
});
describe('opener api', () => {
afterEach(closeAllWindows);
it('can get opener with window.open()', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>;
w.webContents.executeJavaScript('window.open("about:blank")', true);
const [childWindow] = await childPromise;
expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame);
});
it('has no opener when using "noopener"', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>;
w.webContents.executeJavaScript('window.open("about:blank", undefined, "noopener")', true);
const [childWindow] = await childPromise;
expect(childWindow.webContents.opener).to.be.null();
});
it('can get opener with a[target=_blank][rel=opener]', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>;
w.webContents.executeJavaScript(`(function() {
const a = document.createElement('a');
a.target = '_blank';
a.rel = 'opener';
a.href = 'about:blank';
a.click();
}())`, true);
const [childWindow] = await childPromise;
expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame);
});
it('has no opener with a[target=_blank][rel=noopener]', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>;
w.webContents.executeJavaScript(`(function() {
const a = document.createElement('a');
a.target = '_blank';
a.rel = 'noopener';
a.href = 'about:blank';
a.click();
}())`, true);
const [childWindow] = await childPromise;
expect(childWindow.webContents.opener).to.be.null();
});
});
describe('render view deleted events', () => {
let server: http.Server;
let serverUrl: string;
let crossSiteUrl: string;
before(async () => {
server = http.createServer((req, res) => {
const respond = () => {
if (req.url === '/redirect-cross-site') {
res.setHeader('Location', `${crossSiteUrl}/redirected`);
res.statusCode = 302;
res.end();
} else if (req.url === '/redirected') {
res.end('<html><script>window.localStorage</script></html>');
} else if (req.url === '/first-window-open') {
res.end(`<html><script>window.open('${serverUrl}/second-window-open', 'first child');</script></html>`);
} else if (req.url === '/second-window-open') {
res.end('<html><script>window.open(\'wrong://url\', \'second child\');</script></html>');
} else {
res.end();
}
};
setTimeout().then(respond);
});
serverUrl = (await listen(server)).url;
crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
});
after(() => {
server.close();
});
afterEach(closeAllWindows);
it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => {
const w = new BrowserWindow({ show: false });
let currentRenderViewDeletedEmitted = false;
const renderViewDeletedHandler = () => {
currentRenderViewDeletedEmitted = true;
};
w.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler);
w.webContents.on('did-finish-load', () => {
w.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler);
w.close();
});
const destroyed = once(w.webContents, 'destroyed');
w.loadURL(`${serverUrl}/redirect-cross-site`);
await destroyed;
expect(currentRenderViewDeletedEmitted).to.be.false('current-render-view-deleted was emitted');
});
it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => {
const parentWindow = new BrowserWindow({ show: false });
let currentRenderViewDeletedEmitted = false;
let childWindow: BrowserWindow | null = null;
const destroyed = once(parentWindow.webContents, 'destroyed');
const renderViewDeletedHandler = () => {
currentRenderViewDeletedEmitted = true;
};
const childWindowCreated = new Promise<void>((resolve) => {
app.once('browser-window-created', (event, window) => {
childWindow = window;
window.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler);
resolve();
});
});
parentWindow.loadURL(`${serverUrl}/first-window-open`);
await childWindowCreated;
childWindow!.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler);
parentWindow.close();
await destroyed;
expect(currentRenderViewDeletedEmitted).to.be.false('child window was destroyed');
});
it('emits current-render-view-deleted if the current RVHs are deleted', async () => {
const w = new BrowserWindow({ show: false });
let currentRenderViewDeletedEmitted = false;
w.webContents.on('current-render-view-deleted' as any, () => {
currentRenderViewDeletedEmitted = true;
});
w.webContents.on('did-finish-load', () => {
w.close();
});
const destroyed = once(w.webContents, 'destroyed');
w.loadURL(`${serverUrl}/redirect-cross-site`);
await destroyed;
expect(currentRenderViewDeletedEmitted).to.be.true('current-render-view-deleted wasn\'t emitted');
});
it('emits render-view-deleted if any RVHs are deleted', async () => {
const w = new BrowserWindow({ show: false });
let rvhDeletedCount = 0;
w.webContents.on('render-view-deleted' as any, () => {
rvhDeletedCount++;
});
w.webContents.on('did-finish-load', () => {
w.close();
});
const destroyed = once(w.webContents, 'destroyed');
w.loadURL(`${serverUrl}/redirect-cross-site`);
await destroyed;
const expectedRenderViewDeletedEventCount = 1;
expect(rvhDeletedCount).to.equal(expectedRenderViewDeletedEventCount, 'render-view-deleted wasn\'t emitted the expected nr. of times');
});
});
describe('setIgnoreMenuShortcuts(ignore)', () => {
afterEach(closeAllWindows);
it('does not throw', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.webContents.setIgnoreMenuShortcuts(true);
w.webContents.setIgnoreMenuShortcuts(false);
}).to.not.throw();
});
});
const crashPrefs = [
{
nodeIntegration: true
},
{
sandbox: true
}
];
const nicePrefs = (o: any) => {
let s = '';
for (const key of Object.keys(o)) {
s += `${key}=${o[key]}, `;
}
return `(${s.slice(0, s.length - 2)})`;
};
for (const prefs of crashPrefs) {
describe(`crash with webPreferences ${nicePrefs(prefs)}`, () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
await w.loadURL('about:blank');
});
afterEach(closeAllWindows);
it('isCrashed() is false by default', () => {
expect(w.webContents.isCrashed()).to.equal(false);
});
it('forcefullyCrashRenderer() crashes the process with reason=killed||crashed', async () => {
expect(w.webContents.isCrashed()).to.equal(false);
const crashEvent = once(w.webContents, 'render-process-gone') as Promise<[any, Electron.RenderProcessGoneDetails]>;
w.webContents.forcefullyCrashRenderer();
const [, details] = await crashEvent;
expect(details.reason === 'killed' || details.reason === 'crashed').to.equal(true, 'reason should be killed || crashed');
expect(w.webContents.isCrashed()).to.equal(true);
});
it('a crashed process is recoverable with reload()', async () => {
expect(w.webContents.isCrashed()).to.equal(false);
w.webContents.forcefullyCrashRenderer();
w.webContents.reload();
expect(w.webContents.isCrashed()).to.equal(false);
});
});
}
// Destroying webContents in its event listener is going to crash when
// Electron is built in Debug mode.
describe('destroy()', () => {
let server: http.Server;
let serverUrl: string;
before((done) => {
server = http.createServer((request, response) => {
switch (request.url) {
case '/net-error':
response.destroy();
break;
case '/200':
response.end();
break;
default:
done(new Error('unsupported endpoint'));
}
});
listen(server).then(({ url }) => {
serverUrl = url;
done();
});
});
after(() => {
server.close();
});
const events = [
{ name: 'did-start-loading', url: '/200' },
{ name: 'dom-ready', url: '/200' },
{ name: 'did-stop-loading', url: '/200' },
{ name: 'did-finish-load', url: '/200' },
// FIXME: Multiple Emit calls inside an observer assume that object
// will be alive till end of the observer. Synchronous `destroy` api
// violates this contract and crashes.
{ name: 'did-frame-finish-load', url: '/200' },
{ name: 'did-fail-load', url: '/net-error' }
];
for (const e of events) {
it(`should not crash when invoked synchronously inside ${e.name} handler`, async function () {
// This test is flaky on Windows CI and we don't know why, but the
// purpose of this test is to make sure Electron does not crash so it
// is fine to retry this test for a few times.
this.retries(3);
const contents = (webContents as typeof ElectronInternal.WebContents).create();
const originalEmit = contents.emit.bind(contents);
contents.emit = (...args) => { return originalEmit(...args); };
contents.once(e.name as any, () => contents.destroy());
const destroyed = once(contents, 'destroyed');
contents.loadURL(serverUrl + e.url);
await destroyed;
});
}
});
describe('did-change-theme-color event', () => {
afterEach(closeAllWindows);
it('is triggered with correct theme color', (done) => {
const w = new BrowserWindow({ show: true });
let count = 0;
w.webContents.on('did-change-theme-color', (e, color) => {
try {
if (count === 0) {
count += 1;
expect(color).to.equal('#FFEEDD');
w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
} else if (count === 1) {
expect(color).to.be.null();
done();
}
} catch (e) {
done(e);
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'theme-color.html'));
});
});
describe('console-message event', () => {
afterEach(closeAllWindows);
it('is triggered with correct log message', (done) => {
const w = new BrowserWindow({ show: true });
w.webContents.on('console-message', (e, level, message) => {
// Don't just assert as Chromium might emit other logs that we should ignore.
if (message === 'a') {
done();
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'a.html'));
});
});
describe('ipc-message event', () => {
afterEach(closeAllWindows);
it('emits when the renderer process sends an asynchronous message', async () => {
const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.webContents.loadURL('about:blank');
w.webContents.executeJavaScript(`
require('electron').ipcRenderer.send('message', 'Hello World!')
`);
const [, channel, message] = await once(w.webContents, 'ipc-message');
expect(channel).to.equal('message');
expect(message).to.equal('Hello World!');
});
});
describe('ipc-message-sync event', () => {
afterEach(closeAllWindows);
it('emits when the renderer process sends a synchronous message', async () => {
const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.webContents.loadURL('about:blank');
const promise: Promise<[string, string]> = new Promise(resolve => {
w.webContents.once('ipc-message-sync', (event, channel, arg) => {
event.returnValue = 'foobar';
resolve([channel, arg]);
});
});
const result = await w.webContents.executeJavaScript(`
require('electron').ipcRenderer.sendSync('message', 'Hello World!')
`);
const [channel, message] = await promise;
expect(channel).to.equal('message');
expect(message).to.equal('Hello World!');
expect(result).to.equal('foobar');
});
});
describe('referrer', () => {
afterEach(closeAllWindows);
it('propagates referrer information to new target=_blank windows', (done) => {
const w = new BrowserWindow({ show: false });
const server = http.createServer((req, res) => {
if (req.url === '/should_have_referrer') {
try {
expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`);
return done();
} catch (e) {
return done(e);
} finally {
server.close();
}
}
res.end('<a id="a" href="/should_have_referrer" target="_blank">link</a>');
});
listen(server).then(({ url }) => {
w.webContents.once('did-finish-load', () => {
w.webContents.setWindowOpenHandler(details => {
expect(details.referrer.url).to.equal(url + '/');
expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin');
return { action: 'allow' };
});
w.webContents.executeJavaScript('a.click()');
});
w.loadURL(url);
});
});
it('propagates referrer information to windows opened with window.open', (done) => {
const w = new BrowserWindow({ show: false });
const server = http.createServer((req, res) => {
if (req.url === '/should_have_referrer') {
try {
expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`);
return done();
} catch (e) {
return done(e);
}
}
res.end('');
});
listen(server).then(({ url }) => {
w.webContents.once('did-finish-load', () => {
w.webContents.setWindowOpenHandler(details => {
expect(details.referrer.url).to.equal(url + '/');
expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin');
return { action: 'allow' };
});
w.webContents.executeJavaScript('window.open(location.href + "should_have_referrer")');
});
w.loadURL(url);
});
});
});
describe('webframe messages in sandboxed contents', () => {
afterEach(closeAllWindows);
it('responds to executeJavaScript', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const result = await w.webContents.executeJavaScript('37 + 5');
expect(result).to.equal(42);
});
});
describe('preload-error event', () => {
afterEach(closeAllWindows);
const generateSpecs = (description: string, sandbox: boolean) => {
describe(description, () => {
it('is triggered when unhandled exception is thrown', async () => {
const preload = path.join(fixturesPath, 'module', 'preload-error-exception.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox,
preload
}
});
const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>;
w.loadURL('about:blank');
const [, preloadPath, error] = await promise;
expect(preloadPath).to.equal(preload);
expect(error.message).to.equal('Hello World!');
});
it('is triggered on syntax errors', async () => {
const preload = path.join(fixturesPath, 'module', 'preload-error-syntax.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox,
preload
}
});
const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>;
w.loadURL('about:blank');
const [, preloadPath, error] = await promise;
expect(preloadPath).to.equal(preload);
expect(error.message).to.equal('foobar is not defined');
});
it('is triggered when preload script loading fails', async () => {
const preload = path.join(fixturesPath, 'module', 'preload-invalid.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox,
preload
}
});
const promise = once(w.webContents, 'preload-error') as Promise<[any, string, Error]>;
w.loadURL('about:blank');
const [, preloadPath, error] = await promise;
expect(preloadPath).to.equal(preload);
expect(error.message).to.contain('preload-invalid.js');
});
});
};
generateSpecs('without sandbox', false);
generateSpecs('with sandbox', true);
});
describe('takeHeapSnapshot()', () => {
afterEach(closeAllWindows);
it('works with sandboxed renderers', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
await w.loadURL('about:blank');
const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot');
const cleanup = () => {
try {
fs.unlinkSync(filePath);
} catch {
// ignore error
}
};
try {
await w.webContents.takeHeapSnapshot(filePath);
const stats = fs.statSync(filePath);
expect(stats.size).not.to.be.equal(0);
} finally {
cleanup();
}
});
it('fails with invalid file path', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
await w.loadURL('about:blank');
const badPath = path.join('i', 'am', 'a', 'super', 'bad', 'path');
const promise = w.webContents.takeHeapSnapshot(badPath);
return expect(promise).to.be.eventually.rejectedWith(Error, `Failed to take heap snapshot with invalid file path ${badPath}`);
});
it('fails with invalid render process', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot');
w.webContents.destroy();
const promise = w.webContents.takeHeapSnapshot(filePath);
return expect(promise).to.be.eventually.rejectedWith(Error, 'Failed to take heap snapshot with nonexistent render frame');
});
});
describe('setBackgroundThrottling()', () => {
afterEach(closeAllWindows);
it('does not crash when allowing', () => {
const w = new BrowserWindow({ show: false });
w.webContents.setBackgroundThrottling(true);
});
it('does not crash when called via BrowserWindow', () => {
const w = new BrowserWindow({ show: false });
w.setBackgroundThrottling(true);
});
it('does not crash when disallowing', () => {
const w = new BrowserWindow({ show: false, webPreferences: { backgroundThrottling: true } });
w.webContents.setBackgroundThrottling(false);
});
});
describe('getBackgroundThrottling()', () => {
afterEach(closeAllWindows);
it('works via getter', () => {
const w = new BrowserWindow({ show: false });
w.webContents.setBackgroundThrottling(false);
expect(w.webContents.getBackgroundThrottling()).to.equal(false);
w.webContents.setBackgroundThrottling(true);
expect(w.webContents.getBackgroundThrottling()).to.equal(true);
});
it('works via property', () => {
const w = new BrowserWindow({ show: false });
w.webContents.backgroundThrottling = false;
expect(w.webContents.backgroundThrottling).to.equal(false);
w.webContents.backgroundThrottling = true;
expect(w.webContents.backgroundThrottling).to.equal(true);
});
it('works via BrowserWindow', () => {
const w = new BrowserWindow({ show: false });
w.setBackgroundThrottling(false);
expect(w.getBackgroundThrottling()).to.equal(false);
w.setBackgroundThrottling(true);
expect(w.getBackgroundThrottling()).to.equal(true);
});
});
ifdescribe(features.isPrintingEnabled())('getPrintersAsync()', () => {
afterEach(closeAllWindows);
it('can get printer list', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const printers = await w.webContents.getPrintersAsync();
expect(printers).to.be.an('array');
});
});
ifdescribe(features.isPrintingEnabled())('printToPDF()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
});
afterEach(closeAllWindows);
it('rejects on incorrectly typed parameters', async () => {
const badTypes = {
landscape: [],
displayHeaderFooter: '123',
printBackground: 2,
scale: 'not-a-number',
pageSize: 'IAmAPageSize',
margins: 'terrible',
pageRanges: { oops: 'im-not-the-right-key' },
headerTemplate: [1, 2, 3],
footerTemplate: [4, 5, 6],
preferCSSPageSize: 'no',
generateTaggedPDF: 'wtf',
generateDocumentOutline: [7, 8, 9]
};
await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
// These will hard crash in Chromium unless we type-check
for (const [key, value] of Object.entries(badTypes)) {
const param = { [key]: value };
await expect(w.webContents.printToPDF(param)).to.eventually.be.rejected();
}
});
it('rejects when margins exceed physical page size', async () => {
await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
await expect(w.webContents.printToPDF({
pageSize: 'Letter',
margins: {
top: 100,
bottom: 100,
left: 5,
right: 5
}
})).to.eventually.be.rejectedWith('margins must be less than or equal to pageSize');
});
it('does not crash when called multiple times in parallel', async () => {
await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
const promises = [];
for (let i = 0; i < 3; i++) {
promises.push(w.webContents.printToPDF({}));
}
const results = await Promise.all(promises);
for (const data of results) {
expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
}
});
it('does not crash when called multiple times in sequence', async () => {
await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
const results = [];
for (let i = 0; i < 3; i++) {
const result = await w.webContents.printToPDF({});
results.push(result);
}
for (const data of results) {
expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
}
});
it('can print a PDF with default settings', async () => {
await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
const data = await w.webContents.printToPDF({});
expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
});
type PageSizeString = Exclude<Required<Electron.PrintToPDFOptions>['pageSize'], Electron.Size>;
it('with custom page sizes', async () => {
const paperFormats: Record<PageSizeString, ElectronInternal.PageSize> = {
Letter: { width: 8.5, height: 11 },
Legal: { width: 8.5, height: 14 },
Tabloid: { width: 11, height: 17 },
Ledger: { width: 17, height: 11 },
A0: { width: 33.1, height: 46.8 },
A1: { width: 23.4, height: 33.1 },
A2: { width: 16.54, height: 23.4 },
A3: { width: 11.7, height: 16.54 },
A4: { width: 8.27, height: 11.7 },
A5: { width: 5.83, height: 8.27 },
A6: { width: 4.13, height: 5.83 }
};
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
for (const format of Object.keys(paperFormats) as PageSizeString[]) {
const data = await w.webContents.printToPDF({ pageSize: format });
const doc = await pdfjs.getDocument(data).promise;
const page = await doc.getPage(1);
// page.view is [top, left, width, height].
const width = page.view[2] / 72;
const height = page.view[3] / 72;
const approxEq = (a: number, b: number, epsilon = 0.01) => Math.abs(a - b) <= epsilon;
expect(approxEq(width, paperFormats[format].width)).to.be.true();
expect(approxEq(height, paperFormats[format].height)).to.be.true();
}
});
it('with custom header and footer', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
const data = await w.webContents.printToPDF({
displayHeaderFooter: true,
headerTemplate: '<div>I\'m a PDF header</div>',
footerTemplate: '<div>I\'m a PDF footer</div>'
});
const doc = await pdfjs.getDocument(data).promise;
const page = await doc.getPage(1);
const { items } = await page.getTextContent();
// Check that generated PDF contains a header.
const containsText = (text: RegExp) => items.some(({ str }: { str: string }) => str.match(text));
expect(containsText(/I'm a PDF header/)).to.be.true();
expect(containsText(/I'm a PDF footer/)).to.be.true();
});
it('in landscape mode', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
const data = await w.webContents.printToPDF({ landscape: true });
const doc = await pdfjs.getDocument(data).promise;
const page = await doc.getPage(1);
// page.view is [top, left, width, height].
const width = page.view[2];
const height = page.view[3];
expect(width).to.be.greaterThan(height);
});
it('with custom page ranges', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-large.html'));
const data = await w.webContents.printToPDF({
pageRanges: '1-3',
landscape: true
});
const doc = await pdfjs.getDocument(data).promise;
// Check that correct # of pages are rendered.
expect(doc.numPages).to.equal(3);
});
it('does not tag PDFs by default', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
const data = await w.webContents.printToPDF({});
const doc = await pdfjs.getDocument(data).promise;
const markInfo = await doc.getMarkInfo();
expect(markInfo).to.be.null();
});
it('can generate tag data for PDFs', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
const data = await w.webContents.printToPDF({ generateTaggedPDF: true });
const doc = await pdfjs.getDocument(data).promise;
const markInfo = await doc.getMarkInfo();
expect(markInfo).to.deep.equal({
Marked: true,
UserProperties: false,
Suspects: false
});
});
});
describe('PictureInPicture video', () => {
afterEach(closeAllWindows);
it('works as expected', async function () {
const w = new BrowserWindow({ webPreferences: { sandbox: true } });
// TODO(codebytere): figure out why this workaround is needed and remove.
// It is not germane to the actual test.
await w.loadFile(path.join(fixturesPath, 'blank.html'));
await w.loadFile(path.join(fixturesPath, 'api', 'picture-in-picture.html'));
await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')', true);
const result = await w.webContents.executeJavaScript('runTest(true)', true);
expect(result).to.be.true();
});
});
describe('Shared Workers', () => {
afterEach(closeAllWindows);
it('can get multiple shared workers', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
const ready = once(ipcMain, 'ready');
w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html'));
await ready;
const sharedWorkers = w.webContents.getAllSharedWorkers();
expect(sharedWorkers).to.have.lengthOf(2);
expect(sharedWorkers[0].url).to.contain('shared-worker');
expect(sharedWorkers[1].url).to.contain('shared-worker');
});
it('can inspect a specific shared worker', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
const ready = once(ipcMain, 'ready');
w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html'));
await ready;
const sharedWorkers = w.webContents.getAllSharedWorkers();
const devtoolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.inspectSharedWorkerById(sharedWorkers[0].id);
await devtoolsOpened;
const devtoolsClosed = once(w.webContents, 'devtools-closed');
w.webContents.closeDevTools();
await devtoolsClosed;
});
});
describe('login event', () => {
afterEach(closeAllWindows);
let server: http.Server;
let serverUrl: string;
let serverPort: number;
let proxyServer: http.Server;
let proxyServerPort: number;
before(async () => {
server = http.createServer((request, response) => {
if (request.url === '/no-auth') {
return response.end('ok');
}
if (request.headers.authorization) {
response.writeHead(200, { 'Content-type': 'text/plain' });
return response.end(request.headers.authorization);
}
response
.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' })
.end('401');
});
({ port: serverPort, url: serverUrl } = await listen(server));
});
before(async () => {
proxyServer = http.createServer((request, response) => {
if (request.headers['proxy-authorization']) {
response.writeHead(200, { 'Content-type': 'text/plain' });
return response.end(request.headers['proxy-authorization']);
}
response
.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' })
.end();
});
proxyServerPort = (await listen(proxyServer)).port;
});
afterEach(async () => {
await session.defaultSession.clearAuthCache();
});
after(() => {
server.close();
proxyServer.close();
});
it('is emitted when navigating', async () => {
const [user, pass] = ['user', 'pass'];
const w = new BrowserWindow({ show: false });
let eventRequest: any;
let eventAuthInfo: any;
w.webContents.on('login', (event, request, authInfo, cb) => {
eventRequest = request;
eventAuthInfo = authInfo;
event.preventDefault();
cb(user, pass);
});
await w.loadURL(serverUrl);
const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`);
expect(eventRequest.url).to.equal(serverUrl + '/');
expect(eventAuthInfo.isProxy).to.be.false();
expect(eventAuthInfo.scheme).to.equal('basic');
expect(eventAuthInfo.host).to.equal('127.0.0.1');
expect(eventAuthInfo.port).to.equal(serverPort);
expect(eventAuthInfo.realm).to.equal('Foo');
});
it('is emitted when a proxy requests authorization', async () => {
const customSession = session.fromPartition(`${Math.random()}`);
await customSession.setProxy({ proxyRules: `127.0.0.1:${proxyServerPort}`, proxyBypassRules: '<-loopback>' });
const [user, pass] = ['user', 'pass'];
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
let eventRequest: any;
let eventAuthInfo: any;
w.webContents.on('login', (event, request, authInfo, cb) => {
eventRequest = request;
eventAuthInfo = authInfo;
event.preventDefault();
cb(user, pass);
});
await w.loadURL(`${serverUrl}/no-auth`);
const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`);
expect(eventRequest.url).to.equal(`${serverUrl}/no-auth`);
expect(eventAuthInfo.isProxy).to.be.true();
expect(eventAuthInfo.scheme).to.equal('basic');
expect(eventAuthInfo.host).to.equal('127.0.0.1');
expect(eventAuthInfo.port).to.equal(proxyServerPort);
expect(eventAuthInfo.realm).to.equal('Foo');
});
it('cancels authentication when callback is called with no arguments', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.on('login', (event, request, authInfo, cb) => {
event.preventDefault();
cb();
});
await w.loadURL(serverUrl);
const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
expect(body).to.equal('401');
});
});
describe('page-title-updated event', () => {
afterEach(closeAllWindows);
it('is emitted with a full title for pages with no navigation', async () => {
const bw = new BrowserWindow({ show: false });
await bw.loadURL('about:blank');
bw.webContents.executeJavaScript('child = window.open("", "", "show=no"); null');
const [, child] = await once(app, 'web-contents-created') as [any, WebContents];
bw.webContents.executeJavaScript('child.document.title = "new title"');
const [, title] = await once(child, 'page-title-updated') as [any, string];
expect(title).to.equal('new title');
});
});
describe('context-menu event', () => {
afterEach(closeAllWindows);
it('emits when right-clicked in page', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
const promise = once(w.webContents, 'context-menu') as Promise<[any, Electron.ContextMenuParams]>;
// Simulate right-click to create context-menu event.
const opts = { x: 0, y: 0, button: 'right' as const };
w.webContents.sendInputEvent({ ...opts, type: 'mouseDown' });
w.webContents.sendInputEvent({ ...opts, type: 'mouseUp' });
const [, params] = await promise;
expect(params.pageURL).to.equal(w.webContents.getURL());
expect(params.frame).to.be.an('object');
expect(params.x).to.be.a('number');
expect(params.y).to.be.a('number');
});
});
describe('close() method', () => {
afterEach(closeAllWindows);
it('closes when close() is called', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
const destroyed = once(w, 'destroyed');
w.close();
await destroyed;
expect(w.isDestroyed()).to.be.true();
});
it('closes when close() is called after loading a page', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
await w.loadURL('about:blank');
const destroyed = once(w, 'destroyed');
w.close();
await destroyed;
expect(w.isDestroyed()).to.be.true();
});
it('can be GCed before loading a page', async () => {
const v8Util = process._linkedBinding('electron_common_v8_util');
let registry: FinalizationRegistry<unknown> | null = null;
const cleanedUp = new Promise<number>(resolve => {
registry = new FinalizationRegistry(resolve as any);
});
(() => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
registry!.register(w, 42);
})();
const i = setInterval(() => v8Util.requestGarbageCollectionForTesting(), 100);
defer(() => clearInterval(i));
expect(await cleanedUp).to.equal(42);
});
it('causes its parent browserwindow to be closed', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const closed = once(w, 'closed');
w.webContents.close();
await closed;
expect(w.isDestroyed()).to.be.true();
});
it('ignores beforeunload if waitForBeforeUnload not specified', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
await w.loadURL('about:blank');
await w.executeJavaScript('window.onbeforeunload = () => "hello"; null');
w.on('will-prevent-unload', () => { throw new Error('unexpected will-prevent-unload'); });
const destroyed = once(w, 'destroyed');
w.close();
await destroyed;
expect(w.isDestroyed()).to.be.true();
});
it('runs beforeunload if waitForBeforeUnload is specified', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
await w.loadURL('about:blank');
await w.executeJavaScript('window.onbeforeunload = () => "hello"; null');
const willPreventUnload = once(w, 'will-prevent-unload');
w.close({ waitForBeforeUnload: true });
await willPreventUnload;
expect(w.isDestroyed()).to.be.false();
});
it('overriding beforeunload prevention results in webcontents close', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
await w.loadURL('about:blank');
await w.executeJavaScript('window.onbeforeunload = () => "hello"; null');
w.once('will-prevent-unload', e => e.preventDefault());
const destroyed = once(w, 'destroyed');
w.close({ waitForBeforeUnload: true });
await destroyed;
expect(w.isDestroyed()).to.be.true();
});
});
describe('content-bounds-updated event', () => {
afterEach(closeAllWindows);
it('emits when moveTo is called', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('window.moveTo(100, 100)', true);
const [, rect] = await once(w.webContents, 'content-bounds-updated') as [any, Electron.Rectangle];
const { width, height } = w.getBounds();
expect(rect).to.deep.equal({
x: 100,
y: 100,
width,
height
});
await new Promise(setImmediate);
expect(w.getBounds().x).to.equal(100);
expect(w.getBounds().y).to.equal(100);
});
it('emits when resizeTo is called', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('window.resizeTo(100, 100)', true);
const [, rect] = await once(w.webContents, 'content-bounds-updated') as [any, Electron.Rectangle];
const { x, y } = w.getBounds();
expect(rect).to.deep.equal({
x,
y,
width: 100,
height: 100
});
await new Promise(setImmediate);
expect({
width: w.getBounds().width,
height: w.getBounds().height
}).to.deep.equal(process.platform === 'win32' ? {
// The width is reported as being larger on Windows? I'm not sure why
// this is.
width: 136,
height: 100
} : {
width: 100,
height: 100
});
});
it('does not change window bounds if cancelled', async () => {
const w = new BrowserWindow({ show: false });
const { width, height } = w.getBounds();
w.loadURL('about:blank');
w.webContents.once('content-bounds-updated', e => e.preventDefault());
await w.webContents.executeJavaScript('window.resizeTo(100, 100)', true);
await new Promise(setImmediate);
expect(w.getBounds().width).to.equal(width);
expect(w.getBounds().height).to.equal(height);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 41,497 |
[Bug]: MacOS powerMonitor events don't detect fast user switching
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
26.2.1
### What operating system are you using?
macOS
### Operating System Version
macOS Sonoma 14.2.1
### What arch are you using?
arm64 (including Apple Silicon)
### Last Known Working Electron version
_No response_
### Expected Behavior
`PowerMonitor`'s `user-did-become-active` and `user-did-resign-active` events should be triggered when a user fast-switches to another os user, as per https://github.com/electron/electron/pull/25321
### Actual Behavior
`PowerMonitor`'s `user-did-become-active` and `user-did-resign-active` events are not triggered when a user fast-switches to another os user.
This is also reproducible on Electron v30.0.0-alpha.3 on Electron Fiddle by adding the event handers to `app.on('ready'`.
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/41497
|
https://github.com/electron/electron/pull/41506
|
62a897b75b68ce97ef241bdb0e63ab4ed6a8d8a7
|
a7d664e3a3d06a4d3f059cb51a375ee3155a23d6
| 2024-03-03T21:14:46Z |
c++
| 2024-03-06T11:43:39Z |
shell/browser/api/electron_api_power_monitor_mac.mm
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_power_monitor.h"
#include <vector>
#import <ApplicationServices/ApplicationServices.h>
#import <Cocoa/Cocoa.h>
@interface MacLockMonitor : NSObject {
@private
std::vector<electron::api::PowerMonitor*> emitters;
}
- (void)addEmitter:(electron::api::PowerMonitor*)monitor_;
@end
@implementation MacLockMonitor
- (id)init {
if ((self = [super init])) {
NSDistributedNotificationCenter* distCenter =
[NSDistributedNotificationCenter defaultCenter];
// A notification that the screen was locked.
[distCenter addObserver:self
selector:@selector(onScreenLocked:)
name:@"com.apple.screenIsLocked"
object:nil];
// A notification that the screen was unlocked by the user.
[distCenter addObserver:self
selector:@selector(onScreenUnlocked:)
name:@"com.apple.screenIsUnlocked"
object:nil];
// A notification that the workspace posts before the machine goes to sleep.
[distCenter addObserver:self
selector:@selector(isSuspending:)
name:NSWorkspaceWillSleepNotification
object:nil];
// A notification that the workspace posts when the machine wakes from
// sleep.
[distCenter addObserver:self
selector:@selector(isResuming:)
name:NSWorkspaceDidWakeNotification
object:nil];
// A notification that the workspace posts when the user session becomes
// active.
[distCenter addObserver:self
selector:@selector(onUserDidBecomeActive:)
name:NSWorkspaceSessionDidBecomeActiveNotification
object:nil];
// A notification that the workspace posts when the user session becomes
// inactive.
[distCenter addObserver:self
selector:@selector(onUserDidResignActive:)
name:NSWorkspaceSessionDidResignActiveNotification
object:nil];
}
return self;
}
- (void)dealloc {
[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
}
- (void)addEmitter:(electron::api::PowerMonitor*)monitor_ {
self->emitters.push_back(monitor_);
}
- (void)isSuspending:(NSNotification*)notify {
for (auto* emitter : self->emitters) {
emitter->Emit("suspend");
}
}
- (void)isResuming:(NSNotification*)notify {
for (auto* emitter : self->emitters) {
emitter->Emit("resume");
}
}
- (void)onScreenLocked:(NSNotification*)notification {
for (auto* emitter : self->emitters) {
emitter->Emit("lock-screen");
}
}
- (void)onScreenUnlocked:(NSNotification*)notification {
for (auto* emitter : self->emitters) {
emitter->Emit("unlock-screen");
}
}
- (void)onUserDidBecomeActive:(NSNotification*)notification {
for (auto* emitter : self->emitters) {
emitter->Emit("user-did-become-active");
}
}
- (void)onUserDidResignActive:(NSNotification*)notification {
for (auto* emitter : self->emitters) {
emitter->Emit("user-did-resign-active");
}
}
@end
namespace electron::api {
static MacLockMonitor* g_lock_monitor = nil;
void PowerMonitor::InitPlatformSpecificMonitors() {
if (!g_lock_monitor)
g_lock_monitor = [[MacLockMonitor alloc] init];
[g_lock_monitor addEmitter:this];
}
} // namespace electron::api
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 41,459 |
[Bug]: Cannot open chrome://process-internals (1.x - 25.x can)
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
26.x and above
### What operating system are you using?
Windows
### Operating System Version
Windows 10 and Linux Ubuntu 22.04
### What arch are you using?
x64
### Last Known Working Electron version
25.9.8
### Expected Behavior
Electron can open a subset of Chromium's chrome:// URLs. Two applications I develop rely on being able to open `chrome://gpu` (which works and has always worked), and `chrome://process-internals`. The latter has worked since 1.x.x until 25.9.8. I recently upgraded the apps to Electron 28, and found that chrome://process-internals can no longer be opened. After investigating, it seems every release after 25.x fails to open this. 26-30 beta are all affected. I looked at the breaking changes > https://www.electronjs.org/docs/latest/breaking-changes#planned-breaking-api-changes-260 and there is no mention of this, or a mention of different permissions or process handling.
I tried enabling nodeIntegration, nodeIntegrationInWorker, and disabling contextIsolation and the sandbox, just to see if it would do anything, it doesn't.
### Actual Behavior
chrome://process-internals cannot be opened, while all the other chrome:// URLs work fine.
When trying to open it, the developer tools source pane is blank, and the console only shows one error line > `chromewebdata/:1 Not allowed to load local resource: chrome://process-internals/`
### Testcase Gist URL
_No response_
### Additional Information
If someone wants to test, try running my app here > https://github.com/Alex313031/quark-player and selecting the "Developer" menu item, then clicking "Open chrome://process-internals"
|
https://github.com/electron/electron/issues/41459
|
https://github.com/electron/electron/pull/41476
|
62331f5ac14954367e1e762b9f206c81ebe35109
|
f826506218fc72da8b1792221284a247b09cf800
| 2024-02-28T02:35:00Z |
c++
| 2024-03-07T14:31:16Z |
electron_paks.gni
|
import("//build/config/locales.gni")
import("//electron/buildflags/buildflags.gni")
import("//printing/buildflags/buildflags.gni")
import("//tools/grit/repack.gni")
import("//ui/base/ui_features.gni")
# See: //chrome/chrome_paks.gni
template("electron_repack_percent") {
percent = invoker.percent
repack(target_name) {
forward_variables_from(invoker,
[
"copy_data_to_bundle",
"repack_whitelist",
"visibility",
])
# All sources should also have deps for completeness.
sources = [
"$root_gen_dir/components/components_resources_${percent}_percent.pak",
"$root_gen_dir/third_party/blink/public/resources/blink_scaled_resources_${percent}_percent.pak",
"$root_gen_dir/ui/resources/ui_resources_${percent}_percent.pak",
]
deps = [
"//components/resources",
"//third_party/blink/public:scaled_resources_${percent}_percent",
"//ui/resources",
]
if (defined(invoker.deps)) {
deps += invoker.deps
}
if (toolkit_views) {
sources += [ "$root_gen_dir/ui/views/resources/views_resources_${percent}_percent.pak" ]
deps += [ "//ui/views/resources" ]
}
output = "${invoker.output_dir}/chrome_${percent}_percent.pak"
}
}
template("electron_extra_paks") {
repack(target_name) {
forward_variables_from(invoker,
[
"copy_data_to_bundle",
"repack_whitelist",
"visibility",
])
output = "${invoker.output_dir}/resources.pak"
sources = [
"$root_gen_dir/chrome/accessibility_resources.pak",
"$root_gen_dir/chrome/browser_resources.pak",
"$root_gen_dir/chrome/common_resources.pak",
"$root_gen_dir/chrome/dev_ui_browser_resources.pak",
"$root_gen_dir/components/components_resources.pak",
"$root_gen_dir/content/browser/resources/media/media_internals_resources.pak",
"$root_gen_dir/content/browser/tracing/tracing_resources.pak",
"$root_gen_dir/content/browser/webrtc/resources/webrtc_internals_resources.pak",
"$root_gen_dir/content/content_resources.pak",
"$root_gen_dir/content/gpu_resources.pak",
"$root_gen_dir/mojo/public/js/mojo_bindings_resources.pak",
"$root_gen_dir/net/net_resources.pak",
"$root_gen_dir/third_party/blink/public/resources/blink_resources.pak",
"$root_gen_dir/third_party/blink/public/resources/inspector_overlay_resources.pak",
"$target_gen_dir/electron_resources.pak",
]
deps = [
"//chrome/browser:dev_ui_browser_resources",
"//chrome/browser:resources",
"//chrome/browser/resources/accessibility:resources",
"//chrome/common:resources",
"//components/resources",
"//content:content_resources",
"//content/browser/resources/gpu:resources",
"//content/browser/resources/media:resources",
"//content/browser/tracing:resources",
"//content/browser/webrtc/resources",
"//electron:resources",
"//mojo/public/js:resources",
"//net:net_resources",
"//third_party/blink/public:devtools_inspector_resources",
"//third_party/blink/public:resources",
"//ui/resources",
]
if (defined(invoker.deps)) {
deps += invoker.deps
}
if (defined(invoker.additional_paks)) {
sources += invoker.additional_paks
}
# New paks should be added here by default.
sources += [
"$root_gen_dir/content/browser/devtools/devtools_resources.pak",
"$root_gen_dir/ui/resources/webui_resources.pak",
]
deps += [ "//content/browser/devtools:devtools_resources" ]
if (enable_pdf_viewer) {
sources += [ "$root_gen_dir/chrome/pdf_resources.pak" ]
deps += [ "//chrome/browser/resources/pdf:resources" ]
}
if (enable_print_preview) {
sources += [ "$root_gen_dir/chrome/print_preview_resources.pak" ]
deps += [ "//chrome/browser/resources/print_preview:resources" ]
}
if (enable_electron_extensions) {
sources += [
"$root_gen_dir/chrome/component_extension_resources.pak",
"$root_gen_dir/extensions/extensions_renderer_resources.pak",
"$root_gen_dir/extensions/extensions_resources.pak",
]
deps += [
"//chrome/browser/resources:component_extension_resources",
"//extensions:extensions_resources",
]
}
}
}
template("electron_paks") {
electron_repack_percent("${target_name}_100_percent") {
percent = "100"
forward_variables_from(invoker,
[
"copy_data_to_bundle",
"deps",
"output_dir",
"repack_whitelist",
"visibility",
])
}
if (enable_hidpi) {
electron_repack_percent("${target_name}_200_percent") {
percent = "200"
forward_variables_from(invoker,
[
"copy_data_to_bundle",
"deps",
"output_dir",
"repack_whitelist",
"visibility",
])
}
}
electron_extra_paks("${target_name}_extra") {
forward_variables_from(invoker,
[
"copy_data_to_bundle",
"deps",
"output_dir",
"repack_whitelist",
"visibility",
])
if (defined(invoker.additional_extra_paks)) {
additional_paks = invoker.additional_extra_paks
}
}
repack_locales("${target_name}_locales") {
forward_variables_from(invoker,
[
"copy_data_to_bundle",
"deps",
"visibility",
])
if (defined(invoker.locale_whitelist)) {
repack_whitelist = invoker.locale_whitelist
} else if (defined(invoker.repack_whitelist)) {
repack_whitelist = invoker.repack_whitelist
}
source_patterns = [
"${root_gen_dir}/chrome/chromium_strings_",
"${root_gen_dir}/chrome/locale_settings_",
"${root_gen_dir}/chrome/platform_locale_settings_",
"${root_gen_dir}/chrome/generated_resources_",
"${root_gen_dir}/components/strings/components_locale_settings_",
"${root_gen_dir}/components/strings/components_strings_",
"${root_gen_dir}/device/bluetooth/strings/bluetooth_strings_",
"${root_gen_dir}/extensions/strings/extensions_strings_",
"${root_gen_dir}/services/strings/services_strings_",
"${root_gen_dir}/third_party/blink/public/strings/blink_accessibility_strings_",
"${root_gen_dir}/third_party/blink/public/strings/blink_strings_",
"${root_gen_dir}/ui/strings/app_locale_settings_",
"${root_gen_dir}/ui/strings/ax_strings_",
"${root_gen_dir}/ui/strings/ui_strings_",
]
deps = [
"//chrome/app:branded_strings",
"//chrome/app:generated_resources",
"//chrome/app/resources:locale_settings",
"//chrome/app/resources:platform_locale_settings",
"//components/strings:components_locale_settings",
"//components/strings:components_strings",
"//device/bluetooth/strings",
"//extensions/strings",
"//services/strings",
"//third_party/blink/public/strings",
"//third_party/blink/public/strings:accessibility_strings",
"//ui/strings:app_locale_settings",
"//ui/strings:ax_strings",
"//ui/strings:ui_strings",
]
input_locales = platform_pak_locales
output_dir = "${invoker.output_dir}/locales"
if (is_mac) {
output_locales = locales_as_apple_outputs
} else {
output_locales = platform_pak_locales
}
}
group(target_name) {
forward_variables_from(invoker, [ "deps" ])
public_deps = [
":${target_name}_100_percent",
":${target_name}_extra",
":${target_name}_locales",
]
if (enable_hidpi) {
public_deps += [ ":${target_name}_200_percent" ]
}
if (defined(invoker.public_deps)) {
public_deps += invoker.public_deps
}
}
}
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 41,459 |
[Bug]: Cannot open chrome://process-internals (1.x - 25.x can)
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
26.x and above
### What operating system are you using?
Windows
### Operating System Version
Windows 10 and Linux Ubuntu 22.04
### What arch are you using?
x64
### Last Known Working Electron version
25.9.8
### Expected Behavior
Electron can open a subset of Chromium's chrome:// URLs. Two applications I develop rely on being able to open `chrome://gpu` (which works and has always worked), and `chrome://process-internals`. The latter has worked since 1.x.x until 25.9.8. I recently upgraded the apps to Electron 28, and found that chrome://process-internals can no longer be opened. After investigating, it seems every release after 25.x fails to open this. 26-30 beta are all affected. I looked at the breaking changes > https://www.electronjs.org/docs/latest/breaking-changes#planned-breaking-api-changes-260 and there is no mention of this, or a mention of different permissions or process handling.
I tried enabling nodeIntegration, nodeIntegrationInWorker, and disabling contextIsolation and the sandbox, just to see if it would do anything, it doesn't.
### Actual Behavior
chrome://process-internals cannot be opened, while all the other chrome:// URLs work fine.
When trying to open it, the developer tools source pane is blank, and the console only shows one error line > `chromewebdata/:1 Not allowed to load local resource: chrome://process-internals/`
### Testcase Gist URL
_No response_
### Additional Information
If someone wants to test, try running my app here > https://github.com/Alex313031/quark-player and selecting the "Developer" menu item, then clicking "Open chrome://process-internals"
|
https://github.com/electron/electron/issues/41459
|
https://github.com/electron/electron/pull/41476
|
62331f5ac14954367e1e762b9f206c81ebe35109
|
f826506218fc72da8b1792221284a247b09cf800
| 2024-02-28T02:35:00Z |
c++
| 2024-03-07T14:31:16Z |
spec/chromium-spec.ts
|
import { expect } from 'chai';
import { BrowserWindow, WebContents, webFrameMain, session, ipcMain, app, protocol, webContents, dialog, MessageBoxOptions } from 'electron/main';
import { closeAllWindows } from './lib/window-helpers';
import * as https from 'node:https';
import * as http from 'node:http';
import * as path from 'node:path';
import * as fs from 'node:fs';
import * as url from 'node:url';
import * as ChildProcess from 'node:child_process';
import { EventEmitter, once } from 'node:events';
import { ifit, ifdescribe, defer, itremote, listen } from './lib/spec-helpers';
import { PipeTransport } from './pipe-transport';
import * as ws from 'ws';
import { setTimeout } from 'node:timers/promises';
import { AddressInfo } from 'node:net';
const features = process._linkedBinding('electron_common_features');
const fixturesPath = path.resolve(__dirname, 'fixtures');
const certPath = path.join(fixturesPath, 'certificates');
describe('reporting api', () => {
it('sends a report for an intervention', async () => {
const reporting = new EventEmitter();
// The Reporting API only works on https with valid certs. To dodge having
// to set up a trusted certificate, hack the validator.
session.defaultSession.setCertificateVerifyProc((req, cb) => {
cb(0);
});
const options = {
key: fs.readFileSync(path.join(certPath, 'server.key')),
cert: fs.readFileSync(path.join(certPath, 'server.pem')),
ca: [
fs.readFileSync(path.join(certPath, 'rootCA.pem')),
fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
],
requestCert: true,
rejectUnauthorized: false
};
const server = https.createServer(options, (req, res) => {
if (req.url?.endsWith('report')) {
let data = '';
req.on('data', (d) => { data += d.toString('utf-8'); });
req.on('end', () => {
reporting.emit('report', JSON.parse(data));
});
}
const { port } = server.address() as any;
res.setHeader('Reporting-Endpoints', `default="https://localhost:${port}/report"`);
res.setHeader('Content-Type', 'text/html');
res.end('<script>window.navigator.vibrate(1)</script>');
});
await listen(server);
const bw = new BrowserWindow({ show: false });
try {
const reportGenerated = once(reporting, 'report');
await bw.loadURL(`https://localhost:${(server.address() as AddressInfo).port}/a`);
const [reports] = await reportGenerated;
expect(reports).to.be.an('array').with.lengthOf(1);
const { type, url, body } = reports[0];
expect(type).to.equal('intervention');
expect(url).to.equal(url);
expect(body.id).to.equal('NavigatorVibrate');
expect(body.message).to.match(/Blocked call to navigator.vibrate because user hasn't tapped on the frame or any embedded frame yet/);
} finally {
bw.destroy();
server.close();
}
});
});
describe('window.postMessage', () => {
afterEach(async () => {
await closeAllWindows();
});
it('sets the source and origin correctly', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL(`file://${fixturesPath}/pages/window-open-postMessage-driver.html`);
const [, message] = await once(ipcMain, 'complete');
expect(message.data).to.equal('testing');
expect(message.origin).to.equal('file://');
expect(message.sourceEqualsOpener).to.equal(true);
expect(message.eventOrigin).to.equal('file://');
});
});
describe('focus handling', () => {
let webviewContents: WebContents;
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({
show: true,
webPreferences: {
nodeIntegration: true,
webviewTag: true,
contextIsolation: false
}
});
const webviewReady = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>;
await w.loadFile(path.join(fixturesPath, 'pages', 'tab-focus-loop-elements.html'));
const [, wvContents] = await webviewReady;
webviewContents = wvContents;
await once(webviewContents, 'did-finish-load');
w.focus();
});
afterEach(() => {
webviewContents = null as unknown as WebContents;
w.destroy();
w = null as unknown as BrowserWindow;
});
const expectFocusChange = async () => {
const [, focusedElementId] = await once(ipcMain, 'focus-changed');
return focusedElementId;
};
describe('a TAB press', () => {
const tabPressEvent: any = {
type: 'keyDown',
keyCode: 'Tab'
};
it('moves focus to the next focusable item', async () => {
let focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
let focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-1', `should start focused in element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've moved to element-3, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've looped back to element-1, it's instead in ${focusedElementId}`);
});
});
describe('a SHIFT + TAB press', () => {
const shiftTabPressEvent: any = {
type: 'keyDown',
modifiers: ['Shift'],
keyCode: 'Tab'
};
it('moves focus to the previous focusable item', async () => {
let focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
let focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-3', `should start focused in element-3, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've moved to element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've looped back to element-3, it's instead in ${focusedElementId}`);
});
});
});
describe('web security', () => {
afterEach(closeAllWindows);
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('<body>');
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('engages CORB when web security is not disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'success');
await w.loadURL(`data:text/html,<script>
const s = document.createElement('script')
s.src = "${serverUrl}"
// The script will not load under ORB, refs https://chromium-review.googlesource.com/c/chromium/src/+/3785025.
// Before ORB an empty response is sent, which is now replaced by a network error.
s.onerror = () => { require('electron').ipcRenderer.send('success') }
document.documentElement.appendChild(s)
</script>`);
await p;
});
it('bypasses CORB when web security is disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'success');
await w.loadURL(`data:text/html,
<script>
window.onerror = (e) => { require('electron').ipcRenderer.send('success', e) }
</script>
<script src="${serverUrl}"></script>`);
await p;
});
it('engages CORS when web security is not disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'response');
await w.loadURL(`data:text/html,<script>
(async function() {
try {
await fetch('${serverUrl}');
require('electron').ipcRenderer.send('response', 'passed');
} catch {
require('electron').ipcRenderer.send('response', 'failed');
}
})();
</script>`);
const [, response] = await p;
expect(response).to.equal('failed');
});
it('bypasses CORS when web security is disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'response');
await w.loadURL(`data:text/html,<script>
(async function() {
try {
await fetch('${serverUrl}');
require('electron').ipcRenderer.send('response', 'passed');
} catch {
require('electron').ipcRenderer.send('response', 'failed');
}
})();
</script>`);
const [, response] = await p;
expect(response).to.equal('passed');
});
describe('accessing file://', () => {
async function loadFile (w: BrowserWindow) {
const thisFile = url.format({
pathname: __filename.replaceAll('\\', '/'),
protocol: 'file',
slashes: true
});
await w.loadURL(`data:text/html,<script>
function loadFile() {
return new Promise((resolve) => {
fetch('${thisFile}').then(
() => resolve('loaded'),
() => resolve('failed')
)
});
}
</script>`);
return await w.webContents.executeJavaScript('loadFile()');
}
it('is forbidden when web security is enabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true } });
const result = await loadFile(w);
expect(result).to.equal('failed');
});
it('is allowed when web security is disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false } });
const result = await loadFile(w);
expect(result).to.equal('loaded');
});
});
describe('wasm-eval csp', () => {
async function loadWasm (csp: string) {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
enableBlinkFeatures: 'WebAssemblyCSP'
}
});
await w.loadURL(`data:text/html,<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' ${csp}">
</head>
<script>
function loadWasm() {
const wasmBin = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])
return new Promise((resolve) => {
WebAssembly.instantiate(wasmBin).then(() => {
resolve('loaded')
}).catch((error) => {
resolve(error.message)
})
});
}
</script>`);
return await w.webContents.executeJavaScript('loadWasm()');
}
it('wasm codegen is disallowed by default', async () => {
const r = await loadWasm('');
expect(r).to.equal('WebAssembly.instantiate(): Refused to compile or instantiate WebAssembly module because \'unsafe-eval\' is not an allowed source of script in the following Content Security Policy directive: "script-src \'self\' \'unsafe-inline\'"');
});
it('wasm codegen is allowed with "wasm-unsafe-eval" csp', async () => {
const r = await loadWasm("'wasm-unsafe-eval'");
expect(r).to.equal('loaded');
});
});
describe('csp', () => {
for (const sandbox of [true, false]) {
describe(`when sandbox: ${sandbox}`, () => {
for (const contextIsolation of [true, false]) {
describe(`when contextIsolation: ${contextIsolation}`, () => {
it('prevents eval from running in an inline script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL(`data:text/html,<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'">
</head>
<script>
try {
// We use console.log here because it is easier than making a
// preload script, and the behavior under test changes when
// contextIsolation: false
console.log(eval('true'))
} catch (e) {
console.log(e.message)
}
</script>`);
const [,, message] = await once(w.webContents, 'console-message');
expect(message).to.match(/Refused to evaluate a string/);
});
it('does not prevent eval from running in an inline script when there is no csp', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL(`data:text/html,
<script>
try {
// We use console.log here because it is easier than making a
// preload script, and the behavior under test changes when
// contextIsolation: false
console.log(eval('true'))
} catch (e) {
console.log(e.message)
}
</script>`);
const [,, message] = await once(w.webContents, 'console-message');
expect(message).to.equal('true');
});
it('prevents eval from running in executeJavaScript', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL('data:text/html,<head><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; script-src \'self\' \'unsafe-inline\'"></meta></head>');
await expect(w.webContents.executeJavaScript('eval("true")')).to.be.rejected();
});
it('does not prevent eval from running in executeJavaScript when there is no csp', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL('data:text/html,');
expect(await w.webContents.executeJavaScript('eval("true")')).to.be.true();
});
});
}
});
}
});
it('does not crash when multiple WebContent are created with web security disabled', () => {
const options = { show: false, webPreferences: { webSecurity: false } };
const w1 = new BrowserWindow(options);
w1.loadURL(serverUrl);
const w2 = new BrowserWindow(options);
w2.loadURL(serverUrl);
});
});
describe('command line switches', () => {
let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
afterEach(() => {
if (appProcess && !appProcess.killed) {
appProcess.kill();
appProcess = undefined;
}
});
describe('--lang switch', () => {
const currentLocale = app.getLocale();
const currentSystemLocale = app.getSystemLocale();
const currentPreferredLanguages = JSON.stringify(app.getPreferredSystemLanguages());
const testLocale = async (locale: string, result: string, printEnv: boolean = false) => {
const appPath = path.join(fixturesPath, 'api', 'locale-check');
const args = [appPath, `--set-lang=${locale}`];
if (printEnv) {
args.push('--print-env');
}
appProcess = ChildProcess.spawn(process.execPath, args);
let output = '';
appProcess.stdout.on('data', (data) => { output += data; });
let stderr = '';
appProcess.stderr.on('data', (data) => { stderr += data; });
const [code, signal] = await once(appProcess, 'exit');
if (code !== 0) {
throw new Error(`Process exited with code "${code}" signal "${signal}" output "${output}" stderr "${stderr}"`);
}
output = output.replaceAll(/(\r\n|\n|\r)/gm, '');
expect(output).to.equal(result);
};
it('should set the locale', async () => testLocale('fr', `fr|${currentSystemLocale}|${currentPreferredLanguages}`));
it('should set the locale with country code', async () => testLocale('zh-CN', `zh-CN|${currentSystemLocale}|${currentPreferredLanguages}`));
it('should not set an invalid locale', async () => testLocale('asdfkl', `${currentLocale}|${currentSystemLocale}|${currentPreferredLanguages}`));
const lcAll = String(process.env.LC_ALL);
ifit(process.platform === 'linux')('current process has a valid LC_ALL env', async () => {
// The LC_ALL env should not be set to DOM locale string.
expect(lcAll).to.not.equal(app.getLocale());
});
ifit(process.platform === 'linux')('should not change LC_ALL', async () => testLocale('fr', lcAll, true));
ifit(process.platform === 'linux')('should not change LC_ALL when setting invalid locale', async () => testLocale('asdfkl', lcAll, true));
ifit(process.platform === 'linux')('should not change LC_ALL when --lang is not set', async () => testLocale('', lcAll, true));
});
describe('--remote-debugging-pipe switch', () => {
it('should expose CDP via pipe', async () => {
const electronPath = process.execPath;
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe']
}) as ChildProcess.ChildProcessWithoutNullStreams;
const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
const pipe = new PipeTransport(stdio[3], stdio[4]);
const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
const message = (await versionPromise) as any;
expect(message.id).to.equal(1);
expect(message.result.product).to.contain('Chrome');
expect(message.result.userAgent).to.contain('Electron');
});
it('should override --remote-debugging-port switch', async () => {
const electronPath = process.execPath;
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe', '--remote-debugging-port=0'], {
stdio: ['inherit', 'inherit', 'pipe', 'pipe', 'pipe']
}) as ChildProcess.ChildProcessWithoutNullStreams;
let stderr = '';
appProcess.stderr.on('data', (data: string) => { stderr += data; });
const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
const pipe = new PipeTransport(stdio[3], stdio[4]);
const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
const message = (await versionPromise) as any;
expect(message.id).to.equal(1);
expect(stderr).to.not.include('DevTools listening on');
});
it('should shut down Electron upon Browser.close CDP command', async () => {
const electronPath = process.execPath;
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe']
}) as ChildProcess.ChildProcessWithoutNullStreams;
const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
const pipe = new PipeTransport(stdio[3], stdio[4]);
pipe.send({ id: 1, method: 'Browser.close', params: {} });
await once(appProcess, 'exit');
});
});
describe('--remote-debugging-port switch', () => {
it('should display the discovery page', (done) => {
const electronPath = process.execPath;
let output = '';
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-port=']);
appProcess.stdout.on('data', (data) => {
console.log(data);
});
appProcess.stderr.on('data', (data) => {
console.log(data);
output += data;
const m = /DevTools listening on ws:\/\/127.0.0.1:(\d+)\//.exec(output);
if (m) {
appProcess!.stderr.removeAllListeners('data');
const port = m[1];
http.get(`http://127.0.0.1:${port}`, (res) => {
try {
expect(res.statusCode).to.eql(200);
expect(parseInt(res.headers['content-length']!)).to.be.greaterThan(0);
done();
} catch (e) {
done(e);
} finally {
res.destroy();
}
});
}
});
});
});
});
describe('chromium features', () => {
afterEach(closeAllWindows);
describe('accessing key names also used as Node.js module names', () => {
it('does not crash', (done) => {
const w = new BrowserWindow({ show: false });
w.webContents.once('did-finish-load', () => { done(); });
w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'external-string.html'));
});
});
describe('first party sets', () => {
const fps = [
'https://fps-member1.glitch.me',
'https://fps-member2.glitch.me',
'https://fps-member3.glitch.me'
];
it('loads first party sets', async () => {
const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'base');
const fpsProcess = ChildProcess.spawn(process.execPath, [appPath]);
let output = '';
fpsProcess.stdout.on('data', data => { output += data; });
await once(fpsProcess, 'exit');
expect(output).to.include(fps.join(','));
});
it('loads sets from the command line', async () => {
const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'command-line');
const args = [appPath, `--use-first-party-set=${fps}`];
const fpsProcess = ChildProcess.spawn(process.execPath, args);
let output = '';
fpsProcess.stdout.on('data', data => { output += data; });
await once(fpsProcess, 'exit');
expect(output).to.include(fps.join(','));
});
});
describe('loading jquery', () => {
it('does not crash', (done) => {
const w = new BrowserWindow({ show: false });
w.webContents.once('did-finish-load', () => { done(); });
w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html'));
});
});
describe('navigator.keyboard', () => {
afterEach(closeAllWindows);
it('getLayoutMap() should return a KeyboardLayoutMap object', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const size = await w.webContents.executeJavaScript(`
navigator.keyboard.getLayoutMap().then(map => map.size)
`);
expect(size).to.be.a('number');
});
it('should lock the keyboard', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'modal.html'));
// Test that without lock, with ESC:
// - the window leaves fullscreen
// - the dialog is not closed
const enterFS1 = once(w, 'enter-full-screen');
await w.webContents.executeJavaScript('document.body.requestFullscreen()', true);
await enterFS1;
await w.webContents.executeJavaScript('document.getElementById(\'favDialog\').showModal()', true);
const open1 = await w.webContents.executeJavaScript('document.getElementById(\'favDialog\').open');
expect(open1).to.be.true();
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
await setTimeout(1000);
const openAfter1 = await w.webContents.executeJavaScript('document.getElementById(\'favDialog\').open');
expect(openAfter1).to.be.true();
expect(w.isFullScreen()).to.be.false();
// Test that with lock, with ESC:
// - the window does not leave fullscreen
// - the dialog is closed
const enterFS2 = once(w, 'enter-full-screen');
await w.webContents.executeJavaScript(`
navigator.keyboard.lock(['Escape']);
document.body.requestFullscreen();
`, true);
await enterFS2;
await w.webContents.executeJavaScript('document.getElementById(\'favDialog\').showModal()', true);
const open2 = await w.webContents.executeJavaScript('document.getElementById(\'favDialog\').open');
expect(open2).to.be.true();
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
await setTimeout(1000);
const openAfter2 = await w.webContents.executeJavaScript('document.getElementById(\'favDialog\').open');
expect(openAfter2).to.be.false();
expect(w.isFullScreen()).to.be.true();
});
});
describe('navigator.languages', () => {
it('should return the system locale only', async () => {
const appLocale = app.getLocale();
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const languages = await w.webContents.executeJavaScript('navigator.languages');
expect(languages.length).to.be.greaterThan(0);
expect(languages).to.contain(appLocale);
});
});
describe('navigator.serviceWorker', () => {
it('should register for file scheme', (done) => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'sw-file-scheme-spec',
contextIsolation: false
}
});
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(message);
} else if (channel === 'response') {
expect(message).to.equal('Hello from serviceWorker!');
session.fromPartition('sw-file-scheme-spec').clearStorageData({
storages: ['serviceworkers']
}).then(() => done());
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
});
it('should register for intercepted file scheme', (done) => {
const customSession = session.fromPartition('intercept-file');
customSession.protocol.interceptBufferProtocol('file', (request, callback) => {
let file = url.parse(request.url).pathname!;
if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
const content = fs.readFileSync(path.normalize(file));
const ext = path.extname(file);
let type = 'text/html';
if (ext === '.js') type = 'application/javascript';
callback({ data: content, mimeType: type } as any);
});
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: customSession,
contextIsolation: false
}
});
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(`unexpected error : ${message}`);
} else if (channel === 'response') {
expect(message).to.equal('Hello from serviceWorker!');
customSession.clearStorageData({
storages: ['serviceworkers']
}).then(() => {
customSession.protocol.uninterceptProtocol('file');
done();
});
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
});
it('should register for custom scheme', (done) => {
const customSession = session.fromPartition('custom-scheme');
customSession.protocol.registerFileProtocol(serviceWorkerScheme, (request, callback) => {
let file = url.parse(request.url).pathname!;
if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
callback({ path: path.normalize(file) } as any);
});
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: customSession,
contextIsolation: false
}
});
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(`unexpected error : ${message}`);
} else if (channel === 'response') {
expect(message).to.equal('Hello from serviceWorker!');
customSession.clearStorageData({
storages: ['serviceworkers']
}).then(() => {
customSession.protocol.uninterceptProtocol(serviceWorkerScheme);
done();
});
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'custom-scheme-index.html'));
});
it('should not allow nodeIntegrationInWorker', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
nodeIntegrationInWorker: true,
partition: 'sw-file-scheme-worker-spec',
contextIsolation: false
}
});
await w.loadURL(`file://${fixturesPath}/pages/service-worker/empty.html`);
const data = await w.webContents.executeJavaScript(`
navigator.serviceWorker.register('worker-no-node.js', {
scope: './'
}).then(() => navigator.serviceWorker.ready)
new Promise((resolve) => {
navigator.serviceWorker.onmessage = event => resolve(event.data);
});
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
});
describe('navigator.geolocation', () => {
ifit(features.isFakeLocationProviderEnabled())('returns error when permission is denied', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'geolocation-spec',
contextIsolation: false
}
});
const message = once(w.webContents, 'ipc-message');
w.webContents.session.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'geolocation') {
callback(false);
} else {
callback(true);
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'geolocation', 'index.html'));
const [, channel] = await message;
expect(channel).to.equal('success', 'unexpected response from geolocation api');
});
ifit(!features.isFakeLocationProviderEnabled())('returns position when permission is granted', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
partition: 'geolocation-spec'
}
});
w.webContents.session.setPermissionRequestHandler((_wc, _permission, callback) => {
callback(true);
});
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const position = await w.webContents.executeJavaScript(`new Promise((resolve, reject) =>
navigator.geolocation.getCurrentPosition(
x => resolve({coords: x.coords, timestamp: x.timestamp}),
err => reject(new Error(err.message))))`);
expect(position).to.have.property('coords');
expect(position).to.have.property('timestamp');
});
});
describe('web workers', () => {
let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
afterEach(() => {
if (appProcess && !appProcess.killed) {
appProcess.kill();
appProcess = undefined;
}
});
it('Worker with nodeIntegrationInWorker has access to self.module.paths', async () => {
const appPath = path.join(__dirname, 'fixtures', 'apps', 'self-module-paths');
appProcess = ChildProcess.spawn(process.execPath, [appPath]);
const [code] = await once(appProcess, 'exit');
expect(code).to.equal(0);
});
it('Worker can work', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new Worker('../workers/worker.js');
const message = 'ping';
const eventPromise = new Promise((resolve) => { worker.onmessage = resolve; });
worker.postMessage(message);
eventPromise.then(t => t.data)
`);
expect(data).to.equal('ping');
});
it('Worker has no node integration by default', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new Worker('../workers/worker_node.js');
new Promise((resolve) => { worker.onmessage = e => resolve(e.data); })
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
it('Worker has node integration with nodeIntegrationInWorker', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } });
w.loadURL(`file://${fixturesPath}/pages/worker.html`);
const [, data] = await once(ipcMain, 'worker-result');
expect(data).to.equal('object function object function');
});
describe('SharedWorker', () => {
it('can work', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new SharedWorker('../workers/shared_worker.js');
const message = 'ping';
const eventPromise = new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); });
worker.port.postMessage(message);
eventPromise
`);
expect(data).to.equal('ping');
});
it('has no node integration by default', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new SharedWorker('../workers/shared_worker_node.js');
new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); })
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
it('does not have node integration with nodeIntegrationInWorker', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
nodeIntegrationInWorker: true,
contextIsolation: false
}
});
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new SharedWorker('../workers/shared_worker_node.js');
new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); })
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
});
});
describe('form submit', () => {
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((req, res) => {
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
res.setHeader('Content-Type', 'application/json');
req.on('end', () => {
res.end(`body:${body}`);
});
});
serverUrl = (await listen(server)).url;
});
after(async () => {
server.close();
await closeAllWindows();
});
for (const isSandboxEnabled of [true, false]) {
describe(`sandbox=${isSandboxEnabled}`, () => {
it('posts data in the same window', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: isSandboxEnabled
}
});
await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
const loadPromise = once(w.webContents, 'did-finish-load');
w.webContents.executeJavaScript(`
const form = document.querySelector('form')
form.action = '${serverUrl}';
form.submit();
`);
await loadPromise;
const res = await w.webContents.executeJavaScript('document.body.innerText');
expect(res).to.equal('body:greeting=hello');
});
it('posts data to a new window with target=_blank', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: isSandboxEnabled
}
});
await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
const windowCreatedPromise = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>;
w.webContents.executeJavaScript(`
const form = document.querySelector('form')
form.action = '${serverUrl}';
form.target = '_blank';
form.submit();
`);
const [, newWin] = await windowCreatedPromise;
const res = await newWin.webContents.executeJavaScript('document.body.innerText');
expect(res).to.equal('body:greeting=hello');
});
});
}
});
describe('window.open', () => {
for (const show of [true, false]) {
it(`shows the child regardless of parent visibility when parent {show=${show}}`, async () => {
const w = new BrowserWindow({ show });
// toggle visibility
if (show) {
w.hide();
} else {
w.show();
}
defer(() => { w.close(); });
const promise = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>;
w.loadFile(path.join(fixturesPath, 'pages', 'window-open.html'));
const [, newWindow] = await promise;
expect(newWindow.isVisible()).to.equal(true);
});
}
// FIXME(zcbenz): This test is making the spec runner hang on exit on Windows.
ifit(process.platform !== 'win32')('disables node integration when it is disabled on the parent window', async () => {
const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-node-integration.html'));
windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-node.html`);
const w = new BrowserWindow({ show: false });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const { eventData } = await w.webContents.executeJavaScript(`(async () => {
const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=false')
const e = await message
b.close();
return {
eventData: e.data
}
})()`);
expect(eventData.isProcessGlobalUndefined).to.be.true();
});
it('disables node integration when it is disabled on the parent window for chrome devtools URLs', async () => {
// NB. webSecurity is disabled because native window.open() is not
// allowed to load devtools:// URLs.
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webSecurity: false } });
w.loadURL('about:blank');
w.webContents.executeJavaScript(`
{ b = window.open('devtools://devtools/bundled/inspector.html', '', 'nodeIntegration=no,show=no'); null }
`);
const [, contents] = await once(app, 'web-contents-created') as [any, WebContents];
const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
expect(typeofProcessGlobal).to.equal('undefined');
});
it('can disable node integration when it is enabled on the parent window', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
w.loadURL('about:blank');
w.webContents.executeJavaScript(`
{ b = window.open('about:blank', '', 'nodeIntegration=no,show=no'); null }
`);
const [, contents] = await once(app, 'web-contents-created') as [any, WebContents];
const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
expect(typeofProcessGlobal).to.equal('undefined');
});
// TODO(jkleinsc) fix this flaky test on WOA
ifit(process.platform !== 'win32' || process.arch !== 'arm64')('disables JavaScript when it is disabled on the parent window', async () => {
const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true } });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const windowUrl = require('node:url').format({
pathname: `${fixturesPath}/pages/window-no-javascript.html`,
protocol: 'file',
slashes: true
});
w.webContents.executeJavaScript(`
{ b = window.open(${JSON.stringify(windowUrl)}, '', 'javascript=no,show=no'); null }
`);
const [, contents] = await once(app, 'web-contents-created') as [any, WebContents];
await once(contents, 'did-finish-load');
// Click link on page
contents.sendInputEvent({ type: 'mouseDown', clickCount: 1, x: 1, y: 1 });
contents.sendInputEvent({ type: 'mouseUp', clickCount: 1, x: 1, y: 1 });
const [, window] = await once(app, 'browser-window-created') as [any, BrowserWindow];
const preferences = window.webContents.getLastWebPreferences();
expect(preferences!.javascript).to.be.false();
});
it('defines a window.location getter', async () => {
let targetURL: string;
if (process.platform === 'win32') {
targetURL = `file:///${fixturesPath.replaceAll('\\', '/')}/pages/base-page.html`;
} else {
targetURL = `file://${fixturesPath}/pages/base-page.html`;
}
const w = new BrowserWindow({ show: false });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
w.webContents.executeJavaScript(`{ b = window.open(${JSON.stringify(targetURL)}); null }`);
const [, window] = await once(app, 'browser-window-created') as [any, BrowserWindow];
await once(window.webContents, 'did-finish-load');
expect(await w.webContents.executeJavaScript('b.location.href')).to.equal(targetURL);
});
it('defines a window.location setter', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow];
await once(webContents, 'did-finish-load');
// When it loads, redirect
w.webContents.executeJavaScript(`{ b.location = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
await once(webContents, 'did-finish-load');
});
it('defines a window.location.href setter', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow];
await once(webContents, 'did-finish-load');
// When it loads, redirect
w.webContents.executeJavaScript(`{ b.location.href = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
await once(webContents, 'did-finish-load');
});
it('open a blank page when no URL is specified', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('{ b = window.open(); null }');
const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow];
await once(webContents, 'did-finish-load');
expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
});
it('open a blank page when an empty URL is specified', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('{ b = window.open(\'\'); null }');
const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow];
await once(webContents, 'did-finish-load');
expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
});
it('does not throw an exception when the frameName is a built-in object property', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('{ b = window.open(\'\', \'__proto__\'); null }');
const frameName = await new Promise((resolve) => {
w.webContents.setWindowOpenHandler(details => {
setImmediate(() => resolve(details.frameName));
return { action: 'allow' };
});
});
expect(frameName).to.equal('__proto__');
});
it('works when used in conjunction with the vm module', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
await w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const { contextObject } = await w.webContents.executeJavaScript(`(async () => {
const vm = require('node:vm');
const contextObject = { count: 1, type: 'gecko' };
window.open('');
vm.runInNewContext('count += 1; type = "chameleon";', contextObject);
return { contextObject };
})()`);
expect(contextObject).to.deep.equal({ count: 2, type: 'chameleon' });
});
// FIXME(nornagon): I'm not sure this ... ever was correct?
xit('inherit options of parent window', async () => {
const w = new BrowserWindow({ show: false, width: 123, height: 456 });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const url = `file://${fixturesPath}/pages/window-open-size.html`;
const { width, height, eventData } = await w.webContents.executeJavaScript(`(async () => {
const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
const b = window.open(${JSON.stringify(url)}, '', 'show=false')
const e = await message
b.close();
const width = outerWidth;
const height = outerHeight;
return {
width,
height,
eventData: e.data
}
})()`);
expect(eventData).to.equal(`size: ${width} ${height}`);
expect(eventData).to.equal('size: 123 456');
});
it('does not override child options', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const windowUrl = `file://${fixturesPath}/pages/window-open-size.html`;
const { eventData } = await w.webContents.executeJavaScript(`(async () => {
const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no,width=350,height=450')
const e = await message
b.close();
return { eventData: e.data }
})()`);
expect(eventData).to.equal('size: 350 450');
});
it('loads preload script after setting opener to null', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload: path.join(fixturesPath, 'module', 'preload.js')
}
}
}));
w.loadURL('about:blank');
w.webContents.executeJavaScript('window.child = window.open(); child.opener = null');
const [, { webContents }] = await once(app, 'browser-window-created');
const [,, message] = await once(webContents, 'console-message');
expect(message).to.equal('{"require":"function","module":"object","exports":"object","process":"object","Buffer":"function"}');
});
it('disables the <webview> tag when it is disabled on the parent window', async () => {
const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-webview-tag.html'));
windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-webview.html`);
const w = new BrowserWindow({ show: false });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const { eventData } = await w.webContents.executeJavaScript(`(async () => {
const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
const b = window.open(${JSON.stringify(windowUrl)}, '', 'webviewTag=no,contextIsolation=no,nodeIntegration=yes,show=no')
const e = await message
b.close();
return { eventData: e.data }
})()`);
expect(eventData.isWebViewGlobalUndefined).to.be.true();
});
it('throws an exception when the arguments cannot be converted to strings', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
await expect(
w.webContents.executeJavaScript('window.open(\'\', { toString: null })')
).to.eventually.be.rejected();
await expect(
w.webContents.executeJavaScript('window.open(\'\', \'\', { toString: 3 })')
).to.eventually.be.rejected();
});
it('does not throw an exception when the features include webPreferences', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
await expect(
w.webContents.executeJavaScript('window.open(\'\', \'\', \'show=no,webPreferences=\'); null')
).to.eventually.be.fulfilled();
});
});
describe('window.opener', () => {
it('is null for main window', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'window-opener.html'));
const [, channel, opener] = await once(w.webContents, 'ipc-message');
expect(channel).to.equal('opener');
expect(opener).to.equal(null);
});
it('is not null for window opened by window.open', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const windowUrl = `file://${fixturesPath}/pages/window-opener.html`;
const eventData = await w.webContents.executeJavaScript(`
const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no');
new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data);
`);
expect(eventData).to.equal('object');
});
});
describe('window.opener.postMessage', () => {
it('sets source and origin correctly', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const windowUrl = `file://${fixturesPath}/pages/window-opener-postMessage.html`;
const { sourceIsChild, origin } = await w.webContents.executeJavaScript(`
const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no');
new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => ({
sourceIsChild: e.source === b,
origin: e.origin
}));
`);
expect(sourceIsChild).to.be.true();
expect(origin).to.equal('file://');
});
it('supports windows opened from a <webview>', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
w.loadURL('about:blank');
const childWindowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'webview-opener-postMessage.html'));
childWindowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-postMessage.html`);
const message = await w.webContents.executeJavaScript(`
const webview = new WebView();
webview.allowpopups = true;
webview.setAttribute('webpreferences', 'contextIsolation=no');
webview.src = ${JSON.stringify(childWindowUrl)}
const consoleMessage = new Promise(resolve => webview.addEventListener('console-message', resolve, {once: true}));
document.body.appendChild(webview);
consoleMessage.then(e => e.message)
`);
expect(message).to.equal('message');
});
describe('targetOrigin argument', () => {
let serverURL: string;
let server: any;
beforeEach(async () => {
server = http.createServer((req, res) => {
res.writeHead(200);
const filePath = path.join(fixturesPath, 'pages', 'window-opener-targetOrigin.html');
res.end(fs.readFileSync(filePath, 'utf8'));
});
serverURL = (await listen(server)).url;
});
afterEach(() => {
server.close();
});
it('delivers messages that match the origin', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const data = await w.webContents.executeJavaScript(`
window.open(${JSON.stringify(serverURL)}, '', 'show=no,contextIsolation=no,nodeIntegration=yes');
new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data)
`);
expect(data).to.equal('deliver');
});
});
});
describe('IdleDetection', () => {
afterEach(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.setPermissionRequestHandler(null);
});
it('can grant a permission request', async () => {
session.defaultSession.setPermissionRequestHandler(
(_wc, permission, callback) => {
callback(permission === 'idle-detection');
}
);
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'button.html'));
const permission = await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const button = document.getElementById('button');
button.addEventListener("click", async () => {
const permission = await IdleDetector.requestPermission();
resolve(permission);
});
button.click();
});
`, true);
expect(permission).to.eq('granted');
});
it('can deny a permission request', async () => {
session.defaultSession.setPermissionRequestHandler(
(_wc, permission, callback) => {
callback(permission !== 'idle-detection');
}
);
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'button.html'));
const permission = await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const button = document.getElementById('button');
button.addEventListener("click", async () => {
const permission = await IdleDetector.requestPermission();
resolve(permission);
});
button.click();
});
`, true);
expect(permission).to.eq('denied');
});
it('can allow the IdleDetector to start', async () => {
session.defaultSession.setPermissionCheckHandler((wc, permission) => {
return permission === 'idle-detection';
});
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const result = await w.webContents.executeJavaScript(`
const detector = new IdleDetector({ threshold: 60000 });
detector.start().then(() => {
return 'success';
}).catch(e => e.message);
`, true);
expect(result).to.eq('success');
});
it('can prevent the IdleDetector from starting', async () => {
session.defaultSession.setPermissionCheckHandler((wc, permission) => {
return permission !== 'idle-detection';
});
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const result = await w.webContents.executeJavaScript(`
const detector = new IdleDetector({ threshold: 60000 });
detector.start().then(() => {
console.log('success')
}).catch(e => e.message);
`, true);
expect(result).to.eq('Idle detection permission denied');
});
});
describe('navigator.mediaDevices', () => {
afterEach(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.setPermissionRequestHandler(null);
});
it('can return labels of enumerated devices', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
expect(labels.some((l: any) => l)).to.be.true();
});
it('does not return labels of enumerated devices when permission denied', async () => {
session.defaultSession.setPermissionCheckHandler(() => false);
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
expect(labels.some((l: any) => l)).to.be.false();
});
it('returns the same device ids across reloads', async () => {
const ses = session.fromPartition('persist:media-device-id');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: ses,
contextIsolation: false
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
const [, firstDeviceIds] = await once(ipcMain, 'deviceIds');
w.webContents.reload();
const [, secondDeviceIds] = await once(ipcMain, 'deviceIds');
expect(firstDeviceIds).to.deep.equal(secondDeviceIds);
});
it('can return new device id when cookie storage is cleared', async () => {
const ses = session.fromPartition('persist:media-device-id');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: ses,
contextIsolation: false
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
const [, firstDeviceIds] = await once(ipcMain, 'deviceIds');
await ses.clearStorageData({ storages: ['cookies'] });
w.webContents.reload();
const [, secondDeviceIds] = await once(ipcMain, 'deviceIds');
expect(firstDeviceIds).to.not.deep.equal(secondDeviceIds);
});
it('provides a securityOrigin to the request handler', async () => {
session.defaultSession.setPermissionRequestHandler(
(wc, permission, callback, details) => {
if (details.securityOrigin !== undefined) {
callback(true);
} else {
callback(false);
}
}
);
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const labels = await w.webContents.executeJavaScript(`navigator.mediaDevices.getUserMedia({
video: {
mandatory: {
chromeMediaSource: "desktop",
minWidth: 1280,
maxWidth: 1280,
minHeight: 720,
maxHeight: 720
}
}
}).then((stream) => stream.getVideoTracks())`);
expect(labels.some((l: any) => l)).to.be.true();
});
it('fails with "not supported" for getDisplayMedia', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const { ok, err } = await w.webContents.executeJavaScript('navigator.mediaDevices.getDisplayMedia({video: true}).then(s => ({ok: true}), e => ({ok: false, err: e.message}))', true);
expect(ok).to.be.false();
expect(err).to.equal('Not supported');
});
});
describe('window.opener access', () => {
const scheme = 'app';
const fileUrl = `file://${fixturesPath}/pages/window-opener-location.html`;
const httpUrl1 = `${scheme}://origin1`;
const httpUrl2 = `${scheme}://origin2`;
const fileBlank = `file://${fixturesPath}/pages/blank.html`;
const httpBlank = `${scheme}://origin1/blank`;
const table = [
{ parent: fileBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: false },
{ parent: fileBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: false },
// {parent: httpBlank, child: fileUrl, nodeIntegration: false, openerAccessible: false}, // can't window.open()
// {parent: httpBlank, child: fileUrl, nodeIntegration: true, openerAccessible: false}, // can't window.open()
// NB. this is different from Chrome's behavior, which isolates file: urls from each other
{ parent: fileBlank, child: fileUrl, nodeIntegration: false, openerAccessible: true },
{ parent: fileBlank, child: fileUrl, nodeIntegration: true, openerAccessible: true },
{ parent: httpBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: true },
{ parent: httpBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: true },
{ parent: httpBlank, child: httpUrl2, nodeIntegration: false, openerAccessible: false },
{ parent: httpBlank, child: httpUrl2, nodeIntegration: true, openerAccessible: false }
];
const s = (url: string) => url.startsWith('file') ? 'file://...' : url;
before(() => {
protocol.registerFileProtocol(scheme, (request, callback) => {
if (request.url.includes('blank')) {
callback(`${fixturesPath}/pages/blank.html`);
} else {
callback(`${fixturesPath}/pages/window-opener-location.html`);
}
});
});
after(() => {
protocol.unregisterProtocol(scheme);
});
afterEach(closeAllWindows);
describe('when opened from main window', () => {
for (const { parent, child, nodeIntegration, openerAccessible } of table) {
for (const sandboxPopup of [false, true]) {
const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} sandboxPopup=${sandboxPopup}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
it(description, async () => {
const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
sandbox: sandboxPopup
}
}
}));
await w.loadURL(parent);
const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise(resolve => {
window.addEventListener('message', function f(e) {
resolve(e.data)
})
window.open(${JSON.stringify(child)}, "", "show=no,nodeIntegration=${nodeIntegration ? 'yes' : 'no'}")
})`);
if (openerAccessible) {
expect(childOpenerLocation).to.be.a('string');
} else {
expect(childOpenerLocation).to.be.null();
}
});
}
}
});
describe('when opened from <webview>', () => {
for (const { parent, child, nodeIntegration, openerAccessible } of table) {
const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
it(description, async () => {
// This test involves three contexts:
// 1. The root BrowserWindow in which the test is run,
// 2. A <webview> belonging to the root window,
// 3. A window opened by calling window.open() from within the <webview>.
// We are testing whether context (3) can access context (2) under various conditions.
// This is context (1), the base window for the test.
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } });
await w.loadURL('about:blank');
const parentCode = `new Promise((resolve) => {
// This is context (3), a child window of the WebView.
const child = window.open(${JSON.stringify(child)}, "", "show=no,contextIsolation=no,nodeIntegration=yes")
window.addEventListener("message", e => {
resolve(e.data)
})
})`;
const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
// This is context (2), a WebView which will call window.open()
const webview = new WebView()
webview.setAttribute('nodeintegration', '${nodeIntegration ? 'on' : 'off'}')
webview.setAttribute('webpreferences', 'contextIsolation=no')
webview.setAttribute('allowpopups', 'on')
webview.src = ${JSON.stringify(parent + '?p=' + encodeURIComponent(child))}
webview.addEventListener('dom-ready', async () => {
webview.executeJavaScript(${JSON.stringify(parentCode)}).then(resolve, reject)
})
document.body.appendChild(webview)
})`);
if (openerAccessible) {
expect(childOpenerLocation).to.be.a('string');
} else {
expect(childOpenerLocation).to.be.null();
}
});
}
});
});
describe('storage', () => {
describe('custom non standard schemes', () => {
const protocolName = 'storage';
let contents: WebContents;
before(() => {
protocol.registerFileProtocol(protocolName, (request, callback) => {
const parsedUrl = url.parse(request.url);
let filename;
switch (parsedUrl.pathname) {
case '/localStorage' : filename = 'local_storage.html'; break;
case '/sessionStorage' : filename = 'session_storage.html'; break;
case '/WebSQL' : filename = 'web_sql.html'; break;
case '/indexedDB' : filename = 'indexed_db.html'; break;
case '/cookie' : filename = 'cookie.html'; break;
default : filename = '';
}
callback({ path: `${fixturesPath}/pages/storage/${filename}` });
});
});
after(() => {
protocol.unregisterProtocol(protocolName);
});
beforeEach(() => {
contents = (webContents as typeof ElectronInternal.WebContents).create({
nodeIntegration: true,
contextIsolation: false
});
});
afterEach(() => {
contents.destroy();
contents = null as any;
});
it('cannot access localStorage', async () => {
const response = once(ipcMain, 'local-storage-response');
contents.loadURL(protocolName + '://host/localStorage');
const [, error] = await response;
expect(error).to.equal('Failed to read the \'localStorage\' property from \'Window\': Access is denied for this document.');
});
it('cannot access sessionStorage', async () => {
const response = once(ipcMain, 'session-storage-response');
contents.loadURL(`${protocolName}://host/sessionStorage`);
const [, error] = await response;
expect(error).to.equal('Failed to read the \'sessionStorage\' property from \'Window\': Access is denied for this document.');
});
it('cannot access WebSQL database', async () => {
const response = once(ipcMain, 'web-sql-response');
contents.loadURL(`${protocolName}://host/WebSQL`);
const [, error] = await response;
expect(error).to.equal('Failed to execute \'openDatabase\' on \'Window\': Access to the WebDatabase API is denied in this context.');
});
it('cannot access indexedDB', async () => {
const response = once(ipcMain, 'indexed-db-response');
contents.loadURL(`${protocolName}://host/indexedDB`);
const [, error] = await response;
expect(error).to.equal('Failed to execute \'open\' on \'IDBFactory\': access to the Indexed Database API is denied in this context.');
});
it('cannot access cookie', async () => {
const response = once(ipcMain, 'cookie-response');
contents.loadURL(`${protocolName}://host/cookie`);
const [, error] = await response;
expect(error).to.equal('Failed to set the \'cookie\' property on \'Document\': Access is denied for this document.');
});
});
describe('can be accessed', () => {
let server: http.Server;
let serverUrl: string;
let serverCrossSiteUrl: string;
before(async () => {
server = http.createServer((req, res) => {
const respond = () => {
if (req.url === '/redirect-cross-site') {
res.setHeader('Location', `${serverCrossSiteUrl}/redirected`);
res.statusCode = 302;
res.end();
} else if (req.url === '/redirected') {
res.end('<html><script>window.localStorage</script></html>');
} else {
res.end();
}
};
setTimeout().then(respond);
});
serverUrl = (await listen(server)).url;
serverCrossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
});
after(() => {
server.close();
server = null as any;
});
afterEach(closeAllWindows);
const testLocalStorageAfterXSiteRedirect = (testTitle: string, extraPreferences = {}) => {
it(testTitle, async () => {
const w = new BrowserWindow({
show: false,
...extraPreferences
});
let redirected = false;
w.webContents.on('render-process-gone', () => {
expect.fail('renderer crashed / was killed');
});
w.webContents.on('did-redirect-navigation', (event, url) => {
expect(url).to.equal(`${serverCrossSiteUrl}/redirected`);
redirected = true;
});
await w.loadURL(`${serverUrl}/redirect-cross-site`);
expect(redirected).to.be.true('didnt redirect');
});
};
testLocalStorageAfterXSiteRedirect('after a cross-site redirect');
testLocalStorageAfterXSiteRedirect('after a cross-site redirect in sandbox mode', { sandbox: true });
});
describe('enableWebSQL webpreference', () => {
const origin = `${standardScheme}://fake-host`;
const filePath = path.join(fixturesPath, 'pages', 'storage', 'web_sql.html');
const sqlPartition = 'web-sql-preference-test';
const sqlSession = session.fromPartition(sqlPartition);
const securityError = 'An attempt was made to break through the security policy of the user agent.';
let contents: WebContents, w: BrowserWindow;
before(() => {
sqlSession.protocol.registerFileProtocol(standardScheme, (request, callback) => {
callback({ path: filePath });
});
});
after(() => {
sqlSession.protocol.unregisterProtocol(standardScheme);
});
afterEach(async () => {
if (contents) {
contents.destroy();
contents = null as any;
}
await closeAllWindows();
(w as any) = null;
});
it('default value allows websql', async () => {
contents = (webContents as typeof ElectronInternal.WebContents).create({
session: sqlSession,
nodeIntegration: true,
contextIsolation: false
});
contents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.be.null();
});
it('when set to false can disallow websql', async () => {
contents = (webContents as typeof ElectronInternal.WebContents).create({
session: sqlSession,
nodeIntegration: true,
enableWebSQL: false,
contextIsolation: false
});
contents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.equal(securityError);
});
it('when set to false does not disable indexedDB', async () => {
contents = (webContents as typeof ElectronInternal.WebContents).create({
session: sqlSession,
nodeIntegration: true,
enableWebSQL: false,
contextIsolation: false
});
contents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.equal(securityError);
const dbName = 'random';
const result = await contents.executeJavaScript(`
new Promise((resolve, reject) => {
try {
let req = window.indexedDB.open('${dbName}');
req.onsuccess = (event) => {
let db = req.result;
resolve(db.name);
}
req.onerror = (event) => { resolve(event.target.code); }
} catch (e) {
resolve(e.message);
}
});
`);
expect(result).to.equal(dbName);
});
it('child webContents can override when the embedder has allowed websql', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
webviewTag: true,
session: sqlSession,
contextIsolation: false
}
});
w.webContents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.be.null();
const webviewResult = once(ipcMain, 'web-sql-response');
await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = new WebView();
webview.setAttribute('src', '${origin}');
webview.setAttribute('webpreferences', 'enableWebSQL=0,contextIsolation=no');
webview.setAttribute('partition', '${sqlPartition}');
webview.setAttribute('nodeIntegration', 'on');
document.body.appendChild(webview);
webview.addEventListener('dom-ready', () => resolve());
});
`);
const [, childError] = await webviewResult;
expect(childError).to.equal(securityError);
});
it('child webContents cannot override when the embedder has disallowed websql', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
enableWebSQL: false,
webviewTag: true,
session: sqlSession,
contextIsolation: false
}
});
w.webContents.loadURL('data:text/html,<html></html>');
const webviewResult = once(ipcMain, 'web-sql-response');
await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = new WebView();
webview.setAttribute('src', '${origin}');
webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no');
webview.setAttribute('partition', '${sqlPartition}');
webview.setAttribute('nodeIntegration', 'on');
document.body.appendChild(webview);
webview.addEventListener('dom-ready', () => resolve());
});
`);
const [, childError] = await webviewResult;
expect(childError).to.equal(securityError);
});
it('child webContents can use websql when the embedder has allowed websql', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
webviewTag: true,
session: sqlSession,
contextIsolation: false
}
});
w.webContents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.be.null();
const webviewResult = once(ipcMain, 'web-sql-response');
await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = new WebView();
webview.setAttribute('src', '${origin}');
webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no');
webview.setAttribute('partition', '${sqlPartition}');
webview.setAttribute('nodeIntegration', 'on');
document.body.appendChild(webview);
webview.addEventListener('dom-ready', () => resolve());
});
`);
const [, childError] = await webviewResult;
expect(childError).to.be.null();
});
});
describe('DOM storage quota increase', () => {
for (const storageName of ['localStorage', 'sessionStorage']) {
it(`allows saving at least 40MiB in ${storageName}`, async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
// Although JavaScript strings use UTF-16, the underlying
// storage provider may encode strings differently, muddling the
// translation between character and byte counts. However,
// a string of 40 * 2^20 characters will require at least 40MiB
// and presumably no more than 80MiB, a size guaranteed to
// to exceed the original 10MiB quota yet stay within the
// new 100MiB quota.
// Note that both the key name and value affect the total size.
const testKeyName = '_electronDOMStorageQuotaIncreasedTest';
const length = 40 * Math.pow(2, 20) - testKeyName.length;
await w.webContents.executeJavaScript(`
${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length}));
`);
// Wait at least one turn of the event loop to help avoid false positives
// Although not entirely necessary, the previous version of this test case
// failed to detect a real problem (perhaps related to DOM storage data caching)
// wherein calling `getItem` immediately after `setItem` would appear to work
// but then later (e.g. next tick) it would not.
await setTimeout(1);
try {
const storedLength = await w.webContents.executeJavaScript(`${storageName}.getItem(${JSON.stringify(testKeyName)}).length`);
expect(storedLength).to.equal(length);
} finally {
await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`);
}
});
it(`throws when attempting to use more than 128MiB in ${storageName}`, async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
await expect((async () => {
const testKeyName = '_electronDOMStorageQuotaStillEnforcedTest';
const length = 128 * Math.pow(2, 20) - testKeyName.length;
try {
await w.webContents.executeJavaScript(`
${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length}));
`);
} finally {
await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`);
}
})()).to.eventually.be.rejected();
});
}
});
describe('persistent storage', () => {
it('can be requested', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const grantedBytes = await w.webContents.executeJavaScript(`new Promise(resolve => {
navigator.webkitPersistentStorage.requestQuota(1024 * 1024, resolve);
})`);
expect(grantedBytes).to.equal(1048576);
});
});
});
ifdescribe(features.isPDFViewerEnabled())('PDF Viewer', () => {
const pdfSource = url.format({
pathname: path.join(__dirname, 'fixtures', 'cat.pdf').replaceAll('\\', '/'),
protocol: 'file',
slashes: true
});
it('successfully loads a PDF file', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL(pdfSource);
await once(w.webContents, 'did-finish-load');
});
it('opens when loading a pdf resource as top level navigation', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL(pdfSource);
const [, contents] = await once(app, 'web-contents-created') as [any, WebContents];
await once(contents, 'did-navigate');
expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
});
it('opens when loading a pdf resource in a iframe', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'pdf-in-iframe.html'));
const [, contents] = await once(app, 'web-contents-created') as [any, WebContents];
await once(contents, 'did-navigate');
expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
});
});
describe('window.history', () => {
describe('window.history.pushState', () => {
it('should push state after calling history.pushState() from the same url', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
// History should have current page by now.
expect(w.webContents.length()).to.equal(1);
const waitCommit = once(w.webContents, 'navigation-entry-committed');
w.webContents.executeJavaScript('window.history.pushState({}, "")');
await waitCommit;
// Initial page + pushed state.
expect(w.webContents.length()).to.equal(2);
});
});
describe('window.history.back', () => {
it('should not allow sandboxed iframe to modify main frame state', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('data:text/html,<iframe sandbox="allow-scripts"></iframe>');
await Promise.all([
once(w.webContents, 'navigation-entry-committed'),
once(w.webContents, 'did-frame-navigate'),
once(w.webContents, 'did-navigate')
]);
w.webContents.executeJavaScript('window.history.pushState(1, "")');
await Promise.all([
once(w.webContents, 'navigation-entry-committed'),
once(w.webContents, 'did-navigate-in-page')
]);
w.webContents.once('navigation-entry-committed' as any, () => {
expect.fail('Unexpected navigation-entry-committed');
});
w.webContents.once('did-navigate-in-page', () => {
expect.fail('Unexpected did-navigate-in-page');
});
await w.webContents.mainFrame.frames[0].executeJavaScript('window.history.back()');
expect(await w.webContents.executeJavaScript('window.history.state')).to.equal(1);
expect(w.webContents.getActiveIndex()).to.equal(1);
});
});
});
describe('chrome:// pages', () => {
const urls = [
'chrome://accessibility',
'chrome://gpu',
'chrome://media-internals',
'chrome://tracing',
'chrome://webrtc-internals'
];
for (const url of urls) {
describe(url, () => {
it('loads the page successfully', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(url);
const pageExists = await w.webContents.executeJavaScript(
"window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
);
expect(pageExists).to.be.true();
});
});
}
});
describe('document.hasFocus', () => {
it('has correct value when multiple windows are opened', async () => {
const w1 = new BrowserWindow({ show: true });
const w2 = new BrowserWindow({ show: true });
const w3 = new BrowserWindow({ show: false });
await w1.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
await w2.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
await w3.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
expect(webContents.getFocusedWebContents()?.id).to.equal(w2.webContents.id);
let focus = false;
focus = await w1.webContents.executeJavaScript(
'document.hasFocus()'
);
expect(focus).to.be.false();
focus = await w2.webContents.executeJavaScript(
'document.hasFocus()'
);
expect(focus).to.be.true();
focus = await w3.webContents.executeJavaScript(
'document.hasFocus()'
);
expect(focus).to.be.false();
});
});
// https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation
describe('navigator.connection', () => {
it('returns the correct value', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.session.enableNetworkEmulation({
latency: 500,
downloadThroughput: 6400,
uploadThroughput: 6400
});
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const rtt = await w.webContents.executeJavaScript('navigator.connection.rtt');
expect(rtt).to.be.a('number');
const downlink = await w.webContents.executeJavaScript('navigator.connection.downlink');
expect(downlink).to.be.a('number');
const effectiveTypes = ['slow-2g', '2g', '3g', '4g'];
const effectiveType = await w.webContents.executeJavaScript('navigator.connection.effectiveType');
expect(effectiveTypes).to.include(effectiveType);
});
});
describe('navigator.userAgentData', () => {
// These tests are done on an http server because navigator.userAgentData
// requires a secure context.
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('');
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
describe('is not empty', () => {
it('by default', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(serverUrl);
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
it('when there is a session-wide UA override', async () => {
const ses = session.fromPartition(`${Math.random()}`);
ses.setUserAgent('foobar');
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
await w.loadURL(serverUrl);
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
it('when there is a WebContents-specific UA override', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.setUserAgent('foo');
await w.loadURL(serverUrl);
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
it('when there is a WebContents-specific UA override at load time', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(serverUrl, {
userAgent: 'foo'
});
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
});
describe('brand list', () => {
it('contains chromium', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(serverUrl);
const brands = await w.webContents.executeJavaScript('navigator.userAgentData.brands');
expect(brands.map((b: any) => b.brand)).to.include('Chromium');
});
});
});
describe('Badging API', () => {
it('does not crash', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
await w.webContents.executeJavaScript('navigator.setAppBadge(42)');
await w.webContents.executeJavaScript('navigator.setAppBadge()');
await w.webContents.executeJavaScript('navigator.clearAppBadge()');
});
});
describe('navigator.webkitGetUserMedia', () => {
it('calls its callbacks', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
await w.webContents.executeJavaScript(`new Promise((resolve) => {
navigator.webkitGetUserMedia({
audio: true,
video: false
}, () => resolve(),
() => resolve());
})`);
});
});
describe('navigator.language', () => {
it('should not be empty', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(await w.webContents.executeJavaScript('navigator.language')).to.not.equal('');
});
});
describe('heap snapshot', () => {
it('does not crash', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
await w.webContents.executeJavaScript('process._linkedBinding(\'electron_common_v8_util\').takeHeapSnapshot()');
});
});
// This is intentionally disabled on arm macs: https://chromium-review.googlesource.com/c/chromium/src/+/4143761
ifdescribe(process.platform === 'darwin' && process.arch !== 'arm64')('webgl', () => {
it('can be gotten as context in canvas', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const canWebglContextBeCreated = await w.webContents.executeJavaScript(`
document.createElement('canvas').getContext('webgl') != null;
`);
expect(canWebglContextBeCreated).to.be.true();
});
});
describe('iframe', () => {
it('does not have node integration', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const result = await w.webContents.executeJavaScript(`
const iframe = document.createElement('iframe')
iframe.src = './set-global.html';
document.body.appendChild(iframe);
new Promise(resolve => iframe.onload = e => resolve(iframe.contentWindow.test))
`);
expect(result).to.equal('undefined undefined undefined');
});
});
describe('websockets', () => {
it('has user agent', async () => {
const server = http.createServer();
const { port } = await listen(server);
const wss = new ws.Server({ server: server });
const finished = new Promise<string | undefined>((resolve, reject) => {
wss.on('error', reject);
wss.on('connection', (ws, upgradeReq) => {
resolve(upgradeReq.headers['user-agent']);
});
});
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript(`
new WebSocket('ws://127.0.0.1:${port}');
`);
expect(await finished).to.include('Electron');
});
});
describe('fetch', () => {
it('does not crash', async () => {
const server = http.createServer((req, res) => {
res.end('test');
});
defer(() => server.close());
const { port } = await listen(server);
const w = new BrowserWindow({ show: false });
w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const x = await w.webContents.executeJavaScript(`
fetch('http://127.0.0.1:${port}').then((res) => res.body.getReader())
.then((reader) => {
return reader.read().then((r) => {
reader.cancel();
return r.value;
});
})
`);
expect(x).to.deep.equal(new Uint8Array([116, 101, 115, 116]));
});
});
describe('Promise', () => {
before(() => {
ipcMain.handle('ping', (e, arg) => arg);
});
after(() => {
ipcMain.removeHandler('ping');
});
itremote('resolves correctly in Node.js calls', async () => {
await new Promise<void>((resolve, reject) => {
class XElement extends HTMLElement {}
customElements.define('x-element', XElement);
setImmediate(() => {
let called = false;
Promise.resolve().then(() => {
if (called) resolve();
else reject(new Error('wrong sequence'));
});
document.createElement('x-element');
called = true;
});
});
});
itremote('resolves correctly in Electron calls', async () => {
await new Promise<void>((resolve, reject) => {
class YElement extends HTMLElement {}
customElements.define('y-element', YElement);
require('electron').ipcRenderer.invoke('ping').then(() => {
let called = false;
Promise.resolve().then(() => {
if (called) resolve();
else reject(new Error('wrong sequence'));
});
document.createElement('y-element');
called = true;
});
});
});
});
describe('synchronous prompts', () => {
describe('window.alert(message, title)', () => {
itremote('throws an exception when the arguments cannot be converted to strings', () => {
expect(() => {
window.alert({ toString: null });
}).to.throw('Cannot convert object to primitive value');
});
it('shows a message box', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
const p = once(w.webContents, '-run-dialog');
w.webContents.executeJavaScript('alert("hello")', true);
const [info] = await p;
expect(info.frame).to.equal(w.webContents.mainFrame);
expect(info.messageText).to.equal('hello');
expect(info.dialogType).to.equal('alert');
});
it('does not crash if a webContents is destroyed while an alert is showing', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
const p = once(w.webContents, '-run-dialog');
w.webContents.executeJavaScript('alert("hello")', true);
await p;
w.webContents.close();
});
});
describe('window.confirm(message, title)', () => {
itremote('throws an exception when the arguments cannot be converted to strings', () => {
expect(() => {
(window.confirm as any)({ toString: null }, 'title');
}).to.throw('Cannot convert object to primitive value');
});
it('shows a message box', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
const p = once(w.webContents, '-run-dialog');
const resultPromise = w.webContents.executeJavaScript('confirm("hello")', true);
const [info, cb] = await p;
expect(info.frame).to.equal(w.webContents.mainFrame);
expect(info.messageText).to.equal('hello');
expect(info.dialogType).to.equal('confirm');
cb(true, '');
const result = await resultPromise;
expect(result).to.be.true();
});
});
describe('safeDialogs web preference', () => {
const originalShowMessageBox = dialog.showMessageBox;
afterEach(() => {
dialog.showMessageBox = originalShowMessageBox;
if (protocol.isProtocolHandled('https')) protocol.unhandle('https');
if (protocol.isProtocolHandled('file')) protocol.unhandle('file');
});
it('does not show the checkbox if not enabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { safeDialogs: false } });
w.loadURL('about:blank');
// 1. The first alert() doesn't show the safeDialogs message.
dialog.showMessageBox = () => Promise.resolve({ response: 0, checkboxChecked: false });
await w.webContents.executeJavaScript('alert("hi")');
let recordedOpts: MessageBoxOptions | undefined;
dialog.showMessageBox = (bw, opts?: MessageBoxOptions) => {
recordedOpts = opts;
return Promise.resolve({ response: 0, checkboxChecked: false });
};
await w.webContents.executeJavaScript('alert("hi")');
expect(recordedOpts?.checkboxLabel).to.equal('');
});
it('is respected', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { safeDialogs: true } });
w.loadURL('about:blank');
// 1. The first alert() doesn't show the safeDialogs message.
dialog.showMessageBox = () => Promise.resolve({ response: 0, checkboxChecked: false });
await w.webContents.executeJavaScript('alert("hi")');
// 2. The second alert() shows the message with a checkbox. Respond that we checked it.
let recordedOpts: MessageBoxOptions | undefined;
dialog.showMessageBox = (bw, opts?: MessageBoxOptions) => {
recordedOpts = opts;
return Promise.resolve({ response: 0, checkboxChecked: true });
};
await w.webContents.executeJavaScript('alert("hi")');
expect(recordedOpts?.checkboxLabel).to.be.a('string').with.length.above(0);
// 3. The third alert() shouldn't show a dialog.
dialog.showMessageBox = () => Promise.reject(new Error('unexpected showMessageBox'));
await w.webContents.executeJavaScript('alert("hi")');
});
it('shows the safeDialogMessage', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { safeDialogs: true, safeDialogsMessage: 'foo bar' } });
w.loadURL('about:blank');
dialog.showMessageBox = () => Promise.resolve({ response: 0, checkboxChecked: false });
await w.webContents.executeJavaScript('alert("hi")');
let recordedOpts: MessageBoxOptions | undefined;
dialog.showMessageBox = (bw, opts?: MessageBoxOptions) => {
recordedOpts = opts;
return Promise.resolve({ response: 0, checkboxChecked: true });
};
await w.webContents.executeJavaScript('alert("hi")');
expect(recordedOpts?.checkboxLabel).to.equal('foo bar');
});
it('has persistent state across navigations', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { safeDialogs: true } });
w.loadURL('about:blank');
// 1. The first alert() doesn't show the safeDialogs message.
dialog.showMessageBox = () => Promise.resolve({ response: 0, checkboxChecked: false });
await w.webContents.executeJavaScript('alert("hi")');
// 2. The second alert() shows the message with a checkbox. Respond that we checked it.
dialog.showMessageBox = () => Promise.resolve({ response: 0, checkboxChecked: true });
await w.webContents.executeJavaScript('alert("hi")');
// 3. The third alert() shouldn't show a dialog.
dialog.showMessageBox = () => Promise.reject(new Error('unexpected showMessageBox'));
await w.webContents.executeJavaScript('alert("hi")');
// 4. After navigating to the same origin, message boxes should still be hidden.
w.loadURL('about:blank');
await w.webContents.executeJavaScript('alert("hi")');
});
it('is separated by origin', async () => {
protocol.handle('https', () => new Response(''));
const w = new BrowserWindow({ show: false, webPreferences: { safeDialogs: true } });
w.loadURL('https://example1');
dialog.showMessageBox = () => Promise.resolve({ response: 0, checkboxChecked: false });
await w.webContents.executeJavaScript('alert("hi")');
dialog.showMessageBox = () => Promise.resolve({ response: 0, checkboxChecked: true });
await w.webContents.executeJavaScript('alert("hi")');
dialog.showMessageBox = () => Promise.reject(new Error('unexpected showMessageBox'));
await w.webContents.executeJavaScript('alert("hi")');
// A different origin is allowed to show message boxes after navigation.
w.loadURL('https://example2');
let dialogWasShown = false;
dialog.showMessageBox = () => {
dialogWasShown = true;
return Promise.resolve({ response: 0, checkboxChecked: false });
};
await w.webContents.executeJavaScript('alert("hi")');
expect(dialogWasShown).to.be.true();
// Navigating back to the first origin means alerts are blocked again.
w.loadURL('https://example1');
dialog.showMessageBox = () => Promise.reject(new Error('unexpected showMessageBox'));
await w.webContents.executeJavaScript('alert("hi")');
});
it('treats different file: paths as different origins', async () => {
protocol.handle('file', () => new Response(''));
const w = new BrowserWindow({ show: false, webPreferences: { safeDialogs: true } });
w.loadURL('file:///path/1');
dialog.showMessageBox = () => Promise.resolve({ response: 0, checkboxChecked: false });
await w.webContents.executeJavaScript('alert("hi")');
dialog.showMessageBox = () => Promise.resolve({ response: 0, checkboxChecked: true });
await w.webContents.executeJavaScript('alert("hi")');
dialog.showMessageBox = () => Promise.reject(new Error('unexpected showMessageBox'));
await w.webContents.executeJavaScript('alert("hi")');
w.loadURL('file:///path/2');
let dialogWasShown = false;
dialog.showMessageBox = () => {
dialogWasShown = true;
return Promise.resolve({ response: 0, checkboxChecked: false });
};
await w.webContents.executeJavaScript('alert("hi")');
expect(dialogWasShown).to.be.true();
});
});
describe('disableDialogs web preference', () => {
const originalShowMessageBox = dialog.showMessageBox;
afterEach(() => {
dialog.showMessageBox = originalShowMessageBox;
if (protocol.isProtocolHandled('https')) protocol.unhandle('https');
});
it('is respected', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { disableDialogs: true } });
w.loadURL('about:blank');
dialog.showMessageBox = () => Promise.reject(new Error('unexpected message box'));
await w.webContents.executeJavaScript('alert("hi")');
});
});
});
describe('window.history', () => {
describe('window.history.go(offset)', () => {
itremote('throws an exception when the argument cannot be converted to a string', () => {
expect(() => {
(window.history.go as any)({ toString: null });
}).to.throw('Cannot convert object to primitive value');
});
});
});
describe('console functions', () => {
itremote('should exist', () => {
expect(console.log, 'log').to.be.a('function');
expect(console.error, 'error').to.be.a('function');
expect(console.warn, 'warn').to.be.a('function');
expect(console.info, 'info').to.be.a('function');
expect(console.debug, 'debug').to.be.a('function');
expect(console.trace, 'trace').to.be.a('function');
expect(console.time, 'time').to.be.a('function');
expect(console.timeEnd, 'timeEnd').to.be.a('function');
});
});
// FIXME(nornagon): this is broken on CI, it triggers:
// [FATAL:speech_synthesis.mojom-shared.h(237)] The outgoing message will
// trigger VALIDATION_ERROR_UNEXPECTED_NULL_POINTER at the receiving side
// (null text in SpeechSynthesisUtterance struct).
describe('SpeechSynthesis', () => {
itremote('should emit lifecycle events', async () => {
const sentence = `long sentence which will take at least a few seconds to
utter so that it's possible to pause and resume before the end`;
const utter = new SpeechSynthesisUtterance(sentence);
// Create a dummy utterance so that speech synthesis state
// is initialized for later calls.
speechSynthesis.speak(new SpeechSynthesisUtterance());
speechSynthesis.cancel();
speechSynthesis.speak(utter);
// paused state after speak()
expect(speechSynthesis.paused).to.be.false();
await new Promise((resolve) => { utter.onstart = resolve; });
// paused state after start event
expect(speechSynthesis.paused).to.be.false();
speechSynthesis.pause();
// paused state changes async, right before the pause event
expect(speechSynthesis.paused).to.be.false();
await new Promise((resolve) => { utter.onpause = resolve; });
expect(speechSynthesis.paused).to.be.true();
speechSynthesis.resume();
await new Promise((resolve) => { utter.onresume = resolve; });
// paused state after resume event
expect(speechSynthesis.paused).to.be.false();
await new Promise((resolve) => { utter.onend = resolve; });
});
});
});
describe('font fallback', () => {
async function getRenderedFonts (html: string) {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL(`data:text/html,${html}`);
w.webContents.debugger.attach();
const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams);
const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0];
await sendCommand('CSS.enable');
const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId });
return fonts;
} finally {
w.close();
}
}
it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => {
const html = '<body style="font-family: sans-serif">test</body>';
const fonts = await getRenderedFonts(html);
expect(fonts).to.be.an('array');
expect(fonts).to.have.length(1);
if (process.platform === 'win32') {
expect(fonts[0].familyName).to.equal('Arial');
} else if (process.platform === 'darwin') {
expect(fonts[0].familyName).to.equal('Helvetica');
} else if (process.platform === 'linux') {
expect(fonts[0].familyName).to.equal('DejaVu Sans');
} // I think this depends on the distro? We don't specify a default.
});
ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () {
const html = `
<html lang="ja-JP">
<head>
<meta charset="utf-8" />
</head>
<body style="font-family: sans-serif">test 智史</body>
</html>
`;
const fonts = await getRenderedFonts(html);
expect(fonts).to.be.an('array');
expect(fonts).to.have.length(1);
if (process.platform === 'win32') { expect(fonts[0].familyName).to.be.oneOf(['Meiryo', 'Yu Gothic']); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Hiragino Kaku Gothic ProN'); }
});
});
describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => {
const fullscreenChildHtml = fs.promises.readFile(
path.join(fixturesPath, 'pages', 'fullscreen-oopif.html')
);
let w: BrowserWindow;
let server: http.Server;
let crossSiteUrl: string;
beforeEach(async () => {
server = http.createServer(async (_req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(await fullscreenChildHtml);
res.end();
});
const serverUrl = (await listen(server)).url;
crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
w = new BrowserWindow({
show: true,
fullscreen: true,
webPreferences: {
nodeIntegration: true,
nodeIntegrationInSubFrames: true,
contextIsolation: false
}
});
});
afterEach(async () => {
await closeAllWindows();
(w as any) = null;
server.close();
});
ifit(process.platform !== 'darwin')('can fullscreen from out-of-process iframes (non-macOS)', async () => {
const fullscreenChange = once(ipcMain, 'fullscreenChange');
const html =
`<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`;
w.loadURL(`data:text/html,${html}`);
await fullscreenChange;
const fullscreenWidth = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(fullscreenWidth > 0).to.be.true();
await w.webContents.executeJavaScript(
"document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
);
await setTimeout(500);
const width = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(width).to.equal(0);
});
ifit(process.platform === 'darwin')('can fullscreen from out-of-process iframes (macOS)', async () => {
await once(w, 'enter-full-screen');
const fullscreenChange = once(ipcMain, 'fullscreenChange');
const html =
`<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`;
w.loadURL(`data:text/html,${html}`);
await fullscreenChange;
const fullscreenWidth = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(fullscreenWidth > 0).to.be.true();
await w.webContents.executeJavaScript(
"document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
);
await once(w.webContents, 'leave-html-full-screen');
const width = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(width).to.equal(0);
w.setFullScreen(false);
await once(w, 'leave-full-screen');
});
// TODO(jkleinsc) fix this flaky test on WOA
ifit(process.platform !== 'win32' || process.arch !== 'arm64')('can fullscreen from in-process iframes', async () => {
if (process.platform === 'darwin') await once(w, 'enter-full-screen');
const fullscreenChange = once(ipcMain, 'fullscreenChange');
w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html'));
await fullscreenChange;
const fullscreenWidth = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(fullscreenWidth > 0).to.true();
await w.webContents.executeJavaScript('document.exitFullscreen()');
const width = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(width).to.equal(0);
});
});
describe('navigator.serial', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
const getPorts: any = () => {
return w.webContents.executeJavaScript(`
navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString());
`, true);
};
const notFoundError = 'NotFoundError: Failed to execute \'requestPort\' on \'Serial\': No port selected by the user.';
after(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.removeAllListeners('select-serial-port');
});
it('does not return a port if select-serial-port event is not defined', async () => {
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const port = await getPorts();
expect(port).to.equal(notFoundError);
});
it('does not return a port when permission denied', async () => {
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
callback(portList[0].portId);
});
session.defaultSession.setPermissionCheckHandler(() => false);
const port = await getPorts();
expect(port).to.equal(notFoundError);
});
it('does not crash when select-serial-port is called with an invalid port', async () => {
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
callback('i-do-not-exist');
});
const port = await getPorts();
expect(port).to.equal(notFoundError);
});
it('returns a port when select-serial-port event is defined', async () => {
let havePorts = false;
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
if (portList.length > 0) {
havePorts = true;
callback(portList[0].portId);
} else {
callback('');
}
});
const port = await getPorts();
if (havePorts) {
expect(port).to.equal('[object SerialPort]');
} else {
expect(port).to.equal(notFoundError);
}
});
it('navigator.serial.getPorts() returns values', async () => {
let havePorts = false;
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
if (portList.length > 0) {
havePorts = true;
callback(portList[0].portId);
} else {
callback('');
}
});
await getPorts();
if (havePorts) {
const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
expect(grantedPorts).to.not.be.empty();
}
});
it('supports port.forget()', async () => {
let forgottenPortFromEvent = {};
let havePorts = false;
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
if (portList.length > 0) {
havePorts = true;
callback(portList[0].portId);
} else {
callback('');
}
});
w.webContents.session.on('serial-port-revoked', (event, details) => {
forgottenPortFromEvent = details.port;
});
await getPorts();
if (havePorts) {
const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
if (grantedPorts.length > 0) {
const forgottenPort = await w.webContents.executeJavaScript(`
navigator.serial.getPorts().then(async(ports) => {
const portInfo = await ports[0].getInfo();
await ports[0].forget();
if (portInfo.usbVendorId && portInfo.usbProductId) {
return {
vendorId: '' + portInfo.usbVendorId,
productId: '' + portInfo.usbProductId
}
} else {
return {};
}
})
`);
const grantedPorts2 = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
expect(grantedPorts2.length).to.be.lessThan(grantedPorts.length);
if (forgottenPort.vendorId && forgottenPort.productId) {
expect(forgottenPortFromEvent).to.include(forgottenPort);
}
}
}
});
});
describe('window.getScreenDetails', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
after(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionRequestHandler(null);
});
const getScreenDetails: any = () => {
return w.webContents.executeJavaScript('window.getScreenDetails().then(data => data.screens).catch(err => err.message)', true);
};
it('returns screens when a PermissionRequestHandler is not defined', async () => {
const screens = await getScreenDetails();
expect(screens).to.not.equal('Read permission denied.');
});
it('returns an error when permission denied', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'window-management') {
callback(false);
} else {
callback(true);
}
});
const screens = await getScreenDetails();
expect(screens).to.equal('Permission denied.');
});
it('returns screens when permission is granted', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'window-management') {
callback(true);
} else {
callback(false);
}
});
const screens = await getScreenDetails();
expect(screens).to.not.equal('Permission denied.');
});
});
describe('navigator.clipboard.read', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow();
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
const readClipboard: any = () => {
return w.webContents.executeJavaScript(`
navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message);
`, true);
};
after(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionRequestHandler(null);
});
it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => {
const clipboard = await readClipboard();
expect(clipboard).to.not.contain('Read permission denied.');
});
it('returns an error when permission denied', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'clipboard-read') {
callback(false);
} else {
callback(true);
}
});
const clipboard = await readClipboard();
expect(clipboard).to.contain('Read permission denied.');
});
it('returns clipboard contents when permission is granted', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'clipboard-read') {
callback(true);
} else {
callback(false);
}
});
const clipboard = await readClipboard();
expect(clipboard).to.not.contain('Read permission denied.');
});
});
describe('navigator.clipboard.write', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow();
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
const writeClipboard: any = () => {
return w.webContents.executeJavaScript(`
navigator.clipboard.writeText('Hello World!').catch(err => err.message);
`, true);
};
after(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionRequestHandler(null);
});
it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => {
const clipboard = await writeClipboard();
expect(clipboard).to.be.undefined();
});
it('returns an error when permission denied', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'clipboard-sanitized-write') {
callback(false);
} else {
callback(true);
}
});
const clipboard = await writeClipboard();
expect(clipboard).to.contain('Write permission denied.');
});
it('returns clipboard contents when permission is granted', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'clipboard-sanitized-write') {
callback(true);
} else {
callback(false);
}
});
const clipboard = await writeClipboard();
expect(clipboard).to.be.undefined();
});
});
ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => {
let w: BrowserWindow;
const expectedBadgeCount = 42;
const fireAppBadgeAction: any = (action: string, value: any) => {
return w.webContents.executeJavaScript(`
navigator.${action}AppBadge(${value}).then(() => 'success').catch(err => err.message)`);
};
// For some reason on macOS changing the badge count doesn't happen right away, so wait
// until it changes.
async function waitForBadgeCount (value: number) {
let badgeCount = app.getBadgeCount();
while (badgeCount !== value) {
await setTimeout(10);
badgeCount = app.getBadgeCount();
}
return badgeCount;
}
describe('in the renderer', () => {
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
after(() => {
app.badgeCount = 0;
closeAllWindows();
});
it('setAppBadge can set a numerical value', async () => {
const result = await fireAppBadgeAction('set', expectedBadgeCount);
expect(result).to.equal('success');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
});
it('setAppBadge can set an empty(dot) value', async () => {
const result = await fireAppBadgeAction('set');
expect(result).to.equal('success');
expect(waitForBadgeCount(0)).to.eventually.equal(0);
});
it('clearAppBadge can clear a value', async () => {
let result = await fireAppBadgeAction('set', expectedBadgeCount);
expect(result).to.equal('success');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
result = await fireAppBadgeAction('clear');
expect(result).to.equal('success');
expect(waitForBadgeCount(0)).to.eventually.equal(0);
});
});
describe('in a service worker', () => {
beforeEach(async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'sw-file-scheme-spec',
contextIsolation: false
}
});
});
afterEach(() => {
app.badgeCount = 0;
closeAllWindows();
});
it('setAppBadge can be called in a ServiceWorker', (done) => {
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(message);
} else if (channel === 'response') {
expect(message).to.equal('SUCCESS setting app badge');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
session.fromPartition('sw-file-scheme-spec').clearStorageData({
storages: ['serviceworkers']
}).then(() => done());
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?setBadge' });
});
it('clearAppBadge can be called in a ServiceWorker', (done) => {
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'setAppBadge') {
expect(message).to.equal('SUCCESS setting app badge');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
} else if (channel === 'error') {
done(message);
} else if (channel === 'response') {
expect(message).to.equal('SUCCESS clearing app badge');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
session.fromPartition('sw-file-scheme-spec').clearStorageData({
storages: ['serviceworkers']
}).then(() => done());
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?clearBadge' });
});
});
});
describe('navigator.bluetooth', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
enableBlinkFeatures: 'WebBluetooth'
}
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
after(closeAllWindows);
it('can request bluetooth devices', async () => {
const bluetooth = await w.webContents.executeJavaScript(`
navigator.bluetooth.requestDevice({ acceptAllDevices: true}).then(device => "Found a device!").catch(err => err.message);`, true);
expect(bluetooth).to.be.oneOf(['Found a device!', 'Bluetooth adapter not available.', 'User cancelled the requestDevice() chooser.']);
});
});
describe('navigator.hid', () => {
let w: BrowserWindow;
let server: http.Server;
let serverUrl: string;
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('<body>');
});
serverUrl = (await listen(server)).url;
});
const requestDevices: any = () => {
return w.webContents.executeJavaScript(`
navigator.hid.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString());
`, true);
};
after(() => {
server.close();
closeAllWindows();
});
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.setDevicePermissionHandler(null);
session.defaultSession.removeAllListeners('select-hid-device');
});
it('does not return a device if select-hid-device event is not defined', async () => {
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const device = await requestDevices();
expect(device).to.equal('');
});
it('does not return a device when permission denied', async () => {
let selectFired = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
selectFired = true;
callback();
});
session.defaultSession.setPermissionCheckHandler(() => false);
const device = await requestDevices();
expect(selectFired).to.be.false();
expect(device).to.equal('');
});
it('returns a device when select-hid-device event is defined', async () => {
let haveDevices = false;
let selectFired = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number');
selectFired = true;
if (details.deviceList.length > 0) {
haveDevices = true;
callback(details.deviceList[0].deviceId);
} else {
callback();
}
});
const device = await requestDevices();
expect(selectFired).to.be.true();
if (haveDevices) {
expect(device).to.contain('[object HIDDevice]');
} else {
expect(device).to.equal('');
}
if (haveDevices) {
// Verify that navigation will clear device permissions
const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
expect(grantedDevices).to.not.be.empty();
w.loadURL(serverUrl);
const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate');
const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
expect(!!frame).to.be.true();
if (frame) {
const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.hid.getDevices()');
expect(grantedDevicesOnNewPage).to.be.empty();
}
}
});
it('returns a device when DevicePermissionHandler is defined', async () => {
let haveDevices = false;
let selectFired = false;
let gotDevicePerms = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
selectFired = true;
if (details.deviceList.length > 0) {
const foundDevice = details.deviceList.find((device) => {
if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') {
haveDevices = true;
return true;
}
});
if (foundDevice) {
callback(foundDevice.deviceId);
return;
}
}
callback();
});
session.defaultSession.setDevicePermissionHandler(() => {
gotDevicePerms = true;
return true;
});
await w.webContents.executeJavaScript('navigator.hid.getDevices();', true);
const device = await requestDevices();
expect(selectFired).to.be.true();
if (haveDevices) {
expect(device).to.contain('[object HIDDevice]');
expect(gotDevicePerms).to.be.true();
} else {
expect(device).to.equal('');
}
});
it('excludes a device when a exclusionFilter is specified', async () => {
const exclusionFilters = <any>[];
let haveDevices = false;
let checkForExcludedDevice = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
if (details.deviceList.length > 0) {
details.deviceList.find((device) => {
if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') {
if (checkForExcludedDevice) {
const compareDevice = {
vendorId: device.vendorId,
productId: device.productId
};
expect(compareDevice).to.not.equal(exclusionFilters[0], 'excluded device should not be returned');
} else {
haveDevices = true;
exclusionFilters.push({
vendorId: device.vendorId,
productId: device.productId
});
return true;
}
}
});
}
callback();
});
await requestDevices();
if (haveDevices) {
// We have devices to exclude, so check if exclusionFilters work
checkForExcludedDevice = true;
await w.webContents.executeJavaScript(`
navigator.hid.requestDevice({filters: [], exclusionFilters: ${JSON.stringify(exclusionFilters)}}).then(device => device.toString()).catch(err => err.toString());
`, true);
}
});
it('supports device.forget()', async () => {
let deletedDeviceFromEvent;
let haveDevices = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
if (details.deviceList.length > 0) {
haveDevices = true;
callback(details.deviceList[0].deviceId);
} else {
callback();
}
});
w.webContents.session.on('hid-device-revoked', (event, details) => {
deletedDeviceFromEvent = details.device;
});
await requestDevices();
if (haveDevices) {
const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
if (grantedDevices.length > 0) {
const deletedDevice = await w.webContents.executeJavaScript(`
navigator.hid.getDevices().then(devices => {
devices[0].forget();
return {
vendorId: devices[0].vendorId,
productId: devices[0].productId,
name: devices[0].productName
}
})
`);
const grantedDevices2 = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length);
if (deletedDevice.name !== '' && deletedDevice.productId && deletedDevice.vendorId) {
expect(deletedDeviceFromEvent).to.include(deletedDevice);
}
}
}
});
});
describe('navigator.usb', () => {
let w: BrowserWindow;
let server: http.Server;
let serverUrl: string;
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('<body>');
});
serverUrl = (await listen(server)).url;
});
const requestDevices: any = () => {
return w.webContents.executeJavaScript(`
navigator.usb.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString());
`, true);
};
const notFoundError = 'NotFoundError: Failed to execute \'requestDevice\' on \'USB\': No device selected.';
after(() => {
server.close();
closeAllWindows();
});
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.setDevicePermissionHandler(null);
session.defaultSession.removeAllListeners('select-usb-device');
});
it('does not return a device if select-usb-device event is not defined', async () => {
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const device = await requestDevices();
expect(device).to.equal(notFoundError);
});
it('does not return a device when permission denied', async () => {
let selectFired = false;
w.webContents.session.on('select-usb-device', (event, details, callback) => {
selectFired = true;
callback();
});
session.defaultSession.setPermissionCheckHandler(() => false);
const device = await requestDevices();
expect(selectFired).to.be.false();
expect(device).to.equal(notFoundError);
});
it('returns a device when select-usb-device event is defined', async () => {
let haveDevices = false;
let selectFired = false;
w.webContents.session.on('select-usb-device', (event, details, callback) => {
expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number');
selectFired = true;
if (details.deviceList.length > 0) {
haveDevices = true;
callback(details.deviceList[0].deviceId);
} else {
callback();
}
});
const device = await requestDevices();
expect(selectFired).to.be.true();
if (haveDevices) {
expect(device).to.contain('[object USBDevice]');
} else {
expect(device).to.equal(notFoundError);
}
if (haveDevices) {
// Verify that navigation will clear device permissions
const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
expect(grantedDevices).to.not.be.empty();
w.loadURL(serverUrl);
const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate');
const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
expect(!!frame).to.be.true();
if (frame) {
const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.usb.getDevices()');
expect(grantedDevicesOnNewPage).to.be.empty();
}
}
});
it('returns a device when DevicePermissionHandler is defined', async () => {
let haveDevices = false;
let selectFired = false;
let gotDevicePerms = false;
w.webContents.session.on('select-usb-device', (event, details, callback) => {
selectFired = true;
if (details.deviceList.length > 0) {
const foundDevice = details.deviceList.find((device) => {
if (device.productName && device.productName !== '' && device.serialNumber && device.serialNumber !== '') {
haveDevices = true;
return true;
}
});
if (foundDevice) {
callback(foundDevice.deviceId);
return;
}
}
callback();
});
session.defaultSession.setDevicePermissionHandler(() => {
gotDevicePerms = true;
return true;
});
await w.webContents.executeJavaScript('navigator.usb.getDevices();', true);
const device = await requestDevices();
expect(selectFired).to.be.true();
if (haveDevices) {
expect(device).to.contain('[object USBDevice]');
expect(gotDevicePerms).to.be.true();
} else {
expect(device).to.equal(notFoundError);
}
});
it('supports device.forget()', async () => {
let deletedDeviceFromEvent;
let haveDevices = false;
w.webContents.session.on('select-usb-device', (event, details, callback) => {
if (details.deviceList.length > 0) {
haveDevices = true;
callback(details.deviceList[0].deviceId);
} else {
callback();
}
});
w.webContents.session.on('usb-device-revoked', (event, details) => {
deletedDeviceFromEvent = details.device;
});
await requestDevices();
if (haveDevices) {
const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
if (grantedDevices.length > 0) {
const deletedDevice: Electron.USBDevice = await w.webContents.executeJavaScript(`
navigator.usb.getDevices().then(devices => {
devices[0].forget();
return {
vendorId: devices[0].vendorId,
productId: devices[0].productId,
productName: devices[0].productName
}
})
`);
const grantedDevices2 = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length);
if (deletedDevice.productName !== '' && deletedDevice.productId && deletedDevice.vendorId) {
expect(deletedDeviceFromEvent).to.include(deletedDevice);
}
}
}
});
});
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,222 |
win_snmp not working ?
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
<!--- Explain the problem briefly below -->
win_snmp module doesnt set / add community strings or managers. playbook results always shows the current configuration but no changes
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
win_snmp
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.8.1
config file = /root/myplatform/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /root/.local/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.5 (default, Apr 9 2019, 14:30:50) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
Windows server 2016 standard edition
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
simple playbook based on documentation sample. tested with kerberos and ntlm method, also with become:
<!--- Paste example playbooks or commands between quotes below -->
```yaml
---
- name: SNMP test
hosts: testhost
gather_facts: no
vars:
ansible_user: AD username
ansible_password: AD password
ansible_connection: winrm
ansible_winrm_transport: ntlm
ansible_winrm_server_cert_validation: ignore
snmp_community_ro:
- private
snmp_managers:
- localhost
- 10.10.10.10
tasks:
- name: Replace SNMP communities
win_snmp:
communities: "{{ snmp_community_ro}}"
managers: "{{ snmp_managers }}"
action: set
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
expected to get SNMP settings changed
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
playbook result only shows the current SNMP settings - no changes are applied
<!--- Paste verbatim command output between quotes -->
```paste below
PLAY [SNMP test] ***************************************************************
TASK [Replace SNMP communities] ************************************************
ok: [testhost] => {"changed": false, "community_strings": [], "permitted_managers": ["localhost"]}
PLAY RECAP *********************************************************************
testhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
```
|
https://github.com/ansible/ansible/issues/58222
|
https://github.com/ansible/ansible/pull/58261
|
75ca8eb42f49e2814fbe80cb429690537122ef65
|
372b896ed1a43ad94c4f7c81bbe17d4cd7b3a671
| 2019-06-22T02:16:23Z |
python
| 2019-06-24T07:00:18Z |
lib/ansible/modules/windows/win_snmp.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Ansible, inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: win_snmp
version_added: '2.8'
short_description: Configures the Windows SNMP service
description:
- This module configures the Windows SNMP service.
options:
permitted_managers:
description:
- The list of permitted SNMP managers.
type: list
community_strings:
description:
- The list of read-only SNMP community strings.
type: list
action:
description:
- C(add) will add new SNMP community strings and/or SNMP managers
- C(set) will replace SNMP community strings and/or SNMP managers. An
empty list for either C(community_strings) or C(permitted_managers)
will result in the respective lists being removed entirely.
- C(remove) will remove SNMP community strings and/or SNMP managers
type: str
choices: [ add, set, remove ]
default: set
author:
- Michael Cassaniti (@mcassaniti)
'''
EXAMPLES = r'''
---
- hosts: Windows
tasks:
- name: Replace SNMP communities and managers
win_snmp:
communities:
- public
managers:
- 192.168.1.2
action: set
- hosts: Windows
tasks:
- name: Replace SNMP communities and clear managers
win_snmp:
communities:
- public
managers: []
action: set
'''
RETURN = r'''
community_strings:
description: The list of community strings for this machine.
type: list
returned: always
sample:
- public
- snmp-ro
permitted_managers:
description: The list of permitted managers for this machine.
type: list
returned: always
sample:
- 192.168.1.1
- 192.168.1.2
'''
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,158 |
BUG in sysctl module: local variable 'err' referenced before assignment
|
##### SUMMARY
```
master:/usr/local/lib/python2.7/site-packages/ansible/modules/system/sysctl.py", line 297, in reload_sysctl
UnboundLocalError: local variable 'err' referenced before assignment
```
- Bug exists in Ansible 2.7.11 and the latest git repo
- Related source file: https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/system/sysctl.py#L278
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
- sysctl
##### ANSIBLE VERSION
```paste below
$ ansible --version
ansible 2.7.11
config file = /Users/zhb/projects/pro/ansible.cfg
configured module search path = [u'/Users/zhb/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python2.7/site-packages/ansible
executable location = /usr/local/bin/ansible
python version = 2.7.16 (default, May 24 2019, 09:49:36) [GCC 4.2.1 Compatible Apple LLVM 10.0.1 (clang-1001.0.46.4)]
```
##### OS / ENVIRONMENT
- Host OS: macOS 10.14.5
- Target OS: OpenBSD 6.5 (amd64)
|
https://github.com/ansible/ansible/issues/58158
|
https://github.com/ansible/ansible/pull/58161
|
a09aa205e12ddcd6ca979c52ab719197f87d269d
|
9069a681aabdef45aa201bf39577405070d63af6
| 2019-06-21T06:23:22Z |
python
| 2019-06-25T15:13:34Z |
changelogs/fragments/58158-sysctl-fix-referenced-before-assignment.yaml
| |
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,158 |
BUG in sysctl module: local variable 'err' referenced before assignment
|
##### SUMMARY
```
master:/usr/local/lib/python2.7/site-packages/ansible/modules/system/sysctl.py", line 297, in reload_sysctl
UnboundLocalError: local variable 'err' referenced before assignment
```
- Bug exists in Ansible 2.7.11 and the latest git repo
- Related source file: https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/system/sysctl.py#L278
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
- sysctl
##### ANSIBLE VERSION
```paste below
$ ansible --version
ansible 2.7.11
config file = /Users/zhb/projects/pro/ansible.cfg
configured module search path = [u'/Users/zhb/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python2.7/site-packages/ansible
executable location = /usr/local/bin/ansible
python version = 2.7.16 (default, May 24 2019, 09:49:36) [GCC 4.2.1 Compatible Apple LLVM 10.0.1 (clang-1001.0.46.4)]
```
##### OS / ENVIRONMENT
- Host OS: macOS 10.14.5
- Target OS: OpenBSD 6.5 (amd64)
|
https://github.com/ansible/ansible/issues/58158
|
https://github.com/ansible/ansible/pull/58161
|
a09aa205e12ddcd6ca979c52ab719197f87d269d
|
9069a681aabdef45aa201bf39577405070d63af6
| 2019-06-21T06:23:22Z |
python
| 2019-06-25T15:13:34Z |
lib/ansible/modules/system/sysctl.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2012, David "DaviXX" CHANIAL <[email protected]>
# (c) 2014, James Tanner <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
DOCUMENTATION = '''
---
module: sysctl
short_description: Manage entries in sysctl.conf.
description:
- This module manipulates sysctl entries and optionally performs a C(/sbin/sysctl -p) after changing them.
version_added: "1.0"
options:
name:
description:
- The dot-separated path (aka I(key)) specifying the sysctl variable.
required: true
aliases: [ 'key' ]
value:
description:
- Desired value of the sysctl key.
aliases: [ 'val' ]
state:
description:
- Whether the entry should be present or absent in the sysctl file.
choices: [ "present", "absent" ]
default: present
ignoreerrors:
description:
- Use this option to ignore errors about unknown keys.
type: bool
default: 'no'
reload:
description:
- If C(yes), performs a I(/sbin/sysctl -p) if the C(sysctl_file) is
updated. If C(no), does not reload I(sysctl) even if the
C(sysctl_file) is updated.
type: bool
default: 'yes'
sysctl_file:
description:
- Specifies the absolute path to C(sysctl.conf), if not C(/etc/sysctl.conf).
default: /etc/sysctl.conf
sysctl_set:
description:
- Verify token value with the sysctl command and set with -w if necessary
type: bool
default: 'no'
version_added: 1.5
author: "David CHANIAL (@davixx) <[email protected]>"
'''
EXAMPLES = '''
# Set vm.swappiness to 5 in /etc/sysctl.conf
- sysctl:
name: vm.swappiness
value: '5'
state: present
# Remove kernel.panic entry from /etc/sysctl.conf
- sysctl:
name: kernel.panic
state: absent
sysctl_file: /etc/sysctl.conf
# Set kernel.panic to 3 in /tmp/test_sysctl.conf
- sysctl:
name: kernel.panic
value: '3'
sysctl_file: /tmp/test_sysctl.conf
reload: no
# Set ip forwarding on in /proc and verify token value with the sysctl command
- sysctl:
name: net.ipv4.ip_forward
value: '1'
sysctl_set: yes
# Set ip forwarding on in /proc and in the sysctl file and reload if necessary
- sysctl:
name: net.ipv4.ip_forward
value: '1'
sysctl_set: yes
state: present
reload: yes
'''
# ==============================================================
import os
import re
import tempfile
from ansible.module_utils.basic import get_platform, AnsibleModule
from ansible.module_utils.six import string_types
from ansible.module_utils.parsing.convert_bool import BOOLEANS_FALSE, BOOLEANS_TRUE
from ansible.module_utils._text import to_native
class SysctlModule(object):
# We have to use LANG=C because we are capturing STDERR of sysctl to detect
# success or failure.
LANG_ENV = {'LANG': 'C', 'LC_ALL': 'C', 'LC_MESSAGES': 'C'}
def __init__(self, module):
self.module = module
self.args = self.module.params
self.sysctl_cmd = self.module.get_bin_path('sysctl', required=True)
self.sysctl_file = self.args['sysctl_file']
self.proc_value = None # current token value in proc fs
self.file_value = None # current token value in file
self.file_lines = [] # all lines in the file
self.file_values = {} # dict of token values
self.changed = False # will change occur
self.set_proc = False # does sysctl need to set value
self.write_file = False # does the sysctl file need to be reloaded
self.process()
# ==============================================================
# LOGIC
# ==============================================================
def process(self):
self.platform = get_platform().lower()
# Whitespace is bad
self.args['name'] = self.args['name'].strip()
self.args['value'] = self._parse_value(self.args['value'])
thisname = self.args['name']
# get the current proc fs value
self.proc_value = self.get_token_curr_value(thisname)
# get the currect sysctl file value
self.read_sysctl_file()
if thisname not in self.file_values:
self.file_values[thisname] = None
# update file contents with desired token/value
self.fix_lines()
# what do we need to do now?
if self.file_values[thisname] is None and self.args['state'] == "present":
self.changed = True
self.write_file = True
elif self.file_values[thisname] is None and self.args['state'] == "absent":
self.changed = False
elif self.file_values[thisname] and self.args['state'] == "absent":
self.changed = True
self.write_file = True
elif self.file_values[thisname] != self.args['value']:
self.changed = True
self.write_file = True
# use the sysctl command or not?
if self.args['sysctl_set']:
if self.proc_value is None:
self.changed = True
elif not self._values_is_equal(self.proc_value, self.args['value']):
self.changed = True
self.set_proc = True
# Do the work
if not self.module.check_mode:
if self.write_file:
self.write_sysctl()
if self.write_file and self.args['reload']:
self.reload_sysctl()
if self.set_proc:
self.set_token_value(self.args['name'], self.args['value'])
def _values_is_equal(self, a, b):
"""Expects two string values. It will split the string by whitespace
and compare each value. It will return True if both lists are the same,
contain the same elements and the same order."""
if a is None or b is None:
return False
a = a.split()
b = b.split()
if len(a) != len(b):
return False
return len([i for i, j in zip(a, b) if i == j]) == len(a)
def _parse_value(self, value):
if value is None:
return ''
elif isinstance(value, bool):
if value:
return '1'
else:
return '0'
elif isinstance(value, string_types):
if value.lower() in BOOLEANS_TRUE:
return '1'
elif value.lower() in BOOLEANS_FALSE:
return '0'
else:
return value.strip()
else:
return value
def _stderr_failed(self, err):
# sysctl can fail to set a value even if it returns an exit status 0
# (https://bugzilla.redhat.com/show_bug.cgi?id=1264080). That's why we
# also have to check stderr for errors. For now we will only fail on
# specific errors defined by the regex below.
errors_regex = r'^sysctl: setting key "[^"]+": (Invalid argument|Read-only file system)$'
return re.search(errors_regex, err, re.MULTILINE) is not None
# ==============================================================
# SYSCTL COMMAND MANAGEMENT
# ==============================================================
# Use the sysctl command to find the current value
def get_token_curr_value(self, token):
if self.platform == 'openbsd':
# openbsd doesn't support -e, just drop it
thiscmd = "%s -n %s" % (self.sysctl_cmd, token)
else:
thiscmd = "%s -e -n %s" % (self.sysctl_cmd, token)
rc, out, err = self.module.run_command(thiscmd, environ_update=self.LANG_ENV)
if rc != 0:
return None
else:
return out
# Use the sysctl command to set the current value
def set_token_value(self, token, value):
if len(value.split()) > 0:
value = '"' + value + '"'
if self.platform == 'openbsd':
# openbsd doesn't accept -w, but since it's not needed, just drop it
thiscmd = "%s %s=%s" % (self.sysctl_cmd, token, value)
elif self.platform == 'freebsd':
ignore_missing = ''
if self.args['ignoreerrors']:
ignore_missing = '-i'
# freebsd doesn't accept -w, but since it's not needed, just drop it
thiscmd = "%s %s %s=%s" % (self.sysctl_cmd, ignore_missing, token, value)
else:
ignore_missing = ''
if self.args['ignoreerrors']:
ignore_missing = '-e'
thiscmd = "%s %s -w %s=%s" % (self.sysctl_cmd, ignore_missing, token, value)
rc, out, err = self.module.run_command(thiscmd, environ_update=self.LANG_ENV)
if rc != 0 or self._stderr_failed(err):
self.module.fail_json(msg='setting %s failed: %s' % (token, out + err))
else:
return rc
# Run sysctl -p
def reload_sysctl(self):
# do it
if self.platform == 'freebsd':
# freebsd doesn't support -p, so reload the sysctl service
rc, out, err = self.module.run_command('/etc/rc.d/sysctl reload', environ_update=self.LANG_ENV)
elif self.platform == 'openbsd':
# openbsd doesn't support -p and doesn't have a sysctl service,
# so we have to set every value with its own sysctl call
for k, v in self.file_values.items():
rc = 0
if k != self.args['name']:
rc = self.set_token_value(k, v)
if rc != 0:
break
if rc == 0 and self.args['state'] == "present":
rc = self.set_token_value(self.args['name'], self.args['value'])
else:
# system supports reloading via the -p flag to sysctl, so we'll use that
sysctl_args = [self.sysctl_cmd, '-p', self.sysctl_file]
if self.args['ignoreerrors']:
sysctl_args.insert(1, '-e')
rc, out, err = self.module.run_command(sysctl_args, environ_update=self.LANG_ENV)
if rc != 0 or self._stderr_failed(err):
self.module.fail_json(msg="Failed to reload sysctl: %s" % to_native(out) + to_native(err))
# ==============================================================
# SYSCTL FILE MANAGEMENT
# ==============================================================
# Get the token value from the sysctl file
def read_sysctl_file(self):
lines = []
if os.path.isfile(self.sysctl_file):
try:
with open(self.sysctl_file, "r") as read_file:
lines = read_file.readlines()
except IOError as e:
self.module.fail_json(msg="Failed to open %s: %s" % (to_native(self.sysctl_file), to_native(e)))
for line in lines:
line = line.strip()
self.file_lines.append(line)
# don't split empty lines or comments or line without equal sign
if not line or line.startswith(("#", ";")) or "=" not in line:
continue
k, v = line.split('=', 1)
k = k.strip()
v = v.strip()
self.file_values[k] = v.strip()
# Fix the value in the sysctl file content
def fix_lines(self):
checked = []
self.fixed_lines = []
for line in self.file_lines:
if not line.strip() or line.strip().startswith(("#", ";")) or "=" not in line:
self.fixed_lines.append(line)
continue
tmpline = line.strip()
k, v = tmpline.split('=', 1)
k = k.strip()
v = v.strip()
if k not in checked:
checked.append(k)
if k == self.args['name']:
if self.args['state'] == "present":
new_line = "%s=%s\n" % (k, self.args['value'])
self.fixed_lines.append(new_line)
else:
new_line = "%s=%s\n" % (k, v)
self.fixed_lines.append(new_line)
if self.args['name'] not in checked and self.args['state'] == "present":
new_line = "%s=%s\n" % (self.args['name'], self.args['value'])
self.fixed_lines.append(new_line)
# Completely rewrite the sysctl file
def write_sysctl(self):
# open a tmp file
fd, tmp_path = tempfile.mkstemp('.conf', '.ansible_m_sysctl_', os.path.dirname(self.sysctl_file))
f = open(tmp_path, "w")
try:
for l in self.fixed_lines:
f.write(l.strip() + "\n")
except IOError as e:
self.module.fail_json(msg="Failed to write to file %s: %s" % (tmp_path, to_native(e)))
f.flush()
f.close()
# replace the real one
self.module.atomic_move(tmp_path, self.sysctl_file)
# ==============================================================
# main
def main():
# defining module
module = AnsibleModule(
argument_spec=dict(
name=dict(aliases=['key'], required=True),
value=dict(aliases=['val'], required=False, type='str'),
state=dict(default='present', choices=['present', 'absent']),
reload=dict(default=True, type='bool'),
sysctl_set=dict(default=False, type='bool'),
ignoreerrors=dict(default=False, type='bool'),
sysctl_file=dict(default='/etc/sysctl.conf', type='path')
),
supports_check_mode=True,
required_if=[('state', 'present', ['value'])],
)
if module.params['name'] is None:
module.fail_json(msg="name cannot be None")
if module.params['state'] == 'present' and module.params['value'] is None:
module.fail_json(msg="value cannot be None")
# In case of in-line params
if module.params['name'] == '':
module.fail_json(msg="name cannot be blank")
if module.params['state'] == 'present' and module.params['value'] == '':
module.fail_json(msg="value cannot be blank")
result = SysctlModule(module)
module.exit_json(changed=result.changed)
if __name__ == '__main__':
main()
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,310 |
setup module became excessively verbose in 2.8, but only if used implicitly
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
implicit fact gathering (`gather_facts: true`) has started dumping the entire setup output with just a single `-v`, which is new with 2.8.0 and still present in 2.8.1 (not present in 2.7.11). this does *not* happen with `-v` if `gather_facts: false` and `setup` task is run manually in the play.
please restore the many-years-old, established behavior of implicit fact gathering to not have so much spam in `-v` output, which will also restore consistency with manual `setup` module invocation.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
setup
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```
ansible 2.8.1
config file = /path/to/playbase/.ansible.cfg
configured module search path = [u'/path/to/playbase/lib']
ansible python module location = /usr/local/lib/python2.7/dist-packages/ansible
executable location = /usr/local/bin/ansible
python version = 2.7.15+ (default, Feb 3 2019, 13:13:16) [GCC 8.2.0]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```
ANSIBLE_NOCOWS(/path/to/playbase/.ansible.cfg) = True
DEFAULT_GATHER_SUBSET(/path/to/playbase/.ansible.cfg) = [u'!all', u'min', u'network']
DEFAULT_LOAD_CALLBACK_PLUGINS(/path/to/playbase/.ansible.cfg) = True
DEFAULT_MODULE_PATH(/path/to/playbase/.ansible.cfg) = [u'/path/to/playbase/lib']
DEFAULT_STDOUT_CALLBACK(/path/to/playbase/.ansible.cfg) = default
DISPLAY_ARGS_TO_STDOUT(/path/to/playbase/.ansible.cfg) = False
DISPLAY_SKIPPED_HOSTS(/path/to/playbase/.ansible.cfg) = False
```
(irrelevant removed)
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
controller: debian 9
target: ubuntu 16
##### STEPS TO REPRODUCE
good (non-execessive) output from `ansible-playbook -v`:
```yaml
- hosts: localhost
connection: local
gather_facts: false
tasks:
- setup:
- meta: noop
```
bad (excessive, entire setup fact structure dumped) output from `ansible-playbook -v`:
```yaml
- hosts: localhost
connection: local
gather_facts: true
tasks:
- meta: noop
```
##### EXPECTED RESULTS
expect that setup doesn't show entire set of gathered facts just with a simple `-v`, filling our logs with orders of magnitude more spam and forcing us to rewrite all our plays for explicit fact gathering to avoid it and all our roles to check if facts are present and run setup if not
removing `-v` is not an option because that's far too little information in most cases, we want more than "ok" for most things, the output is totally fine for all other modules under `-v` but setup module has now changed its long standing behavior. expect it to behave same way as it has for years, looking something like this:
```
ok: [localhost]
```
##### ACTUAL RESULTS
huge dump of entire json structure:
```
ok: [localhost] => {"ansible_facts": {"ansible_all_ipv4_addresses": ... <snipped>
```
furthermore, it's inconsistent between implicit and explicit gathering.
|
https://github.com/ansible/ansible/issues/58310
|
https://github.com/ansible/ansible/pull/58339
|
18d713e6d5bc4a09dd2b129039b43f1bacd1c212
|
bc25ac20e13255ecd0142d45965798b7adb568cd
| 2019-06-25T01:48:00Z |
python
| 2019-06-25T15:28:09Z |
changelogs/fragments/58310-gather-facts-verbosity.yml
| |
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,310 |
setup module became excessively verbose in 2.8, but only if used implicitly
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
implicit fact gathering (`gather_facts: true`) has started dumping the entire setup output with just a single `-v`, which is new with 2.8.0 and still present in 2.8.1 (not present in 2.7.11). this does *not* happen with `-v` if `gather_facts: false` and `setup` task is run manually in the play.
please restore the many-years-old, established behavior of implicit fact gathering to not have so much spam in `-v` output, which will also restore consistency with manual `setup` module invocation.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
setup
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```
ansible 2.8.1
config file = /path/to/playbase/.ansible.cfg
configured module search path = [u'/path/to/playbase/lib']
ansible python module location = /usr/local/lib/python2.7/dist-packages/ansible
executable location = /usr/local/bin/ansible
python version = 2.7.15+ (default, Feb 3 2019, 13:13:16) [GCC 8.2.0]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```
ANSIBLE_NOCOWS(/path/to/playbase/.ansible.cfg) = True
DEFAULT_GATHER_SUBSET(/path/to/playbase/.ansible.cfg) = [u'!all', u'min', u'network']
DEFAULT_LOAD_CALLBACK_PLUGINS(/path/to/playbase/.ansible.cfg) = True
DEFAULT_MODULE_PATH(/path/to/playbase/.ansible.cfg) = [u'/path/to/playbase/lib']
DEFAULT_STDOUT_CALLBACK(/path/to/playbase/.ansible.cfg) = default
DISPLAY_ARGS_TO_STDOUT(/path/to/playbase/.ansible.cfg) = False
DISPLAY_SKIPPED_HOSTS(/path/to/playbase/.ansible.cfg) = False
```
(irrelevant removed)
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
controller: debian 9
target: ubuntu 16
##### STEPS TO REPRODUCE
good (non-execessive) output from `ansible-playbook -v`:
```yaml
- hosts: localhost
connection: local
gather_facts: false
tasks:
- setup:
- meta: noop
```
bad (excessive, entire setup fact structure dumped) output from `ansible-playbook -v`:
```yaml
- hosts: localhost
connection: local
gather_facts: true
tasks:
- meta: noop
```
##### EXPECTED RESULTS
expect that setup doesn't show entire set of gathered facts just with a simple `-v`, filling our logs with orders of magnitude more spam and forcing us to rewrite all our plays for explicit fact gathering to avoid it and all our roles to check if facts are present and run setup if not
removing `-v` is not an option because that's far too little information in most cases, we want more than "ok" for most things, the output is totally fine for all other modules under `-v` but setup module has now changed its long standing behavior. expect it to behave same way as it has for years, looking something like this:
```
ok: [localhost]
```
##### ACTUAL RESULTS
huge dump of entire json structure:
```
ok: [localhost] => {"ansible_facts": {"ansible_all_ipv4_addresses": ... <snipped>
```
furthermore, it's inconsistent between implicit and explicit gathering.
|
https://github.com/ansible/ansible/issues/58310
|
https://github.com/ansible/ansible/pull/58339
|
18d713e6d5bc4a09dd2b129039b43f1bacd1c212
|
bc25ac20e13255ecd0142d45965798b7adb568cd
| 2019-06-25T01:48:00Z |
python
| 2019-06-25T15:28:09Z |
lib/ansible/plugins/action/gather_facts.py
|
# Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import time
from ansible import constants as C
from ansible.executor.module_common import get_action_args_with_defaults
from ansible.plugins.action import ActionBase
from ansible.utils.vars import combine_vars
class ActionModule(ActionBase):
def _get_module_args(self, fact_module, task_vars):
mod_args = self._task.args.copy()
# deal with 'setup specific arguments'
if fact_module != 'setup':
# network facts modules must support gather_subset
if self._connection._load_name not in ('network_cli', 'httpapi', 'netconf'):
subset = mod_args.pop('gather_subset', None)
if subset not in ('all', ['all']):
self._display.warning('Ignoring subset(%s) for %s' % (subset, fact_module))
timeout = mod_args.pop('gather_timeout', None)
if timeout is not None:
self._display.warning('Ignoring timeout(%s) for %s' % (timeout, fact_module))
fact_filter = mod_args.pop('filter', None)
if fact_filter is not None:
self._display.warning('Ignoring filter(%s) for %s' % (fact_filter, fact_module))
# Strip out keys with ``None`` values, effectively mimicking ``omit`` behavior
# This ensures we don't pass a ``None`` value as an argument expecting a specific type
mod_args = dict((k, v) for k, v in mod_args.items() if v is not None)
# handle module defaults
mod_args = get_action_args_with_defaults(fact_module, mod_args, self._task.module_defaults, self._templar)
return mod_args
def run(self, tmp=None, task_vars=None):
self._supports_check_mode = True
result = super(ActionModule, self).run(tmp, task_vars)
result['ansible_facts'] = {}
modules = C.config.get_config_value('FACTS_MODULES', variables=task_vars)
parallel = task_vars.pop('ansible_facts_parallel', self._task.args.pop('parallel', None))
if 'smart' in modules:
connection_map = C.config.get_config_value('CONNECTION_FACTS_MODULES', variables=task_vars)
modules.extend([connection_map.get(self._connection._load_name, 'setup')])
modules.pop(modules.index('smart'))
failed = {}
skipped = {}
if parallel is False or (len(modules) == 1 and parallel is None):
# serially execute each module
for fact_module in modules:
# just one module, no need for fancy async
mod_args = self._get_module_args(fact_module, task_vars)
res = self._execute_module(module_name=fact_module, module_args=mod_args, task_vars=task_vars, wrap_async=False)
if res.get('failed', False):
failed[fact_module] = res.get('msg')
elif res.get('skipped', False):
skipped[fact_module] = res.get('msg')
else:
result = combine_vars(result, {'ansible_facts': res.get('ansible_facts', {})})
self._remove_tmp_path(self._connection._shell.tmpdir)
else:
# do it async
jobs = {}
for fact_module in modules:
mod_args = self._get_module_args(fact_module, task_vars)
self._display.vvvv("Running %s" % fact_module)
jobs[fact_module] = (self._execute_module(module_name=fact_module, module_args=mod_args, task_vars=task_vars, wrap_async=True))
while jobs:
for module in jobs:
poll_args = {'jid': jobs[module]['ansible_job_id'], '_async_dir': os.path.dirname(jobs[module]['results_file'])}
res = self._execute_module(module_name='async_status', module_args=poll_args, task_vars=task_vars, wrap_async=False)
if res.get('finished', 0) == 1:
if res.get('failed', False):
failed[module] = res.get('msg')
elif res.get('skipped', False):
skipped[module] = res.get('msg')
else:
result = combine_vars(result, {'ansible_facts': res.get('ansible_facts', {})})
del jobs[module]
break
else:
time.sleep(0.1)
else:
time.sleep(0.5)
if skipped:
result['msg'] = "The following modules were skipped: %s\n" % (', '.join(skipped.keys()))
for skip in skipped:
result['msg'] += ' %s: %s\n' % (skip, skipped[skip])
if len(skipped) == len(modules):
result['skipped'] = True
if failed:
result['failed'] = True
result['msg'] = "The following modules failed to execute: %s\n" % (', '.join(failed.keys()))
for fail in failed:
result['msg'] += ' %s: %s\n' % (fail, failed[fail])
# tell executor facts were gathered
result['ansible_facts']['_ansible_facts_gathered'] = True
return result
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,282 |
jinja2 invalid syntax results in string instead of error
|
##### SUMMARY
An invalid syntax within a jinja2 statement results in the statement being returned instead of an syntax error.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
jinja2
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.9.0.dev0
config file = /etc/ansible/ansible.cfg
configured module search path = ['/home/user/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /home/user/PycharmProjects/ansible-2/lib/ansible
executable location = /home/user/PycharmProjects/ansible-2/bin/ansible
python version = 3.7.3 (default, Mar 26 2019, 21:43:19) [GCC 8.2.1 20181127]
```
##### CONFIGURATION
##### OS / ENVIRONMENT
ArchLinux
##### STEPS TO REPRODUCE
```yaml
- name: Test
hosts: localhost
gather_facts: false
become: false
strategy: linear
tasks:
- debug:
msg: "{{ foo | ipaddr('address')) }}"
```
##### EXPECTED RESULTS
Syntax error (two closing `)`-characters)
##### ACTUAL RESULTS
```paste below
ok: [localhost] => {
"msg": "{{ foo | ipaddr('address')) }}"
}
```
@sivel
|
https://github.com/ansible/ansible/issues/58282
|
https://github.com/ansible/ansible/pull/58290
|
f5b9bd81fcc0334113411f4dbefeb40214bb0837
|
e32d60bbcd44ccc7761268c6d6f00db036db962b
| 2019-06-24T14:50:48Z |
python
| 2019-06-25T15:54:37Z |
lib/ansible/playbook/helpers.py
|
# (c) 2012-2014, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ansible import constants as C
from ansible.errors import AnsibleParserError, AnsibleUndefinedVariable, AnsibleFileNotFound, AnsibleAssertionError
from ansible.module_utils._text import to_native
from ansible.module_utils.six import string_types
from ansible.parsing.mod_args import ModuleArgsParser
from ansible.utils.display import Display
display = Display()
def load_list_of_blocks(ds, play, parent_block=None, role=None, task_include=None, use_handlers=False, variable_manager=None, loader=None):
'''
Given a list of mixed task/block data (parsed from YAML),
return a list of Block() objects, where implicit blocks
are created for each bare Task.
'''
# we import here to prevent a circular dependency with imports
from ansible.playbook.block import Block
if not isinstance(ds, (list, type(None))):
raise AnsibleAssertionError('%s should be a list or None but is %s' % (ds, type(ds)))
block_list = []
if ds:
count = iter(range(len(ds)))
for i in count:
block_ds = ds[i]
# Implicit blocks are created by bare tasks listed in a play without
# an explicit block statement. If we have two implicit blocks in a row,
# squash them down to a single block to save processing time later.
implicit_blocks = []
while block_ds is not None and not Block.is_block(block_ds):
implicit_blocks.append(block_ds)
i += 1
# Advance the iterator, so we don't repeat
next(count, None)
try:
block_ds = ds[i]
except IndexError:
block_ds = None
# Loop both implicit blocks and block_ds as block_ds is the next in the list
for b in (implicit_blocks, block_ds):
if b:
block_list.append(
Block.load(
b,
play=play,
parent_block=parent_block,
role=role,
task_include=task_include,
use_handlers=use_handlers,
variable_manager=variable_manager,
loader=loader,
)
)
return block_list
def load_list_of_tasks(ds, play, block=None, role=None, task_include=None, use_handlers=False, variable_manager=None, loader=None):
'''
Given a list of task datastructures (parsed from YAML),
return a list of Task() or TaskInclude() objects.
'''
# we import here to prevent a circular dependency with imports
from ansible.playbook.block import Block
from ansible.playbook.handler import Handler
from ansible.playbook.task import Task
from ansible.playbook.task_include import TaskInclude
from ansible.playbook.role_include import IncludeRole
from ansible.playbook.handler_task_include import HandlerTaskInclude
from ansible.template import Templar
if not isinstance(ds, list):
raise AnsibleAssertionError('The ds (%s) should be a list but was a %s' % (ds, type(ds)))
task_list = []
for task_ds in ds:
if not isinstance(task_ds, dict):
raise AnsibleAssertionError('The ds (%s) should be a dict but was a %s' % (ds, type(ds)))
if 'block' in task_ds:
t = Block.load(
task_ds,
play=play,
parent_block=block,
role=role,
task_include=task_include,
use_handlers=use_handlers,
variable_manager=variable_manager,
loader=loader,
)
task_list.append(t)
else:
collection_list = task_ds.get('collections')
if collection_list is None and block is not None and block.collections:
collection_list = block.collections
args_parser = ModuleArgsParser(task_ds, collection_list=collection_list)
try:
(action, args, delegate_to) = args_parser.parse()
except AnsibleParserError as e:
# if the raises exception was created with obj=ds args, then it includes the detail
# so we dont need to add it so we can just re raise.
if e._obj:
raise
# But if it wasn't, we can add the yaml object now to get more detail
raise AnsibleParserError(to_native(e), obj=task_ds, orig_exc=e)
if action in ('include', 'import_tasks', 'include_tasks'):
if use_handlers:
include_class = HandlerTaskInclude
else:
include_class = TaskInclude
t = include_class.load(
task_ds,
block=block,
role=role,
task_include=None,
variable_manager=variable_manager,
loader=loader
)
all_vars = variable_manager.get_vars(play=play, task=t)
templar = Templar(loader=loader, variables=all_vars)
# check to see if this include is dynamic or static:
# 1. the user has set the 'static' option to false or true
# 2. one of the appropriate config options was set
if action == 'include_tasks':
is_static = False
elif action == 'import_tasks':
is_static = True
elif t.static is not None:
display.deprecated("The use of 'static' has been deprecated. "
"Use 'import_tasks' for static inclusion, or 'include_tasks' for dynamic inclusion", version='2.12')
is_static = t.static
else:
is_static = C.DEFAULT_TASK_INCLUDES_STATIC or \
(use_handlers and C.DEFAULT_HANDLER_INCLUDES_STATIC) or \
(not templar.is_template(t.args['_raw_params']) and t.all_parents_static() and not t.loop)
if is_static:
if t.loop is not None:
if action == 'import_tasks':
raise AnsibleParserError("You cannot use loops on 'import_tasks' statements. You should use 'include_tasks' instead.", obj=task_ds)
else:
raise AnsibleParserError("You cannot use 'static' on an include with a loop", obj=task_ds)
# we set a flag to indicate this include was static
t.statically_loaded = True
# handle relative includes by walking up the list of parent include
# tasks and checking the relative result to see if it exists
parent_include = block
cumulative_path = None
found = False
subdir = 'tasks'
if use_handlers:
subdir = 'handlers'
while parent_include is not None:
if not isinstance(parent_include, TaskInclude):
parent_include = parent_include._parent
continue
try:
parent_include_dir = os.path.dirname(templar.template(parent_include.args.get('_raw_params')))
except AnsibleUndefinedVariable as e:
if not parent_include.statically_loaded:
raise AnsibleParserError(
"Error when evaluating variable in dynamic parent include path: %s. "
"When using static imports, the parent dynamic include cannot utilize host facts "
"or variables from inventory" % parent_include.args.get('_raw_params'),
obj=task_ds,
suppress_extended_error=True,
orig_exc=e
)
raise
if cumulative_path is None:
cumulative_path = parent_include_dir
elif not os.path.isabs(cumulative_path):
cumulative_path = os.path.join(parent_include_dir, cumulative_path)
include_target = templar.template(t.args['_raw_params'])
if t._role:
new_basedir = os.path.join(t._role._role_path, subdir, cumulative_path)
include_file = loader.path_dwim_relative(new_basedir, subdir, include_target)
else:
include_file = loader.path_dwim_relative(loader.get_basedir(), cumulative_path, include_target)
if os.path.exists(include_file):
found = True
break
else:
parent_include = parent_include._parent
if not found:
try:
include_target = templar.template(t.args['_raw_params'])
except AnsibleUndefinedVariable as e:
raise AnsibleParserError(
"Error when evaluating variable in import path: %s.\n\n"
"When using static imports, ensure that any variables used in their names are defined in vars/vars_files\n"
"or extra-vars passed in from the command line. Static imports cannot use variables from facts or inventory\n"
"sources like group or host vars." % t.args['_raw_params'],
obj=task_ds,
suppress_extended_error=True,
orig_exc=e)
if t._role:
include_file = loader.path_dwim_relative(t._role._role_path, subdir, include_target)
else:
include_file = loader.path_dwim(include_target)
try:
data = loader.load_from_file(include_file)
if data is None:
display.warning('file %s is empty and had no tasks to include' % include_file)
continue
elif not isinstance(data, list):
raise AnsibleParserError("included task files must contain a list of tasks", obj=data)
# since we can't send callbacks here, we display a message directly in
# the same fashion used by the on_include callback. We also do it here,
# because the recursive nature of helper methods means we may be loading
# nested includes, and we want the include order printed correctly
display.vv("statically imported: %s" % include_file)
except AnsibleFileNotFound:
if action != 'include' or t.static or \
C.DEFAULT_TASK_INCLUDES_STATIC or \
C.DEFAULT_HANDLER_INCLUDES_STATIC and use_handlers:
raise
display.deprecated(
"Included file '%s' not found, however since this include is not "
"explicitly marked as 'static: yes', we will try and include it dynamically "
"later. In the future, this will be an error unless 'static: no' is used "
"on the include task. If you do not want missing includes to be considered "
"dynamic, use 'static: yes' on the include or set the global ansible.cfg "
"options to make all includes static for tasks and/or handlers" % include_file, version="2.12"
)
task_list.append(t)
continue
ti_copy = t.copy(exclude_parent=True)
ti_copy._parent = block
included_blocks = load_list_of_blocks(
data,
play=play,
parent_block=None,
task_include=ti_copy,
role=role,
use_handlers=use_handlers,
loader=loader,
variable_manager=variable_manager,
)
# FIXME: remove once 'include' is removed
# pop tags out of the include args, if they were specified there, and assign
# them to the include. If the include already had tags specified, we raise an
# error so that users know not to specify them both ways
tags = ti_copy.vars.pop('tags', [])
if isinstance(tags, string_types):
tags = tags.split(',')
if len(tags) > 0:
if action in ('include_tasks', 'import_tasks'):
raise AnsibleParserError('You cannot specify "tags" inline to the task, it is a task keyword')
if len(ti_copy.tags) > 0:
raise AnsibleParserError(
"Include tasks should not specify tags in more than one way (both via args and directly on the task). "
"Mixing styles in which tags are specified is prohibited for whole import hierarchy, not only for single import statement",
obj=task_ds,
suppress_extended_error=True,
)
display.deprecated("You should not specify tags in the include parameters. All tags should be specified using the task-level option",
version="2.12")
else:
tags = ti_copy.tags[:]
# now we extend the tags on each of the included blocks
for b in included_blocks:
b.tags = list(set(b.tags).union(tags))
# END FIXME
# FIXME: handlers shouldn't need this special handling, but do
# right now because they don't iterate blocks correctly
if use_handlers:
for b in included_blocks:
task_list.extend(b.block)
else:
task_list.extend(included_blocks)
else:
t.is_static = False
task_list.append(t)
elif action in ('include_role', 'import_role'):
ir = IncludeRole.load(
task_ds,
block=block,
role=role,
task_include=None,
variable_manager=variable_manager,
loader=loader,
)
# 1. the user has set the 'static' option to false or true
# 2. one of the appropriate config options was set
is_static = False
if action == 'import_role':
is_static = True
elif ir.static is not None:
display.deprecated("The use of 'static' for 'include_role' has been deprecated. "
"Use 'import_role' for static inclusion, or 'include_role' for dynamic inclusion", version='2.12')
is_static = ir.static
if is_static:
if ir.loop is not None:
if action == 'import_role':
raise AnsibleParserError("You cannot use loops on 'import_role' statements. You should use 'include_role' instead.", obj=task_ds)
else:
raise AnsibleParserError("You cannot use 'static' on an include_role with a loop", obj=task_ds)
# we set a flag to indicate this include was static
ir.statically_loaded = True
# template the role name now, if needed
all_vars = variable_manager.get_vars(play=play, task=ir)
templar = Templar(loader=loader, variables=all_vars)
if templar.is_template(ir._role_name):
ir._role_name = templar.template(ir._role_name)
# uses compiled list from object
blocks, _ = ir.get_block_list(variable_manager=variable_manager, loader=loader)
task_list.extend(blocks)
else:
# passes task object itself for latter generation of list
task_list.append(ir)
else:
if use_handlers:
t = Handler.load(task_ds, block=block, role=role, task_include=task_include, variable_manager=variable_manager, loader=loader)
else:
t = Task.load(task_ds, block=block, role=role, task_include=task_include, variable_manager=variable_manager, loader=loader)
task_list.append(t)
return task_list
def load_list_of_roles(ds, play, current_role_path=None, variable_manager=None, loader=None):
'''
Loads and returns a list of RoleInclude objects from the datastructure
list of role definitions
'''
# we import here to prevent a circular dependency with imports
from ansible.playbook.role.include import RoleInclude
if not isinstance(ds, list):
raise AnsibleAssertionError('ds (%s) should be a list but was a %s' % (ds, type(ds)))
roles = []
for role_def in ds:
i = RoleInclude.load(role_def, play=play, current_role_path=current_role_path, variable_manager=variable_manager,
loader=loader, collection_list=play.collections)
roles.append(i)
return roles
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,282 |
jinja2 invalid syntax results in string instead of error
|
##### SUMMARY
An invalid syntax within a jinja2 statement results in the statement being returned instead of an syntax error.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
jinja2
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.9.0.dev0
config file = /etc/ansible/ansible.cfg
configured module search path = ['/home/user/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /home/user/PycharmProjects/ansible-2/lib/ansible
executable location = /home/user/PycharmProjects/ansible-2/bin/ansible
python version = 3.7.3 (default, Mar 26 2019, 21:43:19) [GCC 8.2.1 20181127]
```
##### CONFIGURATION
##### OS / ENVIRONMENT
ArchLinux
##### STEPS TO REPRODUCE
```yaml
- name: Test
hosts: localhost
gather_facts: false
become: false
strategy: linear
tasks:
- debug:
msg: "{{ foo | ipaddr('address')) }}"
```
##### EXPECTED RESULTS
Syntax error (two closing `)`-characters)
##### ACTUAL RESULTS
```paste below
ok: [localhost] => {
"msg": "{{ foo | ipaddr('address')) }}"
}
```
@sivel
|
https://github.com/ansible/ansible/issues/58282
|
https://github.com/ansible/ansible/pull/58290
|
f5b9bd81fcc0334113411f4dbefeb40214bb0837
|
e32d60bbcd44ccc7761268c6d6f00db036db962b
| 2019-06-24T14:50:48Z |
python
| 2019-06-25T15:54:37Z |
lib/ansible/playbook/role/definition.py
|
# (c) 2014 Michael DeHaan, <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ansible import constants as C
from ansible.errors import AnsibleError, AnsibleAssertionError
from ansible.module_utils.six import iteritems, string_types
from ansible.parsing.yaml.objects import AnsibleBaseYAMLObject, AnsibleMapping
from ansible.playbook.attribute import Attribute, FieldAttribute
from ansible.playbook.base import Base
from ansible.playbook.collectionsearch import CollectionSearch
from ansible.playbook.conditional import Conditional
from ansible.playbook.taggable import Taggable
from ansible.template import Templar
from ansible.utils.collection_loader import get_collection_role_path, is_collection_ref
from ansible.utils.path import unfrackpath
from ansible.utils.display import Display
__all__ = ['RoleDefinition']
display = Display()
class RoleDefinition(Base, Conditional, Taggable, CollectionSearch):
_role = FieldAttribute(isa='string')
def __init__(self, play=None, role_basedir=None, variable_manager=None, loader=None, collection_list=None):
super(RoleDefinition, self).__init__()
self._play = play
self._variable_manager = variable_manager
self._loader = loader
self._role_path = None
self._role_collection = None
self._role_basedir = role_basedir
self._role_params = dict()
self._collection_list = collection_list
# def __repr__(self):
# return 'ROLEDEF: ' + self._attributes.get('role', '<no name set>')
@staticmethod
def load(data, variable_manager=None, loader=None):
raise AnsibleError("not implemented")
def preprocess_data(self, ds):
# role names that are simply numbers can be parsed by PyYAML
# as integers even when quoted, so turn it into a string type
if isinstance(ds, int):
ds = "%s" % ds
if not isinstance(ds, dict) and not isinstance(ds, string_types) and not isinstance(ds, AnsibleBaseYAMLObject):
raise AnsibleAssertionError()
if isinstance(ds, dict):
ds = super(RoleDefinition, self).preprocess_data(ds)
# save the original ds for use later
self._ds = ds
# we create a new data structure here, using the same
# object used internally by the YAML parsing code so we
# can preserve file:line:column information if it exists
new_ds = AnsibleMapping()
if isinstance(ds, AnsibleBaseYAMLObject):
new_ds.ansible_pos = ds.ansible_pos
# first we pull the role name out of the data structure,
# and then use that to determine the role path (which may
# result in a new role name, if it was a file path)
role_name = self._load_role_name(ds)
(role_name, role_path) = self._load_role_path(role_name)
# next, we split the role params out from the valid role
# attributes and update the new datastructure with that
# result and the role name
if isinstance(ds, dict):
(new_role_def, role_params) = self._split_role_params(ds)
new_ds.update(new_role_def)
self._role_params = role_params
# set the role name in the new ds
new_ds['role'] = role_name
# we store the role path internally
self._role_path = role_path
# and return the cleaned-up data structure
return new_ds
def _load_role_name(self, ds):
'''
Returns the role name (either the role: or name: field) from
the role definition, or (when the role definition is a simple
string), just that string
'''
if isinstance(ds, string_types):
return ds
role_name = ds.get('role', ds.get('name'))
if not role_name or not isinstance(role_name, string_types):
raise AnsibleError('role definitions must contain a role name', obj=ds)
# if we have the required datastructures, and if the role_name
# contains a variable, try and template it now
if self._variable_manager:
all_vars = self._variable_manager.get_vars(play=self._play)
templar = Templar(loader=self._loader, variables=all_vars)
if templar.is_template(role_name):
role_name = templar.template(role_name)
return role_name
def _load_role_path(self, role_name):
'''
the 'role', as specified in the ds (or as a bare string), can either
be a simple name or a full path. If it is a full path, we use the
basename as the role name, otherwise we take the name as-given and
append it to the default role path
'''
# create a templar class to template the dependency names, in
# case they contain variables
if self._variable_manager is not None:
all_vars = self._variable_manager.get_vars(play=self._play)
else:
all_vars = dict()
templar = Templar(loader=self._loader, variables=all_vars)
role_name = templar.template(role_name)
role_tuple = None
# try to load as a collection-based role first
if self._collection_list or is_collection_ref(role_name):
role_tuple = get_collection_role_path(role_name, self._collection_list)
if role_tuple:
# we found it, stash collection data and return the name/path tuple
self._role_collection = role_tuple[2]
return role_tuple[0:2]
# FUTURE: refactor this to be callable from internal so we can properly order ansible.legacy searches with the collections keyword
if self._collection_list and 'ansible.legacy' not in self._collection_list:
raise AnsibleError("the role '%s' was not found in %s" % (role_name, ":".join(self._collection_list)), obj=self._ds)
# we always start the search for roles in the base directory of the playbook
role_search_paths = [
os.path.join(self._loader.get_basedir(), u'roles'),
]
# also search in the configured roles path
if C.DEFAULT_ROLES_PATH:
role_search_paths.extend(C.DEFAULT_ROLES_PATH)
# next, append the roles basedir, if it was set, so we can
# search relative to that directory for dependent roles
if self._role_basedir:
role_search_paths.append(self._role_basedir)
# finally as a last resort we look in the current basedir as set
# in the loader (which should be the playbook dir itself) but without
# the roles/ dir appended
role_search_paths.append(self._loader.get_basedir())
# now iterate through the possible paths and return the first one we find
for path in role_search_paths:
path = templar.template(path)
role_path = unfrackpath(os.path.join(path, role_name))
if self._loader.path_exists(role_path):
return (role_name, role_path)
# if not found elsewhere try to extract path from name
role_path = unfrackpath(role_name)
if self._loader.path_exists(role_path):
role_name = os.path.basename(role_name)
return (role_name, role_path)
raise AnsibleError("the role '%s' was not found in %s" % (role_name, ":".join(role_search_paths)), obj=self._ds)
def _split_role_params(self, ds):
'''
Splits any random role params off from the role spec and store
them in a dictionary of params for parsing later
'''
role_def = dict()
role_params = dict()
base_attribute_names = frozenset(self._valid_attrs.keys())
for (key, value) in iteritems(ds):
# use the list of FieldAttribute values to determine what is and is not
# an extra parameter for this role (or sub-class of this role)
# FIXME: hard-coded list of exception key names here corresponds to the
# connection fields in the Base class. There may need to be some
# other mechanism where we exclude certain kinds of field attributes,
# or make this list more automatic in some way so we don't have to
# remember to update it manually.
if key not in base_attribute_names:
# this key does not match a field attribute, so it must be a role param
role_params[key] = value
else:
# this is a field attribute, so copy it over directly
role_def[key] = value
return (role_def, role_params)
def get_role_params(self):
return self._role_params.copy()
def get_role_path(self):
return self._role_path
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,282 |
jinja2 invalid syntax results in string instead of error
|
##### SUMMARY
An invalid syntax within a jinja2 statement results in the statement being returned instead of an syntax error.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
jinja2
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.9.0.dev0
config file = /etc/ansible/ansible.cfg
configured module search path = ['/home/user/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /home/user/PycharmProjects/ansible-2/lib/ansible
executable location = /home/user/PycharmProjects/ansible-2/bin/ansible
python version = 3.7.3 (default, Mar 26 2019, 21:43:19) [GCC 8.2.1 20181127]
```
##### CONFIGURATION
##### OS / ENVIRONMENT
ArchLinux
##### STEPS TO REPRODUCE
```yaml
- name: Test
hosts: localhost
gather_facts: false
become: false
strategy: linear
tasks:
- debug:
msg: "{{ foo | ipaddr('address')) }}"
```
##### EXPECTED RESULTS
Syntax error (two closing `)`-characters)
##### ACTUAL RESULTS
```paste below
ok: [localhost] => {
"msg": "{{ foo | ipaddr('address')) }}"
}
```
@sivel
|
https://github.com/ansible/ansible/issues/58282
|
https://github.com/ansible/ansible/pull/58290
|
f5b9bd81fcc0334113411f4dbefeb40214bb0837
|
e32d60bbcd44ccc7761268c6d6f00db036db962b
| 2019-06-24T14:50:48Z |
python
| 2019-06-25T15:54:37Z |
lib/ansible/template/__init__.py
|
# (c) 2012-2014, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import ast
import datetime
import os
import pkgutil
import pwd
import re
import time
from numbers import Number
try:
from hashlib import sha1
except ImportError:
from sha import sha as sha1
from jinja2.exceptions import TemplateSyntaxError, UndefinedError
from jinja2.loaders import FileSystemLoader
from jinja2.runtime import Context, StrictUndefined
from ansible import constants as C
from ansible.errors import AnsibleError, AnsibleFilterError, AnsibleUndefinedVariable, AnsibleAssertionError
from ansible.module_utils.six import iteritems, string_types, text_type
from ansible.module_utils._text import to_native, to_text, to_bytes
from ansible.module_utils.common._collections_compat import Sequence, Mapping, MutableMapping
from ansible.plugins.loader import filter_loader, lookup_loader, test_loader
from ansible.template.safe_eval import safe_eval
from ansible.template.template import AnsibleJ2Template
from ansible.template.vars import AnsibleJ2Vars
from ansible.utils.display import Display
from ansible.utils.unsafe_proxy import UnsafeProxy, wrap_var
# HACK: keep Python 2.6 controller tests happy in CI until they're properly split
try:
from importlib import import_module
except ImportError:
import_module = __import__
display = Display()
__all__ = ['Templar', 'generate_ansible_template_vars']
# A regex for checking to see if a variable we're trying to
# expand is just a single variable name.
# Primitive Types which we don't want Jinja to convert to strings.
NON_TEMPLATED_TYPES = (bool, Number)
JINJA2_OVERRIDE = '#jinja2:'
USE_JINJA2_NATIVE = False
if C.DEFAULT_JINJA2_NATIVE:
try:
from jinja2.nativetypes import NativeEnvironment as Environment
from ansible.template.native_helpers import ansible_native_concat as j2_concat
USE_JINJA2_NATIVE = True
except ImportError:
from jinja2 import Environment
from jinja2.utils import concat as j2_concat
from jinja2 import __version__ as j2_version
display.warning(
'jinja2_native requires Jinja 2.10 and above. '
'Version detected: %s. Falling back to default.' % j2_version
)
else:
from jinja2 import Environment
from jinja2.utils import concat as j2_concat
JINJA2_BEGIN_TOKENS = frozenset(('variable_begin', 'block_begin', 'comment_begin', 'raw_begin'))
JINJA2_END_TOKENS = frozenset(('variable_end', 'block_end', 'comment_end', 'raw_end'))
def generate_ansible_template_vars(path, dest_path=None):
b_path = to_bytes(path)
try:
template_uid = pwd.getpwuid(os.stat(b_path).st_uid).pw_name
except (KeyError, TypeError):
template_uid = os.stat(b_path).st_uid
temp_vars = {
'template_host': to_text(os.uname()[1]),
'template_path': path,
'template_mtime': datetime.datetime.fromtimestamp(os.path.getmtime(b_path)),
'template_uid': to_text(template_uid),
'template_fullpath': os.path.abspath(path),
'template_run_date': datetime.datetime.now(),
'template_destpath': to_native(dest_path) if dest_path else None,
}
managed_default = C.DEFAULT_MANAGED_STR
managed_str = managed_default.format(
host=temp_vars['template_host'],
uid=temp_vars['template_uid'],
file=temp_vars['template_path'],
)
temp_vars['ansible_managed'] = to_text(time.strftime(to_native(managed_str), time.localtime(os.path.getmtime(b_path))))
return temp_vars
def _escape_backslashes(data, jinja_env):
"""Double backslashes within jinja2 expressions
A user may enter something like this in a playbook::
debug:
msg: "Test Case 1\\3; {{ test1_name | regex_replace('^(.*)_name$', '\\1')}}"
The string inside of the {{ gets interpreted multiple times First by yaml.
Then by python. And finally by jinja2 as part of it's variable. Because
it is processed by both python and jinja2, the backslash escaped
characters get unescaped twice. This means that we'd normally have to use
four backslashes to escape that. This is painful for playbook authors as
they have to remember different rules for inside vs outside of a jinja2
expression (The backslashes outside of the "{{ }}" only get processed by
yaml and python. So they only need to be escaped once). The following
code fixes this by automatically performing the extra quoting of
backslashes inside of a jinja2 expression.
"""
if '\\' in data and '{{' in data:
new_data = []
d2 = jinja_env.preprocess(data)
in_var = False
for token in jinja_env.lex(d2):
if token[1] == 'variable_begin':
in_var = True
new_data.append(token[2])
elif token[1] == 'variable_end':
in_var = False
new_data.append(token[2])
elif in_var and token[1] == 'string':
# Double backslashes only if we're inside of a jinja2 variable
new_data.append(token[2].replace('\\', '\\\\'))
else:
new_data.append(token[2])
data = ''.join(new_data)
return data
def is_template(data, jinja_env):
"""This function attempts to quickly detect whether a value is a jinja2
template. To do so, we look for the first 2 matching jinja2 tokens for
start and end delimiters.
"""
found = None
start = True
comment = False
d2 = jinja_env.preprocess(data)
# This wraps a lot of code, but this is due to lex returing a generator
# so we may get an exception at any part of the loop
try:
for token in jinja_env.lex(d2):
if token[1] in JINJA2_BEGIN_TOKENS:
if start and token[1] == 'comment_begin':
# Comments can wrap other token types
comment = True
start = False
# Example: variable_end -> variable
found = token[1].split('_')[0]
elif token[1] in JINJA2_END_TOKENS:
if token[1].split('_')[0] == found:
return True
elif comment:
continue
return False
except TemplateSyntaxError:
return False
return False
def _count_newlines_from_end(in_str):
'''
Counts the number of newlines at the end of a string. This is used during
the jinja2 templating to ensure the count matches the input, since some newlines
may be thrown away during the templating.
'''
try:
i = len(in_str)
j = i - 1
while in_str[j] == '\n':
j -= 1
return i - 1 - j
except IndexError:
# Uncommon cases: zero length string and string containing only newlines
return i
def recursive_check_defined(item):
from jinja2.runtime import Undefined
if isinstance(item, MutableMapping):
for key in item:
recursive_check_defined(item[key])
elif isinstance(item, list):
for i in item:
recursive_check_defined(i)
else:
if isinstance(item, Undefined):
raise AnsibleFilterError("{0} is undefined".format(item))
class AnsibleUndefined(StrictUndefined):
'''
A custom Undefined class, which returns further Undefined objects on access,
rather than throwing an exception.
'''
def __getattr__(self, name):
# Return original Undefined object to preserve the first failure context
return self
def __getitem__(self, key):
# Return original Undefined object to preserve the first failure context
return self
def __repr__(self):
return 'AnsibleUndefined'
class AnsibleContext(Context):
'''
A custom context, which intercepts resolve() calls and sets a flag
internally if any variable lookup returns an AnsibleUnsafe value. This
flag is checked post-templating, and (when set) will result in the
final templated result being wrapped via UnsafeProxy.
'''
def __init__(self, *args, **kwargs):
super(AnsibleContext, self).__init__(*args, **kwargs)
self.unsafe = False
def _is_unsafe(self, val):
'''
Our helper function, which will also recursively check dict and
list entries due to the fact that they may be repr'd and contain
a key or value which contains jinja2 syntax and would otherwise
lose the AnsibleUnsafe value.
'''
if isinstance(val, dict):
for key in val.keys():
if self._is_unsafe(val[key]):
return True
elif isinstance(val, list):
for item in val:
if self._is_unsafe(item):
return True
elif isinstance(val, string_types) and hasattr(val, '__UNSAFE__'):
return True
return False
def _update_unsafe(self, val):
if val is not None and not self.unsafe and self._is_unsafe(val):
self.unsafe = True
def resolve(self, key):
'''
The intercepted resolve(), which uses the helper above to set the
internal flag whenever an unsafe variable value is returned.
'''
val = super(AnsibleContext, self).resolve(key)
self._update_unsafe(val)
return val
def resolve_or_missing(self, key):
val = super(AnsibleContext, self).resolve_or_missing(key)
self._update_unsafe(val)
return val
class JinjaPluginIntercept(MutableMapping):
def __init__(self, delegatee, pluginloader, *args, **kwargs):
super(JinjaPluginIntercept, self).__init__(*args, **kwargs)
self._delegatee = delegatee
self._pluginloader = pluginloader
if self._pluginloader.class_name == 'FilterModule':
self._method_map_name = 'filters'
self._dirname = 'filter'
elif self._pluginloader.class_name == 'TestModule':
self._method_map_name = 'tests'
self._dirname = 'test'
self._collection_jinja_func_cache = {}
# FUTURE: we can cache FQ filter/test calls for the entire duration of a run, since a given collection's impl's
# aren't supposed to change during a run
def __getitem__(self, key):
if not isinstance(key, string_types):
raise ValueError('key must be a string')
key = to_native(key)
if '.' not in key: # might be a built-in value, delegate to base dict
return self._delegatee.__getitem__(key)
func = self._collection_jinja_func_cache.get(key)
if func:
return func
components = key.split('.')
if len(components) != 3:
raise KeyError('invalid plugin name: {0}'.format(key))
collection_name = '.'.join(components[0:2])
collection_pkg = 'ansible_collections.{0}.plugins.{1}'.format(collection_name, self._dirname)
# FIXME: error handling for bogus plugin name, bogus impl, bogus filter/test
# FIXME: move this capability into the Jinja plugin loader
pkg = import_module(collection_pkg)
for dummy, module_name, ispkg in pkgutil.iter_modules(pkg.__path__, prefix=collection_name + '.'):
if ispkg:
continue
plugin_impl = self._pluginloader.get(module_name)
method_map = getattr(plugin_impl, self._method_map_name)
for f in iteritems(method_map()):
fq_name = '.'.join((collection_name, f[0]))
self._collection_jinja_func_cache[fq_name] = f[1]
function_impl = self._collection_jinja_func_cache[key]
# FIXME: detect/warn on intra-collection function name collisions
return function_impl
def __setitem__(self, key, value):
return self._delegatee.__setitem__(key, value)
def __delitem__(self, key):
raise NotImplementedError()
def __iter__(self):
# not strictly accurate since we're not counting dynamically-loaded values
return iter(self._delegatee)
def __len__(self):
# not strictly accurate since we're not counting dynamically-loaded values
return len(self._delegatee)
class AnsibleEnvironment(Environment):
'''
Our custom environment, which simply allows us to override the class-level
values for the Template and Context classes used by jinja2 internally.
'''
context_class = AnsibleContext
template_class = AnsibleJ2Template
def __init__(self, *args, **kwargs):
super(AnsibleEnvironment, self).__init__(*args, **kwargs)
self.filters = JinjaPluginIntercept(self.filters, filter_loader)
self.tests = JinjaPluginIntercept(self.tests, test_loader)
class Templar:
'''
The main class for templating, with the main entry-point of template().
'''
def __init__(self, loader, shared_loader_obj=None, variables=None):
variables = {} if variables is None else variables
self._loader = loader
self._filters = None
self._tests = None
self._available_variables = variables
self._cached_result = {}
if loader:
self._basedir = loader.get_basedir()
else:
self._basedir = './'
if shared_loader_obj:
self._filter_loader = getattr(shared_loader_obj, 'filter_loader')
self._test_loader = getattr(shared_loader_obj, 'test_loader')
self._lookup_loader = getattr(shared_loader_obj, 'lookup_loader')
else:
self._filter_loader = filter_loader
self._test_loader = test_loader
self._lookup_loader = lookup_loader
# flags to determine whether certain failures during templating
# should result in fatal errors being raised
self._fail_on_lookup_errors = True
self._fail_on_filter_errors = True
self._fail_on_undefined_errors = C.DEFAULT_UNDEFINED_VAR_BEHAVIOR
self.environment = AnsibleEnvironment(
trim_blocks=True,
undefined=AnsibleUndefined,
extensions=self._get_extensions(),
finalize=self._finalize,
loader=FileSystemLoader(self._basedir),
)
# the current rendering context under which the templar class is working
self.cur_context = None
self.SINGLE_VAR = re.compile(r"^%s\s*(\w*)\s*%s$" % (self.environment.variable_start_string, self.environment.variable_end_string))
self._clean_regex = re.compile(r'(?:%s|%s|%s|%s)' % (
self.environment.variable_start_string,
self.environment.block_start_string,
self.environment.block_end_string,
self.environment.variable_end_string
))
self._no_type_regex = re.compile(r'.*?\|\s*(?:%s)(?:\([^\|]*\))?\s*\)?\s*(?:%s)' %
('|'.join(C.STRING_TYPE_FILTERS), self.environment.variable_end_string))
def _get_filters(self):
'''
Returns filter plugins, after loading and caching them if need be
'''
if self._filters is not None:
return self._filters.copy()
self._filters = dict()
for fp in self._filter_loader.all():
self._filters.update(fp.filters())
return self._filters.copy()
def _get_tests(self):
'''
Returns tests plugins, after loading and caching them if need be
'''
if self._tests is not None:
return self._tests.copy()
self._tests = dict()
for fp in self._test_loader.all():
self._tests.update(fp.tests())
return self._tests.copy()
def _get_extensions(self):
'''
Return jinja2 extensions to load.
If some extensions are set via jinja_extensions in ansible.cfg, we try
to load them with the jinja environment.
'''
jinja_exts = []
if C.DEFAULT_JINJA2_EXTENSIONS:
# make sure the configuration directive doesn't contain spaces
# and split extensions in an array
jinja_exts = C.DEFAULT_JINJA2_EXTENSIONS.replace(" ", "").split(',')
return jinja_exts
@property
def available_variables(self):
return self._available_variables
@available_variables.setter
def available_variables(self, variables):
'''
Sets the list of template variables this Templar instance will use
to template things, so we don't have to pass them around between
internal methods. We also clear the template cache here, as the variables
are being changed.
'''
if not isinstance(variables, dict):
raise AnsibleAssertionError("the type of 'variables' should be a dict but was a %s" % (type(variables)))
self._available_variables = variables
self._cached_result = {}
def set_available_variables(self, variables):
display.deprecated(
'set_available_variables is being deprecated. Use "@available_variables.setter" instead.',
version='2.13'
)
self.available_variables = variables
def template(self, variable, convert_bare=False, preserve_trailing_newlines=True, escape_backslashes=True, fail_on_undefined=None, overrides=None,
convert_data=True, static_vars=None, cache=True, disable_lookups=False):
'''
Templates (possibly recursively) any given data as input. If convert_bare is
set to True, the given data will be wrapped as a jinja2 variable ('{{foo}}')
before being sent through the template engine.
'''
static_vars = [''] if static_vars is None else static_vars
# Don't template unsafe variables, just return them.
if hasattr(variable, '__UNSAFE__'):
return variable
if fail_on_undefined is None:
fail_on_undefined = self._fail_on_undefined_errors
try:
if convert_bare:
variable = self._convert_bare_variable(variable)
if isinstance(variable, string_types):
result = variable
if self.is_template(variable):
# Check to see if the string we are trying to render is just referencing a single
# var. In this case we don't want to accidentally change the type of the variable
# to a string by using the jinja template renderer. We just want to pass it.
only_one = self.SINGLE_VAR.match(variable)
if only_one:
var_name = only_one.group(1)
if var_name in self._available_variables:
resolved_val = self._available_variables[var_name]
if isinstance(resolved_val, NON_TEMPLATED_TYPES):
return resolved_val
elif resolved_val is None:
return C.DEFAULT_NULL_REPRESENTATION
# Using a cache in order to prevent template calls with already templated variables
sha1_hash = None
if cache:
variable_hash = sha1(text_type(variable).encode('utf-8'))
options_hash = sha1(
(
text_type(preserve_trailing_newlines) +
text_type(escape_backslashes) +
text_type(fail_on_undefined) +
text_type(overrides)
).encode('utf-8')
)
sha1_hash = variable_hash.hexdigest() + options_hash.hexdigest()
if cache and sha1_hash in self._cached_result:
result = self._cached_result[sha1_hash]
else:
result = self.do_template(
variable,
preserve_trailing_newlines=preserve_trailing_newlines,
escape_backslashes=escape_backslashes,
fail_on_undefined=fail_on_undefined,
overrides=overrides,
disable_lookups=disable_lookups,
)
if not USE_JINJA2_NATIVE:
unsafe = hasattr(result, '__UNSAFE__')
if convert_data and not self._no_type_regex.match(variable):
# if this looks like a dictionary or list, convert it to such using the safe_eval method
if (result.startswith("{") and not result.startswith(self.environment.variable_start_string)) or \
result.startswith("[") or result in ("True", "False"):
eval_results = safe_eval(result, include_exceptions=True)
if eval_results[1] is None:
result = eval_results[0]
if unsafe:
result = wrap_var(result)
else:
# FIXME: if the safe_eval raised an error, should we do something with it?
pass
# we only cache in the case where we have a single variable
# name, to make sure we're not putting things which may otherwise
# be dynamic in the cache (filters, lookups, etc.)
if cache:
self._cached_result[sha1_hash] = result
return result
elif isinstance(variable, (list, tuple)):
return [self.template(
v,
preserve_trailing_newlines=preserve_trailing_newlines,
fail_on_undefined=fail_on_undefined,
overrides=overrides,
disable_lookups=disable_lookups,
) for v in variable]
elif isinstance(variable, (dict, Mapping)):
d = {}
# we don't use iteritems() here to avoid problems if the underlying dict
# changes sizes due to the templating, which can happen with hostvars
for k in variable.keys():
if k not in static_vars:
d[k] = self.template(
variable[k],
preserve_trailing_newlines=preserve_trailing_newlines,
fail_on_undefined=fail_on_undefined,
overrides=overrides,
disable_lookups=disable_lookups,
)
else:
d[k] = variable[k]
return d
else:
return variable
except AnsibleFilterError:
if self._fail_on_filter_errors:
raise
else:
return variable
def is_template(self, data):
''' lets us know if data has a template'''
if isinstance(data, string_types):
return is_template(data, self.environment)
elif isinstance(data, (list, tuple)):
for v in data:
if self.is_template(v):
return True
elif isinstance(data, dict):
for k in data:
if self.is_template(k) or self.is_template(data[k]):
return True
return False
templatable = _contains_vars = is_template
def _convert_bare_variable(self, variable):
'''
Wraps a bare string, which may have an attribute portion (ie. foo.bar)
in jinja2 variable braces so that it is evaluated properly.
'''
if isinstance(variable, string_types):
contains_filters = "|" in variable
first_part = variable.split("|")[0].split(".")[0].split("[")[0]
if (contains_filters or first_part in self._available_variables) and self.environment.variable_start_string not in variable:
return "%s%s%s" % (self.environment.variable_start_string, variable, self.environment.variable_end_string)
# the variable didn't meet the conditions to be converted,
# so just return it as-is
return variable
def _finalize(self, thing):
'''
A custom finalize method for jinja2, which prevents None from being returned. This
avoids a string of ``"None"`` as ``None`` has no importance in YAML.
If using ANSIBLE_JINJA2_NATIVE we bypass this and return the actual value always
'''
if USE_JINJA2_NATIVE:
return thing
return thing if thing is not None else ''
def _fail_lookup(self, name, *args, **kwargs):
raise AnsibleError("The lookup `%s` was found, however lookups were disabled from templating" % name)
def _now_datetime(self, utc=False, fmt=None):
'''jinja2 global function to return current datetime, potentially formatted via strftime'''
if utc:
now = datetime.datetime.utcnow()
else:
now = datetime.datetime.now()
if fmt:
return now.strftime(fmt)
return now
def _query_lookup(self, name, *args, **kwargs):
''' wrapper for lookup, force wantlist true'''
kwargs['wantlist'] = True
return self._lookup(name, *args, **kwargs)
def _lookup(self, name, *args, **kwargs):
instance = self._lookup_loader.get(name.lower(), loader=self._loader, templar=self)
if instance is not None:
wantlist = kwargs.pop('wantlist', False)
allow_unsafe = kwargs.pop('allow_unsafe', C.DEFAULT_ALLOW_UNSAFE_LOOKUPS)
errors = kwargs.pop('errors', 'strict')
from ansible.utils.listify import listify_lookup_plugin_terms
loop_terms = listify_lookup_plugin_terms(terms=args, templar=self, loader=self._loader, fail_on_undefined=True, convert_bare=False)
# safely catch run failures per #5059
try:
ran = instance.run(loop_terms, variables=self._available_variables, **kwargs)
except (AnsibleUndefinedVariable, UndefinedError) as e:
raise AnsibleUndefinedVariable(e)
except Exception as e:
if self._fail_on_lookup_errors:
msg = u"An unhandled exception occurred while running the lookup plugin '%s'. Error was a %s, original message: %s" % \
(name, type(e), to_text(e))
if errors == 'warn':
display.warning(msg)
elif errors == 'ignore':
display.display(msg, log_only=True)
else:
raise AnsibleError(to_native(msg))
ran = [] if wantlist else None
if ran and not allow_unsafe:
if wantlist:
ran = wrap_var(ran)
else:
try:
ran = UnsafeProxy(",".join(ran))
except TypeError:
# Lookup Plugins should always return lists. Throw an error if that's not
# the case:
if not isinstance(ran, Sequence):
raise AnsibleError("The lookup plugin '%s' did not return a list."
% name)
# The TypeError we can recover from is when the value *inside* of the list
# is not a string
if len(ran) == 1:
ran = wrap_var(ran[0])
else:
ran = wrap_var(ran)
if self.cur_context:
self.cur_context.unsafe = True
return ran
else:
raise AnsibleError("lookup plugin (%s) not found" % name)
def do_template(self, data, preserve_trailing_newlines=True, escape_backslashes=True, fail_on_undefined=None, overrides=None, disable_lookups=False):
if USE_JINJA2_NATIVE and not isinstance(data, string_types):
return data
# For preserving the number of input newlines in the output (used
# later in this method)
data_newlines = _count_newlines_from_end(data)
if fail_on_undefined is None:
fail_on_undefined = self._fail_on_undefined_errors
try:
# allows template header overrides to change jinja2 options.
if overrides is None:
myenv = self.environment.overlay()
else:
myenv = self.environment.overlay(overrides)
# Get jinja env overrides from template
if hasattr(data, 'startswith') and data.startswith(JINJA2_OVERRIDE):
eol = data.find('\n')
line = data[len(JINJA2_OVERRIDE):eol]
data = data[eol + 1:]
for pair in line.split(','):
(key, val) = pair.split(':')
key = key.strip()
setattr(myenv, key, ast.literal_eval(val.strip()))
# Adds Ansible custom filters and tests
myenv.filters.update(self._get_filters())
myenv.tests.update(self._get_tests())
if escape_backslashes:
# Allow users to specify backslashes in playbooks as "\\" instead of as "\\\\".
data = _escape_backslashes(data, myenv)
try:
t = myenv.from_string(data)
except TemplateSyntaxError as e:
raise AnsibleError("template error while templating string: %s. String: %s" % (to_native(e), to_native(data)))
except Exception as e:
if 'recursion' in to_native(e):
raise AnsibleError("recursive loop detected in template string: %s" % to_native(data))
else:
return data
# jinja2 global is inconsistent across versions, this normalizes them
t.globals['dict'] = dict
if disable_lookups:
t.globals['query'] = t.globals['q'] = t.globals['lookup'] = self._fail_lookup
else:
t.globals['lookup'] = self._lookup
t.globals['query'] = t.globals['q'] = self._query_lookup
t.globals['now'] = self._now_datetime
t.globals['finalize'] = self._finalize
jvars = AnsibleJ2Vars(self, t.globals)
self.cur_context = new_context = t.new_context(jvars, shared=True)
rf = t.root_render_func(new_context)
try:
res = j2_concat(rf)
if getattr(new_context, 'unsafe', False):
res = wrap_var(res)
except TypeError as te:
if 'AnsibleUndefined' in to_native(te):
errmsg = "Unable to look up a name or access an attribute in template string (%s).\n" % to_native(data)
errmsg += "Make sure your variable name does not contain invalid characters like '-': %s" % to_native(te)
raise AnsibleUndefinedVariable(errmsg)
else:
display.debug("failing because of a type error, template data is: %s" % to_text(data))
raise AnsibleError("Unexpected templating type error occurred on (%s): %s" % (to_native(data), to_native(te)))
if USE_JINJA2_NATIVE and not isinstance(res, string_types):
return res
if preserve_trailing_newlines:
# The low level calls above do not preserve the newline
# characters at the end of the input data, so we use the
# calculate the difference in newlines and append them
# to the resulting output for parity
#
# jinja2 added a keep_trailing_newline option in 2.7 when
# creating an Environment. That would let us make this code
# better (remove a single newline if
# preserve_trailing_newlines is False). Once we can depend on
# that version being present, modify our code to set that when
# initializing self.environment and remove a single trailing
# newline here if preserve_newlines is False.
res_newlines = _count_newlines_from_end(res)
if data_newlines > res_newlines:
res += self.environment.newline_sequence * (data_newlines - res_newlines)
return res
except (UndefinedError, AnsibleUndefinedVariable) as e:
if fail_on_undefined:
raise AnsibleUndefinedVariable(e)
else:
display.debug("Ignoring undefined failure: %s" % to_text(e))
return data
# for backwards compatibility in case anyone is using old private method directly
_do_template = do_template
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,282 |
jinja2 invalid syntax results in string instead of error
|
##### SUMMARY
An invalid syntax within a jinja2 statement results in the statement being returned instead of an syntax error.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
jinja2
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.9.0.dev0
config file = /etc/ansible/ansible.cfg
configured module search path = ['/home/user/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /home/user/PycharmProjects/ansible-2/lib/ansible
executable location = /home/user/PycharmProjects/ansible-2/bin/ansible
python version = 3.7.3 (default, Mar 26 2019, 21:43:19) [GCC 8.2.1 20181127]
```
##### CONFIGURATION
##### OS / ENVIRONMENT
ArchLinux
##### STEPS TO REPRODUCE
```yaml
- name: Test
hosts: localhost
gather_facts: false
become: false
strategy: linear
tasks:
- debug:
msg: "{{ foo | ipaddr('address')) }}"
```
##### EXPECTED RESULTS
Syntax error (two closing `)`-characters)
##### ACTUAL RESULTS
```paste below
ok: [localhost] => {
"msg": "{{ foo | ipaddr('address')) }}"
}
```
@sivel
|
https://github.com/ansible/ansible/issues/58282
|
https://github.com/ansible/ansible/pull/58290
|
f5b9bd81fcc0334113411f4dbefeb40214bb0837
|
e32d60bbcd44ccc7761268c6d6f00db036db962b
| 2019-06-24T14:50:48Z |
python
| 2019-06-25T15:54:37Z |
test/units/template/test_templar.py
|
# (c) 2012-2014, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from jinja2.runtime import Context
from units.compat import unittest
from units.compat.mock import patch
from ansible import constants as C
from ansible.errors import AnsibleError, AnsibleUndefinedVariable
from ansible.module_utils.six import string_types
from ansible.template import Templar, AnsibleContext, AnsibleEnvironment
from ansible.utils.unsafe_proxy import AnsibleUnsafe, wrap_var
from units.mock.loader import DictDataLoader
class BaseTemplar(object):
def setUp(self):
self.test_vars = dict(
foo="bar",
bam="{{foo}}",
num=1,
var_true=True,
var_false=False,
var_dict=dict(a="b"),
bad_dict="{a='b'",
var_list=[1],
recursive="{{recursive}}",
some_var="blip",
some_static_var="static_blip",
some_keyword="{{ foo }}",
some_unsafe_var=wrap_var("unsafe_blip"),
some_static_unsafe_var=wrap_var("static_unsafe_blip"),
some_unsafe_keyword=wrap_var("{{ foo }}"),
str_with_error="{{ 'str' | from_json }}",
)
self.fake_loader = DictDataLoader({
"/path/to/my_file.txt": "foo\n",
})
self.templar = Templar(loader=self.fake_loader, variables=self.test_vars)
def is_unsafe(self, obj):
if obj is None:
return False
if hasattr(obj, '__UNSAFE__'):
return True
if isinstance(obj, AnsibleUnsafe):
return True
if isinstance(obj, dict):
for key in obj.keys():
if self.is_unsafe(key) or self.is_unsafe(obj[key]):
return True
if isinstance(obj, list):
for item in obj:
if self.is_unsafe(item):
return True
if isinstance(obj, string_types) and hasattr(obj, '__UNSAFE__'):
return True
return False
# class used for testing arbitrary objects passed to template
class SomeClass(object):
foo = 'bar'
def __init__(self):
self.blip = 'blip'
class SomeUnsafeClass(AnsibleUnsafe):
def __init__(self):
super(SomeUnsafeClass, self).__init__()
self.blip = 'unsafe blip'
class TestTemplarTemplate(BaseTemplar, unittest.TestCase):
def test_lookup_jinja_dict_key_in_static_vars(self):
res = self.templar.template("{'some_static_var': '{{ some_var }}'}",
static_vars=['some_static_var'])
# self.assertEqual(res['{{ a_keyword }}'], "blip")
print(res)
def test_is_template_true(self):
tests = [
'{{ foo }}',
'{% foo %}',
'{# foo #}',
'{# {{ foo }} #}',
'{# {{ nothing }} {# #}',
'{# {{ nothing }} {# #} #}',
'{% raw %}{{ foo }}{% endraw %}',
]
for test in tests:
self.assertTrue(self.templar.is_template(test))
def test_is_template_false(self):
tests = [
'foo',
'{{ foo',
'{% foo',
'{# foo',
'{{ foo %}',
'{{ foo #}',
'{% foo }}',
'{% foo #}',
'{# foo %}',
'{# foo }}',
'{{ foo {{',
'{% raw %}{% foo %}',
]
for test in tests:
self.assertFalse(self.templar.is_template(test))
def test_is_template_raw_string(self):
res = self.templar.is_template('foo')
self.assertFalse(res)
def test_is_template_none(self):
res = self.templar.is_template(None)
self.assertFalse(res)
def test_template_convert_bare_string(self):
res = self.templar.template('foo', convert_bare=True)
self.assertEqual(res, 'bar')
def test_template_convert_bare_nested(self):
res = self.templar.template('bam', convert_bare=True)
self.assertEqual(res, 'bar')
def test_template_convert_bare_unsafe(self):
res = self.templar.template('some_unsafe_var', convert_bare=True)
self.assertEqual(res, 'unsafe_blip')
# self.assertIsInstance(res, AnsibleUnsafe)
self.assertTrue(self.is_unsafe(res), 'returned value from template.template (%s) is not marked unsafe' % res)
def test_template_convert_bare_filter(self):
res = self.templar.template('bam|capitalize', convert_bare=True)
self.assertEqual(res, 'Bar')
def test_template_convert_bare_filter_unsafe(self):
res = self.templar.template('some_unsafe_var|capitalize', convert_bare=True)
self.assertEqual(res, 'Unsafe_blip')
# self.assertIsInstance(res, AnsibleUnsafe)
self.assertTrue(self.is_unsafe(res), 'returned value from template.template (%s) is not marked unsafe' % res)
def test_template_convert_data(self):
res = self.templar.template('{{foo}}', convert_data=True)
self.assertTrue(res)
self.assertEqual(res, 'bar')
@patch('ansible.template.safe_eval', side_effect=AnsibleError)
def test_template_convert_data_template_in_data(self, mock_safe_eval):
res = self.templar.template('{{bam}}', convert_data=True)
self.assertTrue(res)
self.assertEqual(res, 'bar')
def test_template_convert_data_bare(self):
res = self.templar.template('bam', convert_data=True)
self.assertTrue(res)
self.assertEqual(res, 'bam')
def test_template_convert_data_to_json(self):
res = self.templar.template('{{bam|to_json}}', convert_data=True)
self.assertTrue(res)
self.assertEqual(res, '"bar"')
def test_template_convert_data_convert_bare_data_bare(self):
res = self.templar.template('bam', convert_data=True, convert_bare=True)
self.assertTrue(res)
self.assertEqual(res, 'bar')
def test_template_unsafe_non_string(self):
unsafe_obj = AnsibleUnsafe()
res = self.templar.template(unsafe_obj)
self.assertTrue(self.is_unsafe(res), 'returned value from template.template (%s) is not marked unsafe' % res)
def test_template_unsafe_non_string_subclass(self):
unsafe_obj = SomeUnsafeClass()
res = self.templar.template(unsafe_obj)
self.assertTrue(self.is_unsafe(res), 'returned value from template.template (%s) is not marked unsafe' % res)
def test_weird(self):
data = u'''1 2 #}huh{# %}ddfg{% }}dfdfg{{ {%what%} {{#foo#}} {%{bar}%} {#%blip%#} {{asdfsd%} 3 4 {{foo}} 5 6 7'''
self.assertRaisesRegexp(AnsibleError,
'template error while templating string',
self.templar.template,
data)
def test_template_with_error(self):
"""Check that AnsibleError is raised, fail if an unhandled exception is raised"""
self.assertRaises(AnsibleError, self.templar.template, "{{ str_with_error }}")
class TestTemplarMisc(BaseTemplar, unittest.TestCase):
def test_templar_simple(self):
templar = self.templar
# test some basic templating
self.assertEqual(templar.template("{{foo}}"), "bar")
self.assertEqual(templar.template("{{foo}}\n"), "bar\n")
self.assertEqual(templar.template("{{foo}}\n", preserve_trailing_newlines=True), "bar\n")
self.assertEqual(templar.template("{{foo}}\n", preserve_trailing_newlines=False), "bar")
self.assertEqual(templar.template("{{bam}}"), "bar")
self.assertEqual(templar.template("{{num}}"), 1)
self.assertEqual(templar.template("{{var_true}}"), True)
self.assertEqual(templar.template("{{var_false}}"), False)
self.assertEqual(templar.template("{{var_dict}}"), dict(a="b"))
self.assertEqual(templar.template("{{bad_dict}}"), "{a='b'")
self.assertEqual(templar.template("{{var_list}}"), [1])
self.assertEqual(templar.template(1, convert_bare=True), 1)
# force errors
self.assertRaises(AnsibleUndefinedVariable, templar.template, "{{bad_var}}")
self.assertRaises(AnsibleUndefinedVariable, templar.template, "{{lookup('file', bad_var)}}")
self.assertRaises(AnsibleError, templar.template, "{{lookup('bad_lookup')}}")
self.assertRaises(AnsibleError, templar.template, "{{recursive}}")
self.assertRaises(AnsibleUndefinedVariable, templar.template, "{{foo-bar}}")
# test with fail_on_undefined=False
self.assertEqual(templar.template("{{bad_var}}", fail_on_undefined=False), "{{bad_var}}")
# test setting available_variables
templar.available_variables = dict(foo="bam")
self.assertEqual(templar.template("{{foo}}"), "bam")
# variables must be a dict() for available_variables setter
# FIXME Use assertRaises() as a context manager (added in 2.7) once we do not run tests on Python 2.6 anymore.
try:
templar.available_variables = "foo=bam"
except AssertionError as e:
pass
except Exception:
self.fail(e)
def test_templar_escape_backslashes(self):
# Rule of thumb: If escape backslashes is True you should end up with
# the same number of backslashes as when you started.
self.assertEqual(self.templar.template("\t{{foo}}", escape_backslashes=True), "\tbar")
self.assertEqual(self.templar.template("\t{{foo}}", escape_backslashes=False), "\tbar")
self.assertEqual(self.templar.template("\\{{foo}}", escape_backslashes=True), "\\bar")
self.assertEqual(self.templar.template("\\{{foo}}", escape_backslashes=False), "\\bar")
self.assertEqual(self.templar.template("\\{{foo + '\t' }}", escape_backslashes=True), "\\bar\t")
self.assertEqual(self.templar.template("\\{{foo + '\t' }}", escape_backslashes=False), "\\bar\t")
self.assertEqual(self.templar.template("\\{{foo + '\\t' }}", escape_backslashes=True), "\\bar\\t")
self.assertEqual(self.templar.template("\\{{foo + '\\t' }}", escape_backslashes=False), "\\bar\t")
self.assertEqual(self.templar.template("\\{{foo + '\\\\t' }}", escape_backslashes=True), "\\bar\\\\t")
self.assertEqual(self.templar.template("\\{{foo + '\\\\t' }}", escape_backslashes=False), "\\bar\\t")
def test_template_jinja2_extensions(self):
fake_loader = DictDataLoader({})
templar = Templar(loader=fake_loader)
old_exts = C.DEFAULT_JINJA2_EXTENSIONS
try:
C.DEFAULT_JINJA2_EXTENSIONS = "foo,bar"
self.assertEqual(templar._get_extensions(), ['foo', 'bar'])
finally:
C.DEFAULT_JINJA2_EXTENSIONS = old_exts
class TestTemplarLookup(BaseTemplar, unittest.TestCase):
def test_lookup_missing_plugin(self):
self.assertRaisesRegexp(AnsibleError,
r'lookup plugin \(not_a_real_lookup_plugin\) not found',
self.templar._lookup,
'not_a_real_lookup_plugin',
'an_arg', a_keyword_arg='a_keyword_arg_value')
def test_lookup_list(self):
res = self.templar._lookup('list', 'an_arg', 'another_arg')
self.assertEqual(res, 'an_arg,another_arg')
def test_lookup_jinja_undefined(self):
self.assertRaisesRegexp(AnsibleUndefinedVariable,
"'an_undefined_jinja_var' is undefined",
self.templar._lookup,
'list', '{{ an_undefined_jinja_var }}')
def test_lookup_jinja_defined(self):
res = self.templar._lookup('list', '{{ some_var }}')
self.assertTrue(self.is_unsafe(res))
# self.assertIsInstance(res, AnsibleUnsafe)
def test_lookup_jinja_dict_string_passed(self):
self.assertRaisesRegexp(AnsibleError,
"with_dict expects a dict",
self.templar._lookup,
'dict',
'{{ some_var }}')
def test_lookup_jinja_dict_list_passed(self):
self.assertRaisesRegexp(AnsibleError,
"with_dict expects a dict",
self.templar._lookup,
'dict',
['foo', 'bar'])
def test_lookup_jinja_kwargs(self):
res = self.templar._lookup('list', 'blip', random_keyword='12345')
self.assertTrue(self.is_unsafe(res))
# self.assertIsInstance(res, AnsibleUnsafe)
def test_lookup_jinja_list_wantlist(self):
res = self.templar._lookup('list', '{{ some_var }}', wantlist=True)
self.assertEqual(res, ["blip"])
def test_lookup_jinja_list_wantlist_undefined(self):
self.assertRaisesRegexp(AnsibleUndefinedVariable,
"'some_undefined_var' is undefined",
self.templar._lookup,
'list',
'{{ some_undefined_var }}',
wantlist=True)
def test_lookup_jinja_list_wantlist_unsafe(self):
res = self.templar._lookup('list', '{{ some_unsafe_var }}', wantlist=True)
for lookup_result in res:
self.assertTrue(self.is_unsafe(lookup_result))
# self.assertIsInstance(lookup_result, AnsibleUnsafe)
# Should this be an AnsibleUnsafe
# self.assertIsInstance(res, AnsibleUnsafe)
def test_lookup_jinja_dict(self):
res = self.templar._lookup('list', {'{{ a_keyword }}': '{{ some_var }}'})
self.assertEqual(res['{{ a_keyword }}'], "blip")
# TODO: Should this be an AnsibleUnsafe
# self.assertIsInstance(res['{{ a_keyword }}'], AnsibleUnsafe)
# self.assertIsInstance(res, AnsibleUnsafe)
def test_lookup_jinja_dict_unsafe(self):
res = self.templar._lookup('list', {'{{ some_unsafe_key }}': '{{ some_unsafe_var }}'})
self.assertTrue(self.is_unsafe(res['{{ some_unsafe_key }}']))
# self.assertIsInstance(res['{{ some_unsafe_key }}'], AnsibleUnsafe)
# TODO: Should this be an AnsibleUnsafe
# self.assertIsInstance(res, AnsibleUnsafe)
def test_lookup_jinja_dict_unsafe_value(self):
res = self.templar._lookup('list', {'{{ a_keyword }}': '{{ some_unsafe_var }}'})
self.assertTrue(self.is_unsafe(res['{{ a_keyword }}']))
# self.assertIsInstance(res['{{ a_keyword }}'], AnsibleUnsafe)
# TODO: Should this be an AnsibleUnsafe
# self.assertIsInstance(res, AnsibleUnsafe)
def test_lookup_jinja_none(self):
res = self.templar._lookup('list', None)
self.assertIsNone(res)
class TestAnsibleContext(BaseTemplar, unittest.TestCase):
def _context(self, variables=None):
variables = variables or {}
env = AnsibleEnvironment()
context = AnsibleContext(env, parent={}, name='some_context',
blocks={})
for key, value in variables.items():
context.vars[key] = value
return context
def test(self):
context = self._context()
self.assertIsInstance(context, AnsibleContext)
self.assertIsInstance(context, Context)
def test_resolve_unsafe(self):
context = self._context(variables={'some_unsafe_key': wrap_var('some_unsafe_string')})
res = context.resolve('some_unsafe_key')
# self.assertIsInstance(res, AnsibleUnsafe)
self.assertTrue(self.is_unsafe(res),
'return of AnsibleContext.resolve (%s) was expected to be marked unsafe but was not' % res)
def test_resolve_unsafe_list(self):
context = self._context(variables={'some_unsafe_key': [wrap_var('some unsafe string 1')]})
res = context.resolve('some_unsafe_key')
# self.assertIsInstance(res[0], AnsibleUnsafe)
self.assertTrue(self.is_unsafe(res),
'return of AnsibleContext.resolve (%s) was expected to be marked unsafe but was not' % res)
def test_resolve_unsafe_dict(self):
context = self._context(variables={'some_unsafe_key':
{'an_unsafe_dict': wrap_var('some unsafe string 1')}
})
res = context.resolve('some_unsafe_key')
self.assertTrue(self.is_unsafe(res['an_unsafe_dict']),
'return of AnsibleContext.resolve (%s) was expected to be marked unsafe but was not' % res['an_unsafe_dict'])
def test_resolve(self):
context = self._context(variables={'some_key': 'some_string'})
res = context.resolve('some_key')
self.assertEqual(res, 'some_string')
# self.assertNotIsInstance(res, AnsibleUnsafe)
self.assertFalse(self.is_unsafe(res),
'return of AnsibleContext.resolve (%s) was not expected to be marked unsafe but was' % res)
def test_resolve_none(self):
context = self._context(variables={'some_key': None})
res = context.resolve('some_key')
self.assertEqual(res, None)
# self.assertNotIsInstance(res, AnsibleUnsafe)
self.assertFalse(self.is_unsafe(res),
'return of AnsibleContext.resolve (%s) was not expected to be marked unsafe but was' % res)
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,418 |
The read_csv integration test fails when LC_ALL is not set.
|
##### SUMMARY
The read_csv integration test fails when LC_ALL is not set.
##### ISSUE TYPE
Bug Report
##### COMPONENT NAME
read_csv
##### ANSIBLE VERSION
devel
##### CONFIGURATION
N/A
##### OS / ENVIRONMENT
N/A
##### STEPS TO REPRODUCE
1. Set `ansible_connection=ssh ansible_host=localhost` for `testhost` to prevent modules from inheriting the environment from the controller: https://github.com/ansible/ansible/blob/edcb5b6775adac09eee5412b499b8f0aa5194610/test/integration/inventory#L6
2. Run the test in an environment where LC_ALL is not set by default: `ansible-test integration read_csv --remote freebsd/12.0 -v`
##### EXPECTED RESULTS
Tests pass.
##### ACTUAL RESULTS
Tests traceback:
```
TASK [read_csv : Read users from CSV file and return a dictionary] ******************************************************************************************************
fatal: [testhost]: FAILED! => {"changed": false, "module_stderr": "Shared connection to localhost closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n File \"/root/.ansible/tmp/ansible-tmp-1561575641.134005-97732254058242/AnsiballZ_read_csv.py\", line 139, in <module>\r\n _ansiballz_main()\r\n File \"/root/.ansible/tmp/ansible-tmp-1561575641.134005-97732254058242/AnsiballZ_read_csv.py\", line 131, in _ansiballz_main\r\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n File \"/root/.ansible/tmp/ansible-tmp-1561575641.134005-97732254058242/AnsiballZ_read_csv.py\", line 65, in invoke_module\r\n spec.loader.exec_module(module)\r\n File \"<frozen importlib._bootstrap_external>\", line 678, in exec_module\r\n File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\r\n File \"/tmp/ansible_read_csv_payload_dllmyumq/__main__.py\", line 235, in <module>\r\n File \"/tmp/ansible_read_csv_payload_dllmyumq/__main__.py\", line 210, in main\r\n File \"/usr/local/lib/python3.6/csv.py\", line 98, in fieldnames\r\n self._fieldnames = next(self.reader)\r\n File \"/usr/local/lib/python3.6/encodings/ascii.py\", line 26, in decode\r\n return codecs.ascii_decode(input, self.errors)[0]\r\nUnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 38: ordinal not in range(128)\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}
```
Failure on Shippable: https://app.shippable.com/github/ansible/ansible/runs/129521/18/tests
|
https://github.com/ansible/ansible/issues/58418
|
https://github.com/ansible/ansible/pull/58450
|
18f95957191af6d4bc6fd8d300097aff6ac966a7
|
de8ac7983252c9338c6bdc80cf33f8f0af247833
| 2019-06-26T19:02:08Z |
python
| 2019-06-27T15:02:35Z |
lib/ansible/modules/files/read_csv.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Dag Wieers (@dagwieers) <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: read_csv
version_added: '2.8'
short_description: Read a CSV file
description:
- Read a CSV file and return a list or a dictionary, containing one dictionary per row.
author:
- Dag Wieers (@dagwieers)
options:
path:
description:
- The CSV filename to read data from.
type: path
required: yes
aliases: [ filename ]
key:
description:
- The column name used as a key for the resulting dictionary.
- If C(key) is unset, the module returns a list of dictionaries,
where each dictionary is a row in the CSV file.
type: str
dialect:
description:
- The CSV dialect to use when parsing the CSV file.
- Possible values include C(excel), C(excel-tab) or C(unix).
type: str
default: excel
fieldnames:
description:
- A list of field names for every column.
- This is needed if the CSV does not have a header.
type: list
unique:
description:
- Whether the C(key) used is expected to be unique.
type: bool
default: yes
delimiter:
description:
- A one-character string used to separate fields.
- When using this parameter, you change the default value used by C(dialect).
- The default value depends on the dialect used.
type: str
skipinitialspace:
description:
- Whether to ignore any whitespaces immediately following the delimiter.
- When using this parameter, you change the default value used by C(dialect).
- The default value depends on the dialect used.
type: bool
strict:
description:
- Whether to raise an exception on bad CSV input.
- When using this parameter, you change the default value used by C(dialect).
- The default value depends on the dialect used.
type: bool
notes:
- Ansible also ships with the C(csvfile) lookup plugin, which can be used to do selective lookups in CSV files from Jinja.
'''
EXAMPLES = r'''
# Example CSV file with header
#
# name,uid,gid
# dag,500,500
# jeroen,501,500
# Read a CSV file and access user 'dag'
- name: Read users from CSV file and return a dictionary
read_csv:
path: users.csv
key: name
register: users
delegate_to: localhost
- debug:
msg: 'User {{ users.dict.dag.name }} has UID {{ users.dict.dag.uid }} and GID {{ users.dict.dag.gid }}'
# Read a CSV file and access the first item
- name: Read users from CSV file and return a list
read_csv:
path: users.csv
register: users
delegate_to: localhost
- debug:
msg: 'User {{ users.list.1.name }} has UID {{ users.list.1.uid }} and GID {{ users.list.1.gid }}'
# Example CSV file without header and semi-colon delimiter
#
# dag;500;500
# jeroen;501;500
# Read a CSV file without headers
- name: Read users from CSV file and return a list
read_csv:
path: users.csv
fieldnames: name,uid,gid
delimiter: ';'
register: users
delegate_to: localhost
'''
RETURN = r'''
dict:
description: The CSV content as a dictionary.
returned: success
type: dict
sample:
dag:
name: dag
uid: 500
gid: 500
jeroen:
name: jeroen
uid: 501
gid: 500
list:
description: The CSV content as a list.
returned: success
type: list
sample:
- name: dag
uid: 500
gid: 500
- name: jeroen
uid: 501
gid: 500
'''
import csv
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_text
# Add Unix dialect from Python 3
class unix_dialect(csv.Dialect):
"""Describe the usual properties of Unix-generated CSV files."""
delimiter = ','
quotechar = '"'
doublequote = True
skipinitialspace = False
lineterminator = '\n'
quoting = csv.QUOTE_ALL
csv.register_dialect("unix", unix_dialect)
def main():
module = AnsibleModule(
argument_spec=dict(
path=dict(type='path', required=True, aliases=['filename']),
dialect=dict(type='str', default='excel'),
key=dict(type='str'),
fieldnames=dict(type='list'),
unique=dict(type='bool', default=True),
delimiter=dict(type='str'),
skipinitialspace=dict(type='bool'),
strict=dict(type='bool'),
),
supports_check_mode=True,
)
path = module.params['path']
dialect = module.params['dialect']
key = module.params['key']
fieldnames = module.params['fieldnames']
unique = module.params['unique']
if dialect not in csv.list_dialects():
module.fail_json(msg="Dialect '%s' is not supported by your version of python." % dialect)
dialect_options = dict(
delimiter=module.params['delimiter'],
skipinitialspace=module.params['skipinitialspace'],
strict=module.params['strict'],
)
# Create a dictionary from only set options
dialect_params = dict((k, v) for k, v in dialect_options.items() if v is not None)
if dialect_params:
try:
csv.register_dialect('custom', dialect, **dialect_params)
except TypeError as e:
module.fail_json(msg="Unable to create custom dialect: %s" % to_text(e))
dialect = 'custom'
try:
f = open(path, 'r')
except (IOError, OSError) as e:
module.fail_json(msg="Unable to open file: %s" % to_text(e))
reader = csv.DictReader(f, fieldnames=fieldnames, dialect=dialect)
if key and key not in reader.fieldnames:
module.fail_json(msg="Key '%s' was not found in the CSV header fields: %s" % (key, ', '.join(reader.fieldnames)))
data_dict = dict()
data_list = list()
if key is None:
try:
for row in reader:
data_list.append(row)
except csv.Error as e:
module.fail_json(msg="Unable to process file: %s" % to_text(e))
else:
try:
for row in reader:
if unique and row[key] in data_dict:
module.fail_json(msg="Key '%s' is not unique for value '%s'" % (key, row[key]))
data_dict[row[key]] = row
except csv.Error as e:
module.fail_json(msg="Unable to process file: %s" % to_text(e))
module.exit_json(dict=data_dict, list=data_list)
if __name__ == '__main__':
main()
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,436 |
Wrong error repot
|
##### SUMMARY
The error message for include task with wrong filename show the parent file (in my example ok.yml instead of typo.yml)
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
import_tasks
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
both
ansible 2.8.1
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/nirr/.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
python version = 2.7.15 (default, Oct 15 2018, 15:26:09) [GCC 8.2.1 20180801 (Red Hat 8.2.1-2)]
and
ansible 2.9.0.dev0
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/nirr/.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
python version = 2.7.15 (default, Oct 15 2018, 15:26:09) [GCC 8.2.1 20180801 (Red Hat 8.2.1-2)]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
ANSIBLE_COW_SELECTION(/etc/ansible/ansible.cfg) = small
ANSIBLE_NOCOWS(/etc/ansible/ansible.cfg) = False
ANSIBLE_PIPELINING(/etc/ansible/ansible.cfg) = True
DEFAULT_BECOME_METHOD(/etc/ansible/ansible.cfg) = sudo
DEFAULT_BECOME_USER(/etc/ansible/ansible.cfg) = root
DEFAULT_CALLBACK_WHITELIST(/etc/ansible/ansible.cfg) = [u'timer']
DEFAULT_FORKS(/etc/ansible/ansible.cfg) = 80
DEFAULT_LIBVIRT_LXC_NOSECLABEL(/etc/ansible/ansible.cfg) = True
DEFAULT_LOAD_CALLBACK_PLUGINS(/etc/ansible/ansible.cfg) = True
DEFAULT_LOG_PATH(/etc/ansible/ansible.cfg) = /home/nirr/.ansible/ansible.log
DEFAULT_POLL_INTERVAL(/etc/ansible/ansible.cfg) = 15
DEFAULT_REMOTE_PORT(/etc/ansible/ansible.cfg) = 23
DEFAULT_REMOTE_USER(/etc/ansible/ansible.cfg) = dev
DEFAULT_ROLES_PATH(/etc/ansible/ansible.cfg) = [u'/tmp/roles', u'/etc/ansible/roles', u'/etc/roles']
DEFAULT_SCP_IF_SSH(/etc/ansible/ansible.cfg) = smart
HOST_KEY_CHECKING(/etc/ansible/ansible.cfg) = False
RETRY_FILES_ENABLED(/etc/ansible/ansible.cfg) = False
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
fedora 29
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
playbook under ./tmp.yml:
```yaml
---
- hosts: localhost
connection: local
gather_facts: no
roles:
- my_role
```
task under ./roles/my_role/main.yml
```yaml
- name: include tasks
include_tasks: "ok.yml"
```
task under ./roles/my_role/ok.yml
```yaml
- name: task with typo
import_tasks: typo.yml
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
as in 2.7.10:
ansible-playbook -i localhost, try.yml
```
fatal: [localhost]: FAILED! => {"reason": "Unable to retrieve file contents\nCould not find or access '/tmp/typo.yml' on the Ansible Controller.\nIf you are using a module and expect the file to exist on the remote, see the remote_src option"}
```
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
ansible-playbook -i localhost, try.yml -vvv
```paste below
ansible-playbook 2.8.1
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/nirr/.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.15 (default, Oct 15 2018, 15:26:09) [GCC 8.2.1 20180801 (Red Hat 8.2.1-2)]
Using /etc/ansible/ansible.cfg as config file
Parsed localhost, inventory source with host_list plugin
___________________
< PLAYBOOK: try.yml >
-------------------
\ ,__,
\ (oo)____
(__) )\
||--|| *
1 plays in try.yml
__________________
< PLAY [localhost] >
------------------
\ ,__,
\ (oo)____
(__) )\
||--|| *
META: ran handlers
________________________________
< TASK [my_role : include tasks] >
--------------------------------
\ ,__,
\ (oo)____
(__) )\
||--|| *
task path: /tmp/roles/my_role/tasks/main.yml:1
fatal: [localhost]: FAILED! => {
"reason": "Could not find or access '/tmp/roles/my_role/tasks/ok.yml' on the Ansible Controller."
}
```
|
https://github.com/ansible/ansible/issues/58436
|
https://github.com/ansible/ansible/pull/58464
|
20ad120829e5e1ee0f51aab4f4f88afc1d956697
|
939e2b4c799b60bac4ceaea649737912a2c9a115
| 2019-06-26T21:19:00Z |
python
| 2019-06-27T19:05:42Z |
changelogs/fragments/58436-include-correct-error.yml
| |
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,436 |
Wrong error repot
|
##### SUMMARY
The error message for include task with wrong filename show the parent file (in my example ok.yml instead of typo.yml)
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
import_tasks
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
both
ansible 2.8.1
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/nirr/.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
python version = 2.7.15 (default, Oct 15 2018, 15:26:09) [GCC 8.2.1 20180801 (Red Hat 8.2.1-2)]
and
ansible 2.9.0.dev0
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/nirr/.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
python version = 2.7.15 (default, Oct 15 2018, 15:26:09) [GCC 8.2.1 20180801 (Red Hat 8.2.1-2)]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
ANSIBLE_COW_SELECTION(/etc/ansible/ansible.cfg) = small
ANSIBLE_NOCOWS(/etc/ansible/ansible.cfg) = False
ANSIBLE_PIPELINING(/etc/ansible/ansible.cfg) = True
DEFAULT_BECOME_METHOD(/etc/ansible/ansible.cfg) = sudo
DEFAULT_BECOME_USER(/etc/ansible/ansible.cfg) = root
DEFAULT_CALLBACK_WHITELIST(/etc/ansible/ansible.cfg) = [u'timer']
DEFAULT_FORKS(/etc/ansible/ansible.cfg) = 80
DEFAULT_LIBVIRT_LXC_NOSECLABEL(/etc/ansible/ansible.cfg) = True
DEFAULT_LOAD_CALLBACK_PLUGINS(/etc/ansible/ansible.cfg) = True
DEFAULT_LOG_PATH(/etc/ansible/ansible.cfg) = /home/nirr/.ansible/ansible.log
DEFAULT_POLL_INTERVAL(/etc/ansible/ansible.cfg) = 15
DEFAULT_REMOTE_PORT(/etc/ansible/ansible.cfg) = 23
DEFAULT_REMOTE_USER(/etc/ansible/ansible.cfg) = dev
DEFAULT_ROLES_PATH(/etc/ansible/ansible.cfg) = [u'/tmp/roles', u'/etc/ansible/roles', u'/etc/roles']
DEFAULT_SCP_IF_SSH(/etc/ansible/ansible.cfg) = smart
HOST_KEY_CHECKING(/etc/ansible/ansible.cfg) = False
RETRY_FILES_ENABLED(/etc/ansible/ansible.cfg) = False
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
fedora 29
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
playbook under ./tmp.yml:
```yaml
---
- hosts: localhost
connection: local
gather_facts: no
roles:
- my_role
```
task under ./roles/my_role/main.yml
```yaml
- name: include tasks
include_tasks: "ok.yml"
```
task under ./roles/my_role/ok.yml
```yaml
- name: task with typo
import_tasks: typo.yml
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
as in 2.7.10:
ansible-playbook -i localhost, try.yml
```
fatal: [localhost]: FAILED! => {"reason": "Unable to retrieve file contents\nCould not find or access '/tmp/typo.yml' on the Ansible Controller.\nIf you are using a module and expect the file to exist on the remote, see the remote_src option"}
```
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
ansible-playbook -i localhost, try.yml -vvv
```paste below
ansible-playbook 2.8.1
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/nirr/.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.15 (default, Oct 15 2018, 15:26:09) [GCC 8.2.1 20180801 (Red Hat 8.2.1-2)]
Using /etc/ansible/ansible.cfg as config file
Parsed localhost, inventory source with host_list plugin
___________________
< PLAYBOOK: try.yml >
-------------------
\ ,__,
\ (oo)____
(__) )\
||--|| *
1 plays in try.yml
__________________
< PLAY [localhost] >
------------------
\ ,__,
\ (oo)____
(__) )\
||--|| *
META: ran handlers
________________________________
< TASK [my_role : include tasks] >
--------------------------------
\ ,__,
\ (oo)____
(__) )\
||--|| *
task path: /tmp/roles/my_role/tasks/main.yml:1
fatal: [localhost]: FAILED! => {
"reason": "Could not find or access '/tmp/roles/my_role/tasks/ok.yml' on the Ansible Controller."
}
```
|
https://github.com/ansible/ansible/issues/58436
|
https://github.com/ansible/ansible/pull/58464
|
20ad120829e5e1ee0f51aab4f4f88afc1d956697
|
939e2b4c799b60bac4ceaea649737912a2c9a115
| 2019-06-26T21:19:00Z |
python
| 2019-06-27T19:05:42Z |
lib/ansible/plugins/strategy/__init__.py
|
# (c) 2012-2014, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import cmd
import functools
import os
import pprint
import sys
import threading
import time
from collections import deque
from multiprocessing import Lock
from jinja2.exceptions import UndefinedError
from ansible import constants as C
from ansible import context
from ansible.errors import AnsibleError, AnsibleFileNotFound, AnsibleParserError, AnsibleUndefinedVariable
from ansible.executor import action_write_locks
from ansible.executor.process.worker import WorkerProcess
from ansible.executor.task_result import TaskResult
from ansible.inventory.host import Host
from ansible.module_utils.six.moves import queue as Queue
from ansible.module_utils.six import iteritems, itervalues, string_types
from ansible.module_utils._text import to_text
from ansible.module_utils.connection import Connection, ConnectionError
from ansible.playbook.helpers import load_list_of_blocks
from ansible.playbook.included_file import IncludedFile
from ansible.playbook.task_include import TaskInclude
from ansible.plugins.loader import action_loader, connection_loader, filter_loader, lookup_loader, module_loader, test_loader
from ansible.template import Templar
from ansible.utils.display import Display
from ansible.utils.vars import combine_vars
from ansible.vars.clean import strip_internal_keys, module_response_deepcopy
display = Display()
__all__ = ['StrategyBase']
class StrategySentinel:
pass
# TODO: this should probably be in the plugins/__init__.py, with
# a smarter mechanism to set all of the attributes based on
# the loaders created there
class SharedPluginLoaderObj:
'''
A simple object to make pass the various plugin loaders to
the forked processes over the queue easier
'''
def __init__(self):
self.action_loader = action_loader
self.connection_loader = connection_loader
self.filter_loader = filter_loader
self.test_loader = test_loader
self.lookup_loader = lookup_loader
self.module_loader = module_loader
_sentinel = StrategySentinel()
def results_thread_main(strategy):
while True:
try:
result = strategy._final_q.get()
if isinstance(result, StrategySentinel):
break
else:
strategy._results_lock.acquire()
strategy._results.append(result)
strategy._results_lock.release()
except (IOError, EOFError):
break
except Queue.Empty:
pass
def debug_closure(func):
"""Closure to wrap ``StrategyBase._process_pending_results`` and invoke the task debugger"""
@functools.wraps(func)
def inner(self, iterator, one_pass=False, max_passes=None):
status_to_stats_map = (
('is_failed', 'failures'),
('is_unreachable', 'dark'),
('is_changed', 'changed'),
('is_skipped', 'skipped'),
)
# We don't know the host yet, copy the previous states, for lookup after we process new results
prev_host_states = iterator._host_states.copy()
results = func(self, iterator, one_pass=one_pass, max_passes=max_passes)
_processed_results = []
for result in results:
task = result._task
host = result._host
_queued_task_args = self._queued_task_cache.pop((host.name, task._uuid), None)
task_vars = _queued_task_args['task_vars']
play_context = _queued_task_args['play_context']
# Try to grab the previous host state, if it doesn't exist use get_host_state to generate an empty state
try:
prev_host_state = prev_host_states[host.name]
except KeyError:
prev_host_state = iterator.get_host_state(host)
while result.needs_debugger(globally_enabled=self.debugger_active):
next_action = NextAction()
dbg = Debugger(task, host, task_vars, play_context, result, next_action)
dbg.cmdloop()
if next_action.result == NextAction.REDO:
# rollback host state
self._tqm.clear_failed_hosts()
iterator._host_states[host.name] = prev_host_state
for method, what in status_to_stats_map:
if getattr(result, method)():
self._tqm._stats.decrement(what, host.name)
self._tqm._stats.decrement('ok', host.name)
# redo
self._queue_task(host, task, task_vars, play_context)
_processed_results.extend(debug_closure(func)(self, iterator, one_pass))
break
elif next_action.result == NextAction.CONTINUE:
_processed_results.append(result)
break
elif next_action.result == NextAction.EXIT:
# Matches KeyboardInterrupt from bin/ansible
sys.exit(99)
else:
_processed_results.append(result)
return _processed_results
return inner
class StrategyBase:
'''
This is the base class for strategy plugins, which contains some common
code useful to all strategies like running handlers, cleanup actions, etc.
'''
def __init__(self, tqm):
self._tqm = tqm
self._inventory = tqm.get_inventory()
self._workers = tqm.get_workers()
self._variable_manager = tqm.get_variable_manager()
self._loader = tqm.get_loader()
self._final_q = tqm._final_q
self._step = context.CLIARGS.get('step', False)
self._diff = context.CLIARGS.get('diff', False)
self.flush_cache = context.CLIARGS.get('flush_cache', False)
# the task cache is a dictionary of tuples of (host.name, task._uuid)
# used to find the original task object of in-flight tasks and to store
# the task args/vars and play context info used to queue the task.
self._queued_task_cache = {}
# Backwards compat: self._display isn't really needed, just import the global display and use that.
self._display = display
# internal counters
self._pending_results = 0
self._cur_worker = 0
# this dictionary is used to keep track of hosts that have
# outstanding tasks still in queue
self._blocked_hosts = dict()
# this dictionary is used to keep track of hosts that have
# flushed handlers
self._flushed_hosts = dict()
self._results = deque()
self._results_lock = threading.Condition(threading.Lock())
# create the result processing thread for reading results in the background
self._results_thread = threading.Thread(target=results_thread_main, args=(self,))
self._results_thread.daemon = True
self._results_thread.start()
# holds the list of active (persistent) connections to be shutdown at
# play completion
self._active_connections = dict()
self.debugger_active = C.ENABLE_TASK_DEBUGGER
def cleanup(self):
# close active persistent connections
for sock in itervalues(self._active_connections):
try:
conn = Connection(sock)
conn.reset()
except ConnectionError as e:
# most likely socket is already closed
display.debug("got an error while closing persistent connection: %s" % e)
self._final_q.put(_sentinel)
self._results_thread.join()
def run(self, iterator, play_context, result=0):
# execute one more pass through the iterator without peeking, to
# make sure that all of the hosts are advanced to their final task.
# This should be safe, as everything should be ITERATING_COMPLETE by
# this point, though the strategy may not advance the hosts itself.
inv_hosts = self._inventory.get_hosts(iterator._play.hosts, order=iterator._play.order)
[iterator.get_next_task_for_host(host) for host in inv_hosts if host.name not in self._tqm._unreachable_hosts]
# save the failed/unreachable hosts, as the run_handlers()
# method will clear that information during its execution
failed_hosts = iterator.get_failed_hosts()
unreachable_hosts = self._tqm._unreachable_hosts.keys()
display.debug("running handlers")
handler_result = self.run_handlers(iterator, play_context)
if isinstance(handler_result, bool) and not handler_result:
result |= self._tqm.RUN_ERROR
elif not handler_result:
result |= handler_result
# now update with the hosts (if any) that failed or were
# unreachable during the handler execution phase
failed_hosts = set(failed_hosts).union(iterator.get_failed_hosts())
unreachable_hosts = set(unreachable_hosts).union(self._tqm._unreachable_hosts.keys())
# return the appropriate code, depending on the status hosts after the run
if not isinstance(result, bool) and result != self._tqm.RUN_OK:
return result
elif len(unreachable_hosts) > 0:
return self._tqm.RUN_UNREACHABLE_HOSTS
elif len(failed_hosts) > 0:
return self._tqm.RUN_FAILED_HOSTS
else:
return self._tqm.RUN_OK
def get_hosts_remaining(self, play):
return [host for host in self._inventory.get_hosts(play.hosts)
if host.name not in self._tqm._failed_hosts and host.name not in self._tqm._unreachable_hosts]
def get_failed_hosts(self, play):
return [host for host in self._inventory.get_hosts(play.hosts) if host.name in self._tqm._failed_hosts]
def add_tqm_variables(self, vars, play):
'''
Base class method to add extra variables/information to the list of task
vars sent through the executor engine regarding the task queue manager state.
'''
vars['ansible_current_hosts'] = [h.name for h in self.get_hosts_remaining(play)]
vars['ansible_failed_hosts'] = [h.name for h in self.get_failed_hosts(play)]
def _queue_task(self, host, task, task_vars, play_context):
''' handles queueing the task up to be sent to a worker '''
display.debug("entering _queue_task() for %s/%s" % (host.name, task.action))
# Add a write lock for tasks.
# Maybe this should be added somewhere further up the call stack but
# this is the earliest in the code where we have task (1) extracted
# into its own variable and (2) there's only a single code path
# leading to the module being run. This is called by three
# functions: __init__.py::_do_handler_run(), linear.py::run(), and
# free.py::run() so we'd have to add to all three to do it there.
# The next common higher level is __init__.py::run() and that has
# tasks inside of play_iterator so we'd have to extract them to do it
# there.
if task.action not in action_write_locks.action_write_locks:
display.debug('Creating lock for %s' % task.action)
action_write_locks.action_write_locks[task.action] = Lock()
# and then queue the new task
try:
# create a dummy object with plugin loaders set as an easier
# way to share them with the forked processes
shared_loader_obj = SharedPluginLoaderObj()
queued = False
starting_worker = self._cur_worker
while True:
worker_prc = self._workers[self._cur_worker]
if worker_prc is None or not worker_prc.is_alive():
self._queued_task_cache[(host.name, task._uuid)] = {
'host': host,
'task': task,
'task_vars': task_vars,
'play_context': play_context
}
worker_prc = WorkerProcess(self._final_q, task_vars, host, task, play_context, self._loader, self._variable_manager, shared_loader_obj)
self._workers[self._cur_worker] = worker_prc
self._tqm.send_callback('v2_runner_on_start', host, task)
worker_prc.start()
display.debug("worker is %d (out of %d available)" % (self._cur_worker + 1, len(self._workers)))
queued = True
self._cur_worker += 1
if self._cur_worker >= len(self._workers):
self._cur_worker = 0
if queued:
break
elif self._cur_worker == starting_worker:
time.sleep(0.0001)
self._pending_results += 1
except (EOFError, IOError, AssertionError) as e:
# most likely an abort
display.debug("got an error while queuing: %s" % e)
return
display.debug("exiting _queue_task() for %s/%s" % (host.name, task.action))
def get_task_hosts(self, iterator, task_host, task):
if task.run_once:
host_list = [host for host in self._inventory.get_hosts(iterator._play.hosts) if host.name not in self._tqm._unreachable_hosts]
else:
host_list = [task_host]
return host_list
def get_delegated_hosts(self, result, task):
host_name = result.get('_ansible_delegated_vars', {}).get('ansible_delegated_host', None)
if host_name is not None:
actual_host = self._inventory.get_host(host_name)
if actual_host is None:
actual_host = Host(name=host_name)
else:
actual_host = Host(name=task.delegate_to)
return [actual_host]
@debug_closure
def _process_pending_results(self, iterator, one_pass=False, max_passes=None):
'''
Reads results off the final queue and takes appropriate action
based on the result (executing callbacks, updating state, etc.).
'''
ret_results = []
def get_original_host(host_name):
# FIXME: this should not need x2 _inventory
host_name = to_text(host_name)
if host_name in self._inventory.hosts:
return self._inventory.hosts[host_name]
else:
return self._inventory.get_host(host_name)
def search_handler_blocks_by_name(handler_name, handler_blocks):
# iterate in reversed order since last handler loaded with the same name wins
for handler_block in reversed(handler_blocks):
for handler_task in handler_block.block:
if handler_task.name:
if not handler_task.cached_name:
handler_vars = self._variable_manager.get_vars(play=iterator._play, task=handler_task)
templar = Templar(loader=self._loader, variables=handler_vars)
handler_task.name = templar.template(handler_task.name)
handler_task.cached_name = True
try:
# first we check with the full result of get_name(), which may
# include the role name (if the handler is from a role). If that
# is not found, we resort to the simple name field, which doesn't
# have anything extra added to it.
if handler_task.name == handler_name:
return handler_task
else:
if handler_task.get_name() == handler_name:
return handler_task
except (UndefinedError, AnsibleUndefinedVariable):
# We skip this handler due to the fact that it may be using
# a variable in the name that was conditionally included via
# set_fact or some other method, and we don't want to error
# out unnecessarily
continue
return None
cur_pass = 0
while True:
try:
self._results_lock.acquire()
task_result = self._results.popleft()
except IndexError:
break
finally:
self._results_lock.release()
# get the original host and task. We then assign them to the TaskResult for use in callbacks/etc.
original_host = get_original_host(task_result._host)
queue_cache_entry = (original_host.name, task_result._task)
found_task = self._queued_task_cache.get(queue_cache_entry)['task']
original_task = found_task.copy(exclude_parent=True, exclude_tasks=True)
original_task._parent = found_task._parent
original_task.from_attrs(task_result._task_fields)
task_result._host = original_host
task_result._task = original_task
# send callbacks for 'non final' results
if '_ansible_retry' in task_result._result:
self._tqm.send_callback('v2_runner_retry', task_result)
continue
elif '_ansible_item_result' in task_result._result:
if task_result.is_failed() or task_result.is_unreachable():
self._tqm.send_callback('v2_runner_item_on_failed', task_result)
elif task_result.is_skipped():
self._tqm.send_callback('v2_runner_item_on_skipped', task_result)
else:
if 'diff' in task_result._result:
if self._diff or getattr(original_task, 'diff', False):
self._tqm.send_callback('v2_on_file_diff', task_result)
self._tqm.send_callback('v2_runner_item_on_ok', task_result)
continue
if original_task.register:
host_list = self.get_task_hosts(iterator, original_host, original_task)
clean_copy = strip_internal_keys(module_response_deepcopy(task_result._result))
if 'invocation' in clean_copy:
del clean_copy['invocation']
for target_host in host_list:
self._variable_manager.set_nonpersistent_facts(target_host, {original_task.register: clean_copy})
# all host status messages contain 2 entries: (msg, task_result)
role_ran = False
if task_result.is_failed():
role_ran = True
ignore_errors = original_task.ignore_errors
if not ignore_errors:
display.debug("marking %s as failed" % original_host.name)
if original_task.run_once:
# if we're using run_once, we have to fail every host here
for h in self._inventory.get_hosts(iterator._play.hosts):
if h.name not in self._tqm._unreachable_hosts:
state, _ = iterator.get_next_task_for_host(h, peek=True)
iterator.mark_host_failed(h)
state, new_task = iterator.get_next_task_for_host(h, peek=True)
else:
iterator.mark_host_failed(original_host)
# grab the current state and if we're iterating on the rescue portion
# of a block then we save the failed task in a special var for use
# within the rescue/always
state, _ = iterator.get_next_task_for_host(original_host, peek=True)
if iterator.is_failed(original_host) and state and state.run_state == iterator.ITERATING_COMPLETE:
self._tqm._failed_hosts[original_host.name] = True
if state and iterator.get_active_state(state).run_state == iterator.ITERATING_RESCUE:
self._tqm._stats.increment('rescued', original_host.name)
self._variable_manager.set_nonpersistent_facts(
original_host,
dict(
ansible_failed_task=original_task.serialize(),
ansible_failed_result=task_result._result,
),
)
else:
self._tqm._stats.increment('failures', original_host.name)
else:
self._tqm._stats.increment('ok', original_host.name)
self._tqm._stats.increment('ignored', original_host.name)
if 'changed' in task_result._result and task_result._result['changed']:
self._tqm._stats.increment('changed', original_host.name)
self._tqm.send_callback('v2_runner_on_failed', task_result, ignore_errors=ignore_errors)
elif task_result.is_unreachable():
ignore_unreachable = original_task.ignore_unreachable
if not ignore_unreachable:
self._tqm._unreachable_hosts[original_host.name] = True
iterator._play._removed_hosts.append(original_host.name)
else:
self._tqm._stats.increment('skipped', original_host.name)
task_result._result['skip_reason'] = 'Host %s is unreachable' % original_host.name
self._tqm._stats.increment('dark', original_host.name)
self._tqm.send_callback('v2_runner_on_unreachable', task_result)
elif task_result.is_skipped():
self._tqm._stats.increment('skipped', original_host.name)
self._tqm.send_callback('v2_runner_on_skipped', task_result)
else:
role_ran = True
if original_task.loop:
# this task had a loop, and has more than one result, so
# loop over all of them instead of a single result
result_items = task_result._result.get('results', [])
else:
result_items = [task_result._result]
for result_item in result_items:
if '_ansible_notify' in result_item:
if task_result.is_changed():
# The shared dictionary for notified handlers is a proxy, which
# does not detect when sub-objects within the proxy are modified.
# So, per the docs, we reassign the list so the proxy picks up and
# notifies all other threads
for handler_name in result_item['_ansible_notify']:
found = False
# Find the handler using the above helper. First we look up the
# dependency chain of the current task (if it's from a role), otherwise
# we just look through the list of handlers in the current play/all
# roles and use the first one that matches the notify name
target_handler = search_handler_blocks_by_name(handler_name, iterator._play.handlers)
if target_handler is not None:
found = True
if target_handler.notify_host(original_host):
self._tqm.send_callback('v2_playbook_on_notify', target_handler, original_host)
for listening_handler_block in iterator._play.handlers:
for listening_handler in listening_handler_block.block:
listeners = getattr(listening_handler, 'listen', []) or []
if handler_name not in listeners:
continue
else:
found = True
if listening_handler.notify_host(original_host):
self._tqm.send_callback('v2_playbook_on_notify', listening_handler, original_host)
# and if none were found, then we raise an error
if not found:
msg = ("The requested handler '%s' was not found in either the main handlers list nor in the listening "
"handlers list" % handler_name)
if C.ERROR_ON_MISSING_HANDLER:
raise AnsibleError(msg)
else:
display.warning(msg)
if 'add_host' in result_item:
# this task added a new host (add_host module)
new_host_info = result_item.get('add_host', dict())
self._add_host(new_host_info, iterator)
elif 'add_group' in result_item:
# this task added a new group (group_by module)
self._add_group(original_host, result_item)
if 'ansible_facts' in result_item:
# if delegated fact and we are delegating facts, we need to change target host for them
if original_task.delegate_to is not None and original_task.delegate_facts:
host_list = self.get_delegated_hosts(result_item, original_task)
else:
host_list = self.get_task_hosts(iterator, original_host, original_task)
if original_task.action == 'include_vars':
for (var_name, var_value) in iteritems(result_item['ansible_facts']):
# find the host we're actually referring too here, which may
# be a host that is not really in inventory at all
for target_host in host_list:
self._variable_manager.set_host_variable(target_host, var_name, var_value)
else:
cacheable = result_item.pop('_ansible_facts_cacheable', False)
for target_host in host_list:
# so set_fact is a misnomer but 'cacheable = true' was meant to create an 'actual fact'
# to avoid issues with precedence and confusion with set_fact normal operation,
# we set BOTH fact and nonpersistent_facts (aka hostvar)
# when fact is retrieved from cache in subsequent operations it will have the lower precedence,
# but for playbook setting it the 'higher' precedence is kept
if original_task.action != 'set_fact' or cacheable:
self._variable_manager.set_host_facts(target_host, result_item['ansible_facts'].copy())
if original_task.action == 'set_fact':
self._variable_manager.set_nonpersistent_facts(target_host, result_item['ansible_facts'].copy())
if 'ansible_stats' in result_item and 'data' in result_item['ansible_stats'] and result_item['ansible_stats']['data']:
if 'per_host' not in result_item['ansible_stats'] or result_item['ansible_stats']['per_host']:
host_list = self.get_task_hosts(iterator, original_host, original_task)
else:
host_list = [None]
data = result_item['ansible_stats']['data']
aggregate = 'aggregate' in result_item['ansible_stats'] and result_item['ansible_stats']['aggregate']
for myhost in host_list:
for k in data.keys():
if aggregate:
self._tqm._stats.update_custom_stats(k, data[k], myhost)
else:
self._tqm._stats.set_custom_stats(k, data[k], myhost)
if 'diff' in task_result._result:
if self._diff or getattr(original_task, 'diff', False):
self._tqm.send_callback('v2_on_file_diff', task_result)
if not isinstance(original_task, TaskInclude):
self._tqm._stats.increment('ok', original_host.name)
if 'changed' in task_result._result and task_result._result['changed']:
self._tqm._stats.increment('changed', original_host.name)
# finally, send the ok for this task
self._tqm.send_callback('v2_runner_on_ok', task_result)
self._pending_results -= 1
if original_host.name in self._blocked_hosts:
del self._blocked_hosts[original_host.name]
# If this is a role task, mark the parent role as being run (if
# the task was ok or failed, but not skipped or unreachable)
if original_task._role is not None and role_ran: # TODO: and original_task.action != 'include_role':?
# lookup the role in the ROLE_CACHE to make sure we're dealing
# with the correct object and mark it as executed
for (entry, role_obj) in iteritems(iterator._play.ROLE_CACHE[original_task._role._role_name]):
if role_obj._uuid == original_task._role._uuid:
role_obj._had_task_run[original_host.name] = True
ret_results.append(task_result)
if one_pass or max_passes is not None and (cur_pass + 1) >= max_passes:
break
cur_pass += 1
return ret_results
def _wait_on_handler_results(self, iterator, handler, notified_hosts):
'''
Wait for the handler tasks to complete, using a short sleep
between checks to ensure we don't spin lock
'''
ret_results = []
handler_results = 0
display.debug("waiting for handler results...")
while (self._pending_results > 0 and
handler_results < len(notified_hosts) and
not self._tqm._terminated):
if self._tqm.has_dead_workers():
raise AnsibleError("A worker was found in a dead state")
results = self._process_pending_results(iterator)
ret_results.extend(results)
handler_results += len([
r._host for r in results if r._host in notified_hosts and
r.task_name == handler.name])
if self._pending_results > 0:
time.sleep(C.DEFAULT_INTERNAL_POLL_INTERVAL)
display.debug("no more pending handlers, returning what we have")
return ret_results
def _wait_on_pending_results(self, iterator):
'''
Wait for the shared counter to drop to zero, using a short sleep
between checks to ensure we don't spin lock
'''
ret_results = []
display.debug("waiting for pending results...")
while self._pending_results > 0 and not self._tqm._terminated:
if self._tqm.has_dead_workers():
raise AnsibleError("A worker was found in a dead state")
results = self._process_pending_results(iterator)
ret_results.extend(results)
if self._pending_results > 0:
time.sleep(C.DEFAULT_INTERNAL_POLL_INTERVAL)
display.debug("no more pending results, returning what we have")
return ret_results
def _add_host(self, host_info, iterator):
'''
Helper function to add a new host to inventory based on a task result.
'''
if host_info:
host_name = host_info.get('host_name')
# Check if host in inventory, add if not
if host_name not in self._inventory.hosts:
self._inventory.add_host(host_name, 'all')
new_host = self._inventory.hosts.get(host_name)
# Set/update the vars for this host
new_host.vars = combine_vars(new_host.get_vars(), host_info.get('host_vars', dict()))
new_groups = host_info.get('groups', [])
for group_name in new_groups:
if group_name not in self._inventory.groups:
self._inventory.add_group(group_name)
new_group = self._inventory.groups[group_name]
new_group.add_host(self._inventory.hosts[host_name])
# reconcile inventory, ensures inventory rules are followed
self._inventory.reconcile_inventory()
def _add_group(self, host, result_item):
'''
Helper function to add a group (if it does not exist), and to assign the
specified host to that group.
'''
changed = False
# the host here is from the executor side, which means it was a
# serialized/cloned copy and we'll need to look up the proper
# host object from the master inventory
real_host = self._inventory.hosts.get(host.name)
if real_host is None:
if host.name == self._inventory.localhost.name:
real_host = self._inventory.localhost
else:
raise AnsibleError('%s cannot be matched in inventory' % host.name)
group_name = result_item.get('add_group')
parent_group_names = result_item.get('parent_groups', [])
for name in [group_name] + parent_group_names:
if name not in self._inventory.groups:
# create the new group and add it to inventory
self._inventory.add_group(name)
changed = True
group = self._inventory.groups[group_name]
for parent_group_name in parent_group_names:
parent_group = self._inventory.groups[parent_group_name]
parent_group.add_child_group(group)
if real_host.name not in group.get_hosts():
group.add_host(real_host)
changed = True
if group_name not in host.get_groups():
real_host.add_group(group)
changed = True
if changed:
self._inventory.reconcile_inventory()
return changed
def _copy_included_file(self, included_file):
'''
A proven safe and performant way to create a copy of an included file
'''
ti_copy = included_file._task.copy(exclude_parent=True)
ti_copy._parent = included_file._task._parent
temp_vars = ti_copy.vars.copy()
temp_vars.update(included_file._vars)
ti_copy.vars = temp_vars
return ti_copy
def _load_included_file(self, included_file, iterator, is_handler=False):
'''
Loads an included YAML file of tasks, applying the optional set of variables.
'''
display.debug("loading included file: %s" % included_file._filename)
try:
data = self._loader.load_from_file(included_file._filename)
if data is None:
return []
elif not isinstance(data, list):
raise AnsibleError("included task files must contain a list of tasks")
ti_copy = self._copy_included_file(included_file)
# pop tags out of the include args, if they were specified there, and assign
# them to the include. If the include already had tags specified, we raise an
# error so that users know not to specify them both ways
tags = included_file._task.vars.pop('tags', [])
if isinstance(tags, string_types):
tags = tags.split(',')
if len(tags) > 0:
if len(included_file._task.tags) > 0:
raise AnsibleParserError("Include tasks should not specify tags in more than one way (both via args and directly on the task). "
"Mixing tag specify styles is prohibited for whole import hierarchy, not only for single import statement",
obj=included_file._task._ds)
display.deprecated("You should not specify tags in the include parameters. All tags should be specified using the task-level option",
version='2.12')
included_file._task.tags = tags
block_list = load_list_of_blocks(
data,
play=iterator._play,
parent_block=ti_copy.build_parent_block(),
role=included_file._task._role,
use_handlers=is_handler,
loader=self._loader,
variable_manager=self._variable_manager,
)
# since we skip incrementing the stats when the task result is
# first processed, we do so now for each host in the list
for host in included_file._hosts:
self._tqm._stats.increment('ok', host.name)
except AnsibleError as e:
if isinstance(e, AnsibleFileNotFound):
reason = "Could not find or access '%s' on the Ansible Controller." % to_text(included_file._filename)
else:
reason = to_text(e)
# mark all of the hosts including this file as failed, send callbacks,
# and increment the stats for this host
for host in included_file._hosts:
tr = TaskResult(host=host, task=included_file._task, return_data=dict(failed=True, reason=reason))
iterator.mark_host_failed(host)
self._tqm._failed_hosts[host.name] = True
self._tqm._stats.increment('failures', host.name)
self._tqm.send_callback('v2_runner_on_failed', tr)
return []
# finally, send the callback and return the list of blocks loaded
self._tqm.send_callback('v2_playbook_on_include', included_file)
display.debug("done processing included file")
return block_list
def run_handlers(self, iterator, play_context):
'''
Runs handlers on those hosts which have been notified.
'''
result = self._tqm.RUN_OK
for handler_block in iterator._play.handlers:
# FIXME: handlers need to support the rescue/always portions of blocks too,
# but this may take some work in the iterator and gets tricky when
# we consider the ability of meta tasks to flush handlers
for handler in handler_block.block:
if handler.notified_hosts:
result = self._do_handler_run(handler, handler.get_name(), iterator=iterator, play_context=play_context)
if not result:
break
return result
def _do_handler_run(self, handler, handler_name, iterator, play_context, notified_hosts=None):
# FIXME: need to use iterator.get_failed_hosts() instead?
# if not len(self.get_hosts_remaining(iterator._play)):
# self._tqm.send_callback('v2_playbook_on_no_hosts_remaining')
# result = False
# break
if notified_hosts is None:
notified_hosts = handler.notified_hosts[:]
notified_hosts = self._filter_notified_hosts(notified_hosts)
if len(notified_hosts) > 0:
saved_name = handler.name
handler.name = handler_name
self._tqm.send_callback('v2_playbook_on_handler_task_start', handler)
handler.name = saved_name
bypass_host_loop = False
try:
action = action_loader.get(handler.action, class_only=True)
if getattr(action, 'BYPASS_HOST_LOOP', False):
bypass_host_loop = True
except KeyError:
# we don't care here, because the action may simply not have a
# corresponding action plugin
pass
host_results = []
for host in notified_hosts:
if not iterator.is_failed(host) or iterator._play.force_handlers:
task_vars = self._variable_manager.get_vars(play=iterator._play, host=host, task=handler)
self.add_tqm_variables(task_vars, play=iterator._play)
self._queue_task(host, handler, task_vars, play_context)
templar = Templar(loader=self._loader, variables=task_vars)
if templar.template(handler.run_once) or bypass_host_loop:
break
# collect the results from the handler run
host_results = self._wait_on_handler_results(iterator, handler, notified_hosts)
included_files = IncludedFile.process_include_results(
host_results,
iterator=iterator,
loader=self._loader,
variable_manager=self._variable_manager
)
result = True
if len(included_files) > 0:
for included_file in included_files:
try:
new_blocks = self._load_included_file(included_file, iterator=iterator, is_handler=True)
# for every task in each block brought in by the include, add the list
# of hosts which included the file to the notified_handlers dict
for block in new_blocks:
iterator._play.handlers.append(block)
for task in block.block:
task_name = task.get_name()
display.debug("adding task '%s' included in handler '%s'" % (task_name, handler_name))
task.notified_hosts = included_file._hosts[:]
result = self._do_handler_run(
handler=task,
handler_name=task_name,
iterator=iterator,
play_context=play_context,
notified_hosts=included_file._hosts[:],
)
if not result:
break
except AnsibleError as e:
for host in included_file._hosts:
iterator.mark_host_failed(host)
self._tqm._failed_hosts[host.name] = True
display.warning(to_text(e))
continue
# remove hosts from notification list
handler.notified_hosts = [
h for h in handler.notified_hosts
if h not in notified_hosts]
display.debug("done running handlers, result is: %s" % result)
return result
def _filter_notified_hosts(self, notified_hosts):
'''
Filter notified hosts accordingly to strategy
'''
# As main strategy is linear, we do not filter hosts
# We return a copy to avoid race conditions
return notified_hosts[:]
def _take_step(self, task, host=None):
ret = False
msg = u'Perform task: %s ' % task
if host:
msg += u'on %s ' % host
msg += u'(N)o/(y)es/(c)ontinue: '
resp = display.prompt(msg)
if resp.lower() in ['y', 'yes']:
display.debug("User ran task")
ret = True
elif resp.lower() in ['c', 'continue']:
display.debug("User ran task and canceled step mode")
self._step = False
ret = True
else:
display.debug("User skipped task")
display.banner(msg)
return ret
def _cond_not_supported_warn(self, task_name):
display.warning("%s task does not support when conditional" % task_name)
def _execute_meta(self, task, play_context, iterator, target_host):
# meta tasks store their args in the _raw_params field of args,
# since they do not use k=v pairs, so get that
meta_action = task.args.get('_raw_params')
def _evaluate_conditional(h):
all_vars = self._variable_manager.get_vars(play=iterator._play, host=h, task=task)
templar = Templar(loader=self._loader, variables=all_vars)
return task.evaluate_conditional(templar, all_vars)
skipped = False
msg = ''
if meta_action == 'noop':
# FIXME: issue a callback for the noop here?
if task.when:
self._cond_not_supported_warn(meta_action)
msg = "noop"
elif meta_action == 'flush_handlers':
if task.when:
self._cond_not_supported_warn(meta_action)
self._flushed_hosts[target_host] = True
self.run_handlers(iterator, play_context)
self._flushed_hosts[target_host] = False
msg = "ran handlers"
elif meta_action == 'refresh_inventory' or self.flush_cache:
if task.when:
self._cond_not_supported_warn(meta_action)
self._inventory.refresh_inventory()
msg = "inventory successfully refreshed"
elif meta_action == 'clear_facts':
if _evaluate_conditional(target_host):
for host in self._inventory.get_hosts(iterator._play.hosts):
hostname = host.get_name()
self._variable_manager.clear_facts(hostname)
msg = "facts cleared"
else:
skipped = True
elif meta_action == 'clear_host_errors':
if _evaluate_conditional(target_host):
for host in self._inventory.get_hosts(iterator._play.hosts):
self._tqm._failed_hosts.pop(host.name, False)
self._tqm._unreachable_hosts.pop(host.name, False)
iterator._host_states[host.name].fail_state = iterator.FAILED_NONE
msg = "cleared host errors"
else:
skipped = True
elif meta_action == 'end_play':
if _evaluate_conditional(target_host):
for host in self._inventory.get_hosts(iterator._play.hosts):
if host.name not in self._tqm._unreachable_hosts:
iterator._host_states[host.name].run_state = iterator.ITERATING_COMPLETE
msg = "ending play"
elif meta_action == 'end_host':
if _evaluate_conditional(target_host):
iterator._host_states[target_host.name].run_state = iterator.ITERATING_COMPLETE
msg = "ending play for %s" % target_host.name
else:
skipped = True
msg = "end_host conditional evaluated to false, continuing execution for %s" % target_host.name
elif meta_action == 'reset_connection':
all_vars = self._variable_manager.get_vars(play=iterator._play, host=target_host, task=task)
templar = Templar(loader=self._loader, variables=all_vars)
# apply the given task's information to the connection info,
# which may override some fields already set by the play or
# the options specified on the command line
play_context = play_context.set_task_and_variable_override(task=task, variables=all_vars, templar=templar)
# fields set from the play/task may be based on variables, so we have to
# do the same kind of post validation step on it here before we use it.
play_context.post_validate(templar=templar)
# now that the play context is finalized, if the remote_addr is not set
# default to using the host's address field as the remote address
if not play_context.remote_addr:
play_context.remote_addr = target_host.address
# We also add "magic" variables back into the variables dict to make sure
# a certain subset of variables exist.
play_context.update_vars(all_vars)
if task.when:
self._cond_not_supported_warn(meta_action)
if target_host in self._active_connections:
connection = Connection(self._active_connections[target_host])
del self._active_connections[target_host]
else:
connection = connection_loader.get(play_context.connection, play_context, os.devnull)
play_context.set_attributes_from_plugin(connection)
if connection:
try:
connection.reset()
msg = 'reset connection'
except ConnectionError as e:
# most likely socket is already closed
display.debug("got an error while closing persistent connection: %s" % e)
else:
msg = 'no connection, nothing to reset'
else:
raise AnsibleError("invalid meta action requested: %s" % meta_action, obj=task._ds)
result = {'msg': msg}
if skipped:
result['skipped'] = True
else:
result['changed'] = False
display.vv("META: %s" % msg)
return [TaskResult(target_host, task, result)]
def get_hosts_left(self, iterator):
''' returns list of available hosts for this iterator by filtering out unreachables '''
hosts_left = []
for host in self._inventory.get_hosts(iterator._play.hosts, order=iterator._play.order):
if host.name not in self._tqm._unreachable_hosts:
hosts_left.append(host)
return hosts_left
def update_active_connections(self, results):
''' updates the current active persistent connections '''
for r in results:
if 'args' in r._task_fields:
socket_path = r._task_fields['args'].get('_ansible_socket')
if socket_path:
if r._host not in self._active_connections:
self._active_connections[r._host] = socket_path
class NextAction(object):
""" The next action after an interpreter's exit. """
REDO = 1
CONTINUE = 2
EXIT = 3
def __init__(self, result=EXIT):
self.result = result
class Debugger(cmd.Cmd):
prompt_continuous = '> ' # multiple lines
def __init__(self, task, host, task_vars, play_context, result, next_action):
# cmd.Cmd is old-style class
cmd.Cmd.__init__(self)
self.prompt = '[%s] %s (debug)> ' % (host, task)
self.intro = None
self.scope = {}
self.scope['task'] = task
self.scope['task_vars'] = task_vars
self.scope['host'] = host
self.scope['play_context'] = play_context
self.scope['result'] = result
self.next_action = next_action
def cmdloop(self):
try:
cmd.Cmd.cmdloop(self)
except KeyboardInterrupt:
pass
do_h = cmd.Cmd.do_help
def do_EOF(self, args):
"""Quit"""
return self.do_quit(args)
def do_quit(self, args):
"""Quit"""
display.display('User interrupted execution')
self.next_action.result = NextAction.EXIT
return True
do_q = do_quit
def do_continue(self, args):
"""Continue to next result"""
self.next_action.result = NextAction.CONTINUE
return True
do_c = do_continue
def do_redo(self, args):
"""Schedule task for re-execution. The re-execution may not be the next result"""
self.next_action.result = NextAction.REDO
return True
do_r = do_redo
def do_update_task(self, args):
"""Recreate the task from ``task._ds``, and template with updated ``task_vars``"""
templar = Templar(None, shared_loader_obj=None, variables=self.scope['task_vars'])
task = self.scope['task']
task = task.load_data(task._ds)
task.post_validate(templar)
self.scope['task'] = task
do_u = do_update_task
def evaluate(self, args):
try:
return eval(args, globals(), self.scope)
except Exception:
t, v = sys.exc_info()[:2]
if isinstance(t, str):
exc_type_name = t
else:
exc_type_name = t.__name__
display.display('***%s:%s' % (exc_type_name, repr(v)))
raise
def do_pprint(self, args):
"""Pretty Print"""
try:
result = self.evaluate(args)
display.display(pprint.pformat(result))
except Exception:
pass
do_p = do_pprint
def execute(self, args):
try:
code = compile(args + '\n', '<stdin>', 'single')
exec(code, globals(), self.scope)
except Exception:
t, v = sys.exc_info()[:2]
if isinstance(t, str):
exc_type_name = t
else:
exc_type_name = t.__name__
display.display('***%s:%s' % (exc_type_name, repr(v)))
raise
def default(self, line):
try:
self.execute(line)
except Exception:
pass
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,240 |
set_fact and run_once incorrectly setting facts
|
##### SUMMARY
If set_fact is used with run_once the fact gets applied to all hosts.
Edit: Documentation should mention `delegate_facts: True` is required.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
run_once
##### ANSIBLE VERSION
```paste below
ansible 2.9.0.dev0
config file = /etc/ansible/ansible.cfg
configured module search path = ['/home/user/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /home/user/PycharmProjects/ansible-2/lib/ansible
executable location = /home/user/PycharmProjects/ansible-2/bin/ansible
python version = 3.7.3 (default, Mar 26 2019, 21:43:19) [GCC 8.2.1 20181127]
```
##### CONFIGURATION
##### OS / ENVIRONMENT
ArchLinux
##### STEPS TO REPRODUCE
There are at least two hosts in the group TestGroup
```yaml
- name: Test
hosts: TestGroup
become: false
gather_facts: false
tasks:
- set_fact:
foo: foo
- run_once: yes
block:
- set_fact:
foo: bar
- ping: null
when: foo == "bar"
```
##### EXPECTED RESULTS
The final ping gets executed for all hosts except the one that was randomly chosen for the RunOnce block.
##### ACTUAL RESULTS
The final ping gets skipped for all hosts.
|
https://github.com/ansible/ansible/issues/58240
|
https://github.com/ansible/ansible/pull/58241
|
1b90e10cf0c77e770cb217d99f6e9fe3b4833408
|
ee52b60d7dacc86f6b4a41083ca033a024f63949
| 2019-06-22T20:34:04Z |
python
| 2019-06-27T21:19:22Z |
docs/docsite/rst/user_guide/playbooks_delegation.rst
|
.. _playbooks_delegation:
Delegation, Rolling Updates, and Local Actions
==============================================
.. contents:: Topics
Being designed for multi-tier deployments since the beginning, Ansible is great at doing things on one host on behalf of another, or doing local steps with reference to some remote hosts.
This in particular is very applicable when setting up continuous deployment infrastructure or zero downtime rolling updates, where you might be talking with load balancers or monitoring systems.
Additional features allow for tuning the orders in which things complete, and assigning a batch window size for how many machines to process at once during a rolling update.
This section covers all of these features. For examples of these items in use, `please see the ansible-examples repository <https://github.com/ansible/ansible-examples/>`_. There are quite a few examples of zero-downtime update procedures for different kinds of applications.
You should also consult the :ref:`module documentation<modules_by_category>` section. Modules like :ref:`ec2_elb<ec2_elb_module>`, :ref:`nagios<nagios_module>`, :ref:`bigip_pool<bigip_pool_module>`, and other :ref:`network_modules` dovetail neatly with the concepts mentioned here.
You'll also want to read up on :ref:`playbooks_reuse_roles`, as the 'pre_task' and 'post_task' concepts are the places where you would typically call these modules.
Be aware that certain tasks are impossible to delegate, i.e. `include`, `add_host`, `debug`, etc as they always execute on the controller.
.. _rolling_update_batch_size:
Rolling Update Batch Size
`````````````````````````
By default, Ansible will try to manage all of the machines referenced in a play in parallel. For a rolling update use case, you can define how many hosts Ansible should manage at a single time by using the ``serial`` keyword::
- name: test play
hosts: webservers
serial: 2
gather_facts: False
tasks:
- name: task one
command: hostname
- name: task two
command: hostname
In the above example, if we had 4 hosts in the group 'webservers', 2
would complete the play completely before moving on to the next 2 hosts::
PLAY [webservers] ****************************************
TASK [task one] ******************************************
changed: [web2]
changed: [web1]
TASK [task two] ******************************************
changed: [web1]
changed: [web2]
PLAY [webservers] ****************************************
TASK [task one] ******************************************
changed: [web3]
changed: [web4]
TASK [task two] ******************************************
changed: [web3]
changed: [web4]
PLAY RECAP ***********************************************
web1 : ok=2 changed=2 unreachable=0 failed=0
web2 : ok=2 changed=2 unreachable=0 failed=0
web3 : ok=2 changed=2 unreachable=0 failed=0
web4 : ok=2 changed=2 unreachable=0 failed=0
The ``serial`` keyword can also be specified as a percentage, which will be applied to the total number of hosts in a
play, in order to determine the number of hosts per pass::
- name: test play
hosts: webservers
serial: "30%"
If the number of hosts does not divide equally into the number of passes, the final pass will contain the remainder.
As of Ansible 2.2, the batch sizes can be specified as a list, as follows::
- name: test play
hosts: webservers
serial:
- 1
- 5
- 10
In the above example, the first batch would contain a single host, the next would contain 5 hosts, and (if there are any hosts left),
every following batch would contain 10 hosts until all available hosts are used.
It is also possible to list multiple batch sizes as percentages::
- name: test play
hosts: webservers
serial:
- "10%"
- "20%"
- "100%"
You can also mix and match the values::
- name: test play
hosts: webservers
serial:
- 1
- 5
- "20%"
.. note::
No matter how small the percentage, the number of hosts per pass will always be 1 or greater.
.. _maximum_failure_percentage:
Maximum Failure Percentage
``````````````````````````
By default, Ansible will continue executing actions as long as there are hosts in the batch that have not yet failed. The batch size for a play is determined by the ``serial`` parameter. If ``serial`` is not set, then batch size is all the hosts specified in the ``hosts:`` field.
In some situations, such as with the rolling updates described above, it may be desirable to abort the play when a
certain threshold of failures have been reached. To achieve this, you can set a maximum failure
percentage on a play as follows::
- hosts: webservers
max_fail_percentage: 30
serial: 10
In the above example, if more than 3 of the 10 servers in the group were to fail, the rest of the play would be aborted.
.. note::
The percentage set must be exceeded, not equaled. For example, if serial were set to 4 and you wanted the task to abort
when 2 of the systems failed, the percentage should be set at 49 rather than 50.
.. _delegation:
Delegation
``````````
This isn't actually rolling update specific but comes up frequently in those cases.
If you want to perform a task on one host with reference to other hosts, use the 'delegate_to' keyword on a task.
This is ideal for placing nodes in a load balanced pool, or removing them. It is also very useful for controlling outage windows.
Be aware that it does not make sense to delegate all tasks, debug, add_host, include, etc always get executed on the controller.
Using this with the 'serial' keyword to control the number of hosts executing at one time is also a good idea::
---
- hosts: webservers
serial: 5
tasks:
- name: take out of load balancer pool
command: /usr/bin/take_out_of_pool {{ inventory_hostname }}
delegate_to: 127.0.0.1
- name: actual steps would go here
yum:
name: acme-web-stack
state: latest
- name: add back to load balancer pool
command: /usr/bin/add_back_to_pool {{ inventory_hostname }}
delegate_to: 127.0.0.1
These commands will run on 127.0.0.1, which is the machine running Ansible. There is also a shorthand syntax that you can use on a per-task basis: 'local_action'. Here is the same playbook as above, but using the shorthand syntax for delegating to 127.0.0.1::
---
# ...
tasks:
- name: take out of load balancer pool
local_action: command /usr/bin/take_out_of_pool {{ inventory_hostname }}
# ...
- name: add back to load balancer pool
local_action: command /usr/bin/add_back_to_pool {{ inventory_hostname }}
A common pattern is to use a local action to call 'rsync' to recursively copy files to the managed servers.
Here is an example::
---
# ...
tasks:
- name: recursively copy files from management server to target
local_action: command rsync -a /path/to/files {{ inventory_hostname }}:/path/to/target/
Note that you must have passphrase-less SSH keys or an ssh-agent configured for this to work, otherwise rsync
will need to ask for a passphrase.
In case you have to specify more arguments you can use the following syntax::
---
# ...
tasks:
- name: Send summary mail
local_action:
module: mail
subject: "Summary Mail"
to: "{{ mail_recipient }}"
body: "{{ mail_body }}"
run_once: True
The `ansible_host` variable (`ansible_ssh_host` in 1.x or specific to ssh/paramiko plugins) reflects the host a task is delegated to.
.. _delegate_facts:
Delegated facts
```````````````
By default, any fact gathered by a delegated task are assigned to the `inventory_hostname` (the current host) instead of the host which actually produced the facts (the delegated to host).
The directive `delegate_facts` may be set to `True` to assign the task's gathered facts to the delegated host instead of the current one.::
- hosts: app_servers
tasks:
- name: gather facts from db servers
setup:
delegate_to: "{{item}}"
delegate_facts: True
loop: "{{groups['dbservers']}}"
The above will gather facts for the machines in the dbservers group and assign the facts to those machines and not to app_servers.
This way you can lookup `hostvars['dbhost1']['ansible_default_ipv4']['address']` even though dbservers were not part of the play, or left out by using `--limit`.
.. _run_once:
Run Once
````````
In some cases there may be a need to only run a task one time for a batch of hosts.
This can be achieved by configuring "run_once" on a task::
---
# ...
tasks:
# ...
- command: /opt/application/upgrade_db.py
run_once: true
# ...
This directive forces the task to attempt execution on the first host in the current batch and then applies all results and facts to all the hosts in the same batch.
This approach is similar to applying a conditional to a task such as::
- command: /opt/application/upgrade_db.py
when: inventory_hostname == webservers[0]
But the results are applied to all the hosts.
Like most tasks, this can be optionally paired with "delegate_to" to specify an individual host to execute on::
- command: /opt/application/upgrade_db.py
run_once: true
delegate_to: web01.example.org
As always with delegation, the action will be executed on the delegated host, but the information is still that of the original host in the task.
.. note::
When used together with "serial", tasks marked as "run_once" will be run on one host in *each* serial batch.
If it's crucial that the task is run only once regardless of "serial" mode, use
:code:`when: inventory_hostname == ansible_play_hosts_all[0]` construct.
.. note::
Any conditional (i.e `when:`) will use the variables of the 'first host' to decide if the task runs or not, no other hosts will be tested.
.. _local_playbooks:
Local Playbooks
```````````````
It may be useful to use a playbook locally, rather than by connecting over SSH. This can be useful
for assuring the configuration of a system by putting a playbook in a crontab. This may also be used
to run a playbook inside an OS installer, such as an Anaconda kickstart.
To run an entire playbook locally, just set the "hosts:" line to "hosts: 127.0.0.1" and then run the playbook like so::
ansible-playbook playbook.yml --connection=local
Alternatively, a local connection can be used in a single playbook play, even if other plays in the playbook
use the default remote connection type::
- hosts: 127.0.0.1
connection: local
.. note::
If you set the connection to local and there is no ansible_python_interpreter set, modules will run under /usr/bin/python and not
under {{ ansible_playbook_python }}. Be sure to set ansible_python_interpreter: "{{ ansible_playbook_python }}" in
host_vars/localhost.yml, for example. You can avoid this issue by using ``local_action`` or ``delegate_to: localhost`` instead.
.. _interrupt_execution_on_any_error:
Interrupt execution on any error
````````````````````````````````
With the ''any_errors_fatal'' option, any failure on any host in a multi-host play will be treated as fatal and Ansible will exit immediately without waiting for the other hosts.
Sometimes ''serial'' execution is unsuitable; the number of hosts is unpredictable (because of dynamic inventory) and speed is crucial (simultaneous execution is required), but all tasks must be 100% successful to continue playbook execution.
For example, consider a service located in many datacenters with some load balancers to pass traffic from users to the service. There is a deploy playbook to upgrade service deb-packages. The playbook has the stages:
- disable traffic on load balancers (must be turned off simultaneously)
- gracefully stop the service
- upgrade software (this step includes tests and starting the service)
- enable traffic on the load balancers (which should be turned on simultaneously)
The service can't be stopped with "alive" load balancers; they must be disabled first. Because of this, the second stage can't be played if any server failed in the first stage.
For datacenter "A", the playbook can be written this way::
---
- hosts: load_balancers_dc_a
any_errors_fatal: True
tasks:
- name: 'shutting down datacenter [ A ]'
command: /usr/bin/disable-dc
- hosts: frontends_dc_a
tasks:
- name: 'stopping service'
command: /usr/bin/stop-software
- name: 'updating software'
command: /usr/bin/upgrade-software
- hosts: load_balancers_dc_a
tasks:
- name: 'Starting datacenter [ A ]'
command: /usr/bin/enable-dc
In this example Ansible will start the software upgrade on the front ends only if all of the load balancers are successfully disabled.
.. seealso::
:ref:`playbooks_intro`
An introduction to playbooks
`Ansible Examples on GitHub <https://github.com/ansible/ansible-examples>`_
Many examples of full-stack deployments
`User Mailing List <https://groups.google.com/group/ansible-devel>`_
Have a question? Stop by the google group!
`irc.freenode.net <http://irc.freenode.net>`_
#ansible IRC chat channel
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,326 |
VMware: Unable to use vmware_tag_manager module
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
Unable to run a playbook with vmware_tag_manager module.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
vmware_tag_manager
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.8.1
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```yaml
- hosts: "{{ target }}"
gather_facts: no
tasks:
- name: add tags
vmware_tag_manager:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: yes
tag_names:
- tag1
- tag2
object_name: "{{ target | upper }}"
object_type: VirtualMachine
state: add
delegate_to: localhost
become: yes
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
Red Hat Enterprise Linux Server release 7.6 (Maipo)
Python 2.7.5
pip list
```
Package Version
---------------------------------- ------------------
ansible 2.8.1
asn1crypto 0.24.0
Babel 0.9.6
backports.ssl-match-hostname 3.5.0.1
certifi 2018.4.16
cffi 1.12.3
chardet 3.0.4
click 6.7
configobj 4.7.2
cryptography 2.7
decorator 3.4.0
dnspython 1.12.0
docopt 0.6.2
enum34 1.0.4
ethtool 0.8
httplib2 0.9.1
idna 2.7
iniparse 0.4
ipaddress 1.0.16
isodate 0.5.0
javapackages 1.0.0
Jinja2 2.7.2
jmespath 0.9.0
jsoncsv 2.0.6
kitchen 1.1.1
lxml 4.3.4
M2Crypto 0.21.1
Magic-file-extensions 0.2
MarkupSafe 0.11
netaddr 0.7.19
netsnmp-python 1.0a1
nsx-policy-python-sdk 2.3.0.0.3.13851140
nsx-python-sdk 2.3.0.0.3.13851140
nsx-vmc-aws-integration-python-sdk 2.3.0.0.3.13851140
nsx-vmc-policy-python-sdk 2.3.0.0.3.13851140
paramiko 2.1.1
passlib 1.6.5
pciutils 1.7.3
perf 0.1
pip 19.1.1
ply 3.4
pulp-common 2.16.4.1
pyasn1 0.1.9
pycparser 2.14
pycurl 7.19.0
pygobject 3.22.0
pygpgme 0.3
pyinotify 0.9.4
pykickstart 1.99.66.19
pyliblzma 0.5.3
pyOpenSSL 19.0.0
pyparsing 1.5.6
python-dateutil 1.5
python-dmidecode 3.10.13
python-linux-procfs 0.4.9
pyudev 0.15
pyvmomi 6.7.1.2018.12
pyxattr 0.5.1
PyYAML 3.10
requests 2.22.0
schedutils 0.4
setuptools 0.9.8
simplejson 3.16.0
six 1.12.0
slip 0.4.0
slip.dbus 0.4.0
subscription-manager 1.21.10
suds 0.4
urlgrabber 3.10
urllib3 1.25.3
vapi-client-bindings 3.0.0
vapi-common-client 2.12.0
vapi-runtime 2.12.0
vmc-client-bindings 1.6.0
wheel 0.24.0
xlwt 1.3.0
yum-metadata-parser 1.1.4
```
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
Run a playbook with vmware_tag_manager module on the same environment. Same issue with validate_certs: yes et validate_certs: no,
<!--- Paste example playbooks or commands between quotes below -->
```
ansible-playbook test.yml -i nonproduction --ask-vault -e "target=mytestvm"
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
Playbook should run without errors and tags should be added to the VM.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
Errors related to supported versions of some packages or attach or detach privilege on urn:vmomi:InventoryServiceTag.
<!--- Paste verbatim command output between quotes -->
With validate_certs: yes
```paste below
fatal: [mytestvm -> localhost]: FAILED! => {"changed": false, "module_stderr": "/usr/lib/python2.7/site-packages/requests/__init__.py:91: RequestsDependencyWarning: urllib3 (1.25.3) or chardet (2.2.1) doesn't match a supported version!\n RequestsDependencyWarning)\nTraceback (most recent call last):\n File \"/root/.ansible/tmp/ansible-tmp-1561462780.71-111378165335699/AnsiballZ_vmware_tag_manager.py\", line 114, in <module>\n _ansiballz_main()\n File \"/root/.ansible/tmp/ansible-tmp-1561462780.71-111378165335699/AnsiballZ_vmware_tag_manager.py\", line 106, in _ansiballz_main\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n File \"/root/.ansible/tmp/ansible-tmp-1561462780.71-111378165335699/AnsiballZ_vmware_tag_manager.py\", line 49, in invoke_module\n imp.load_module('__main__', mod, module, MOD_DESC)\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/__main__.py\", line 283, in <module>\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/__main__.py\", line 278, in main\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/__main__.py\", line 151, in __init__\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/ansible_vmware_tag_manager_payload.zip/ansible/module_utils/vmware_rest_client.py\", line 61, in __init__\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/ansible_vmware_tag_manager_payload.zip/ansible/module_utils/vmware_rest_client.py\", line 116, in connect_to_rest\n File \"/usr/lib/python2.7/site-packages/com/vmware/cis_client.py\", line 198, in create\n return self._invoke('create', None)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 345, in _invoke\n return self._api_interface.native_invoke(ctx, _method_name, kwargs)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 266, in native_invoke\n method_result = self.invoke(ctx, method_id, data_val)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 202, in invoke\n ctx)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/security/client/security_context_filter.py\", line 102, in invoke\n self, service_id, operation_id, input_value, ctx)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/provider/filter.py\", line 76, in invoke\n service_id, operation_id, input_value, ctx)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/protocol/client/msg/json_connector.py\", line 79, in invoke\n response = self._do_request(VAPI_INVOKE, ctx, params)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/protocol/client/msg/json_connector.py\", line 122, in _do_request\n headers=request_headers, body=request_body))\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/protocol/client/rpc/requests_provider.py\", line 98, in do_request\n cookies=http_request.cookies, timeout=timeout)\n File \"/usr/lib/python2.7/site-packages/requests/sessions.py\", line 533, in request\n resp = self.send(prep, **send_kwargs)\n File \"/usr/lib/python2.7/site-packages/requests/sessions.py\", line 646, in send\n r = adapter.send(request, **kwargs)\n File \"/usr/lib/python2.7/site-packages/requests/adapters.py\", line 514, in send\n raise SSLError(e, request=request)\nrequests.exceptions.SSLError: HTTPSConnectionPool(host='vcenter.example.com', port=443): Max retries exceeded with url: /api (Caused by SSLError(SSLError(\"bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)\",),))\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}
```
With validate_certs: no
```
fatal: [mytestvm -> localhost]: FAILED! => {"changed": false, "module_stderr": "/usr/lib/python2.7/site-packages/requests/__init__.py:91: RequestsDependencyWarning: urllib3 (1.25.3) or chardet (2.2.1) doesn't match a supported version!\n RequestsDependencyWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\nTraceback (most recent call last):\n File \"/root/.ansible/tmp/ansible-tmp-1561462878.88-208452166425456/AnsiballZ_vmware_tag_manager.py\", line 114, in <module>\n _ansiballz_main()\n File \"/root/.ansible/tmp/ansible-tmp-1561462878.88-208452166425456/AnsiballZ_vmware_tag_manager.py\", line 106, in _ansiballz_main\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n File \"/root/.ansible/tmp/ansible-tmp-1561462878.88-208452166425456/AnsiballZ_vmware_tag_manager.py\", line 49, in invoke_module\n imp.load_module('__main__', mod, module, MOD_DESC)\n File \"/tmp/ansible_vmware_tag_manager_payload_pmXHEt/__main__.py\", line 283, in <module>\n File \"/tmp/ansible_vmware_tag_manager_payload_pmXHEt/__main__.py\", line 279, in main\n File \"/tmp/ansible_vmware_tag_manager_payload_pmXHEt/__main__.py\", line 244, in ensure_state\n File \"/usr/lib/python2.7/site-packages/com/vmware/cis/tagging_client.py\", line 1168, in attach\n 'object_id': object_id,\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 345, in _invoke\n return self._api_interface.native_invoke(ctx, _method_name, kwargs)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 298, in native_invoke\n self._rest_converter_mode)\ncom.vmware.vapi.std.errors_client.Unauthorized: {error_type : None, messages : [LocalizableMessage(default_message='MYDOMAIN.COM\\\\service_account does not have attach or detach privilege on urn:vmomi:InventoryServiceTag:bcf7a240-1dda-43ed-a98e-dfb9806d1849:GLOBAL', args=['MYDOMAIN.COM\\\\service_account', 'attach or detach', 'urn:vmomi:InventoryServiceTag:bcf7a240-1dda-43ed-a98e-dfb9806d1849:GLOBAL'], params=None, id='cis.tagging.unauthorized.error', localized=None)], data : None}\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}
```
|
https://github.com/ansible/ansible/issues/58326
|
https://github.com/ansible/ansible/pull/58405
|
242f160747638fda253d7ac7e96ea4a5c4d0c03e
|
e2d159c40c42946256bc37887322f0e82853e93b
| 2019-06-25T11:45:30Z |
python
| 2019-06-28T02:29:54Z |
changelogs/fragments/58326-vmware_rest_client-handle_unauth.yml
| |
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,326 |
VMware: Unable to use vmware_tag_manager module
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
Unable to run a playbook with vmware_tag_manager module.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
vmware_tag_manager
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.8.1
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```yaml
- hosts: "{{ target }}"
gather_facts: no
tasks:
- name: add tags
vmware_tag_manager:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: yes
tag_names:
- tag1
- tag2
object_name: "{{ target | upper }}"
object_type: VirtualMachine
state: add
delegate_to: localhost
become: yes
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
Red Hat Enterprise Linux Server release 7.6 (Maipo)
Python 2.7.5
pip list
```
Package Version
---------------------------------- ------------------
ansible 2.8.1
asn1crypto 0.24.0
Babel 0.9.6
backports.ssl-match-hostname 3.5.0.1
certifi 2018.4.16
cffi 1.12.3
chardet 3.0.4
click 6.7
configobj 4.7.2
cryptography 2.7
decorator 3.4.0
dnspython 1.12.0
docopt 0.6.2
enum34 1.0.4
ethtool 0.8
httplib2 0.9.1
idna 2.7
iniparse 0.4
ipaddress 1.0.16
isodate 0.5.0
javapackages 1.0.0
Jinja2 2.7.2
jmespath 0.9.0
jsoncsv 2.0.6
kitchen 1.1.1
lxml 4.3.4
M2Crypto 0.21.1
Magic-file-extensions 0.2
MarkupSafe 0.11
netaddr 0.7.19
netsnmp-python 1.0a1
nsx-policy-python-sdk 2.3.0.0.3.13851140
nsx-python-sdk 2.3.0.0.3.13851140
nsx-vmc-aws-integration-python-sdk 2.3.0.0.3.13851140
nsx-vmc-policy-python-sdk 2.3.0.0.3.13851140
paramiko 2.1.1
passlib 1.6.5
pciutils 1.7.3
perf 0.1
pip 19.1.1
ply 3.4
pulp-common 2.16.4.1
pyasn1 0.1.9
pycparser 2.14
pycurl 7.19.0
pygobject 3.22.0
pygpgme 0.3
pyinotify 0.9.4
pykickstart 1.99.66.19
pyliblzma 0.5.3
pyOpenSSL 19.0.0
pyparsing 1.5.6
python-dateutil 1.5
python-dmidecode 3.10.13
python-linux-procfs 0.4.9
pyudev 0.15
pyvmomi 6.7.1.2018.12
pyxattr 0.5.1
PyYAML 3.10
requests 2.22.0
schedutils 0.4
setuptools 0.9.8
simplejson 3.16.0
six 1.12.0
slip 0.4.0
slip.dbus 0.4.0
subscription-manager 1.21.10
suds 0.4
urlgrabber 3.10
urllib3 1.25.3
vapi-client-bindings 3.0.0
vapi-common-client 2.12.0
vapi-runtime 2.12.0
vmc-client-bindings 1.6.0
wheel 0.24.0
xlwt 1.3.0
yum-metadata-parser 1.1.4
```
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
Run a playbook with vmware_tag_manager module on the same environment. Same issue with validate_certs: yes et validate_certs: no,
<!--- Paste example playbooks or commands between quotes below -->
```
ansible-playbook test.yml -i nonproduction --ask-vault -e "target=mytestvm"
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
Playbook should run without errors and tags should be added to the VM.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
Errors related to supported versions of some packages or attach or detach privilege on urn:vmomi:InventoryServiceTag.
<!--- Paste verbatim command output between quotes -->
With validate_certs: yes
```paste below
fatal: [mytestvm -> localhost]: FAILED! => {"changed": false, "module_stderr": "/usr/lib/python2.7/site-packages/requests/__init__.py:91: RequestsDependencyWarning: urllib3 (1.25.3) or chardet (2.2.1) doesn't match a supported version!\n RequestsDependencyWarning)\nTraceback (most recent call last):\n File \"/root/.ansible/tmp/ansible-tmp-1561462780.71-111378165335699/AnsiballZ_vmware_tag_manager.py\", line 114, in <module>\n _ansiballz_main()\n File \"/root/.ansible/tmp/ansible-tmp-1561462780.71-111378165335699/AnsiballZ_vmware_tag_manager.py\", line 106, in _ansiballz_main\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n File \"/root/.ansible/tmp/ansible-tmp-1561462780.71-111378165335699/AnsiballZ_vmware_tag_manager.py\", line 49, in invoke_module\n imp.load_module('__main__', mod, module, MOD_DESC)\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/__main__.py\", line 283, in <module>\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/__main__.py\", line 278, in main\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/__main__.py\", line 151, in __init__\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/ansible_vmware_tag_manager_payload.zip/ansible/module_utils/vmware_rest_client.py\", line 61, in __init__\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/ansible_vmware_tag_manager_payload.zip/ansible/module_utils/vmware_rest_client.py\", line 116, in connect_to_rest\n File \"/usr/lib/python2.7/site-packages/com/vmware/cis_client.py\", line 198, in create\n return self._invoke('create', None)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 345, in _invoke\n return self._api_interface.native_invoke(ctx, _method_name, kwargs)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 266, in native_invoke\n method_result = self.invoke(ctx, method_id, data_val)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 202, in invoke\n ctx)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/security/client/security_context_filter.py\", line 102, in invoke\n self, service_id, operation_id, input_value, ctx)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/provider/filter.py\", line 76, in invoke\n service_id, operation_id, input_value, ctx)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/protocol/client/msg/json_connector.py\", line 79, in invoke\n response = self._do_request(VAPI_INVOKE, ctx, params)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/protocol/client/msg/json_connector.py\", line 122, in _do_request\n headers=request_headers, body=request_body))\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/protocol/client/rpc/requests_provider.py\", line 98, in do_request\n cookies=http_request.cookies, timeout=timeout)\n File \"/usr/lib/python2.7/site-packages/requests/sessions.py\", line 533, in request\n resp = self.send(prep, **send_kwargs)\n File \"/usr/lib/python2.7/site-packages/requests/sessions.py\", line 646, in send\n r = adapter.send(request, **kwargs)\n File \"/usr/lib/python2.7/site-packages/requests/adapters.py\", line 514, in send\n raise SSLError(e, request=request)\nrequests.exceptions.SSLError: HTTPSConnectionPool(host='vcenter.example.com', port=443): Max retries exceeded with url: /api (Caused by SSLError(SSLError(\"bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)\",),))\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}
```
With validate_certs: no
```
fatal: [mytestvm -> localhost]: FAILED! => {"changed": false, "module_stderr": "/usr/lib/python2.7/site-packages/requests/__init__.py:91: RequestsDependencyWarning: urllib3 (1.25.3) or chardet (2.2.1) doesn't match a supported version!\n RequestsDependencyWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\nTraceback (most recent call last):\n File \"/root/.ansible/tmp/ansible-tmp-1561462878.88-208452166425456/AnsiballZ_vmware_tag_manager.py\", line 114, in <module>\n _ansiballz_main()\n File \"/root/.ansible/tmp/ansible-tmp-1561462878.88-208452166425456/AnsiballZ_vmware_tag_manager.py\", line 106, in _ansiballz_main\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n File \"/root/.ansible/tmp/ansible-tmp-1561462878.88-208452166425456/AnsiballZ_vmware_tag_manager.py\", line 49, in invoke_module\n imp.load_module('__main__', mod, module, MOD_DESC)\n File \"/tmp/ansible_vmware_tag_manager_payload_pmXHEt/__main__.py\", line 283, in <module>\n File \"/tmp/ansible_vmware_tag_manager_payload_pmXHEt/__main__.py\", line 279, in main\n File \"/tmp/ansible_vmware_tag_manager_payload_pmXHEt/__main__.py\", line 244, in ensure_state\n File \"/usr/lib/python2.7/site-packages/com/vmware/cis/tagging_client.py\", line 1168, in attach\n 'object_id': object_id,\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 345, in _invoke\n return self._api_interface.native_invoke(ctx, _method_name, kwargs)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 298, in native_invoke\n self._rest_converter_mode)\ncom.vmware.vapi.std.errors_client.Unauthorized: {error_type : None, messages : [LocalizableMessage(default_message='MYDOMAIN.COM\\\\service_account does not have attach or detach privilege on urn:vmomi:InventoryServiceTag:bcf7a240-1dda-43ed-a98e-dfb9806d1849:GLOBAL', args=['MYDOMAIN.COM\\\\service_account', 'attach or detach', 'urn:vmomi:InventoryServiceTag:bcf7a240-1dda-43ed-a98e-dfb9806d1849:GLOBAL'], params=None, id='cis.tagging.unauthorized.error', localized=None)], data : None}\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}
```
|
https://github.com/ansible/ansible/issues/58326
|
https://github.com/ansible/ansible/pull/58405
|
242f160747638fda253d7ac7e96ea4a5c4d0c03e
|
e2d159c40c42946256bc37887322f0e82853e93b
| 2019-06-25T11:45:30Z |
python
| 2019-06-28T02:29:54Z |
lib/ansible/module_utils/vmware_rest_client.py
|
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Ansible Project
# Copyright: (c) 2018, Abhijeet Kasurde <[email protected]>
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import traceback
REQUESTS_IMP_ERR = None
try:
import requests
HAS_REQUESTS = True
except ImportError:
REQUESTS_IMP_ERR = traceback.format_exc()
HAS_REQUESTS = False
PYVMOMI_IMP_ERR = None
try:
from pyVim import connect
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
PYVMOMI_IMP_ERR = traceback.format_exc()
HAS_PYVMOMI = False
VSPHERE_IMP_ERR = None
try:
from com.vmware.vapi.std_client import DynamicID
from vmware.vapi.vsphere.client import create_vsphere_client
HAS_VSPHERE = True
except ImportError:
VSPHERE_IMP_ERR = traceback.format_exc()
HAS_VSPHERE = False
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import env_fallback, missing_required_lib
class VmwareRestClient(object):
def __init__(self, module):
"""
Constructor
"""
self.module = module
self.params = module.params
self.check_required_library()
self.api_client = self.connect_to_vsphere_client()
def check_required_library(self):
"""
Check required libraries
"""
if not HAS_REQUESTS:
self.module.fail_json(msg=missing_required_lib('requests'),
exception=REQUESTS_IMP_ERR)
if not HAS_PYVMOMI:
self.module.fail_json(msg=missing_required_lib('PyVmomi'),
exception=PYVMOMI_IMP_ERR)
if not HAS_VSPHERE:
self.module.fail_json(
msg=missing_required_lib('vSphere Automation SDK',
url='https://code.vmware.com/web/sdk/65/vsphere-automation-python'),
exception=VSPHERE_IMP_ERR)
@staticmethod
def vmware_client_argument_spec():
return dict(
hostname=dict(type='str',
fallback=(env_fallback, ['VMWARE_HOST'])),
username=dict(type='str',
fallback=(env_fallback, ['VMWARE_USER']),
aliases=['user', 'admin']),
password=dict(type='str',
fallback=(env_fallback, ['VMWARE_PASSWORD']),
aliases=['pass', 'pwd'],
no_log=True),
protocol=dict(type='str',
default='https',
choices=['https', 'http']),
validate_certs=dict(type='bool',
fallback=(env_fallback, ['VMWARE_VALIDATE_CERTS']),
default=True),
)
def connect_to_vsphere_client(self):
"""
Connect to vSphere API Client with Username and Password
"""
username = self.params.get('username')
password = self.params.get('password')
hostname = self.params.get('hostname')
session = requests.Session()
session.verify = self.params.get('validate_certs')
if not all([hostname, username, password]):
self.module.fail_json(msg="Missing one of the following : hostname, username, password."
" Please read the documentation for more information.")
client = create_vsphere_client(
server=hostname,
username=username,
password=password,
session=session)
if client is None:
self.module.fail_json(msg="Failed to login to %s" % hostname)
return client
def get_tags_for_object(self, tag_service, tag_assoc_svc, dobj):
"""
Return list of tag objects associated with an object
Args:
dobj: Dynamic object
tag_service: Tag service object
tag_assoc_svc: Tag Association object
Returns: List of tag objects associated with the given object
"""
tag_ids = tag_assoc_svc.list_attached_tags(dobj)
tags = []
for tag_id in tag_ids:
tags.append(tag_service.get(tag_id))
return tags
def get_vm_tags(self, tag_service, tag_association_svc, vm_mid=None):
"""
Return list of tag name associated with virtual machine
Args:
tag_service: Tag service object
tag_association_svc: Tag association object
vm_mid: Dynamic object for virtual machine
Returns: List of tag names associated with the given virtual machine
"""
tags = []
if vm_mid is None:
return tags
dynamic_managed_object = DynamicID(type='VirtualMachine', id=vm_mid)
temp_tags_model = self.get_tags_for_object(tag_service, tag_association_svc, dynamic_managed_object)
for t in temp_tags_model:
tags.append(t.name)
return tags
@staticmethod
def search_svc_object_by_name(service, svc_obj_name=None):
"""
Return service object by name
Args:
service: Service object
svc_obj_name: Name of service object to find
Returns: Service object if found else None
"""
if not svc_obj_name:
return None
for svc_object in service.list():
svc_obj = service.get(svc_object)
if svc_obj.name == svc_obj_name:
return svc_obj
return None
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,326 |
VMware: Unable to use vmware_tag_manager module
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
Unable to run a playbook with vmware_tag_manager module.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
vmware_tag_manager
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.8.1
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```yaml
- hosts: "{{ target }}"
gather_facts: no
tasks:
- name: add tags
vmware_tag_manager:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: yes
tag_names:
- tag1
- tag2
object_name: "{{ target | upper }}"
object_type: VirtualMachine
state: add
delegate_to: localhost
become: yes
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
Red Hat Enterprise Linux Server release 7.6 (Maipo)
Python 2.7.5
pip list
```
Package Version
---------------------------------- ------------------
ansible 2.8.1
asn1crypto 0.24.0
Babel 0.9.6
backports.ssl-match-hostname 3.5.0.1
certifi 2018.4.16
cffi 1.12.3
chardet 3.0.4
click 6.7
configobj 4.7.2
cryptography 2.7
decorator 3.4.0
dnspython 1.12.0
docopt 0.6.2
enum34 1.0.4
ethtool 0.8
httplib2 0.9.1
idna 2.7
iniparse 0.4
ipaddress 1.0.16
isodate 0.5.0
javapackages 1.0.0
Jinja2 2.7.2
jmespath 0.9.0
jsoncsv 2.0.6
kitchen 1.1.1
lxml 4.3.4
M2Crypto 0.21.1
Magic-file-extensions 0.2
MarkupSafe 0.11
netaddr 0.7.19
netsnmp-python 1.0a1
nsx-policy-python-sdk 2.3.0.0.3.13851140
nsx-python-sdk 2.3.0.0.3.13851140
nsx-vmc-aws-integration-python-sdk 2.3.0.0.3.13851140
nsx-vmc-policy-python-sdk 2.3.0.0.3.13851140
paramiko 2.1.1
passlib 1.6.5
pciutils 1.7.3
perf 0.1
pip 19.1.1
ply 3.4
pulp-common 2.16.4.1
pyasn1 0.1.9
pycparser 2.14
pycurl 7.19.0
pygobject 3.22.0
pygpgme 0.3
pyinotify 0.9.4
pykickstart 1.99.66.19
pyliblzma 0.5.3
pyOpenSSL 19.0.0
pyparsing 1.5.6
python-dateutil 1.5
python-dmidecode 3.10.13
python-linux-procfs 0.4.9
pyudev 0.15
pyvmomi 6.7.1.2018.12
pyxattr 0.5.1
PyYAML 3.10
requests 2.22.0
schedutils 0.4
setuptools 0.9.8
simplejson 3.16.0
six 1.12.0
slip 0.4.0
slip.dbus 0.4.0
subscription-manager 1.21.10
suds 0.4
urlgrabber 3.10
urllib3 1.25.3
vapi-client-bindings 3.0.0
vapi-common-client 2.12.0
vapi-runtime 2.12.0
vmc-client-bindings 1.6.0
wheel 0.24.0
xlwt 1.3.0
yum-metadata-parser 1.1.4
```
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
Run a playbook with vmware_tag_manager module on the same environment. Same issue with validate_certs: yes et validate_certs: no,
<!--- Paste example playbooks or commands between quotes below -->
```
ansible-playbook test.yml -i nonproduction --ask-vault -e "target=mytestvm"
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
Playbook should run without errors and tags should be added to the VM.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
Errors related to supported versions of some packages or attach or detach privilege on urn:vmomi:InventoryServiceTag.
<!--- Paste verbatim command output between quotes -->
With validate_certs: yes
```paste below
fatal: [mytestvm -> localhost]: FAILED! => {"changed": false, "module_stderr": "/usr/lib/python2.7/site-packages/requests/__init__.py:91: RequestsDependencyWarning: urllib3 (1.25.3) or chardet (2.2.1) doesn't match a supported version!\n RequestsDependencyWarning)\nTraceback (most recent call last):\n File \"/root/.ansible/tmp/ansible-tmp-1561462780.71-111378165335699/AnsiballZ_vmware_tag_manager.py\", line 114, in <module>\n _ansiballz_main()\n File \"/root/.ansible/tmp/ansible-tmp-1561462780.71-111378165335699/AnsiballZ_vmware_tag_manager.py\", line 106, in _ansiballz_main\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n File \"/root/.ansible/tmp/ansible-tmp-1561462780.71-111378165335699/AnsiballZ_vmware_tag_manager.py\", line 49, in invoke_module\n imp.load_module('__main__', mod, module, MOD_DESC)\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/__main__.py\", line 283, in <module>\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/__main__.py\", line 278, in main\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/__main__.py\", line 151, in __init__\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/ansible_vmware_tag_manager_payload.zip/ansible/module_utils/vmware_rest_client.py\", line 61, in __init__\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/ansible_vmware_tag_manager_payload.zip/ansible/module_utils/vmware_rest_client.py\", line 116, in connect_to_rest\n File \"/usr/lib/python2.7/site-packages/com/vmware/cis_client.py\", line 198, in create\n return self._invoke('create', None)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 345, in _invoke\n return self._api_interface.native_invoke(ctx, _method_name, kwargs)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 266, in native_invoke\n method_result = self.invoke(ctx, method_id, data_val)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 202, in invoke\n ctx)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/security/client/security_context_filter.py\", line 102, in invoke\n self, service_id, operation_id, input_value, ctx)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/provider/filter.py\", line 76, in invoke\n service_id, operation_id, input_value, ctx)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/protocol/client/msg/json_connector.py\", line 79, in invoke\n response = self._do_request(VAPI_INVOKE, ctx, params)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/protocol/client/msg/json_connector.py\", line 122, in _do_request\n headers=request_headers, body=request_body))\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/protocol/client/rpc/requests_provider.py\", line 98, in do_request\n cookies=http_request.cookies, timeout=timeout)\n File \"/usr/lib/python2.7/site-packages/requests/sessions.py\", line 533, in request\n resp = self.send(prep, **send_kwargs)\n File \"/usr/lib/python2.7/site-packages/requests/sessions.py\", line 646, in send\n r = adapter.send(request, **kwargs)\n File \"/usr/lib/python2.7/site-packages/requests/adapters.py\", line 514, in send\n raise SSLError(e, request=request)\nrequests.exceptions.SSLError: HTTPSConnectionPool(host='vcenter.example.com', port=443): Max retries exceeded with url: /api (Caused by SSLError(SSLError(\"bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)\",),))\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}
```
With validate_certs: no
```
fatal: [mytestvm -> localhost]: FAILED! => {"changed": false, "module_stderr": "/usr/lib/python2.7/site-packages/requests/__init__.py:91: RequestsDependencyWarning: urllib3 (1.25.3) or chardet (2.2.1) doesn't match a supported version!\n RequestsDependencyWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\nTraceback (most recent call last):\n File \"/root/.ansible/tmp/ansible-tmp-1561462878.88-208452166425456/AnsiballZ_vmware_tag_manager.py\", line 114, in <module>\n _ansiballz_main()\n File \"/root/.ansible/tmp/ansible-tmp-1561462878.88-208452166425456/AnsiballZ_vmware_tag_manager.py\", line 106, in _ansiballz_main\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n File \"/root/.ansible/tmp/ansible-tmp-1561462878.88-208452166425456/AnsiballZ_vmware_tag_manager.py\", line 49, in invoke_module\n imp.load_module('__main__', mod, module, MOD_DESC)\n File \"/tmp/ansible_vmware_tag_manager_payload_pmXHEt/__main__.py\", line 283, in <module>\n File \"/tmp/ansible_vmware_tag_manager_payload_pmXHEt/__main__.py\", line 279, in main\n File \"/tmp/ansible_vmware_tag_manager_payload_pmXHEt/__main__.py\", line 244, in ensure_state\n File \"/usr/lib/python2.7/site-packages/com/vmware/cis/tagging_client.py\", line 1168, in attach\n 'object_id': object_id,\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 345, in _invoke\n return self._api_interface.native_invoke(ctx, _method_name, kwargs)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 298, in native_invoke\n self._rest_converter_mode)\ncom.vmware.vapi.std.errors_client.Unauthorized: {error_type : None, messages : [LocalizableMessage(default_message='MYDOMAIN.COM\\\\service_account does not have attach or detach privilege on urn:vmomi:InventoryServiceTag:bcf7a240-1dda-43ed-a98e-dfb9806d1849:GLOBAL', args=['MYDOMAIN.COM\\\\service_account', 'attach or detach', 'urn:vmomi:InventoryServiceTag:bcf7a240-1dda-43ed-a98e-dfb9806d1849:GLOBAL'], params=None, id='cis.tagging.unauthorized.error', localized=None)], data : None}\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}
```
|
https://github.com/ansible/ansible/issues/58326
|
https://github.com/ansible/ansible/pull/58405
|
242f160747638fda253d7ac7e96ea4a5c4d0c03e
|
e2d159c40c42946256bc37887322f0e82853e93b
| 2019-06-25T11:45:30Z |
python
| 2019-06-28T02:29:54Z |
lib/ansible/modules/cloud/vmware/vmware_category.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Ansible Project
# Copyright: (c) 2018, Abhijeet Kasurde <[email protected]>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_category
short_description: Manage VMware categories
description:
- This module can be used to create / delete / update VMware categories.
- Tag feature is introduced in vSphere 6 version, so this module is not supported in the earlier versions of vSphere.
- All variables and VMware object names are case sensitive.
version_added: '2.7'
author:
- Abhijeet Kasurde (@Akasurde)
notes:
- Tested on vSphere 6.5
requirements:
- python >= 2.6
- PyVmomi
- vSphere Automation SDK
options:
category_name:
description:
- The name of category to manage.
required: True
category_description:
description:
- The category description.
- This is required only if C(state) is set to C(present).
- This parameter is ignored, when C(state) is set to C(absent).
default: ''
category_cardinality:
description:
- The category cardinality.
- This parameter is ignored, when updating existing category.
choices: ['multiple', 'single']
default: 'multiple'
new_category_name:
description:
- The new name for an existing category.
- This value is used while updating an existing category.
state:
description:
- The state of category.
- If set to C(present) and category does not exists, then category is created.
- If set to C(present) and category exists, then category is updated.
- If set to C(absent) and category exists, then category is deleted.
- If set to C(absent) and category does not exists, no action is taken.
- Process of updating category only allows name, description change.
default: 'present'
choices: [ 'present', 'absent' ]
extends_documentation_fragment: vmware_rest_client.documentation
'''
EXAMPLES = r'''
- name: Create a category
vmware_category:
hostname: "{{ vcenter_server }}"
username: "{{ vcenter_user }}"
password: "{{ vcenter_pass }}"
category_name: Sample_Cat_0001
category_description: Sample Description
category_cardinality: 'multiple'
state: present
- name: Rename category
vmware_category:
hostname: "{{ vcenter_server }}"
username: "{{ vcenter_user }}"
password: "{{ vcenter_pass }}"
category_name: Sample_Category_0001
new_category_name: Sample_Category_0002
state: present
- name: Update category description
vmware_category:
hostname: "{{ vcenter_server }}"
username: "{{ vcenter_user }}"
password: "{{ vcenter_pass }}"
category_name: Sample_Category_0001
category_description: Some fancy description
state: present
- name: Delete category
vmware_category:
hostname: "{{ vcenter_server }}"
username: "{{ vcenter_user }}"
password: "{{ vcenter_pass }}"
category_name: Sample_Category_0002
state: absent
'''
RETURN = r'''
category_results:
description: dictionary of category metadata
returned: on success
type: dict
sample: {
"category_id": "urn:vmomi:InventoryServiceCategory:d7120bda-9fa5-4f92-9d71-aa1acff2e5a8:GLOBAL",
"msg": "Category NewCat_0001 updated."
}
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware_rest_client import VmwareRestClient
try:
from com.vmware.cis.tagging_client import CategoryModel
except ImportError:
pass
class VmwareCategory(VmwareRestClient):
def __init__(self, module):
super(VmwareCategory, self).__init__(module)
self.category_service = self.api_client.tagging.Category
self.global_categories = dict()
self.category_name = self.params.get('category_name')
self.get_all_categories()
def ensure_state(self):
"""Manage internal states of categories. """
desired_state = self.params.get('state')
states = {
'present': {
'present': self.state_update_category,
'absent': self.state_create_category,
},
'absent': {
'present': self.state_delete_category,
'absent': self.state_unchanged,
}
}
states[desired_state][self.check_category_status()]()
def state_create_category(self):
"""Create category."""
category_spec = self.category_service.CreateSpec()
category_spec.name = self.category_name
category_spec.description = self.params.get('category_description')
if self.params.get('category_cardinality') == 'single':
category_spec.cardinality = CategoryModel.Cardinality.SINGLE
else:
category_spec.cardinality = CategoryModel.Cardinality.MULTIPLE
category_spec.associable_types = set()
category_id = self.category_service.create(category_spec)
if category_id:
self.module.exit_json(changed=True,
category_results=dict(msg="Category '%s' created." % category_spec.name,
category_id=category_id))
self.module.exit_json(changed=False,
category_results=dict(msg="No category created", category_id=''))
def state_unchanged(self):
"""Return unchanged state."""
self.module.exit_json(changed=False)
def state_update_category(self):
"""Update category."""
category_id = self.global_categories[self.category_name]['category_id']
changed = False
results = dict(msg="Category %s is unchanged." % self.category_name,
category_id=category_id)
category_update_spec = self.category_service.UpdateSpec()
change_list = []
old_cat_desc = self.global_categories[self.category_name]['category_description']
new_cat_desc = self.params.get('category_description')
if new_cat_desc and new_cat_desc != old_cat_desc:
category_update_spec.description = new_cat_desc
results['msg'] = 'Category %s updated.' % self.category_name
change_list.append(True)
new_cat_name = self.params.get('new_category_name')
if new_cat_name in self.global_categories:
self.module.fail_json(msg="Unable to rename %s as %s already"
" exists in configuration." % (self.category_name, new_cat_name))
old_cat_name = self.global_categories[self.category_name]['category_name']
if new_cat_name and new_cat_name != old_cat_name:
category_update_spec.name = new_cat_name
results['msg'] = 'Category %s updated.' % self.category_name
change_list.append(True)
if any(change_list):
self.category_service.update(category_id, category_update_spec)
changed = True
self.module.exit_json(changed=changed,
category_results=results)
def state_delete_category(self):
"""Delete category."""
category_id = self.global_categories[self.category_name]['category_id']
self.category_service.delete(category_id=category_id)
self.module.exit_json(changed=True,
category_results=dict(msg="Category '%s' deleted." % self.category_name,
category_id=category_id))
def check_category_status(self):
"""
Check if category exists or not
Returns: 'present' if category found, else 'absent'
"""
if self.category_name in self.global_categories:
return 'present'
else:
return 'absent'
def get_all_categories(self):
"""Retrieve all category information."""
for category in self.category_service.list():
category_obj = self.category_service.get(category)
self.global_categories[category_obj.name] = dict(
category_description=category_obj.description,
category_used_by=category_obj.used_by,
category_cardinality=str(category_obj.cardinality),
category_associable_types=category_obj.associable_types,
category_id=category_obj.id,
category_name=category_obj.name,
)
def main():
argument_spec = VmwareRestClient.vmware_client_argument_spec()
argument_spec.update(
category_name=dict(type='str', required=True),
category_description=dict(type='str', default='', required=False),
category_cardinality=dict(type='str', choices=["multiple", "single"], default="multiple"),
new_category_name=dict(type='str'),
state=dict(type='str', choices=['present', 'absent'], default='present'),
)
module = AnsibleModule(argument_spec=argument_spec)
vmware_category = VmwareCategory(module)
vmware_category.ensure_state()
if __name__ == '__main__':
main()
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,326 |
VMware: Unable to use vmware_tag_manager module
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
Unable to run a playbook with vmware_tag_manager module.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
vmware_tag_manager
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.8.1
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```yaml
- hosts: "{{ target }}"
gather_facts: no
tasks:
- name: add tags
vmware_tag_manager:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: yes
tag_names:
- tag1
- tag2
object_name: "{{ target | upper }}"
object_type: VirtualMachine
state: add
delegate_to: localhost
become: yes
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
Red Hat Enterprise Linux Server release 7.6 (Maipo)
Python 2.7.5
pip list
```
Package Version
---------------------------------- ------------------
ansible 2.8.1
asn1crypto 0.24.0
Babel 0.9.6
backports.ssl-match-hostname 3.5.0.1
certifi 2018.4.16
cffi 1.12.3
chardet 3.0.4
click 6.7
configobj 4.7.2
cryptography 2.7
decorator 3.4.0
dnspython 1.12.0
docopt 0.6.2
enum34 1.0.4
ethtool 0.8
httplib2 0.9.1
idna 2.7
iniparse 0.4
ipaddress 1.0.16
isodate 0.5.0
javapackages 1.0.0
Jinja2 2.7.2
jmespath 0.9.0
jsoncsv 2.0.6
kitchen 1.1.1
lxml 4.3.4
M2Crypto 0.21.1
Magic-file-extensions 0.2
MarkupSafe 0.11
netaddr 0.7.19
netsnmp-python 1.0a1
nsx-policy-python-sdk 2.3.0.0.3.13851140
nsx-python-sdk 2.3.0.0.3.13851140
nsx-vmc-aws-integration-python-sdk 2.3.0.0.3.13851140
nsx-vmc-policy-python-sdk 2.3.0.0.3.13851140
paramiko 2.1.1
passlib 1.6.5
pciutils 1.7.3
perf 0.1
pip 19.1.1
ply 3.4
pulp-common 2.16.4.1
pyasn1 0.1.9
pycparser 2.14
pycurl 7.19.0
pygobject 3.22.0
pygpgme 0.3
pyinotify 0.9.4
pykickstart 1.99.66.19
pyliblzma 0.5.3
pyOpenSSL 19.0.0
pyparsing 1.5.6
python-dateutil 1.5
python-dmidecode 3.10.13
python-linux-procfs 0.4.9
pyudev 0.15
pyvmomi 6.7.1.2018.12
pyxattr 0.5.1
PyYAML 3.10
requests 2.22.0
schedutils 0.4
setuptools 0.9.8
simplejson 3.16.0
six 1.12.0
slip 0.4.0
slip.dbus 0.4.0
subscription-manager 1.21.10
suds 0.4
urlgrabber 3.10
urllib3 1.25.3
vapi-client-bindings 3.0.0
vapi-common-client 2.12.0
vapi-runtime 2.12.0
vmc-client-bindings 1.6.0
wheel 0.24.0
xlwt 1.3.0
yum-metadata-parser 1.1.4
```
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
Run a playbook with vmware_tag_manager module on the same environment. Same issue with validate_certs: yes et validate_certs: no,
<!--- Paste example playbooks or commands between quotes below -->
```
ansible-playbook test.yml -i nonproduction --ask-vault -e "target=mytestvm"
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
Playbook should run without errors and tags should be added to the VM.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
Errors related to supported versions of some packages or attach or detach privilege on urn:vmomi:InventoryServiceTag.
<!--- Paste verbatim command output between quotes -->
With validate_certs: yes
```paste below
fatal: [mytestvm -> localhost]: FAILED! => {"changed": false, "module_stderr": "/usr/lib/python2.7/site-packages/requests/__init__.py:91: RequestsDependencyWarning: urllib3 (1.25.3) or chardet (2.2.1) doesn't match a supported version!\n RequestsDependencyWarning)\nTraceback (most recent call last):\n File \"/root/.ansible/tmp/ansible-tmp-1561462780.71-111378165335699/AnsiballZ_vmware_tag_manager.py\", line 114, in <module>\n _ansiballz_main()\n File \"/root/.ansible/tmp/ansible-tmp-1561462780.71-111378165335699/AnsiballZ_vmware_tag_manager.py\", line 106, in _ansiballz_main\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n File \"/root/.ansible/tmp/ansible-tmp-1561462780.71-111378165335699/AnsiballZ_vmware_tag_manager.py\", line 49, in invoke_module\n imp.load_module('__main__', mod, module, MOD_DESC)\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/__main__.py\", line 283, in <module>\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/__main__.py\", line 278, in main\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/__main__.py\", line 151, in __init__\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/ansible_vmware_tag_manager_payload.zip/ansible/module_utils/vmware_rest_client.py\", line 61, in __init__\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/ansible_vmware_tag_manager_payload.zip/ansible/module_utils/vmware_rest_client.py\", line 116, in connect_to_rest\n File \"/usr/lib/python2.7/site-packages/com/vmware/cis_client.py\", line 198, in create\n return self._invoke('create', None)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 345, in _invoke\n return self._api_interface.native_invoke(ctx, _method_name, kwargs)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 266, in native_invoke\n method_result = self.invoke(ctx, method_id, data_val)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 202, in invoke\n ctx)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/security/client/security_context_filter.py\", line 102, in invoke\n self, service_id, operation_id, input_value, ctx)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/provider/filter.py\", line 76, in invoke\n service_id, operation_id, input_value, ctx)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/protocol/client/msg/json_connector.py\", line 79, in invoke\n response = self._do_request(VAPI_INVOKE, ctx, params)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/protocol/client/msg/json_connector.py\", line 122, in _do_request\n headers=request_headers, body=request_body))\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/protocol/client/rpc/requests_provider.py\", line 98, in do_request\n cookies=http_request.cookies, timeout=timeout)\n File \"/usr/lib/python2.7/site-packages/requests/sessions.py\", line 533, in request\n resp = self.send(prep, **send_kwargs)\n File \"/usr/lib/python2.7/site-packages/requests/sessions.py\", line 646, in send\n r = adapter.send(request, **kwargs)\n File \"/usr/lib/python2.7/site-packages/requests/adapters.py\", line 514, in send\n raise SSLError(e, request=request)\nrequests.exceptions.SSLError: HTTPSConnectionPool(host='vcenter.example.com', port=443): Max retries exceeded with url: /api (Caused by SSLError(SSLError(\"bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)\",),))\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}
```
With validate_certs: no
```
fatal: [mytestvm -> localhost]: FAILED! => {"changed": false, "module_stderr": "/usr/lib/python2.7/site-packages/requests/__init__.py:91: RequestsDependencyWarning: urllib3 (1.25.3) or chardet (2.2.1) doesn't match a supported version!\n RequestsDependencyWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\nTraceback (most recent call last):\n File \"/root/.ansible/tmp/ansible-tmp-1561462878.88-208452166425456/AnsiballZ_vmware_tag_manager.py\", line 114, in <module>\n _ansiballz_main()\n File \"/root/.ansible/tmp/ansible-tmp-1561462878.88-208452166425456/AnsiballZ_vmware_tag_manager.py\", line 106, in _ansiballz_main\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n File \"/root/.ansible/tmp/ansible-tmp-1561462878.88-208452166425456/AnsiballZ_vmware_tag_manager.py\", line 49, in invoke_module\n imp.load_module('__main__', mod, module, MOD_DESC)\n File \"/tmp/ansible_vmware_tag_manager_payload_pmXHEt/__main__.py\", line 283, in <module>\n File \"/tmp/ansible_vmware_tag_manager_payload_pmXHEt/__main__.py\", line 279, in main\n File \"/tmp/ansible_vmware_tag_manager_payload_pmXHEt/__main__.py\", line 244, in ensure_state\n File \"/usr/lib/python2.7/site-packages/com/vmware/cis/tagging_client.py\", line 1168, in attach\n 'object_id': object_id,\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 345, in _invoke\n return self._api_interface.native_invoke(ctx, _method_name, kwargs)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 298, in native_invoke\n self._rest_converter_mode)\ncom.vmware.vapi.std.errors_client.Unauthorized: {error_type : None, messages : [LocalizableMessage(default_message='MYDOMAIN.COM\\\\service_account does not have attach or detach privilege on urn:vmomi:InventoryServiceTag:bcf7a240-1dda-43ed-a98e-dfb9806d1849:GLOBAL', args=['MYDOMAIN.COM\\\\service_account', 'attach or detach', 'urn:vmomi:InventoryServiceTag:bcf7a240-1dda-43ed-a98e-dfb9806d1849:GLOBAL'], params=None, id='cis.tagging.unauthorized.error', localized=None)], data : None}\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}
```
|
https://github.com/ansible/ansible/issues/58326
|
https://github.com/ansible/ansible/pull/58405
|
242f160747638fda253d7ac7e96ea4a5c4d0c03e
|
e2d159c40c42946256bc37887322f0e82853e93b
| 2019-06-25T11:45:30Z |
python
| 2019-06-28T02:29:54Z |
lib/ansible/modules/cloud/vmware/vmware_tag.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Ansible Project
# Copyright: (c) 2018, Abhijeet Kasurde <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_tag
short_description: Manage VMware tags
description:
- This module can be used to create / delete / update VMware tags.
- Tag feature is introduced in vSphere 6 version, so this module is not supported in the earlier versions of vSphere.
- All variables and VMware object names are case sensitive.
version_added: '2.6'
author:
- Abhijeet Kasurde (@Akasurde)
notes:
- Tested on vSphere 6.5
requirements:
- python >= 2.6
- PyVmomi
- vSphere Automation SDK
options:
tag_name:
description:
- The name of tag to manage.
required: True
tag_description:
description:
- The tag description.
- This is required only if C(state) is set to C(present).
- This parameter is ignored, when C(state) is set to C(absent).
- Process of updating tag only allows description change.
required: False
default: ''
category_id:
description:
- The unique ID generated by vCenter should be used to.
- User can get this unique ID from facts module.
required: False
state:
description:
- The state of tag.
- If set to C(present) and tag does not exists, then tag is created.
- If set to C(present) and tag exists, then tag is updated.
- If set to C(absent) and tag exists, then tag is deleted.
- If set to C(absent) and tag does not exists, no action is taken.
required: False
default: 'present'
choices: [ 'present', 'absent' ]
extends_documentation_fragment: vmware_rest_client.documentation
'''
EXAMPLES = r'''
- name: Create a tag
vmware_tag:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
validate_certs: no
category_id: 'urn:vmomi:InventoryServiceCategory:e785088d-6981-4b1c-9fb8-1100c3e1f742:GLOBAL'
tag_name: Sample_Tag_0002
tag_description: Sample Description
state: present
delegate_to: localhost
- name: Update tag description
vmware_tag:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
tag_name: Sample_Tag_0002
tag_description: Some fancy description
state: present
delegate_to: localhost
- name: Delete tag
vmware_tag:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
tag_name: Sample_Tag_0002
state: absent
delegate_to: localhost
'''
RETURN = r'''
results:
description: dictionary of tag metadata
returned: on success
type: dict
sample: {
"msg": "Tag 'Sample_Tag_0002' created.",
"tag_id": "urn:vmomi:InventoryServiceTag:bff91819-f529-43c9-80ca-1c9dfda09441:GLOBAL"
}
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware_rest_client import VmwareRestClient
class VmwareTag(VmwareRestClient):
def __init__(self, module):
super(VmwareTag, self).__init__(module)
self.global_tags = dict()
# api_client to call APIs instead of individual service
self.tag_service = self.api_client.tagging.Tag
self.tag_name = self.params.get('tag_name')
self.get_all_tags()
self.category_service = self.api_client.tagging.Category
def ensure_state(self):
"""
Manage internal states of tags
"""
desired_state = self.params.get('state')
states = {
'present': {
'present': self.state_update_tag,
'absent': self.state_create_tag,
},
'absent': {
'present': self.state_delete_tag,
'absent': self.state_unchanged,
}
}
states[desired_state][self.check_tag_status()]()
def state_create_tag(self):
"""
Create tag
"""
tag_spec = self.tag_service.CreateSpec()
tag_spec.name = self.tag_name
tag_spec.description = self.params.get('tag_description')
category_id = self.params.get('category_id', None)
if category_id is None:
self.module.fail_json(msg="'category_id' is required parameter while creating tag.")
category_found = False
for category in self.category_service.list():
category_obj = self.category_service.get(category)
if category_id == category_obj.id:
category_found = True
break
if not category_found:
self.module.fail_json(msg="Unable to find category specified using 'category_id' - %s" % category_id)
tag_spec.category_id = category_id
tag_id = self.tag_service.create(tag_spec)
if tag_id:
self.module.exit_json(changed=True,
results=dict(msg="Tag '%s' created." % tag_spec.name,
tag_id=tag_id))
self.module.exit_json(changed=False,
results=dict(msg="No tag created", tag_id=''))
def state_unchanged(self):
"""
Return unchanged state
"""
self.module.exit_json(changed=False)
def state_update_tag(self):
"""
Update tag
"""
changed = False
tag_id = self.global_tags[self.tag_name]['tag_id']
results = dict(msg="Tag %s is unchanged." % self.tag_name,
tag_id=tag_id)
tag_update_spec = self.tag_service.UpdateSpec()
tag_desc = self.global_tags[self.tag_name]['tag_description']
desired_tag_desc = self.params.get('tag_description')
if tag_desc != desired_tag_desc:
tag_update_spec.description = desired_tag_desc
self.tag_service.update(tag_id, tag_update_spec)
results['msg'] = 'Tag %s updated.' % self.tag_name
changed = True
self.module.exit_json(changed=changed, results=results)
def state_delete_tag(self):
"""
Delete tag
"""
tag_id = self.global_tags[self.tag_name]['tag_id']
self.tag_service.delete(tag_id=tag_id)
self.module.exit_json(changed=True,
results=dict(msg="Tag '%s' deleted." % self.tag_name,
tag_id=tag_id))
def check_tag_status(self):
"""
Check if tag exists or not
Returns: 'present' if tag found, else 'absent'
"""
ret = 'present' if self.tag_name in self.global_tags else 'absent'
return ret
def get_all_tags(self):
"""
Retrieve all tag information
"""
for tag in self.tag_service.list():
tag_obj = self.tag_service.get(tag)
self.global_tags[tag_obj.name] = dict(tag_description=tag_obj.description,
tag_used_by=tag_obj.used_by,
tag_category_id=tag_obj.category_id,
tag_id=tag_obj.id
)
def main():
argument_spec = VmwareRestClient.vmware_client_argument_spec()
argument_spec.update(
tag_name=dict(type='str', required=True),
tag_description=dict(type='str', default='', required=False),
category_id=dict(type='str', required=False),
state=dict(type='str', choices=['present', 'absent'], default='present', required=False),
)
module = AnsibleModule(argument_spec=argument_spec)
vmware_tag = VmwareTag(module)
vmware_tag.ensure_state()
if __name__ == '__main__':
main()
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,326 |
VMware: Unable to use vmware_tag_manager module
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
Unable to run a playbook with vmware_tag_manager module.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
vmware_tag_manager
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.8.1
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```yaml
- hosts: "{{ target }}"
gather_facts: no
tasks:
- name: add tags
vmware_tag_manager:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: yes
tag_names:
- tag1
- tag2
object_name: "{{ target | upper }}"
object_type: VirtualMachine
state: add
delegate_to: localhost
become: yes
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
Red Hat Enterprise Linux Server release 7.6 (Maipo)
Python 2.7.5
pip list
```
Package Version
---------------------------------- ------------------
ansible 2.8.1
asn1crypto 0.24.0
Babel 0.9.6
backports.ssl-match-hostname 3.5.0.1
certifi 2018.4.16
cffi 1.12.3
chardet 3.0.4
click 6.7
configobj 4.7.2
cryptography 2.7
decorator 3.4.0
dnspython 1.12.0
docopt 0.6.2
enum34 1.0.4
ethtool 0.8
httplib2 0.9.1
idna 2.7
iniparse 0.4
ipaddress 1.0.16
isodate 0.5.0
javapackages 1.0.0
Jinja2 2.7.2
jmespath 0.9.0
jsoncsv 2.0.6
kitchen 1.1.1
lxml 4.3.4
M2Crypto 0.21.1
Magic-file-extensions 0.2
MarkupSafe 0.11
netaddr 0.7.19
netsnmp-python 1.0a1
nsx-policy-python-sdk 2.3.0.0.3.13851140
nsx-python-sdk 2.3.0.0.3.13851140
nsx-vmc-aws-integration-python-sdk 2.3.0.0.3.13851140
nsx-vmc-policy-python-sdk 2.3.0.0.3.13851140
paramiko 2.1.1
passlib 1.6.5
pciutils 1.7.3
perf 0.1
pip 19.1.1
ply 3.4
pulp-common 2.16.4.1
pyasn1 0.1.9
pycparser 2.14
pycurl 7.19.0
pygobject 3.22.0
pygpgme 0.3
pyinotify 0.9.4
pykickstart 1.99.66.19
pyliblzma 0.5.3
pyOpenSSL 19.0.0
pyparsing 1.5.6
python-dateutil 1.5
python-dmidecode 3.10.13
python-linux-procfs 0.4.9
pyudev 0.15
pyvmomi 6.7.1.2018.12
pyxattr 0.5.1
PyYAML 3.10
requests 2.22.0
schedutils 0.4
setuptools 0.9.8
simplejson 3.16.0
six 1.12.0
slip 0.4.0
slip.dbus 0.4.0
subscription-manager 1.21.10
suds 0.4
urlgrabber 3.10
urllib3 1.25.3
vapi-client-bindings 3.0.0
vapi-common-client 2.12.0
vapi-runtime 2.12.0
vmc-client-bindings 1.6.0
wheel 0.24.0
xlwt 1.3.0
yum-metadata-parser 1.1.4
```
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
Run a playbook with vmware_tag_manager module on the same environment. Same issue with validate_certs: yes et validate_certs: no,
<!--- Paste example playbooks or commands between quotes below -->
```
ansible-playbook test.yml -i nonproduction --ask-vault -e "target=mytestvm"
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
Playbook should run without errors and tags should be added to the VM.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
Errors related to supported versions of some packages or attach or detach privilege on urn:vmomi:InventoryServiceTag.
<!--- Paste verbatim command output between quotes -->
With validate_certs: yes
```paste below
fatal: [mytestvm -> localhost]: FAILED! => {"changed": false, "module_stderr": "/usr/lib/python2.7/site-packages/requests/__init__.py:91: RequestsDependencyWarning: urllib3 (1.25.3) or chardet (2.2.1) doesn't match a supported version!\n RequestsDependencyWarning)\nTraceback (most recent call last):\n File \"/root/.ansible/tmp/ansible-tmp-1561462780.71-111378165335699/AnsiballZ_vmware_tag_manager.py\", line 114, in <module>\n _ansiballz_main()\n File \"/root/.ansible/tmp/ansible-tmp-1561462780.71-111378165335699/AnsiballZ_vmware_tag_manager.py\", line 106, in _ansiballz_main\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n File \"/root/.ansible/tmp/ansible-tmp-1561462780.71-111378165335699/AnsiballZ_vmware_tag_manager.py\", line 49, in invoke_module\n imp.load_module('__main__', mod, module, MOD_DESC)\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/__main__.py\", line 283, in <module>\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/__main__.py\", line 278, in main\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/__main__.py\", line 151, in __init__\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/ansible_vmware_tag_manager_payload.zip/ansible/module_utils/vmware_rest_client.py\", line 61, in __init__\n File \"/tmp/ansible_vmware_tag_manager_payload_m5YI7p/ansible_vmware_tag_manager_payload.zip/ansible/module_utils/vmware_rest_client.py\", line 116, in connect_to_rest\n File \"/usr/lib/python2.7/site-packages/com/vmware/cis_client.py\", line 198, in create\n return self._invoke('create', None)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 345, in _invoke\n return self._api_interface.native_invoke(ctx, _method_name, kwargs)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 266, in native_invoke\n method_result = self.invoke(ctx, method_id, data_val)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 202, in invoke\n ctx)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/security/client/security_context_filter.py\", line 102, in invoke\n self, service_id, operation_id, input_value, ctx)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/provider/filter.py\", line 76, in invoke\n service_id, operation_id, input_value, ctx)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/protocol/client/msg/json_connector.py\", line 79, in invoke\n response = self._do_request(VAPI_INVOKE, ctx, params)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/protocol/client/msg/json_connector.py\", line 122, in _do_request\n headers=request_headers, body=request_body))\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/protocol/client/rpc/requests_provider.py\", line 98, in do_request\n cookies=http_request.cookies, timeout=timeout)\n File \"/usr/lib/python2.7/site-packages/requests/sessions.py\", line 533, in request\n resp = self.send(prep, **send_kwargs)\n File \"/usr/lib/python2.7/site-packages/requests/sessions.py\", line 646, in send\n r = adapter.send(request, **kwargs)\n File \"/usr/lib/python2.7/site-packages/requests/adapters.py\", line 514, in send\n raise SSLError(e, request=request)\nrequests.exceptions.SSLError: HTTPSConnectionPool(host='vcenter.example.com', port=443): Max retries exceeded with url: /api (Caused by SSLError(SSLError(\"bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)\",),))\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}
```
With validate_certs: no
```
fatal: [mytestvm -> localhost]: FAILED! => {"changed": false, "module_stderr": "/usr/lib/python2.7/site-packages/requests/__init__.py:91: RequestsDependencyWarning: urllib3 (1.25.3) or chardet (2.2.1) doesn't match a supported version!\n RequestsDependencyWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\n/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings\n InsecureRequestWarning)\nTraceback (most recent call last):\n File \"/root/.ansible/tmp/ansible-tmp-1561462878.88-208452166425456/AnsiballZ_vmware_tag_manager.py\", line 114, in <module>\n _ansiballz_main()\n File \"/root/.ansible/tmp/ansible-tmp-1561462878.88-208452166425456/AnsiballZ_vmware_tag_manager.py\", line 106, in _ansiballz_main\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n File \"/root/.ansible/tmp/ansible-tmp-1561462878.88-208452166425456/AnsiballZ_vmware_tag_manager.py\", line 49, in invoke_module\n imp.load_module('__main__', mod, module, MOD_DESC)\n File \"/tmp/ansible_vmware_tag_manager_payload_pmXHEt/__main__.py\", line 283, in <module>\n File \"/tmp/ansible_vmware_tag_manager_payload_pmXHEt/__main__.py\", line 279, in main\n File \"/tmp/ansible_vmware_tag_manager_payload_pmXHEt/__main__.py\", line 244, in ensure_state\n File \"/usr/lib/python2.7/site-packages/com/vmware/cis/tagging_client.py\", line 1168, in attach\n 'object_id': object_id,\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 345, in _invoke\n return self._api_interface.native_invoke(ctx, _method_name, kwargs)\n File \"/usr/lib/python2.7/site-packages/vmware/vapi/bindings/stub.py\", line 298, in native_invoke\n self._rest_converter_mode)\ncom.vmware.vapi.std.errors_client.Unauthorized: {error_type : None, messages : [LocalizableMessage(default_message='MYDOMAIN.COM\\\\service_account does not have attach or detach privilege on urn:vmomi:InventoryServiceTag:bcf7a240-1dda-43ed-a98e-dfb9806d1849:GLOBAL', args=['MYDOMAIN.COM\\\\service_account', 'attach or detach', 'urn:vmomi:InventoryServiceTag:bcf7a240-1dda-43ed-a98e-dfb9806d1849:GLOBAL'], params=None, id='cis.tagging.unauthorized.error', localized=None)], data : None}\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}
```
|
https://github.com/ansible/ansible/issues/58326
|
https://github.com/ansible/ansible/pull/58405
|
242f160747638fda253d7ac7e96ea4a5c4d0c03e
|
e2d159c40c42946256bc37887322f0e82853e93b
| 2019-06-25T11:45:30Z |
python
| 2019-06-28T02:29:54Z |
lib/ansible/modules/cloud/vmware/vmware_tag_manager.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Ansible Project
# Copyright: (c) 2018, Abhijeet Kasurde <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_tag_manager
short_description: Manage association of VMware tags with VMware objects
description:
- This module can be used to assign / remove VMware tags from the given VMware objects.
- Tag feature is introduced in vSphere 6 version, so this module is not supported in the earlier versions of vSphere.
- All variables and VMware object names are case sensitive.
version_added: 2.8
author:
- Abhijeet Kasurde (@Akasurde)
- Frederic Van Reet (@GBrawl)
notes:
- Tested on vSphere 6.5
requirements:
- python >= 2.6
- PyVmomi
- vSphere Automation SDK
options:
tag_names:
description:
- List of tag(s) to be managed.
- You can also specify category name by specifying colon separated value. For example, "category_name:tag_name".
- You can skip category name if you have unique tag names.
required: True
state:
description:
- If C(state) is set to C(add) or C(present) will add the tags to the existing tag list of the given object.
- If C(state) is set to C(remove) or C(absent) will remove the tags from the existing tag list of the given object.
- If C(state) is set to C(set) will replace the tags of the given objects with the user defined list of tags.
default: add
choices: [ present, absent, add, remove, set ]
object_type:
description:
- Type of object to work with.
required: True
choices: [ VirtualMachine, Datacenter, ClusterComputeResource, HostSystem, DistributedVirtualSwitch, DistributedVirtualPortgroup ]
object_name:
description:
- Name of the object to work with.
- For DistributedVirtualPortgroups the format should be "switch_name:portgroup_name"
required: True
extends_documentation_fragment: vmware_rest_client.documentation
'''
EXAMPLES = r'''
- name: Add tags to a virtual machine
vmware_tag_manager:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
validate_certs: no
tag_names:
- Sample_Tag_0002
- Category_0001:Sample_Tag_0003
object_name: Fedora_VM
object_type: VirtualMachine
state: add
delegate_to: localhost
- name: Remove a tag from a virtual machine
vmware_tag_manager:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
validate_certs: no
tag_names:
- Sample_Tag_0002
object_name: Fedora_VM
object_type: VirtualMachine
state: remove
delegate_to: localhost
- name: Add tags to a distributed virtual switch
vmware_tag_manager:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
validate_certs: no
tag_names:
- Sample_Tag_0003
object_name: Switch_0001
object_type: DistributedVirtualSwitch
state: add
delegate_to: localhost
- name: Add tags to a distributed virtual portgroup
vmware_tag_manager:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
validate_certs: no
tag_names:
- Sample_Tag_0004
object_name: Switch_0001:Portgroup_0001
object_type: DistributedVirtualPortgroup
state: add
delegate_to: localhost
'''
RETURN = r'''
tag_status:
description: metadata about tags related to object configuration
returned: on success
type: list
sample: {
"current_tags": [
"backup",
"security"
],
"desired_tags": [
"security"
],
"previous_tags": [
"backup",
"security"
]
}
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware_rest_client import VmwareRestClient
from ansible.module_utils.vmware import (PyVmomi, find_dvs_by_name, find_dvspg_by_name)
try:
from com.vmware.vapi.std_client import DynamicID
except ImportError:
pass
class VmwareTagManager(VmwareRestClient):
def __init__(self, module):
"""
Constructor
"""
super(VmwareTagManager, self).__init__(module)
self.pyv = PyVmomi(module=module)
self.object_type = self.params.get('object_type')
self.object_name = self.params.get('object_name')
self.managed_object = None
if self.object_type == 'VirtualMachine':
self.managed_object = self.pyv.get_vm_or_template(self.object_name)
if self.object_type == 'Datacenter':
self.managed_object = self.pyv.find_datacenter_by_name(self.object_name)
if self.object_type == 'ClusterComputeResource':
self.managed_object = self.pyv.find_cluster_by_name(self.object_name)
if self.object_type == 'HostSystem':
self.managed_object = self.pyv.find_hostsystem_by_name(self.object_name)
if self.object_type == 'DistributedVirtualSwitch':
self.managed_object = find_dvs_by_name(self.pyv.content, self.object_name)
self.object_type = 'VmwareDistributedVirtualSwitch'
if self.object_type == 'DistributedVirtualPortgroup':
dvs_name, pg_name = self.object_name.split(":", 1)
dv_switch = find_dvs_by_name(self.pyv.content, dvs_name)
if dv_switch is None:
self.module.fail_json(msg="A distributed virtual switch with name %s does not exist" % dvs_name)
self.managed_object = find_dvspg_by_name(dv_switch, pg_name)
if self.managed_object is None:
self.module.fail_json(msg="Failed to find the managed object for %s with type %s" % (self.object_name, self.object_type))
if not hasattr(self.managed_object, '_moId'):
self.module.fail_json(msg="Unable to find managed object id for %s managed object" % self.object_name)
self.dynamic_managed_object = DynamicID(type=self.object_type, id=self.managed_object._moId)
self.tag_service = self.api_client.tagging.Tag
self.category_service = self.api_client.tagging.Category
self.tag_association_svc = self.api_client.tagging.TagAssociation
self.tag_names = self.params.get('tag_names')
def is_tag_category(self, cat_obj, tag_obj):
for tag in self.tag_service.list_tags_for_category(cat_obj.id):
if tag_obj.name == self.tag_service.get(tag).name:
return True
return False
def ensure_state(self):
"""
Manage the internal state of tags
"""
results = dict(
changed=False,
tag_status=dict(),
)
changed = False
action = self.params.get('state')
available_tag_obj = self.get_tags_for_object(tag_service=self.tag_service,
tag_assoc_svc=self.tag_association_svc,
dobj=self.dynamic_managed_object)
# Already existing tags from the given object
avail_tag_obj_name_list = [tag.name for tag in available_tag_obj]
results['tag_status']['previous_tags'] = avail_tag_obj_name_list
results['tag_status']['desired_tags'] = self.tag_names
# Check if category and tag combination exists as per user request
removed_tags_for_set = False
for tag in self.tag_names:
category_obj, category_name, tag_name = None, None, None
if ":" in tag:
# User specified category
category_name, tag_name = tag.split(":", 1)
category_obj = self.search_svc_object_by_name(self.category_service, category_name)
if not category_obj:
self.module.fail_json(msg="Unable to find the category %s" % category_name)
else:
# User specified only tag
tag_name = tag
tag_obj = self.search_svc_object_by_name(self.tag_service, tag_name)
if not tag_obj:
self.module.fail_json(msg="Unable to find the tag %s" % tag_name)
if category_name and category_obj and not self.is_tag_category(category_obj, tag_obj):
self.module.fail_json(msg="Category %s does not contain tag %s" % (category_name, tag_name))
if action in ('add', 'present'):
if tag_obj not in available_tag_obj:
# Tag is not already applied
self.tag_association_svc.attach(tag_id=tag_obj.id, object_id=self.dynamic_managed_object)
changed = True
elif action == 'set':
# Remove all tags first
if not removed_tags_for_set:
for av_tag in available_tag_obj:
self.tag_association_svc.detach(tag_id=av_tag.id, object_id=self.dynamic_managed_object)
removed_tags_for_set = True
self.tag_association_svc.attach(tag_id=tag_obj.id, object_id=self.dynamic_managed_object)
changed = True
elif action in ('remove', 'absent'):
if tag_obj in available_tag_obj:
self.tag_association_svc.detach(tag_id=tag_obj.id, object_id=self.dynamic_managed_object)
changed = True
results['tag_status']['current_tags'] = [tag.name for tag in self.get_tags_for_object(self.tag_service,
self.tag_association_svc,
self.dynamic_managed_object)]
results['changed'] = changed
self.module.exit_json(**results)
def main():
argument_spec = VmwareRestClient.vmware_client_argument_spec()
argument_spec.update(
tag_names=dict(type='list', required=True),
state=dict(type='str', choices=['absent', 'add', 'present', 'remove', 'set'], default='add'),
object_name=dict(type='str', required=True),
object_type=dict(type='str', required=True, choices=['VirtualMachine', 'Datacenter', 'ClusterComputeResource',
'HostSystem', 'DistributedVirtualSwitch',
'DistributedVirtualPortgroup']),
)
module = AnsibleModule(argument_spec=argument_spec)
vmware_tag_manager = VmwareTagManager(module)
vmware_tag_manager.ensure_state()
if __name__ == '__main__':
main()
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,451 |
file_module: Hardlink-Example should be corrected
|
<!--- Verify first that your improvement is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
<!--- Explain the problem briefly below, add suggestions to wording or structure -->
Example for the hardlink uses wrong parameter - set to "link" / should be "hard"
<!--- HINT: Did you know the documentation has an "Edit on GitHub" link on every page ? -->
##### ISSUE TYPE
- Documentation Report
##### COMPONENT NAME
<!--- Write the short name of the rst file, module, plugin, task or feature below, use your best guess if unsure -->
file modul
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
2.8
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. OS version, browser, etc. -->
##### ADDITIONAL INFORMATION
<!--- Describe how this improves the documentation, e.g. before/after situation or screenshots -->
<!--- HINT: You can paste gist.github.com links for larger files -->
|
https://github.com/ansible/ansible/issues/58451
|
https://github.com/ansible/ansible/pull/58485
|
5937080977ae50823ee68ed5d87a6c4ad2433e29
|
184143e498f3c5541443e1e61f867bfecf4d165f
| 2019-06-27T09:13:51Z |
python
| 2019-06-28T13:56:45Z |
lib/ansible/modules/files/file.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2012, Michael DeHaan <[email protected]>
# Copyright: (c) 2017, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
DOCUMENTATION = r'''
---
module: file
version_added: historical
short_description: Manage files and file properties
extends_documentation_fragment: files
description:
- Set attributes of files, symlinks or directories.
- Alternatively, remove files, symlinks or directories.
- Many other modules support the same options as the C(file) module - including M(copy), M(template), and M(assemble).
- For Windows targets, use the M(win_file) module instead.
options:
path:
description:
- Path to the file being managed.
type: path
required: yes
aliases: [ dest, name ]
state:
description:
- If C(absent), directories will be recursively deleted, and files or symlinks will
be unlinked. Note that C(absent) will not cause C(file) to fail if the C(path) does
not exist as the state did not change.
- If C(directory), all intermediate subdirectories will be created if they
do not exist. Since Ansible 1.7 they will be created with the supplied permissions.
- If C(file), without any other options this works mostly as a 'stat' and will return the current state of C(path).
Even with other options (i.e C(mode)), the file will be modified but will NOT be created if it does not exist;
see the C(touch) value or the M(copy) or M(template) module if you want that behavior.
- If C(hard), the hard link will be created or changed.
- If C(link), the symbolic link will be created or changed.
- If C(touch) (new in 1.4), an empty file will be created if the C(path) does not
exist, while an existing file or directory will receive updated file access and
modification times (similar to the way C(touch) works from the command line).
type: str
default: file
choices: [ absent, directory, file, hard, link, touch ]
src:
description:
- Path of the file to link to.
- This applies only to C(state=link) and C(state=hard).
- For C(state=link), this will also accept a non-existing path.
- Relative paths are relative to the file being created (C(path)) which is how
the Unix command C(ln -s SRC DEST) treats relative paths.
type: path
recurse:
description:
- Recursively set the specified file attributes on directory contents.
- This applies only when C(state) is set to C(directory).
type: bool
default: no
version_added: '1.1'
force:
description:
- >
Force the creation of the symlinks in two cases: the source file does
not exist (but will appear later); the destination exists and is a file (so, we need to unlink the
C(path) file and create symlink to the C(src) file in place of it).
type: bool
default: no
follow:
description:
- This flag indicates that filesystem links, if they exist, should be followed.
- Previous to Ansible 2.5, this was C(no) by default.
type: bool
default: yes
version_added: '1.8'
modification_time:
description:
- This parameter indicates the time the file's modification time should be set to.
- Should be C(preserve) when no modification is required, C(YYYYMMDDHHMM.SS) when using default time format, or C(now).
- Default is None meaning that C(preserve) is the default for C(state=[file,directory,link,hard]) and C(now) is default for C(state=touch).
type: str
version_added: "2.7"
modification_time_format:
description:
- When used with C(modification_time), indicates the time format that must be used.
- Based on default Python format (see time.strftime doc).
type: str
default: "%Y%m%d%H%M.%S"
version_added: '2.7'
access_time:
description:
- This parameter indicates the time the file's access time should be set to.
- Should be C(preserve) when no modification is required, C(YYYYMMDDHHMM.SS) when using default time format, or C(now).
- Default is C(None) meaning that C(preserve) is the default for C(state=[file,directory,link,hard]) and C(now) is default for C(state=touch).
type: str
version_added: '2.7'
access_time_format:
description:
- When used with C(access_time), indicates the time format that must be used.
- Based on default Python format (see time.strftime doc).
type: str
default: "%Y%m%d%H%M.%S"
version_added: '2.7'
seealso:
- module: assemble
- module: copy
- module: stat
- module: template
- module: win_file
author:
- Ansible Core Team
- Michael DeHaan
'''
EXAMPLES = r'''
- name: Change file ownership, group and permissions
file:
path: /etc/foo.conf
owner: foo
group: foo
mode: '0644'
- name: Create an insecure file
file:
path: /work
owner: root
group: root
mode: '1777'
- name: Create a symbolic link
file:
src: /file/to/link/to
dest: /path/to/symlink
owner: foo
group: foo
state: link
- name: Create two hard links
file:
src: '/tmp/{{ item.src }}'
dest: '{{ item.dest }}'
state: link
with_items:
- { src: x, dest: y }
- { src: z, dest: k }
- name: Touch a file, using symbolic modes to set the permissions (equivalent to 0644)
file:
path: /etc/foo.conf
state: touch
mode: u=rw,g=r,o=r
- name: Touch the same file, but add/remove some permissions
file:
path: /etc/foo.conf
state: touch
mode: u+rw,g-wx,o-rwx
- name: Touch again the same file, but dont change times this makes the task idempotent
file:
path: /etc/foo.conf
state: touch
mode: u+rw,g-wx,o-rwx
modification_time: preserve
access_time: preserve
- name: Create a directory if it does not exist
file:
path: /etc/some_directory
state: directory
mode: '0755'
- name: Update modification and access time of given file
file:
path: /etc/some_file
state: file
modification_time: now
access_time: now
- name: Set access time based on seconds from epoch value
file:
path: /etc/another_file
state: file
access_time: '{{ "%Y%m%d%H%M.%S" | strftime(stat_var.stat.atime) }}'
- name: Recursively change ownership of a directory
file:
path: /etc/foo
state: directory
recurse: yes
owner: foo
group: foo
- name: Remove file (delete file)
file:
path: /etc/foo.txt
state: absent
- name: Recursively remove directory
file:
path: /etc/foo
state: absent
'''
RETURN = r'''
'''
import errno
import os
import shutil
import sys
import time
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_bytes, to_native
# There will only be a single AnsibleModule object per module
module = None
class AnsibleModuleError(Exception):
def __init__(self, results):
self.results = results
def __repr__(self):
print('AnsibleModuleError(results={0})'.format(self.results))
class ParameterError(AnsibleModuleError):
pass
class Sentinel(object):
def __new__(cls, *args, **kwargs):
return cls
def _ansible_excepthook(exc_type, exc_value, tb):
# Using an exception allows us to catch it if the calling code knows it can recover
if issubclass(exc_type, AnsibleModuleError):
module.fail_json(**exc_value.results)
else:
sys.__excepthook__(exc_type, exc_value, tb)
def additional_parameter_handling(params):
"""Additional parameter validation and reformatting"""
# When path is a directory, rewrite the pathname to be the file inside of the directory
# TODO: Why do we exclude link? Why don't we exclude directory? Should we exclude touch?
# I think this is where we want to be in the future:
# when isdir(path):
# if state == absent: Remove the directory
# if state == touch: Touch the directory
# if state == directory: Assert the directory is the same as the one specified
# if state == file: place inside of the directory (use _original_basename)
# if state == link: place inside of the directory (use _original_basename. Fallback to src?)
# if state == hard: place inside of the directory (use _original_basename. Fallback to src?)
if (params['state'] not in ("link", "absent") and os.path.isdir(to_bytes(params['path'], errors='surrogate_or_strict'))):
basename = None
if params['_original_basename']:
basename = params['_original_basename']
elif params['src']:
basename = os.path.basename(params['src'])
if basename:
params['path'] = os.path.join(params['path'], basename)
# state should default to file, but since that creates many conflicts,
# default state to 'current' when it exists.
prev_state = get_state(to_bytes(params['path'], errors='surrogate_or_strict'))
if params['state'] is None:
if prev_state != 'absent':
params['state'] = prev_state
elif params['recurse']:
params['state'] = 'directory'
else:
params['state'] = 'file'
# make sure the target path is a directory when we're doing a recursive operation
if params['recurse'] and params['state'] != 'directory':
raise ParameterError(results={"msg": "recurse option requires state to be 'directory'",
"path": params["path"]})
# Make sure that src makes sense with the state
if params['src'] and params['state'] not in ('link', 'hard'):
params['src'] = None
module.warn("The src option requires state to be 'link' or 'hard'. This will become an"
" error in Ansible 2.10")
# In 2.10, switch to this
# raise ParameterError(results={"msg": "src option requires state to be 'link' or 'hard'",
# "path": params["path"]})
def get_state(path):
''' Find out current state '''
b_path = to_bytes(path, errors='surrogate_or_strict')
try:
if os.path.lexists(b_path):
if os.path.islink(b_path):
return 'link'
elif os.path.isdir(b_path):
return 'directory'
elif os.stat(b_path).st_nlink > 1:
return 'hard'
# could be many other things, but defaulting to file
return 'file'
return 'absent'
except OSError as e:
if e.errno == errno.ENOENT: # It may already have been removed
return 'absent'
else:
raise
# This should be moved into the common file utilities
def recursive_set_attributes(b_path, follow, file_args, mtime, atime):
changed = False
try:
for b_root, b_dirs, b_files in os.walk(b_path):
for b_fsobj in b_dirs + b_files:
b_fsname = os.path.join(b_root, b_fsobj)
if not os.path.islink(b_fsname):
tmp_file_args = file_args.copy()
tmp_file_args['path'] = to_native(b_fsname, errors='surrogate_or_strict')
changed |= module.set_fs_attributes_if_different(tmp_file_args, changed, expand=False)
changed |= update_timestamp_for_file(tmp_file_args['path'], mtime, atime)
else:
# Change perms on the link
tmp_file_args = file_args.copy()
tmp_file_args['path'] = to_native(b_fsname, errors='surrogate_or_strict')
changed |= module.set_fs_attributes_if_different(tmp_file_args, changed, expand=False)
changed |= update_timestamp_for_file(tmp_file_args['path'], mtime, atime)
if follow:
b_fsname = os.path.join(b_root, os.readlink(b_fsname))
# The link target could be nonexistent
if os.path.exists(b_fsname):
if os.path.isdir(b_fsname):
# Link is a directory so change perms on the directory's contents
changed |= recursive_set_attributes(b_fsname, follow, file_args, mtime, atime)
# Change perms on the file pointed to by the link
tmp_file_args = file_args.copy()
tmp_file_args['path'] = to_native(b_fsname, errors='surrogate_or_strict')
changed |= module.set_fs_attributes_if_different(tmp_file_args, changed, expand=False)
changed |= update_timestamp_for_file(tmp_file_args['path'], mtime, atime)
except RuntimeError as e:
# on Python3 "RecursionError" is raised which is derived from "RuntimeError"
# TODO once this function is moved into the common file utilities, this should probably raise more general exception
raise AnsibleModuleError(
results={'msg': "Could not recursively set attributes on %s. Original error was: '%s'" % (to_native(b_path), to_native(e))}
)
return changed
def initial_diff(path, state, prev_state):
diff = {'before': {'path': path},
'after': {'path': path},
}
if prev_state != state:
diff['before']['state'] = prev_state
diff['after']['state'] = state
if state == 'absent':
walklist = {
'directories': [],
'files': [],
}
b_path = to_bytes(path, errors='surrogate_or_strict')
for base_path, sub_folders, files in os.walk(b_path):
for folder in sub_folders:
folderpath = os.path.join(base_path, folder)
walklist['directories'].append(folderpath)
for filename in files:
filepath = os.path.join(base_path, filename)
walklist['files'].append(filepath)
diff['before']['path_content'] = walklist
return diff
#
# States
#
def get_timestamp_for_time(formatted_time, time_format):
if formatted_time == 'preserve':
return None
elif formatted_time == 'now':
return Sentinel
else:
try:
struct = time.strptime(formatted_time, time_format)
struct_time = time.mktime(struct)
except (ValueError, OverflowError) as e:
raise AnsibleModuleError(results={'msg': 'Error while obtaining timestamp for time %s using format %s: %s'
% (formatted_time, time_format, to_native(e, nonstring='simplerepr'))})
return struct_time
def update_timestamp_for_file(path, mtime, atime, diff=None):
b_path = to_bytes(path, errors='surrogate_or_strict')
try:
# When mtime and atime are set to 'now', rely on utime(path, None) which does not require ownership of the file
# https://github.com/ansible/ansible/issues/50943
if mtime is Sentinel and atime is Sentinel:
# It's not exact but we can't rely on os.stat(path).st_mtime after setting os.utime(path, None) as it may
# not be updated. Just use the current time for the diff values
mtime = atime = time.time()
previous_mtime = os.stat(b_path).st_mtime
previous_atime = os.stat(b_path).st_atime
set_time = None
else:
# If both parameters are None 'preserve', nothing to do
if mtime is None and atime is None:
return False
previous_mtime = os.stat(b_path).st_mtime
previous_atime = os.stat(b_path).st_atime
if mtime is None:
mtime = previous_mtime
elif mtime is Sentinel:
mtime = time.time()
if atime is None:
atime = previous_atime
elif atime is Sentinel:
atime = time.time()
# If both timestamps are already ok, nothing to do
if mtime == previous_mtime and atime == previous_atime:
return False
set_time = (atime, mtime)
os.utime(b_path, set_time)
if diff is not None:
if 'before' not in diff:
diff['before'] = {}
if 'after' not in diff:
diff['after'] = {}
if mtime != previous_mtime:
diff['before']['mtime'] = previous_mtime
diff['after']['mtime'] = mtime
if atime != previous_atime:
diff['before']['atime'] = previous_atime
diff['after']['atime'] = atime
except OSError as e:
raise AnsibleModuleError(results={'msg': 'Error while updating modification or access time: %s'
% to_native(e, nonstring='simplerepr'), 'path': path})
return True
def keep_backward_compatibility_on_timestamps(parameter, state):
if state in ['file', 'hard', 'directory', 'link'] and parameter is None:
return 'preserve'
elif state == 'touch' and parameter is None:
return 'now'
else:
return parameter
def execute_diff_peek(path):
"""Take a guess as to whether a file is a binary file"""
b_path = to_bytes(path, errors='surrogate_or_strict')
appears_binary = False
try:
with open(b_path, 'rb') as f:
head = f.read(8192)
except Exception:
# If we can't read the file, we're okay assuming it's text
pass
else:
if b"\x00" in head:
appears_binary = True
return appears_binary
def ensure_absent(path):
b_path = to_bytes(path, errors='surrogate_or_strict')
prev_state = get_state(b_path)
result = {}
if prev_state != 'absent':
diff = initial_diff(path, 'absent', prev_state)
if not module.check_mode:
if prev_state == 'directory':
try:
shutil.rmtree(b_path, ignore_errors=False)
except Exception as e:
raise AnsibleModuleError(results={'msg': "rmtree failed: %s" % to_native(e)})
else:
try:
os.unlink(b_path)
except OSError as e:
if e.errno != errno.ENOENT: # It may already have been removed
raise AnsibleModuleError(results={'msg': "unlinking failed: %s " % to_native(e),
'path': path})
result.update({'path': path, 'changed': True, 'diff': diff, 'state': 'absent'})
else:
result.update({'path': path, 'changed': False, 'state': 'absent'})
return result
def execute_touch(path, follow, timestamps):
b_path = to_bytes(path, errors='surrogate_or_strict')
prev_state = get_state(b_path)
changed = False
result = {'dest': path}
mtime = get_timestamp_for_time(timestamps['modification_time'], timestamps['modification_time_format'])
atime = get_timestamp_for_time(timestamps['access_time'], timestamps['access_time_format'])
if not module.check_mode:
if prev_state == 'absent':
# Create an empty file if the filename did not already exist
try:
open(b_path, 'wb').close()
changed = True
except (OSError, IOError) as e:
raise AnsibleModuleError(results={'msg': 'Error, could not touch target: %s'
% to_native(e, nonstring='simplerepr'),
'path': path})
# Update the attributes on the file
diff = initial_diff(path, 'touch', prev_state)
file_args = module.load_file_common_arguments(module.params)
try:
changed = module.set_fs_attributes_if_different(file_args, changed, diff, expand=False)
changed |= update_timestamp_for_file(file_args['path'], mtime, atime, diff)
except SystemExit as e:
if e.code:
# We take this to mean that fail_json() was called from
# somewhere in basic.py
if prev_state == 'absent':
# If we just created the file we can safely remove it
os.remove(b_path)
raise
result['changed'] = changed
result['diff'] = diff
return result
def ensure_file_attributes(path, follow, timestamps):
b_path = to_bytes(path, errors='surrogate_or_strict')
prev_state = get_state(b_path)
file_args = module.load_file_common_arguments(module.params)
mtime = get_timestamp_for_time(timestamps['modification_time'], timestamps['modification_time_format'])
atime = get_timestamp_for_time(timestamps['access_time'], timestamps['access_time_format'])
if prev_state != 'file':
if follow and prev_state == 'link':
# follow symlink and operate on original
b_path = os.path.realpath(b_path)
path = to_native(b_path, errors='strict')
prev_state = get_state(b_path)
file_args['path'] = path
if prev_state not in ('file', 'hard'):
# file is not absent and any other state is a conflict
raise AnsibleModuleError(results={'msg': 'file (%s) is %s, cannot continue' % (path, prev_state),
'path': path})
diff = initial_diff(path, 'file', prev_state)
changed = module.set_fs_attributes_if_different(file_args, False, diff, expand=False)
changed |= update_timestamp_for_file(file_args['path'], mtime, atime, diff)
return {'path': path, 'changed': changed, 'diff': diff}
def ensure_directory(path, follow, recurse, timestamps):
b_path = to_bytes(path, errors='surrogate_or_strict')
prev_state = get_state(b_path)
file_args = module.load_file_common_arguments(module.params)
mtime = get_timestamp_for_time(timestamps['modification_time'], timestamps['modification_time_format'])
atime = get_timestamp_for_time(timestamps['access_time'], timestamps['access_time_format'])
# For followed symlinks, we need to operate on the target of the link
if follow and prev_state == 'link':
b_path = os.path.realpath(b_path)
path = to_native(b_path, errors='strict')
file_args['path'] = path
prev_state = get_state(b_path)
changed = False
diff = initial_diff(path, 'directory', prev_state)
if prev_state == 'absent':
# Create directory and assign permissions to it
if module.check_mode:
return {'changed': True, 'diff': diff}
curpath = ''
try:
# Split the path so we can apply filesystem attributes recursively
# from the root (/) directory for absolute paths or the base path
# of a relative path. We can then walk the appropriate directory
# path to apply attributes.
# Something like mkdir -p with mode applied to all of the newly created directories
for dirname in path.strip('/').split('/'):
curpath = '/'.join([curpath, dirname])
# Remove leading slash if we're creating a relative path
if not os.path.isabs(path):
curpath = curpath.lstrip('/')
b_curpath = to_bytes(curpath, errors='surrogate_or_strict')
if not os.path.exists(b_curpath):
try:
os.mkdir(b_curpath)
changed = True
except OSError as ex:
# Possibly something else created the dir since the os.path.exists
# check above. As long as it's a dir, we don't need to error out.
if not (ex.errno == errno.EEXIST and os.path.isdir(b_curpath)):
raise
tmp_file_args = file_args.copy()
tmp_file_args['path'] = curpath
changed = module.set_fs_attributes_if_different(tmp_file_args, changed, diff, expand=False)
changed |= update_timestamp_for_file(file_args['path'], mtime, atime, diff)
except Exception as e:
raise AnsibleModuleError(results={'msg': 'There was an issue creating %s as requested:'
' %s' % (curpath, to_native(e)),
'path': path})
return {'path': path, 'changed': changed, 'diff': diff}
elif prev_state != 'directory':
# We already know prev_state is not 'absent', therefore it exists in some form.
raise AnsibleModuleError(results={'msg': '%s already exists as a %s' % (path, prev_state),
'path': path})
#
# previous state == directory
#
changed = module.set_fs_attributes_if_different(file_args, changed, diff, expand=False)
changed |= update_timestamp_for_file(file_args['path'], mtime, atime, diff)
if recurse:
changed |= recursive_set_attributes(b_path, follow, file_args, mtime, atime)
return {'path': path, 'changed': changed, 'diff': diff}
def ensure_symlink(path, src, follow, force, timestamps):
b_path = to_bytes(path, errors='surrogate_or_strict')
b_src = to_bytes(src, errors='surrogate_or_strict')
prev_state = get_state(b_path)
mtime = get_timestamp_for_time(timestamps['modification_time'], timestamps['modification_time_format'])
atime = get_timestamp_for_time(timestamps['access_time'], timestamps['access_time_format'])
# source is both the source of a symlink or an informational passing of the src for a template module
# or copy module, even if this module never uses it, it is needed to key off some things
if src is None:
if follow:
# use the current target of the link as the source
src = to_native(os.path.realpath(b_path), errors='strict')
b_src = to_bytes(src, errors='surrogate_or_strict')
if not os.path.islink(b_path) and os.path.isdir(b_path):
relpath = path
else:
b_relpath = os.path.dirname(b_path)
relpath = to_native(b_relpath, errors='strict')
absrc = os.path.join(relpath, src)
b_absrc = to_bytes(absrc, errors='surrogate_or_strict')
if not force and not os.path.exists(b_absrc):
raise AnsibleModuleError(results={'msg': 'src file does not exist, use "force=yes" if you'
' really want to create the link: %s' % absrc,
'path': path, 'src': src})
if prev_state == 'directory':
if not force:
raise AnsibleModuleError(results={'msg': 'refusing to convert from %s to symlink for %s'
% (prev_state, path),
'path': path})
elif os.listdir(b_path):
# refuse to replace a directory that has files in it
raise AnsibleModuleError(results={'msg': 'the directory %s is not empty, refusing to'
' convert it' % path,
'path': path})
elif prev_state in ('file', 'hard') and not force:
raise AnsibleModuleError(results={'msg': 'refusing to convert from %s to symlink for %s'
% (prev_state, path),
'path': path})
diff = initial_diff(path, 'link', prev_state)
changed = False
if prev_state == 'absent':
changed = True
elif prev_state == 'link':
b_old_src = os.readlink(b_path)
if b_old_src != b_src:
diff['before']['src'] = to_native(b_old_src, errors='strict')
diff['after']['src'] = src
changed = True
elif prev_state == 'hard':
changed = True
if not force:
raise AnsibleModuleError(results={'msg': 'Cannot link because a hard link exists at destination',
'dest': path, 'src': src})
elif prev_state == 'file':
changed = True
if not force:
raise AnsibleModuleError(results={'msg': 'Cannot link because a file exists at destination',
'dest': path, 'src': src})
elif prev_state == 'directory':
changed = True
if os.path.exists(b_path):
if not force:
raise AnsibleModuleError(results={'msg': 'Cannot link because a file exists at destination',
'dest': path, 'src': src})
else:
raise AnsibleModuleError(results={'msg': 'unexpected position reached', 'dest': path, 'src': src})
if changed and not module.check_mode:
if prev_state != 'absent':
# try to replace atomically
b_tmppath = to_bytes(os.path.sep).join(
[os.path.dirname(b_path), to_bytes(".%s.%s.tmp" % (os.getpid(), time.time()))]
)
try:
if prev_state == 'directory':
os.rmdir(b_path)
os.symlink(b_src, b_tmppath)
os.rename(b_tmppath, b_path)
except OSError as e:
if os.path.exists(b_tmppath):
os.unlink(b_tmppath)
raise AnsibleModuleError(results={'msg': 'Error while replacing: %s'
% to_native(e, nonstring='simplerepr'),
'path': path})
else:
try:
os.symlink(b_src, b_path)
except OSError as e:
raise AnsibleModuleError(results={'msg': 'Error while linking: %s'
% to_native(e, nonstring='simplerepr'),
'path': path})
if module.check_mode and not os.path.exists(b_path):
return {'dest': path, 'src': src, 'changed': changed, 'diff': diff}
# Now that we might have created the symlink, get the arguments.
# We need to do it now so we can properly follow the symlink if needed
# because load_file_common_arguments sets 'path' according
# the value of follow and the symlink existance.
file_args = module.load_file_common_arguments(module.params)
# Whenever we create a link to a nonexistent target we know that the nonexistent target
# cannot have any permissions set on it. Skip setting those and emit a warning (the user
# can set follow=False to remove the warning)
if follow and os.path.islink(b_path) and not os.path.exists(file_args['path']):
module.warn('Cannot set fs attributes on a non-existent symlink target. follow should be'
' set to False to avoid this.')
else:
changed = module.set_fs_attributes_if_different(file_args, changed, diff, expand=False)
changed |= update_timestamp_for_file(file_args['path'], mtime, atime, diff)
return {'dest': path, 'src': src, 'changed': changed, 'diff': diff}
def ensure_hardlink(path, src, follow, force, timestamps):
b_path = to_bytes(path, errors='surrogate_or_strict')
b_src = to_bytes(src, errors='surrogate_or_strict')
prev_state = get_state(b_path)
file_args = module.load_file_common_arguments(module.params)
mtime = get_timestamp_for_time(timestamps['modification_time'], timestamps['modification_time_format'])
atime = get_timestamp_for_time(timestamps['access_time'], timestamps['access_time_format'])
# src is the source of a hardlink. We require it if we are creating a new hardlink.
# We require path in the argument_spec so we know it is present at this point.
if src is None:
raise AnsibleModuleError(results={'msg': 'src is required for creating new hardlinks'})
if not os.path.exists(b_src):
raise AnsibleModuleError(results={'msg': 'src does not exist', 'dest': path, 'src': src})
diff = initial_diff(path, 'hard', prev_state)
changed = False
if prev_state == 'absent':
changed = True
elif prev_state == 'link':
b_old_src = os.readlink(b_path)
if b_old_src != b_src:
diff['before']['src'] = to_native(b_old_src, errors='strict')
diff['after']['src'] = src
changed = True
elif prev_state == 'hard':
if not os.stat(b_path).st_ino == os.stat(b_src).st_ino:
changed = True
if not force:
raise AnsibleModuleError(results={'msg': 'Cannot link, different hard link exists at destination',
'dest': path, 'src': src})
elif prev_state == 'file':
changed = True
if not force:
raise AnsibleModuleError(results={'msg': 'Cannot link, %s exists at destination' % prev_state,
'dest': path, 'src': src})
elif prev_state == 'directory':
changed = True
if os.path.exists(b_path):
if os.stat(b_path).st_ino == os.stat(b_src).st_ino:
return {'path': path, 'changed': False}
elif not force:
raise AnsibleModuleError(results={'msg': 'Cannot link: different hard link exists at destination',
'dest': path, 'src': src})
else:
raise AnsibleModuleError(results={'msg': 'unexpected position reached', 'dest': path, 'src': src})
if changed and not module.check_mode:
if prev_state != 'absent':
# try to replace atomically
b_tmppath = to_bytes(os.path.sep).join(
[os.path.dirname(b_path), to_bytes(".%s.%s.tmp" % (os.getpid(), time.time()))]
)
try:
if prev_state == 'directory':
if os.path.exists(b_path):
try:
os.unlink(b_path)
except OSError as e:
if e.errno != errno.ENOENT: # It may already have been removed
raise
os.link(b_src, b_tmppath)
os.rename(b_tmppath, b_path)
except OSError as e:
if os.path.exists(b_tmppath):
os.unlink(b_tmppath)
raise AnsibleModuleError(results={'msg': 'Error while replacing: %s'
% to_native(e, nonstring='simplerepr'),
'path': path})
else:
try:
os.link(b_src, b_path)
except OSError as e:
raise AnsibleModuleError(results={'msg': 'Error while linking: %s'
% to_native(e, nonstring='simplerepr'),
'path': path})
if module.check_mode and not os.path.exists(b_path):
return {'dest': path, 'src': src, 'changed': changed, 'diff': diff}
changed = module.set_fs_attributes_if_different(file_args, changed, diff, expand=False)
changed |= update_timestamp_for_file(file_args['path'], mtime, atime, diff)
return {'dest': path, 'src': src, 'changed': changed, 'diff': diff}
def main():
global module
module = AnsibleModule(
argument_spec=dict(
state=dict(type='str', choices=['absent', 'directory', 'file', 'hard', 'link', 'touch']),
path=dict(type='path', required=True, aliases=['dest', 'name']),
_original_basename=dict(type='str'), # Internal use only, for recursive ops
recurse=dict(type='bool', default=False),
force=dict(type='bool', default=False), # Note: Should not be in file_common_args in future
follow=dict(type='bool', default=True), # Note: Different default than file_common_args
_diff_peek=dict(type='str'), # Internal use only, for internal checks in the action plugins
src=dict(type='path'), # Note: Should not be in file_common_args in future
modification_time=dict(type='str'),
modification_time_format=dict(type='str', default='%Y%m%d%H%M.%S'),
access_time=dict(type='str'),
access_time_format=dict(type='str', default='%Y%m%d%H%M.%S'),
),
add_file_common_args=True,
supports_check_mode=True,
)
# When we rewrite basic.py, we will do something similar to this on instantiating an AnsibleModule
sys.excepthook = _ansible_excepthook
additional_parameter_handling(module.params)
params = module.params
state = params['state']
recurse = params['recurse']
force = params['force']
follow = params['follow']
path = params['path']
src = params['src']
timestamps = {}
timestamps['modification_time'] = keep_backward_compatibility_on_timestamps(params['modification_time'], state)
timestamps['modification_time_format'] = params['modification_time_format']
timestamps['access_time'] = keep_backward_compatibility_on_timestamps(params['access_time'], state)
timestamps['access_time_format'] = params['access_time_format']
# short-circuit for diff_peek
if params['_diff_peek'] is not None:
appears_binary = execute_diff_peek(to_bytes(path, errors='surrogate_or_strict'))
module.exit_json(path=path, changed=False, appears_binary=appears_binary)
if state == 'file':
result = ensure_file_attributes(path, follow, timestamps)
elif state == 'directory':
result = ensure_directory(path, follow, recurse, timestamps)
elif state == 'link':
result = ensure_symlink(path, src, follow, force, timestamps)
elif state == 'hard':
result = ensure_hardlink(path, src, follow, force, timestamps)
elif state == 'touch':
result = execute_touch(path, follow, timestamps)
elif state == 'absent':
result = ensure_absent(path)
module.exit_json(**result)
if __name__ == '__main__':
main()
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,444 |
hostname module cannot be used on Oracle Linux
|
##### SUMMARY
In devel branch, hostname module doesn't recognise Oracle Linux.
Regression from PR #56936 caused by PR #55459.
stable-2.8 branch is OK.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
hostname
##### ANSIBLE VERSION
```
2.9 / devel
```
##### CONFIGURATION
##### OS / ENVIRONMENT
```
$ head -n5 /etc/os-release
NAME="Oracle Linux Server"
VERSION="7.4"
ID="ol"
VERSION_ID="7.4"
PRETTY_NAME="Oracle Linux Server 7.4"
```
##### STEPS TO REPRODUCE
```yaml
- name: set hostname
hostname:
name: "mytesthostname"
```
##### EXPECTED RESULTS
```
changed: [myhost]
```
##### ACTUAL RESULTS
```
fatal: [myhost]: FAILED! => {"changed": false, "msg": "hostname module cannot be used on platform Linux (Oracle)"}
```
##### ANALYSIS
This is a **regression** from PR #56936 caused by PR #55459.
Relevant lines from PR #56936:
[lib/ansible/modules/system/hostname.py#L660](https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/system/hostname.py#L660)
```
class OracleLinuxHostname(Hostname):
platform = 'Linux'
- distribution = 'Oracle'
+ distribution = 'Ol'
strategy_class = RedHatStrategy
```
But the update of bundled distro to 1.4.0 means that `Oracle` is now returned, not `Ol` (#55459):
[lib/ansible/module_utils/distro/_distro.py#L55](https://github.com/ansible/ansible/blob/devel/lib/ansible/module_utils/distro/_distro.py#L55)
```
- NORMALIZED_OS_ID = {
+ NORMALIZED_OS_ID = {
+ 'ol': 'oracle', # Oracle Enterprise Linux
+ }
```
This was not picked up in testing when #56936 was merged into devel because there is no automated testing against Oracle Linux.
**How to fix** - simply revert as shown:
[lib/ansible/modules/system/hostname.py#L660](https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/system/hostname.py#L660)
```
class OracleLinuxHostname(Hostname):
platform = 'Linux'
- distribution = 'Ol'
+ distribution = 'Oracle'
strategy_class = RedHatStrategy
```
**NB:** does not affect stable-2.8 because distro-1.4.0 is not included.
|
https://github.com/ansible/ansible/issues/58444
|
https://github.com/ansible/ansible/pull/58510
|
393ea1cd55ece489d99e53ad317bbc8bbb3261db
|
1a5ae366f49ed117cc32a8c7c5f447d2d346fd94
| 2019-06-27T05:07:09Z |
python
| 2019-06-28T16:24:03Z |
changelogs/fragments/hostname-oracle-linux-regeression.yaml
| |
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,444 |
hostname module cannot be used on Oracle Linux
|
##### SUMMARY
In devel branch, hostname module doesn't recognise Oracle Linux.
Regression from PR #56936 caused by PR #55459.
stable-2.8 branch is OK.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
hostname
##### ANSIBLE VERSION
```
2.9 / devel
```
##### CONFIGURATION
##### OS / ENVIRONMENT
```
$ head -n5 /etc/os-release
NAME="Oracle Linux Server"
VERSION="7.4"
ID="ol"
VERSION_ID="7.4"
PRETTY_NAME="Oracle Linux Server 7.4"
```
##### STEPS TO REPRODUCE
```yaml
- name: set hostname
hostname:
name: "mytesthostname"
```
##### EXPECTED RESULTS
```
changed: [myhost]
```
##### ACTUAL RESULTS
```
fatal: [myhost]: FAILED! => {"changed": false, "msg": "hostname module cannot be used on platform Linux (Oracle)"}
```
##### ANALYSIS
This is a **regression** from PR #56936 caused by PR #55459.
Relevant lines from PR #56936:
[lib/ansible/modules/system/hostname.py#L660](https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/system/hostname.py#L660)
```
class OracleLinuxHostname(Hostname):
platform = 'Linux'
- distribution = 'Oracle'
+ distribution = 'Ol'
strategy_class = RedHatStrategy
```
But the update of bundled distro to 1.4.0 means that `Oracle` is now returned, not `Ol` (#55459):
[lib/ansible/module_utils/distro/_distro.py#L55](https://github.com/ansible/ansible/blob/devel/lib/ansible/module_utils/distro/_distro.py#L55)
```
- NORMALIZED_OS_ID = {
+ NORMALIZED_OS_ID = {
+ 'ol': 'oracle', # Oracle Enterprise Linux
+ }
```
This was not picked up in testing when #56936 was merged into devel because there is no automated testing against Oracle Linux.
**How to fix** - simply revert as shown:
[lib/ansible/modules/system/hostname.py#L660](https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/system/hostname.py#L660)
```
class OracleLinuxHostname(Hostname):
platform = 'Linux'
- distribution = 'Ol'
+ distribution = 'Oracle'
strategy_class = RedHatStrategy
```
**NB:** does not affect stable-2.8 because distro-1.4.0 is not included.
|
https://github.com/ansible/ansible/issues/58444
|
https://github.com/ansible/ansible/pull/58510
|
393ea1cd55ece489d99e53ad317bbc8bbb3261db
|
1a5ae366f49ed117cc32a8c7c5f447d2d346fd94
| 2019-06-27T05:07:09Z |
python
| 2019-06-28T16:24:03Z |
lib/ansible/modules/system/hostname.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2013, Hiroaki Nakamura <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: hostname
author:
- Adrian Likins (@alikins)
- Hideki Saito (@saito-hideki)
version_added: "1.4"
short_description: Manage hostname
requirements: [ hostname ]
description:
- Set system's hostname, supports most OSs/Distributions, including those using systemd.
- Note, this module does *NOT* modify C(/etc/hosts). You need to modify it yourself using other modules like template or replace.
- Windows, HP-UX and AIX are not currently supported.
options:
name:
description:
- Name of the host
required: true
use:
description:
- Which strategy to use to update the hostname.
- If not set we try to autodetect, but this can be problematic, specially with containers as they can present misleading information.
choices: ['generic', 'debian','sles', 'redhat', 'alpine', 'systemd', 'openrc', 'openbsd', 'solaris', 'freebsd']
version_added: '2.9'
'''
EXAMPLES = '''
- hostname:
name: web01
'''
import os
import socket
import traceback
from ansible.module_utils.basic import (
AnsibleModule,
get_distribution,
get_distribution_version,
get_platform,
load_platform_subclass,
)
from ansible.module_utils.facts.system.service_mgr import ServiceMgrFactCollector
from ansible.module_utils._text import to_native
STRATS = {'generic': 'Generic', 'debian': 'Debian', 'sles': 'SLES', 'redhat': 'RedHat', 'alpine': 'Alpine',
'systemd': 'Systemd', 'openrc': 'OpenRC', 'openbsd': 'OpenBSD', 'solaris': 'Solaris', 'freebsd': 'FreeBSD'}
class UnimplementedStrategy(object):
def __init__(self, module):
self.module = module
def update_current_and_permanent_hostname(self):
self.unimplemented_error()
def update_current_hostname(self):
self.unimplemented_error()
def update_permanent_hostname(self):
self.unimplemented_error()
def get_current_hostname(self):
self.unimplemented_error()
def set_current_hostname(self, name):
self.unimplemented_error()
def get_permanent_hostname(self):
self.unimplemented_error()
def set_permanent_hostname(self, name):
self.unimplemented_error()
def unimplemented_error(self):
platform = get_platform()
distribution = get_distribution()
if distribution is not None:
msg_platform = '%s (%s)' % (platform, distribution)
else:
msg_platform = platform
self.module.fail_json(
msg='hostname module cannot be used on platform %s' % msg_platform)
class Hostname(object):
"""
This is a generic Hostname manipulation class that is subclassed
based on platform.
A subclass may wish to set different strategy instance to self.strategy.
All subclasses MUST define platform and distribution (which may be None).
"""
platform = 'Generic'
distribution = None
strategy_class = UnimplementedStrategy
def __new__(cls, *args, **kwargs):
return load_platform_subclass(Hostname, args, kwargs)
def __init__(self, module):
self.module = module
self.name = module.params['name']
self.use = module.params['use']
if self.use is not None:
strat = globals()['%sStrategy' % STRATS[self.use]]
self.strategy = strat(module)
elif self.platform == 'Linux' and ServiceMgrFactCollector.is_systemd_managed(module):
self.strategy = SystemdStrategy(module)
else:
self.strategy = self.strategy_class(module)
def update_current_and_permanent_hostname(self):
return self.strategy.update_current_and_permanent_hostname()
def get_current_hostname(self):
return self.strategy.get_current_hostname()
def set_current_hostname(self, name):
self.strategy.set_current_hostname(name)
def get_permanent_hostname(self):
return self.strategy.get_permanent_hostname()
def set_permanent_hostname(self, name):
self.strategy.set_permanent_hostname(name)
class GenericStrategy(object):
"""
This is a generic Hostname manipulation strategy class.
A subclass may wish to override some or all of these methods.
- get_current_hostname()
- get_permanent_hostname()
- set_current_hostname(name)
- set_permanent_hostname(name)
"""
def __init__(self, module):
self.module = module
self.hostname_cmd = self.module.get_bin_path('hostname', True)
self.changed = False
def update_current_and_permanent_hostname(self):
self.update_current_hostname()
self.update_permanent_hostname()
return self.changed
def update_current_hostname(self):
name = self.module.params['name']
current_name = self.get_current_hostname()
if current_name != name:
if not self.module.check_mode:
self.set_current_hostname(name)
self.changed = True
def update_permanent_hostname(self):
name = self.module.params['name']
permanent_name = self.get_permanent_hostname()
if permanent_name != name:
if not self.module.check_mode:
self.set_permanent_hostname(name)
self.changed = True
def get_current_hostname(self):
cmd = [self.hostname_cmd]
rc, out, err = self.module.run_command(cmd)
if rc != 0:
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))
return to_native(out).strip()
def set_current_hostname(self, name):
cmd = [self.hostname_cmd, name]
rc, out, err = self.module.run_command(cmd)
if rc != 0:
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))
def get_permanent_hostname(self):
return 'UNKNOWN'
def set_permanent_hostname(self, name):
pass
class DebianStrategy(GenericStrategy):
"""
This is a Debian family Hostname manipulation strategy class - it edits
the /etc/hostname file.
"""
HOSTNAME_FILE = '/etc/hostname'
def get_permanent_hostname(self):
if not os.path.isfile(self.HOSTNAME_FILE):
try:
open(self.HOSTNAME_FILE, "a").write("")
except IOError as e:
self.module.fail_json(msg="failed to write file: %s" %
to_native(e), exception=traceback.format_exc())
try:
f = open(self.HOSTNAME_FILE)
try:
return f.read().strip()
finally:
f.close()
except Exception as e:
self.module.fail_json(msg="failed to read hostname: %s" %
to_native(e), exception=traceback.format_exc())
def set_permanent_hostname(self, name):
try:
f = open(self.HOSTNAME_FILE, 'w+')
try:
f.write("%s\n" % name)
finally:
f.close()
except Exception as e:
self.module.fail_json(msg="failed to update hostname: %s" %
to_native(e), exception=traceback.format_exc())
class SLESStrategy(GenericStrategy):
"""
This is a SLES Hostname strategy class - it edits the
/etc/HOSTNAME file.
"""
HOSTNAME_FILE = '/etc/HOSTNAME'
def get_permanent_hostname(self):
if not os.path.isfile(self.HOSTNAME_FILE):
try:
open(self.HOSTNAME_FILE, "a").write("")
except IOError as e:
self.module.fail_json(msg="failed to write file: %s" %
to_native(e), exception=traceback.format_exc())
try:
f = open(self.HOSTNAME_FILE)
try:
return f.read().strip()
finally:
f.close()
except Exception as e:
self.module.fail_json(msg="failed to read hostname: %s" %
to_native(e), exception=traceback.format_exc())
def set_permanent_hostname(self, name):
try:
f = open(self.HOSTNAME_FILE, 'w+')
try:
f.write("%s\n" % name)
finally:
f.close()
except Exception as e:
self.module.fail_json(msg="failed to update hostname: %s" %
to_native(e), exception=traceback.format_exc())
class RedHatStrategy(GenericStrategy):
"""
This is a Redhat Hostname strategy class - it edits the
/etc/sysconfig/network file.
"""
NETWORK_FILE = '/etc/sysconfig/network'
def get_permanent_hostname(self):
try:
f = open(self.NETWORK_FILE, 'rb')
try:
for line in f.readlines():
if line.startswith('HOSTNAME'):
k, v = line.split('=')
return v.strip()
finally:
f.close()
except Exception as e:
self.module.fail_json(msg="failed to read hostname: %s" %
to_native(e), exception=traceback.format_exc())
def set_permanent_hostname(self, name):
try:
lines = []
found = False
f = open(self.NETWORK_FILE, 'rb')
try:
for line in f.readlines():
if line.startswith('HOSTNAME'):
lines.append("HOSTNAME=%s\n" % name)
found = True
else:
lines.append(line)
finally:
f.close()
if not found:
lines.append("HOSTNAME=%s\n" % name)
f = open(self.NETWORK_FILE, 'w+')
try:
f.writelines(lines)
finally:
f.close()
except Exception as e:
self.module.fail_json(msg="failed to update hostname: %s" %
to_native(e), exception=traceback.format_exc())
class AlpineStrategy(GenericStrategy):
"""
This is a Alpine Linux Hostname manipulation strategy class - it edits
the /etc/hostname file then run hostname -F /etc/hostname.
"""
HOSTNAME_FILE = '/etc/hostname'
def update_current_and_permanent_hostname(self):
self.update_permanent_hostname()
self.update_current_hostname()
return self.changed
def get_permanent_hostname(self):
if not os.path.isfile(self.HOSTNAME_FILE):
try:
open(self.HOSTNAME_FILE, "a").write("")
except IOError as e:
self.module.fail_json(msg="failed to write file: %s" %
to_native(e), exception=traceback.format_exc())
try:
f = open(self.HOSTNAME_FILE)
try:
return f.read().strip()
finally:
f.close()
except Exception as e:
self.module.fail_json(msg="failed to read hostname: %s" %
to_native(e), exception=traceback.format_exc())
def set_permanent_hostname(self, name):
try:
f = open(self.HOSTNAME_FILE, 'w+')
try:
f.write("%s\n" % name)
finally:
f.close()
except Exception as e:
self.module.fail_json(msg="failed to update hostname: %s" %
to_native(e), exception=traceback.format_exc())
def set_current_hostname(self, name):
cmd = [self.hostname_cmd, '-F', self.HOSTNAME_FILE]
rc, out, err = self.module.run_command(cmd)
if rc != 0:
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))
class SystemdStrategy(GenericStrategy):
"""
This is a Systemd hostname manipulation strategy class - it uses
the hostnamectl command.
"""
def get_current_hostname(self):
cmd = ['hostname']
rc, out, err = self.module.run_command(cmd)
if rc != 0:
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))
return to_native(out).strip()
def set_current_hostname(self, name):
if len(name) > 64:
self.module.fail_json(msg="name cannot be longer than 64 characters on systemd servers, try a shorter name")
cmd = ['hostnamectl', '--transient', 'set-hostname', name]
rc, out, err = self.module.run_command(cmd)
if rc != 0:
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))
def get_permanent_hostname(self):
cmd = ['hostnamectl', '--static', 'status']
rc, out, err = self.module.run_command(cmd)
if rc != 0:
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))
return to_native(out).strip()
def set_permanent_hostname(self, name):
if len(name) > 64:
self.module.fail_json(msg="name cannot be longer than 64 characters on systemd servers, try a shorter name")
cmd = ['hostnamectl', '--pretty', 'set-hostname', name]
rc, out, err = self.module.run_command(cmd)
if rc != 0:
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))
cmd = ['hostnamectl', '--static', 'set-hostname', name]
rc, out, err = self.module.run_command(cmd)
if rc != 0:
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))
class OpenRCStrategy(GenericStrategy):
"""
This is a Gentoo (OpenRC) Hostname manipulation strategy class - it edits
the /etc/conf.d/hostname file.
"""
HOSTNAME_FILE = '/etc/conf.d/hostname'
def get_permanent_hostname(self):
name = 'UNKNOWN'
try:
try:
f = open(self.HOSTNAME_FILE, 'r')
for line in f:
line = line.strip()
if line.startswith('hostname='):
name = line[10:].strip('"')
break
except Exception as e:
self.module.fail_json(msg="failed to read hostname: %s" %
to_native(e), exception=traceback.format_exc())
finally:
f.close()
return name
def set_permanent_hostname(self, name):
try:
try:
f = open(self.HOSTNAME_FILE, 'r')
lines = [x.strip() for x in f]
for i, line in enumerate(lines):
if line.startswith('hostname='):
lines[i] = 'hostname="%s"' % name
break
f.close()
f = open(self.HOSTNAME_FILE, 'w')
f.write('\n'.join(lines) + '\n')
except Exception as e:
self.module.fail_json(msg="failed to update hostname: %s" %
to_native(e), exception=traceback.format_exc())
finally:
f.close()
class OpenBSDStrategy(GenericStrategy):
"""
This is a OpenBSD family Hostname manipulation strategy class - it edits
the /etc/myname file.
"""
HOSTNAME_FILE = '/etc/myname'
def get_permanent_hostname(self):
if not os.path.isfile(self.HOSTNAME_FILE):
try:
open(self.HOSTNAME_FILE, "a").write("")
except IOError as e:
self.module.fail_json(msg="failed to write file: %s" %
to_native(e), exception=traceback.format_exc())
try:
f = open(self.HOSTNAME_FILE)
try:
return f.read().strip()
finally:
f.close()
except Exception as e:
self.module.fail_json(msg="failed to read hostname: %s" %
to_native(e), exception=traceback.format_exc())
def set_permanent_hostname(self, name):
try:
f = open(self.HOSTNAME_FILE, 'w+')
try:
f.write("%s\n" % name)
finally:
f.close()
except Exception as e:
self.module.fail_json(msg="failed to update hostname: %s" %
to_native(e), exception=traceback.format_exc())
class SolarisStrategy(GenericStrategy):
"""
This is a Solaris11 or later Hostname manipulation strategy class - it
execute hostname command.
"""
def set_current_hostname(self, name):
cmd_option = '-t'
cmd = [self.hostname_cmd, cmd_option, name]
rc, out, err = self.module.run_command(cmd)
if rc != 0:
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))
def get_permanent_hostname(self):
fmri = 'svc:/system/identity:node'
pattern = 'config/nodename'
cmd = '/usr/sbin/svccfg -s %s listprop -o value %s' % (fmri, pattern)
rc, out, err = self.module.run_command(cmd, use_unsafe_shell=True)
if rc != 0:
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))
return to_native(out).strip()
def set_permanent_hostname(self, name):
cmd = [self.hostname_cmd, name]
rc, out, err = self.module.run_command(cmd)
if rc != 0:
self.module.fail_json(msg="Command failed rc=%d, out=%s, err=%s" % (rc, out, err))
class FreeBSDStrategy(GenericStrategy):
"""
This is a FreeBSD hostname manipulation strategy class - it edits
the /etc/rc.conf.d/hostname file.
"""
HOSTNAME_FILE = '/etc/rc.conf.d/hostname'
def get_permanent_hostname(self):
name = 'UNKNOWN'
if not os.path.isfile(self.HOSTNAME_FILE):
try:
open(self.HOSTNAME_FILE, "a").write("hostname=temporarystub\n")
except IOError as e:
self.module.fail_json(msg="failed to write file: %s" %
to_native(e), exception=traceback.format_exc())
try:
try:
f = open(self.HOSTNAME_FILE, 'r')
for line in f:
line = line.strip()
if line.startswith('hostname='):
name = line[10:].strip('"')
break
except Exception as e:
self.module.fail_json(msg="failed to read hostname: %s" %
to_native(e), exception=traceback.format_exc())
finally:
f.close()
return name
def set_permanent_hostname(self, name):
try:
try:
f = open(self.HOSTNAME_FILE, 'r')
lines = [x.strip() for x in f]
for i, line in enumerate(lines):
if line.startswith('hostname='):
lines[i] = 'hostname="%s"' % name
break
f.close()
f = open(self.HOSTNAME_FILE, 'w')
f.write('\n'.join(lines) + '\n')
except Exception as e:
self.module.fail_json(msg="failed to update hostname: %s" %
to_native(e), exception=traceback.format_exc())
finally:
f.close()
class FedoraHostname(Hostname):
platform = 'Linux'
distribution = 'Fedora'
strategy_class = SystemdStrategy
class SLESHostname(Hostname):
platform = 'Linux'
distribution = 'Sles'
try:
distribution_version = get_distribution_version()
# cast to float may raise ValueError on non SLES, we use float for a little more safety over int
if distribution_version and 10 <= float(distribution_version) <= 12:
strategy_class = SLESStrategy
else:
raise ValueError()
except ValueError:
strategy_class = UnimplementedStrategy
class OpenSUSEHostname(Hostname):
platform = 'Linux'
distribution = 'Opensuse'
strategy_class = SystemdStrategy
class OpenSUSELeapHostname(Hostname):
platform = 'Linux'
distribution = 'Opensuse-leap'
strategy_class = SystemdStrategy
class ArchHostname(Hostname):
platform = 'Linux'
distribution = 'Arch'
strategy_class = SystemdStrategy
class ArchARMHostname(Hostname):
platform = 'Linux'
distribution = 'Archarm'
strategy_class = SystemdStrategy
class RHELHostname(Hostname):
platform = 'Linux'
distribution = 'Redhat'
strategy_class = RedHatStrategy
class CentOSHostname(Hostname):
platform = 'Linux'
distribution = 'Centos'
strategy_class = RedHatStrategy
class ClearLinuxHostname(Hostname):
platform = 'Linux'
distribution = 'Clear-linux-os'
strategy_class = SystemdStrategy
class CloudlinuxHostname(Hostname):
platform = 'Linux'
distribution = 'Cloudlinux'
strategy_class = RedHatStrategy
class CoreosHostname(Hostname):
platform = 'Linux'
distribution = 'Coreos'
strategy_class = SystemdStrategy
class ScientificHostname(Hostname):
platform = 'Linux'
distribution = 'Scientific'
strategy_class = RedHatStrategy
class OracleLinuxHostname(Hostname):
platform = 'Linux'
distribution = 'Ol'
strategy_class = RedHatStrategy
class VirtuozzoLinuxHostname(Hostname):
platform = 'Linux'
distribution = 'Virtuozzo'
strategy_class = RedHatStrategy
class AmazonLinuxHostname(Hostname):
platform = 'Linux'
distribution = 'Amazon'
strategy_class = RedHatStrategy
class DebianHostname(Hostname):
platform = 'Linux'
distribution = 'Debian'
strategy_class = DebianStrategy
class CumulusHostname(Hostname):
platform = 'Linux'
distribution = 'Cumulus-linux'
strategy_class = DebianStrategy
class KaliHostname(Hostname):
platform = 'Linux'
distribution = 'Kali'
strategy_class = DebianStrategy
class UbuntuHostname(Hostname):
platform = 'Linux'
distribution = 'Ubuntu'
strategy_class = DebianStrategy
class LinuxmintHostname(Hostname):
platform = 'Linux'
distribution = 'Linuxmint'
strategy_class = DebianStrategy
class LinaroHostname(Hostname):
platform = 'Linux'
distribution = 'Linaro'
strategy_class = DebianStrategy
class DevuanHostname(Hostname):
platform = 'Linux'
distribution = 'Devuan'
strategy_class = DebianStrategy
class RaspbianHostname(Hostname):
platform = 'Linux'
distribution = 'Raspbian'
strategy_class = DebianStrategy
class GentooHostname(Hostname):
platform = 'Linux'
distribution = 'Gentoo'
strategy_class = OpenRCStrategy
class ALTLinuxHostname(Hostname):
platform = 'Linux'
distribution = 'Altlinux'
strategy_class = RedHatStrategy
class AlpineLinuxHostname(Hostname):
platform = 'Linux'
distribution = 'Alpine'
strategy_class = AlpineStrategy
class OpenBSDHostname(Hostname):
platform = 'OpenBSD'
distribution = None
strategy_class = OpenBSDStrategy
class SolarisHostname(Hostname):
platform = 'SunOS'
distribution = None
strategy_class = SolarisStrategy
class FreeBSDHostname(Hostname):
platform = 'FreeBSD'
distribution = None
strategy_class = FreeBSDStrategy
class NetBSDHostname(Hostname):
platform = 'NetBSD'
distribution = None
strategy_class = FreeBSDStrategy
class NeonHostname(Hostname):
platform = 'Linux'
distribution = 'Neon'
strategy_class = DebianStrategy
def main():
module = AnsibleModule(
argument_spec=dict(
name=dict(type='str', required=True),
use=dict(type='str', choices=STRATS.keys())
),
supports_check_mode=True,
)
hostname = Hostname(module)
name = module.params['name']
current_hostname = hostname.get_current_hostname()
permanent_hostname = hostname.get_permanent_hostname()
changed = hostname.update_current_and_permanent_hostname()
if name != current_hostname:
name_before = current_hostname
elif name != permanent_hostname:
name_before = permanent_hostname
kw = dict(changed=changed, name=name,
ansible_facts=dict(ansible_hostname=name.split('.')[0],
ansible_nodename=name,
ansible_fqdn=socket.getfqdn(),
ansible_domain='.'.join(socket.getfqdn().split('.')[1:])))
if changed:
kw['diff'] = {'after': 'hostname = ' + name + '\n',
'before': 'hostname = ' + name_before + '\n'}
module.exit_json(**kw)
if __name__ == '__main__':
main()
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,420 |
The unarchive integration test fails when LC_ALL is not set.
|
##### SUMMARY
The unarchive integration test fails when LC_ALL is not set.
##### ISSUE TYPE
Bug Report
##### COMPONENT NAME
unarchive
##### ANSIBLE VERSION
devel
##### CONFIGURATION
N/A
##### OS / ENVIRONMENT
N/A
##### STEPS TO REPRODUCE
1. Set `ansible_connection=ssh ansible_host=localhost` for `testhost` to prevent modules from inheriting the environment from the controller: https://github.com/ansible/ansible/blob/edcb5b6775adac09eee5412b499b8f0aa5194610/test/integration/inventory#L6
2. Run the test in an environment where LC_ALL is not set by default: `ansible-test integration unarchive --remote freebsd/12.0 -v`
##### EXPECTED RESULTS
Tests pass.
##### ACTUAL RESULTS
Tests traceback:
```
TASK [unarchive : test that unarchive works with an archive that contains non-ascii filenames] **************************************************************************
fatal: [testhost]: FAILED! => {"changed": false, "module_stderr": "Shared connection to localhost closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 139, in <module>\r\n _ansiballz_main()\r\n File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 131, in _ansiballz_main\r\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 65, in invoke_module\r\n spec.loader.exec_module(module)\r\n File \"<frozen importlib._bootstrap_external>\", line 678, in exec_module\r\n File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\r\n File \"/tmp/ansible_unarchive_payload_o9_x930g/__main__.py\", line 909, in <module>\r\n File \"/tmp/ansible_unarchive_payload_o9_x930g/__main__.py\", line 859, in main\r\n File \"/usr/local/lib/python3.6/genericpath.py\", line 42, in isdir\r\n st = os.stat(s)\r\nUnicodeEncodeError: 'ascii' codec can't encode characters in position 51-54: ordinal not in range(128)\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}
```
Failure on Shippable: https://app.shippable.com/github/ansible/ansible/runs/129521/18/tests
|
https://github.com/ansible/ansible/issues/58420
|
https://github.com/ansible/ansible/pull/58431
|
7ed7d374e43819282b21a20048eff768d8a0a018
|
23f0ca0acdc09ad4371e8f9eda3315cff8f75345
| 2019-06-26T19:19:22Z |
python
| 2019-06-28T16:47:10Z |
lib/ansible/modules/files/unarchive.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2012, Michael DeHaan <[email protected]>
# Copyright: (c) 2013, Dylan Martin <[email protected]>
# Copyright: (c) 2015, Toshio Kuratomi <[email protected]>
# Copyright: (c) 2016, Dag Wieers <[email protected]>
# Copyright: (c) 2017, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'core'}
DOCUMENTATION = r'''
---
module: unarchive
version_added: '1.4'
short_description: Unpacks an archive after (optionally) copying it from the local machine.
description:
- The C(unarchive) module unpacks an archive. It will not unpack a compressed file that does not contain an archive.
- By default, it will copy the source file from the local system to the target before unpacking.
- Set C(remote_src=yes) to unpack an archive which already exists on the target.
- If checksum validation is desired, use M(get_url) or M(uri) instead to fetch the file and set C(remote_src=yes).
- For Windows targets, use the M(win_unzip) module instead.
options:
src:
description:
- If C(remote_src=no) (default), local path to archive file to copy to the target server; can be absolute or relative. If C(remote_src=yes), path on the
target server to existing archive file to unpack.
- If C(remote_src=yes) and C(src) contains C(://), the remote machine will download the file from the URL first. (version_added 2.0). This is only for
simple cases, for full download support use the M(get_url) module.
type: path
required: true
dest:
description:
- Remote absolute path where the archive should be unpacked.
type: path
required: true
copy:
description:
- If true, the file is copied from local 'master' to the target machine, otherwise, the plugin will look for src archive at the target machine.
- This option has been deprecated in favor of C(remote_src).
- This option is mutually exclusive with C(remote_src).
type: bool
default: yes
creates:
description:
- If the specified absolute path (file or directory) already exists, this step will B(not) be run.
type: path
version_added: "1.6"
list_files:
description:
- If set to True, return the list of files that are contained in the tarball.
type: bool
default: no
version_added: "2.0"
exclude:
description:
- List the directory and file entries that you would like to exclude from the unarchive action.
type: list
version_added: "2.1"
keep_newer:
description:
- Do not replace existing files that are newer than files from the archive.
type: bool
default: no
version_added: "2.1"
extra_opts:
description:
- Specify additional options by passing in an array.
type: list
default: ""
version_added: "2.1"
remote_src:
description:
- Set to C(yes) to indicate the archived file is already on the remote system and not local to the Ansible controller.
- This option is mutually exclusive with C(copy).
type: bool
default: no
version_added: "2.2"
validate_certs:
description:
- This only applies if using a https URL as the source of the file.
- This should only set to C(no) used on personally controlled sites using self-signed certificate.
- Prior to 2.2 the code worked as if this was set to C(yes).
type: bool
default: yes
version_added: "2.2"
extends_documentation_fragment:
- decrypt
- files
todo:
- Re-implement tar support using native tarfile module.
- Re-implement zip support using native zipfile module.
notes:
- Requires C(gtar)/C(unzip) command on target host.
- Can handle I(.zip) files using C(unzip) as well as I(.tar), I(.tar.gz), I(.tar.bz2) and I(.tar.xz) files using C(gtar).
- Does not handle I(.gz) files, I(.bz2) files or I(.xz) files that do not contain a I(.tar) archive.
- Uses gtar's C(--diff) arg to calculate if changed or not. If this C(arg) is not
supported, it will always unpack the archive.
- Existing files/directories in the destination which are not in the archive
are not touched. This is the same behavior as a normal archive extraction.
- Existing files/directories in the destination which are not in the archive
are ignored for purposes of deciding if the archive should be unpacked or not.
seealso:
- module: archive
- module: iso_extract
- module: win_unzip
author: Michael DeHaan
'''
EXAMPLES = r'''
- name: Extract foo.tgz into /var/lib/foo
unarchive:
src: foo.tgz
dest: /var/lib/foo
- name: Unarchive a file that is already on the remote machine
unarchive:
src: /tmp/foo.zip
dest: /usr/local/bin
remote_src: yes
- name: Unarchive a file that needs to be downloaded (added in 2.0)
unarchive:
src: https://example.com/example.zip
dest: /usr/local/bin
remote_src: yes
- name: Unarchive a file with extra options
unarchive:
src: /tmp/foo.zip
dest: /usr/local/bin
extra_opts:
- --transform
- s/^xxx/yyy/
'''
import binascii
import codecs
import datetime
import fnmatch
import grp
import os
import platform
import pwd
import re
import stat
import time
import traceback
from zipfile import ZipFile, BadZipfile
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.urls import fetch_file
from ansible.module_utils._text import to_bytes, to_native, to_text
try: # python 3.3+
from shlex import quote
except ImportError: # older python
from pipes import quote
# String from tar that shows the tar contents are different from the
# filesystem
OWNER_DIFF_RE = re.compile(r': Uid differs$')
GROUP_DIFF_RE = re.compile(r': Gid differs$')
MODE_DIFF_RE = re.compile(r': Mode differs$')
MOD_TIME_DIFF_RE = re.compile(r': Mod time differs$')
# NEWER_DIFF_RE = re.compile(r' is newer or same age.$')
EMPTY_FILE_RE = re.compile(r': : Warning: Cannot stat: No such file or directory$')
MISSING_FILE_RE = re.compile(r': Warning: Cannot stat: No such file or directory$')
ZIP_FILE_MODE_RE = re.compile(r'([r-][w-][SsTtx-]){3}')
INVALID_OWNER_RE = re.compile(r': Invalid owner')
INVALID_GROUP_RE = re.compile(r': Invalid group')
def crc32(path):
''' Return a CRC32 checksum of a file '''
with open(path, 'rb') as f:
file_content = f.read()
return binascii.crc32(file_content) & 0xffffffff
def shell_escape(string):
''' Quote meta-characters in the args for the unix shell '''
return re.sub(r'([^A-Za-z0-9_])', r'\\\1', string)
class UnarchiveError(Exception):
pass
class ZipArchive(object):
def __init__(self, src, dest, file_args, module):
self.src = src
self.dest = dest
self.file_args = file_args
self.opts = module.params['extra_opts']
self.module = module
self.excludes = module.params['exclude']
self.includes = []
self.cmd_path = self.module.get_bin_path('unzip')
self.zipinfocmd_path = self.module.get_bin_path('zipinfo')
self._files_in_archive = []
self._infodict = dict()
def _permstr_to_octal(self, modestr, umask):
''' Convert a Unix permission string (rw-r--r--) into a mode (0644) '''
revstr = modestr[::-1]
mode = 0
for j in range(0, 3):
for i in range(0, 3):
if revstr[i + 3 * j] in ['r', 'w', 'x', 's', 't']:
mode += 2 ** (i + 3 * j)
# The unzip utility does not support setting the stST bits
# if revstr[i + 3 * j] in ['s', 't', 'S', 'T' ]:
# mode += 2 ** (9 + j)
return (mode & ~umask)
def _legacy_file_list(self, force_refresh=False):
unzip_bin = self.module.get_bin_path('unzip')
if not unzip_bin:
raise UnarchiveError('Python Zipfile cannot read %s and unzip not found' % self.src)
rc, out, err = self.module.run_command([unzip_bin, '-v', self.src])
if rc:
raise UnarchiveError('Neither python zipfile nor unzip can read %s' % self.src)
for line in out.splitlines()[3:-2]:
fields = line.split(None, 7)
self._files_in_archive.append(fields[7])
self._infodict[fields[7]] = int(fields[6])
def _crc32(self, path):
if self._infodict:
return self._infodict[path]
try:
archive = ZipFile(self.src)
except BadZipfile as e:
if e.args[0].lower().startswith('bad magic number'):
# Python2.4 can't handle zipfiles with > 64K files. Try using
# /usr/bin/unzip instead
self._legacy_file_list()
else:
raise
else:
try:
for item in archive.infolist():
self._infodict[item.filename] = int(item.CRC)
except Exception:
archive.close()
raise UnarchiveError('Unable to list files in the archive')
return self._infodict[path]
@property
def files_in_archive(self, force_refresh=False):
if self._files_in_archive and not force_refresh:
return self._files_in_archive
self._files_in_archive = []
try:
archive = ZipFile(self.src)
except BadZipfile as e:
if e.args[0].lower().startswith('bad magic number'):
# Python2.4 can't handle zipfiles with > 64K files. Try using
# /usr/bin/unzip instead
self._legacy_file_list(force_refresh)
else:
raise
else:
try:
for member in archive.namelist():
exclude_flag = False
if self.excludes:
for exclude in self.excludes:
if fnmatch.fnmatch(member, exclude):
exclude_flag = True
break
if not exclude_flag:
self._files_in_archive.append(to_native(member))
except Exception:
archive.close()
raise UnarchiveError('Unable to list files in the archive')
archive.close()
return self._files_in_archive
def is_unarchived(self):
# BSD unzip doesn't support zipinfo listings with timestamp.
cmd = [self.zipinfocmd_path, '-T', '-s', self.src]
if self.excludes:
cmd.extend(['-x', ] + self.excludes)
rc, out, err = self.module.run_command(cmd)
old_out = out
diff = ''
out = ''
if rc == 0:
unarchived = True
else:
unarchived = False
# Get some information related to user/group ownership
umask = os.umask(0)
os.umask(umask)
systemtype = platform.system()
# Get current user and group information
groups = os.getgroups()
run_uid = os.getuid()
run_gid = os.getgid()
try:
run_owner = pwd.getpwuid(run_uid).pw_name
except (TypeError, KeyError):
run_owner = run_uid
try:
run_group = grp.getgrgid(run_gid).gr_name
except (KeyError, ValueError, OverflowError):
run_group = run_gid
# Get future user ownership
fut_owner = fut_uid = None
if self.file_args['owner']:
try:
tpw = pwd.getpwnam(self.file_args['owner'])
except KeyError:
try:
tpw = pwd.getpwuid(self.file_args['owner'])
except (TypeError, KeyError):
tpw = pwd.getpwuid(run_uid)
fut_owner = tpw.pw_name
fut_uid = tpw.pw_uid
else:
try:
fut_owner = run_owner
except Exception:
pass
fut_uid = run_uid
# Get future group ownership
fut_group = fut_gid = None
if self.file_args['group']:
try:
tgr = grp.getgrnam(self.file_args['group'])
except (ValueError, KeyError):
try:
tgr = grp.getgrgid(self.file_args['group'])
except (KeyError, ValueError, OverflowError):
tgr = grp.getgrgid(run_gid)
fut_group = tgr.gr_name
fut_gid = tgr.gr_gid
else:
try:
fut_group = run_group
except Exception:
pass
fut_gid = run_gid
for line in old_out.splitlines():
change = False
pcs = line.split(None, 7)
if len(pcs) != 8:
# Too few fields... probably a piece of the header or footer
continue
# Check first and seventh field in order to skip header/footer
if len(pcs[0]) != 7 and len(pcs[0]) != 10:
continue
if len(pcs[6]) != 15:
continue
# Possible entries:
# -rw-rws--- 1.9 unx 2802 t- defX 11-Aug-91 13:48 perms.2660
# -rw-a-- 1.0 hpf 5358 Tl i4:3 4-Dec-91 11:33 longfilename.hpfs
# -r--ahs 1.1 fat 4096 b- i4:2 14-Jul-91 12:58 EA DATA. SF
# --w------- 1.0 mac 17357 bx i8:2 4-May-92 04:02 unzip.macr
if pcs[0][0] not in 'dl-?' or not frozenset(pcs[0][1:]).issubset('rwxstah-'):
continue
ztype = pcs[0][0]
permstr = pcs[0][1:]
version = pcs[1]
ostype = pcs[2]
size = int(pcs[3])
path = to_text(pcs[7], errors='surrogate_or_strict')
# Skip excluded files
if path in self.excludes:
out += 'Path %s is excluded on request\n' % path
continue
# Itemized change requires L for symlink
if path[-1] == '/':
if ztype != 'd':
err += 'Path %s incorrectly tagged as "%s", but is a directory.\n' % (path, ztype)
ftype = 'd'
elif ztype == 'l':
ftype = 'L'
elif ztype == '-':
ftype = 'f'
elif ztype == '?':
ftype = 'f'
# Some files may be storing FAT permissions, not Unix permissions
# For FAT permissions, we will use a base permissions set of 777 if the item is a directory or has the execute bit set. Otherwise, 666.
# This permission will then be modified by the system UMask.
# BSD always applies the Umask, even to Unix permissions.
# For Unix style permissions on Linux or Mac, we want to use them directly.
# So we set the UMask for this file to zero. That permission set will then be unchanged when calling _permstr_to_octal
if len(permstr) == 6:
if path[-1] == '/':
permstr = 'rwxrwxrwx'
elif permstr == 'rwx---':
permstr = 'rwxrwxrwx'
else:
permstr = 'rw-rw-rw-'
file_umask = umask
elif 'bsd' in systemtype.lower():
file_umask = umask
else:
file_umask = 0
# Test string conformity
if len(permstr) != 9 or not ZIP_FILE_MODE_RE.match(permstr):
raise UnarchiveError('ZIP info perm format incorrect, %s' % permstr)
# DEBUG
# err += "%s%s %10d %s\n" % (ztype, permstr, size, path)
dest = os.path.join(self.dest, path)
try:
st = os.lstat(dest)
except Exception:
change = True
self.includes.append(path)
err += 'Path %s is missing\n' % path
diff += '>%s++++++.?? %s\n' % (ftype, path)
continue
# Compare file types
if ftype == 'd' and not stat.S_ISDIR(st.st_mode):
change = True
self.includes.append(path)
err += 'File %s already exists, but not as a directory\n' % path
diff += 'c%s++++++.?? %s\n' % (ftype, path)
continue
if ftype == 'f' and not stat.S_ISREG(st.st_mode):
change = True
unarchived = False
self.includes.append(path)
err += 'Directory %s already exists, but not as a regular file\n' % path
diff += 'c%s++++++.?? %s\n' % (ftype, path)
continue
if ftype == 'L' and not stat.S_ISLNK(st.st_mode):
change = True
self.includes.append(path)
err += 'Directory %s already exists, but not as a symlink\n' % path
diff += 'c%s++++++.?? %s\n' % (ftype, path)
continue
itemized = list('.%s.......??' % ftype)
# Note: this timestamp calculation has a rounding error
# somewhere... unzip and this timestamp can be one second off
# When that happens, we report a change and re-unzip the file
dt_object = datetime.datetime(*(time.strptime(pcs[6], '%Y%m%d.%H%M%S')[0:6]))
timestamp = time.mktime(dt_object.timetuple())
# Compare file timestamps
if stat.S_ISREG(st.st_mode):
if self.module.params['keep_newer']:
if timestamp > st.st_mtime:
change = True
self.includes.append(path)
err += 'File %s is older, replacing file\n' % path
itemized[4] = 't'
elif stat.S_ISREG(st.st_mode) and timestamp < st.st_mtime:
# Add to excluded files, ignore other changes
out += 'File %s is newer, excluding file\n' % path
self.excludes.append(path)
continue
else:
if timestamp != st.st_mtime:
change = True
self.includes.append(path)
err += 'File %s differs in mtime (%f vs %f)\n' % (path, timestamp, st.st_mtime)
itemized[4] = 't'
# Compare file sizes
if stat.S_ISREG(st.st_mode) and size != st.st_size:
change = True
err += 'File %s differs in size (%d vs %d)\n' % (path, size, st.st_size)
itemized[3] = 's'
# Compare file checksums
if stat.S_ISREG(st.st_mode):
crc = crc32(dest)
if crc != self._crc32(path):
change = True
err += 'File %s differs in CRC32 checksum (0x%08x vs 0x%08x)\n' % (path, self._crc32(path), crc)
itemized[2] = 'c'
# Compare file permissions
# Do not handle permissions of symlinks
if ftype != 'L':
# Use the new mode provided with the action, if there is one
if self.file_args['mode']:
if isinstance(self.file_args['mode'], int):
mode = self.file_args['mode']
else:
try:
mode = int(self.file_args['mode'], 8)
except Exception as e:
try:
mode = AnsibleModule._symbolic_mode_to_octal(st, self.file_args['mode'])
except ValueError as e:
self.module.fail_json(path=path, msg="%s" % to_native(e), exception=traceback.format_exc())
# Only special files require no umask-handling
elif ztype == '?':
mode = self._permstr_to_octal(permstr, 0)
else:
mode = self._permstr_to_octal(permstr, file_umask)
if mode != stat.S_IMODE(st.st_mode):
change = True
itemized[5] = 'p'
err += 'Path %s differs in permissions (%o vs %o)\n' % (path, mode, stat.S_IMODE(st.st_mode))
# Compare file user ownership
owner = uid = None
try:
owner = pwd.getpwuid(st.st_uid).pw_name
except (TypeError, KeyError):
uid = st.st_uid
# If we are not root and requested owner is not our user, fail
if run_uid != 0 and (fut_owner != run_owner or fut_uid != run_uid):
raise UnarchiveError('Cannot change ownership of %s to %s, as user %s' % (path, fut_owner, run_owner))
if owner and owner != fut_owner:
change = True
err += 'Path %s is owned by user %s, not by user %s as expected\n' % (path, owner, fut_owner)
itemized[6] = 'o'
elif uid and uid != fut_uid:
change = True
err += 'Path %s is owned by uid %s, not by uid %s as expected\n' % (path, uid, fut_uid)
itemized[6] = 'o'
# Compare file group ownership
group = gid = None
try:
group = grp.getgrgid(st.st_gid).gr_name
except (KeyError, ValueError, OverflowError):
gid = st.st_gid
if run_uid != 0 and fut_gid not in groups:
raise UnarchiveError('Cannot change group ownership of %s to %s, as user %s' % (path, fut_group, run_owner))
if group and group != fut_group:
change = True
err += 'Path %s is owned by group %s, not by group %s as expected\n' % (path, group, fut_group)
itemized[6] = 'g'
elif gid and gid != fut_gid:
change = True
err += 'Path %s is owned by gid %s, not by gid %s as expected\n' % (path, gid, fut_gid)
itemized[6] = 'g'
# Register changed files and finalize diff output
if change:
if path not in self.includes:
self.includes.append(path)
diff += '%s %s\n' % (''.join(itemized), path)
if self.includes:
unarchived = False
# DEBUG
# out = old_out + out
return dict(unarchived=unarchived, rc=rc, out=out, err=err, cmd=cmd, diff=diff)
def unarchive(self):
cmd = [self.cmd_path, '-o']
if self.opts:
cmd.extend(self.opts)
cmd.append(self.src)
# NOTE: Including (changed) files as arguments is problematic (limits on command line/arguments)
# if self.includes:
# NOTE: Command unzip has this strange behaviour where it expects quoted filenames to also be escaped
# cmd.extend(map(shell_escape, self.includes))
if self.excludes:
cmd.extend(['-x'] + self.excludes)
cmd.extend(['-d', self.dest])
rc, out, err = self.module.run_command(cmd)
return dict(cmd=cmd, rc=rc, out=out, err=err)
def can_handle_archive(self):
if not self.cmd_path:
return False, 'Command "unzip" not found.'
cmd = [self.cmd_path, '-l', self.src]
rc, out, err = self.module.run_command(cmd)
if rc == 0:
return True, None
return False, 'Command "%s" could not handle archive.' % self.cmd_path
class TgzArchive(object):
def __init__(self, src, dest, file_args, module):
self.src = src
self.dest = dest
self.file_args = file_args
self.opts = module.params['extra_opts']
self.module = module
if self.module.check_mode:
self.module.exit_json(skipped=True, msg="remote module (%s) does not support check mode when using gtar" % self.module._name)
self.excludes = [path.rstrip('/') for path in self.module.params['exclude']]
# Prefer gtar (GNU tar) as it supports the compression options -z, -j and -J
self.cmd_path = self.module.get_bin_path('gtar', None)
if not self.cmd_path:
# Fallback to tar
self.cmd_path = self.module.get_bin_path('tar')
self.zipflag = '-z'
self._files_in_archive = []
if self.cmd_path:
self.tar_type = self._get_tar_type()
else:
self.tar_type = None
def _get_tar_type(self):
cmd = [self.cmd_path, '--version']
(rc, out, err) = self.module.run_command(cmd)
tar_type = None
if out.startswith('bsdtar'):
tar_type = 'bsd'
elif out.startswith('tar') and 'GNU' in out:
tar_type = 'gnu'
return tar_type
@property
def files_in_archive(self, force_refresh=False):
if self._files_in_archive and not force_refresh:
return self._files_in_archive
cmd = [self.cmd_path, '--list', '-C', self.dest]
if self.zipflag:
cmd.append(self.zipflag)
if self.opts:
cmd.extend(['--show-transformed-names'] + self.opts)
if self.excludes:
cmd.extend(['--exclude=' + f for f in self.excludes])
cmd.extend(['-f', self.src])
rc, out, err = self.module.run_command(cmd, cwd=self.dest, environ_update=dict(LANG='C', LC_ALL='C', LC_MESSAGES='C'))
if rc != 0:
raise UnarchiveError('Unable to list files in the archive')
for filename in out.splitlines():
# Compensate for locale-related problems in gtar output (octal unicode representation) #11348
# filename = filename.decode('string_escape')
filename = to_native(codecs.escape_decode(filename)[0])
# We don't allow absolute filenames. If the user wants to unarchive rooted in "/"
# they need to use "dest: '/'". This follows the defaults for gtar, pax, etc.
# Allowing absolute filenames here also causes bugs: https://github.com/ansible/ansible/issues/21397
if filename.startswith('/'):
filename = filename[1:]
exclude_flag = False
if self.excludes:
for exclude in self.excludes:
if fnmatch.fnmatch(filename, exclude):
exclude_flag = True
break
if not exclude_flag:
self._files_in_archive.append(to_native(filename))
return self._files_in_archive
def is_unarchived(self):
cmd = [self.cmd_path, '--diff', '-C', self.dest]
if self.zipflag:
cmd.append(self.zipflag)
if self.opts:
cmd.extend(['--show-transformed-names'] + self.opts)
if self.file_args['owner']:
cmd.append('--owner=' + quote(self.file_args['owner']))
if self.file_args['group']:
cmd.append('--group=' + quote(self.file_args['group']))
if self.module.params['keep_newer']:
cmd.append('--keep-newer-files')
if self.excludes:
cmd.extend(['--exclude=' + f for f in self.excludes])
cmd.extend(['-f', self.src])
rc, out, err = self.module.run_command(cmd, cwd=self.dest, environ_update=dict(LANG='C', LC_ALL='C', LC_MESSAGES='C'))
# Check whether the differences are in something that we're
# setting anyway
# What is different
unarchived = True
old_out = out
out = ''
run_uid = os.getuid()
# When unarchiving as a user, or when owner/group/mode is supplied --diff is insufficient
# Only way to be sure is to check request with what is on disk (as we do for zip)
# Leave this up to set_fs_attributes_if_different() instead of inducing a (false) change
for line in old_out.splitlines() + err.splitlines():
# FIXME: Remove the bogus lines from error-output as well !
# Ignore bogus errors on empty filenames (when using --split-component)
if EMPTY_FILE_RE.search(line):
continue
if run_uid == 0 and not self.file_args['owner'] and OWNER_DIFF_RE.search(line):
out += line + '\n'
if run_uid == 0 and not self.file_args['group'] and GROUP_DIFF_RE.search(line):
out += line + '\n'
if not self.file_args['mode'] and MODE_DIFF_RE.search(line):
out += line + '\n'
if MOD_TIME_DIFF_RE.search(line):
out += line + '\n'
if MISSING_FILE_RE.search(line):
out += line + '\n'
if INVALID_OWNER_RE.search(line):
out += line + '\n'
if INVALID_GROUP_RE.search(line):
out += line + '\n'
if out:
unarchived = False
return dict(unarchived=unarchived, rc=rc, out=out, err=err, cmd=cmd)
def unarchive(self):
cmd = [self.cmd_path, '--extract', '-C', self.dest]
if self.zipflag:
cmd.append(self.zipflag)
if self.opts:
cmd.extend(['--show-transformed-names'] + self.opts)
if self.file_args['owner']:
cmd.append('--owner=' + quote(self.file_args['owner']))
if self.file_args['group']:
cmd.append('--group=' + quote(self.file_args['group']))
if self.module.params['keep_newer']:
cmd.append('--keep-newer-files')
if self.excludes:
cmd.extend(['--exclude=' + f for f in self.excludes])
cmd.extend(['-f', self.src])
rc, out, err = self.module.run_command(cmd, cwd=self.dest, environ_update=dict(LANG='C', LC_ALL='C', LC_MESSAGES='C'))
return dict(cmd=cmd, rc=rc, out=out, err=err)
def can_handle_archive(self):
if not self.cmd_path:
return False, 'Commands "gtar" and "tar" not found.'
if self.tar_type != 'gnu':
return False, 'Command "%s" detected as tar type %s. GNU tar required.' % (self.cmd_path, self.tar_type)
try:
if self.files_in_archive:
return True, None
except UnarchiveError:
return False, 'Command "%s" could not handle archive.' % self.cmd_path
# Errors and no files in archive assume that we weren't able to
# properly unarchive it
return False, 'Command "%s" found no files in archive.' % self.cmd_path
# Class to handle tar files that aren't compressed
class TarArchive(TgzArchive):
def __init__(self, src, dest, file_args, module):
super(TarArchive, self).__init__(src, dest, file_args, module)
# argument to tar
self.zipflag = ''
# Class to handle bzip2 compressed tar files
class TarBzipArchive(TgzArchive):
def __init__(self, src, dest, file_args, module):
super(TarBzipArchive, self).__init__(src, dest, file_args, module)
self.zipflag = '-j'
# Class to handle xz compressed tar files
class TarXzArchive(TgzArchive):
def __init__(self, src, dest, file_args, module):
super(TarXzArchive, self).__init__(src, dest, file_args, module)
self.zipflag = '-J'
# try handlers in order and return the one that works or bail if none work
def pick_handler(src, dest, file_args, module):
handlers = [ZipArchive, TgzArchive, TarArchive, TarBzipArchive, TarXzArchive]
reasons = set()
for handler in handlers:
obj = handler(src, dest, file_args, module)
(can_handle, reason) = obj.can_handle_archive()
if can_handle:
return obj
reasons.add(reason)
reason_msg = ' '.join(reasons)
module.fail_json(msg='Failed to find handler for "%s". Make sure the required command to extract the file is installed. %s' % (src, reason_msg))
def main():
module = AnsibleModule(
# not checking because of daisy chain to file module
argument_spec=dict(
src=dict(type='path', required=True),
dest=dict(type='path', required=True),
remote_src=dict(type='bool', default=False),
creates=dict(type='path'),
list_files=dict(type='bool', default=False),
keep_newer=dict(type='bool', default=False),
exclude=dict(type='list', default=[]),
extra_opts=dict(type='list', default=[]),
validate_certs=dict(type='bool', default=True),
),
add_file_common_args=True,
# check-mode only works for zip files, we cover that later
supports_check_mode=True,
)
src = module.params['src']
dest = module.params['dest']
remote_src = module.params['remote_src']
file_args = module.load_file_common_arguments(module.params)
# did tar file arrive?
if not os.path.exists(src):
if not remote_src:
module.fail_json(msg="Source '%s' failed to transfer" % src)
# If remote_src=true, and src= contains ://, try and download the file to a temp directory.
elif '://' in src:
src = fetch_file(module, src)
else:
module.fail_json(msg="Source '%s' does not exist" % src)
if not os.access(src, os.R_OK):
module.fail_json(msg="Source '%s' not readable" % src)
# skip working with 0 size archives
try:
if os.path.getsize(src) == 0:
module.fail_json(msg="Invalid archive '%s', the file is 0 bytes" % src)
except Exception as e:
module.fail_json(msg="Source '%s' not readable, %s" % (src, to_native(e)))
# is dest OK to receive tar file?
if not os.path.isdir(dest):
module.fail_json(msg="Destination '%s' is not a directory" % dest)
handler = pick_handler(src, dest, file_args, module)
res_args = dict(handler=handler.__class__.__name__, dest=dest, src=src)
# do we need to do unpack?
check_results = handler.is_unarchived()
# DEBUG
# res_args['check_results'] = check_results
if module.check_mode:
res_args['changed'] = not check_results['unarchived']
elif check_results['unarchived']:
res_args['changed'] = False
else:
# do the unpack
try:
res_args['extract_results'] = handler.unarchive()
if res_args['extract_results']['rc'] != 0:
module.fail_json(msg="failed to unpack %s to %s" % (src, dest), **res_args)
except IOError:
module.fail_json(msg="failed to unpack %s to %s" % (src, dest), **res_args)
else:
res_args['changed'] = True
# Get diff if required
if check_results.get('diff', False):
res_args['diff'] = {'prepared': check_results['diff']}
# Run only if we found differences (idempotence) or diff was missing
if res_args.get('diff', True) and not module.check_mode:
# do we need to change perms?
for filename in handler.files_in_archive:
file_args['path'] = os.path.join(dest, filename)
try:
res_args['changed'] = module.set_fs_attributes_if_different(file_args, res_args['changed'], expand=False)
except (IOError, OSError) as e:
module.fail_json(msg="Unexpected error when accessing exploded file: %s" % to_native(e), **res_args)
if module.params['list_files']:
res_args['files'] = handler.files_in_archive
module.exit_json(**res_args)
if __name__ == '__main__':
main()
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,420 |
The unarchive integration test fails when LC_ALL is not set.
|
##### SUMMARY
The unarchive integration test fails when LC_ALL is not set.
##### ISSUE TYPE
Bug Report
##### COMPONENT NAME
unarchive
##### ANSIBLE VERSION
devel
##### CONFIGURATION
N/A
##### OS / ENVIRONMENT
N/A
##### STEPS TO REPRODUCE
1. Set `ansible_connection=ssh ansible_host=localhost` for `testhost` to prevent modules from inheriting the environment from the controller: https://github.com/ansible/ansible/blob/edcb5b6775adac09eee5412b499b8f0aa5194610/test/integration/inventory#L6
2. Run the test in an environment where LC_ALL is not set by default: `ansible-test integration unarchive --remote freebsd/12.0 -v`
##### EXPECTED RESULTS
Tests pass.
##### ACTUAL RESULTS
Tests traceback:
```
TASK [unarchive : test that unarchive works with an archive that contains non-ascii filenames] **************************************************************************
fatal: [testhost]: FAILED! => {"changed": false, "module_stderr": "Shared connection to localhost closed.\r\n", "module_stdout": "Traceback (most recent call last):\r\n File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 139, in <module>\r\n _ansiballz_main()\r\n File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 131, in _ansiballz_main\r\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n File \"/root/.ansible/tmp/ansible-tmp-1561576726.3763218-37161750934991/AnsiballZ_unarchive.py\", line 65, in invoke_module\r\n spec.loader.exec_module(module)\r\n File \"<frozen importlib._bootstrap_external>\", line 678, in exec_module\r\n File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\r\n File \"/tmp/ansible_unarchive_payload_o9_x930g/__main__.py\", line 909, in <module>\r\n File \"/tmp/ansible_unarchive_payload_o9_x930g/__main__.py\", line 859, in main\r\n File \"/usr/local/lib/python3.6/genericpath.py\", line 42, in isdir\r\n st = os.stat(s)\r\nUnicodeEncodeError: 'ascii' codec can't encode characters in position 51-54: ordinal not in range(128)\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}
```
Failure on Shippable: https://app.shippable.com/github/ansible/ansible/runs/129521/18/tests
|
https://github.com/ansible/ansible/issues/58420
|
https://github.com/ansible/ansible/pull/58431
|
7ed7d374e43819282b21a20048eff768d8a0a018
|
23f0ca0acdc09ad4371e8f9eda3315cff8f75345
| 2019-06-26T19:19:22Z |
python
| 2019-06-28T16:47:10Z |
test/integration/targets/unarchive/tasks/main.yml
|
# Test code for the unarchive module.
# (c) 2014, Richard Isaacson <[email protected]>
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make sure we start fresh
# Need unzip for unarchive module, and zip for archive creation.
- name: Ensure zip and unzip is present to create test archive (yum)
yum: name=zip,unzip state=latest
when: ansible_pkg_mgr == 'yum'
#- name: Ensure zip is present to create test archive (dnf)
# dnf: name=zip state=latest
# when: ansible_pkg_mgr == 'dnf'
- name: Ensure zip & unzip is present to create test archive (apt)
apt: name=zip,unzip state=latest
when: ansible_pkg_mgr == 'apt'
- name: Ensure zip & unzip is present to create test archive (pkg)
pkgng: name=zip,unzip state=present
when: ansible_pkg_mgr == 'pkgng'
- name: prep our file
copy: src=foo.txt dest={{remote_tmp_dir}}/foo-unarchive.txt
- name: prep a tar file
shell: tar cvf test-unarchive.tar foo-unarchive.txt chdir={{remote_tmp_dir}}
- name: prep a tar.gz file
shell: tar czvf test-unarchive.tar.gz foo-unarchive.txt chdir={{remote_tmp_dir}}
- name: prep a chmodded file for zip
copy: src=foo.txt dest={{remote_tmp_dir}}/foo-unarchive-777.txt mode=0777
- name: prep a windows permission file for our zip
copy: src=foo.txt dest={{remote_tmp_dir}}/FOO-UNAR.TXT
# This gets around an unzip timestamp bug in some distributions
# Recent unzip on Ubuntu and BSD will randomly round some timestamps up.
# But that doesn't seem to happen when the timestamp has an even second.
- name: Bug work around
command: touch -t "201705111530.00" {{remote_tmp_dir}}/foo-unarchive.txt {{remote_tmp_dir}}/foo-unarchive-777.txt {{remote_tmp_dir}}/FOO-UNAR.TXT
# See Ubuntu bug 1691636: https://bugs.launchpad.net/ubuntu/+source/unzip/+bug/1691636
# When these are fixed, this code should be removed.
- name: prep a zip file
shell: zip test-unarchive.zip foo-unarchive.txt foo-unarchive-777.txt chdir={{remote_tmp_dir}}
- name: Prepare - Create test dirs
file:
path: "{{remote_tmp_dir}}/{{item}}"
state: directory
with_items:
- created/include
- created/exclude
- created/other
- name: Prepare - Create test files
file:
path: "{{remote_tmp_dir}}/created/{{item}}"
state: touch
with_items:
- include/include-1.txt
- include/include-2.txt
- include/include-3.txt
- exclude/exclude-1.txt
- exclude/exclude-2.txt
- exclude/exclude-3.txt
- other/include-1.ext
- other/include-2.ext
- other/exclude-1.ext
- other/exclude-2.ext
- other/other-1.ext
- other/other-2.ext
- name: Prepare - zip file
shell: zip -r {{remote_tmp_dir}}/unarchive-00.zip * chdir={{remote_tmp_dir}}/created/
- name: Prepare - tar file
shell: tar czvf {{remote_tmp_dir}}/unarchive-00.tar * chdir={{remote_tmp_dir}}/created/
- name: add a file with Windows permissions to zip file
shell: zip -k test-unarchive.zip FOO-UNAR.TXT chdir={{remote_tmp_dir}}
- name: prep a subdirectory
file: path={{remote_tmp_dir}}/unarchive-dir state=directory
- name: prep our file
copy: src=foo.txt dest={{remote_tmp_dir}}/unarchive-dir/foo-unarchive.txt
- name: prep a tar.gz file with directory
shell: tar czvf test-unarchive-dir.tar.gz unarchive-dir chdir={{remote_tmp_dir}}
- name: create our tar unarchive destination
file: path={{remote_tmp_dir}}/test-unarchive-tar state=directory
- name: unarchive a tar file
unarchive: src={{remote_tmp_dir}}/test-unarchive.tar dest="{{remote_tmp_dir}}/test-unarchive-tar" remote_src=yes
register: unarchive01
- name: verify that the file was marked as changed
assert:
that:
- "unarchive01.changed == true"
- name: verify that the file was unarchived
file: path={{remote_tmp_dir}}/test-unarchive-tar/foo-unarchive.txt state=file
- name: remove our tar unarchive destination
file: path={{remote_tmp_dir}}/test-unarchive-tar state=absent
- name: create our tar.gz unarchive destination
file: path={{remote_tmp_dir}}/test-unarchive-tar-gz state=directory
- name: unarchive a tar.gz file
unarchive: src={{remote_tmp_dir}}/test-unarchive.tar.gz dest={{remote_tmp_dir}}/test-unarchive-tar-gz remote_src=yes
register: unarchive02
- name: verify that the file was marked as changed
assert:
that:
- "unarchive02.changed == true"
# Verify that no file list is generated
- "'files' not in unarchive02"
- name: verify that the file was unarchived
file: path={{remote_tmp_dir}}/test-unarchive-tar-gz/foo-unarchive.txt state=file
- name: remove our tar.gz unarchive destination
file: path={{remote_tmp_dir}}/test-unarchive-tar-gz state=absent
- name: create our tar.gz unarchive destination for creates
file: path={{remote_tmp_dir}}/test-unarchive-tar-gz state=directory
- name: unarchive a tar.gz file with creates set
unarchive: src={{remote_tmp_dir}}/test-unarchive.tar.gz dest={{remote_tmp_dir}}/test-unarchive-tar-gz remote_src=yes creates={{remote_tmp_dir}}/test-unarchive-tar-gz/foo-unarchive.txt
register: unarchive02b
- name: verify that the file was marked as changed
assert:
that:
- "unarchive02b.changed == true"
- name: verify that the file was unarchived
file: path={{remote_tmp_dir}}/test-unarchive-tar-gz/foo-unarchive.txt state=file
- name: unarchive a tar.gz file with creates over an existing file
unarchive: src={{remote_tmp_dir}}/test-unarchive.tar.gz dest={{remote_tmp_dir}}/test-unarchive-tar-gz remote_src=yes creates={{remote_tmp_dir}}/test-unarchive-tar-gz/foo-unarchive.txt
register: unarchive02c
- name: verify that the file was not marked as changed
assert:
that:
- "unarchive02c.changed == false"
- name: unarchive a tar.gz file with creates over an existing file using complex_args
unarchive:
src: "{{remote_tmp_dir}}/test-unarchive.tar.gz"
dest: "{{remote_tmp_dir}}/test-unarchive-tar-gz"
remote_src: yes
creates: "{{remote_tmp_dir}}/test-unarchive-tar-gz/foo-unarchive.txt"
register: unarchive02d
- name: verify that the file was not marked as changed
assert:
that:
- "unarchive02d.changed == false"
- name: remove our tar.gz unarchive destination
file: path={{remote_tmp_dir}}/test-unarchive-tar-gz state=absent
- name: create our zip unarchive destination
file: path={{remote_tmp_dir}}/test-unarchive-zip state=directory
- name: unarchive a zip file
unarchive: src={{remote_tmp_dir}}/test-unarchive.zip dest={{remote_tmp_dir}}/test-unarchive-zip remote_src=yes list_files=True
register: unarchive03
- name: verify that the file was marked as changed
assert:
that:
- "unarchive03.changed == true"
# Verify that file list is generated
- "'files' in unarchive03"
- "{{unarchive03['files']| length}} == 3"
- "'foo-unarchive.txt' in unarchive03['files']"
- "'foo-unarchive-777.txt' in unarchive03['files']"
- "'FOO-UNAR.TXT' in unarchive03['files']"
- name: verify that the file was unarchived
file: path={{remote_tmp_dir}}/test-unarchive-zip/{{item}} state=file
with_items:
- foo-unarchive.txt
- foo-unarchive-777.txt
- FOO-UNAR.TXT
- name: repeat the last request to verify no changes
unarchive: src={{remote_tmp_dir}}/test-unarchive.zip dest={{remote_tmp_dir}}/test-unarchive-zip remote_src=yes list_files=True
register: unarchive03b
- name: verify that the task was not marked as changed
assert:
that:
- "unarchive03b.changed == false"
- name: "Create {{ remote_tmp_dir }}/exclude directory"
file:
state: directory
path: "{{ remote_tmp_dir }}/exclude-{{item}}"
with_items:
- zip
- tar
- name: Unpack archive file excluding regular and glob files.
unarchive:
src: "{{ remote_tmp_dir }}/unarchive-00.{{item}}"
dest: "{{ remote_tmp_dir }}/exclude-{{item}}"
remote_src: yes
exclude:
- "exclude/exclude-*.txt"
- "other/exclude-1.ext"
with_items:
- zip
- tar
- name: verify that the file was unarchived
shell: find {{ remote_tmp_dir }}/exclude-{{item}} chdir={{ remote_tmp_dir }}
register: unarchive00
with_items:
- zip
- tar
- name: verify that archive extraction excluded the files
assert:
that:
- "'exclude/exclude-1.txt' not in item.stdout"
- "'other/exclude-1.ext' not in item.stdout"
with_items:
- "{{ unarchive00.results }}"
- name: remove our zip unarchive destination
file: path={{remote_tmp_dir}}/test-unarchive-zip state=absent
- name: remove our test files for the archive
file: path={{remote_tmp_dir}}/{{item}} state=absent
with_items:
- foo-unarchive.txt
- foo-unarchive-777.txt
- FOO-UNAR.TXT
- name: check if /tmp/foo-unarchive.text exists
stat: path=/tmp/foo-unarchive.txt
ignore_errors: True
register: unarchive04
- name: fail if the proposed destination file exists for safey
fail: msg="/tmp/foo-unarchive.txt already exists, aborting"
when: unarchive04.stat.exists
- name: try unarchiving to /tmp
unarchive: src={{remote_tmp_dir}}/test-unarchive.tar.gz dest=/tmp remote_src=yes
register: unarchive05
- name: verify that the file was marked as changed
assert:
that:
- "unarchive05.changed == true"
- name: verify that the file was unarchived
file: path=/tmp/foo-unarchive.txt state=file
- name: remove our unarchive destination
file: path=/tmp/foo-unarchive.txt state=absent
- name: create our unarchive destination
file: path={{remote_tmp_dir}}/test-unarchive-tar-gz state=directory
- name: unarchive and set mode to 0600, directories 0700
unarchive:
src: "{{ remote_tmp_dir }}/test-unarchive.tar.gz"
dest: "{{ remote_tmp_dir }}/test-unarchive-tar-gz"
remote_src: yes
mode: "u+rwX,g-rwx,o-rwx"
list_files: True
register: unarchive06
- name: Test that the file modes were changed
stat:
path: "{{ remote_tmp_dir }}/test-unarchive-tar-gz/foo-unarchive.txt"
register: unarchive06_stat
- name: Test that the file modes were changed
assert:
that:
- "unarchive06.changed == true"
- "unarchive06_stat.stat.mode == '0600'"
# Verify that file list is generated
- "'files' in unarchive06"
- "{{unarchive06['files']| length}} == 1"
- "'foo-unarchive.txt' in unarchive06['files']"
- name: remove our tar.gz unarchive destination
file: path={{ remote_tmp_dir }}/test-unarchive-tar-gz state=absent
- name: create our unarchive destination
file: path={{remote_tmp_dir}}/test-unarchive-tar-gz state=directory
- name: unarchive over existing extraction and set mode to 0644
unarchive:
src: "{{ remote_tmp_dir }}/test-unarchive.tar.gz"
dest: "{{ remote_tmp_dir }}/test-unarchive-tar-gz"
remote_src: yes
mode: "u+rwX,g-wx,o-wx,g+r,o+r"
register: unarchive06_2
- name: Test that the file modes were changed
stat:
path: "{{ remote_tmp_dir }}/test-unarchive-tar-gz/foo-unarchive.txt"
register: unarchive06_2_stat
- debug: var=unarchive06_2_stat.stat.mode
- name: Test that the files were changed
assert:
that:
- "unarchive06_2.changed == true"
- "unarchive06_2_stat.stat.mode == '0644'"
- name: Repeat the last request to verify no changes
unarchive:
src: "{{ remote_tmp_dir }}/test-unarchive.tar.gz"
dest: "{{ remote_tmp_dir }}/test-unarchive-tar-gz"
remote_src: yes
mode: "u+rwX-x,g-wx,o-wx,g+r,o+r"
list_files: True
register: unarchive07
- name: Test that the files were not changed
assert:
that:
- "unarchive07.changed == false"
# Verify that file list is generated
- "'files' in unarchive07"
- "{{unarchive07['files']| length}} == 1"
- "'foo-unarchive.txt' in unarchive07['files']"
- name: remove our tar.gz unarchive destination
file: path={{ remote_tmp_dir }}/test-unarchive-tar-gz state=absent
- name: create our unarchive destination
file: path={{remote_tmp_dir}}/test-unarchive-zip state=directory
- name: unarchive and set mode to 0601, directories 0700
unarchive:
src: "{{ remote_tmp_dir }}/test-unarchive.zip"
dest: "{{ remote_tmp_dir }}/test-unarchive-zip"
remote_src: yes
mode: "u+rwX-x,g-rwx,o=x"
list_files: True
register: unarchive08
- name: Test that the file modes were changed
stat:
path: "{{ remote_tmp_dir }}/test-unarchive-zip/foo-unarchive.txt"
register: unarchive08_stat
- name: Test that the file modes were changed
assert:
that:
- "unarchive08.changed == true"
- "unarchive08_stat.stat.mode == '0601'"
# Verify that file list is generated
- "'files' in unarchive08"
- "{{unarchive08['files']| length}} == 3"
- "'foo-unarchive.txt' in unarchive08['files']"
- "'foo-unarchive-777.txt' in unarchive08['files']"
- "'FOO-UNAR.TXT' in unarchive08['files']"
- name: unarchive zipfile a second time and set mode to 0601, directories 0700
unarchive:
src: "{{ remote_tmp_dir }}/test-unarchive.zip"
dest: "{{ remote_tmp_dir }}/test-unarchive-zip"
remote_src: yes
mode: "u+rwX-x,g-rwx,o=x"
list_files: True
register: unarchive08
- name: Test that the file modes were not changed
stat:
path: "{{ remote_tmp_dir }}/test-unarchive-zip/foo-unarchive.txt"
register: unarchive08_stat
- debug:
var: unarchive08
- debug:
var: unarchive08_stat
- name: Test that the files did not change
assert:
that:
- "unarchive08.changed == false"
- "unarchive08_stat.stat.mode == '0601'"
# Verify that file list is generated
- "'files' in unarchive08"
- "{{unarchive08['files']| length}} == 3"
- "'foo-unarchive.txt' in unarchive08['files']"
- "'foo-unarchive-777.txt' in unarchive08['files']"
- "'FOO-UNAR.TXT' in unarchive08['files']"
- name: remove our zip unarchive destination
file: path={{ remote_tmp_dir }}/test-unarchive-zip state=absent
- name: create our unarchive destination
file: path={{remote_tmp_dir}}/test-unarchive-tar-gz state=directory
- name: create a directory with quotable chars
file: path="{{ remote_tmp_dir }}/test-quotes~root" state=directory
- name: unarchive into directory with quotable chars
unarchive:
src: "{{ remote_tmp_dir }}/test-unarchive.tar.gz"
dest: "{{ remote_tmp_dir }}/test-quotes~root"
remote_src: yes
register: unarchive08
- name: Test that unarchive succeeded
assert:
that:
- "unarchive08.changed == true"
- name: unarchive into directory with quotable chars a second time
unarchive:
src: "{{ remote_tmp_dir }}/test-unarchive.tar.gz"
dest: "{{ remote_tmp_dir }}/test-quotes~root"
remote_src: yes
register: unarchive09
- name: Test that unarchive did nothing
assert:
that:
- "unarchive09.changed == false"
- name: remove quotable chars test
file: path="{{ remote_tmp_dir }}/test-quotes~root" state=absent
- name: create our unarchive destination
file:
path: "{{ remote_tmp_dir }}/test-unarchive-nonascii-くらとみ-tar-gz"
state: directory
- name: test that unarchive works with an archive that contains non-ascii filenames
unarchive:
# Both the filename of the tarball and the filename inside the tarball have
# nonascii chars
src: "test-unarchive-nonascii-くらとみ.tar.gz"
dest: "{{ remote_tmp_dir }}/test-unarchive-nonascii-くらとみ-tar-gz"
mode: "u+rwX,go+rX"
remote_src: no
register: nonascii_result0
- name: Check that file is really there
stat:
path: "{{ remote_tmp_dir }}/test-unarchive-nonascii-くらとみ-tar-gz/storage/àâæçéèïîôœ(copy)!@#$%^&-().jpg"
register: nonascii_stat0
- name: Assert that nonascii tests succeeded
assert:
that:
- "nonascii_result0.changed == true"
- "nonascii_stat0.stat.exists == true"
- name: remove nonascii test
file: path="{{ remote_tmp_dir }}/test-unarchive-nonascii-くらとみ-tar-gz" state=absent
# Test that unarchiving is performed if files are missing
# https://github.com/ansible/ansible-modules-core/issues/1064
- name: create our unarchive destination
file: path={{remote_tmp_dir}}/test-unarchive-tar-gz state=directory
- name: unarchive a tar that has directories
unarchive:
src: "{{ remote_tmp_dir }}/test-unarchive-dir.tar.gz"
dest: "{{ remote_tmp_dir }}/test-unarchive-tar-gz"
mode: "0700"
remote_src: yes
register: unarchive10
- name: Test that unarchive succeeded
assert:
that:
- "unarchive10.changed == true"
- name: Change the mode of the toplevel dir
file:
path: "{{ remote_tmp_dir }}/test-unarchive-tar-gz/unarchive-dir"
mode: 0701
- name: Remove a file from the extraction point
file:
path: "{{ remote_tmp_dir }}/test-unarchive-tar-gz/unarchive-dir/foo-unarchive.txt"
state: absent
- name: unarchive a tar that has directories
unarchive:
src: "{{ remote_tmp_dir }}/test-unarchive-dir.tar.gz"
dest: "{{ remote_tmp_dir }}/test-unarchive-tar-gz"
mode: "0700"
remote_src: yes
register: unarchive10_1
- name: Test that unarchive succeeded
assert:
that:
- "unarchive10_1.changed == true"
- name: remove our tar.gz unarchive destination
file: path={{ remote_tmp_dir }}/test-unarchive-tar-gz state=absent
#
# Symlink tests
#
- name: Create a destination dir
file:
path: "{{ remote_tmp_dir }}/test-unarchive-tar-gz"
state: directory
- name: Create a symlink to the detination dir
file:
path: "{{ remote_tmp_dir }}/link-to-unarchive-dir"
src: "{{ remote_tmp_dir }}/test-unarchive-tar-gz"
state: "link"
- name: test that unarchive works when dest is a symlink to a dir
unarchive:
src: "{{ remote_tmp_dir }}/test-unarchive.tar.gz"
dest: "{{ remote_tmp_dir }}/link-to-unarchive-dir"
mode: "u+rwX,go+rX"
remote_src: yes
register: unarchive_11
- name: Check that file is really there
stat:
path: "{{ remote_tmp_dir }}/test-unarchive-tar-gz/foo-unarchive.txt"
register: unarchive11_stat0
- name: Assert that unarchive when dest is a symlink to a dir worked
assert:
that:
- "unarchive_11.changed == true"
- "unarchive11_stat0.stat.exists == true"
- name: remove our tar.gz unarchive destination
file: path={{ remote_tmp_dir }}/test-unarchive-tar-gz state=absent
- name: Create a file
file:
path: "{{ remote_tmp_dir }}/test-unarchive-tar-gz"
state: touch
- name: Create a symlink to the file
file:
path: "{{ remote_tmp_dir }}/link-to-unarchive-file"
src: "{{ remote_tmp_dir }}/test-unarchive-tar-gz"
state: "link"
- name: test that unarchive fails when dest is a link to a file
unarchive:
src: "{{ remote_tmp_dir }}/test-unarchive.tar.gz"
dest: "{{ remote_tmp_dir }}/link-to-unarchive-file"
mode: "u+rwX,go+rX"
remote_src: yes
ignore_errors: True
register: unarchive_12
- name: Assert that unarchive when dest is a file failed
assert:
that:
- "unarchive_12.failed == true"
- name: remove our tar.gz unarchive destination
file: path={{ remote_tmp_dir }}/test-unarchive-tar-gz state=absent
# Test downloading a file before unarchiving it
- name: create our unarchive destination
file: path={{remote_tmp_dir}}/test-unarchive-tar-gz state=directory
- name: unarchive a tar from an URL
unarchive:
src: "https://releases.ansible.com/ansible/ansible-latest.tar.gz"
dest: "{{ remote_tmp_dir }}/test-unarchive-tar-gz"
mode: "0700"
remote_src: yes
register: unarchive13
- name: Test that unarchive succeeded
assert:
that:
- "unarchive13.changed == true"
- name: remove our tar.gz unarchive destination
file: path={{ remote_tmp_dir }}/test-unarchive-tar-gz state=absent
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,351 |
AnsibleVaultEncryptedUnicode.__str__() will traceback on python2 with non-ascii strings.
|
##### SUMMARY
This line of code will traceback on Python2 if a vaulted string contains non-ascii characters:
https://github.com/ansible/ansible/blob/devel/lib/ansible/parsing/yaml/objects.py#L131
The function should be defined like this:
``` python
def __str__(self):
return to_native(self.data, errors='surrogate_or_strict')
```
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
lib/ansible/parsing/yaml/objects.py
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
Current devel (2.9) and previous versions
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
##### STEPS TO REPRODUCE
I'm not sure if the current ```__str__()``` method ever gets called on Python2. A quick test by tracing the following playbook shows that ```__unicode__()``` gets called in that playbook.
```
---
- hosts: localhost
gather_facts: False
vars:
the_secret: !vault |
$ANSIBLE_VAULT;1.1;AES256
62666630343233373162323132363462633332356664636165616339303536333334366231303963
6433666337653864653163623063353932386130646530370a303234633037383966343366343037
39336433656461656261326165643431633363313562343764373136613338363039366136366439
6666633836343935660a396336393834326232383636613665316133666464393834623831326562
6165
tasks:
- debug: msg="{{ the_secret }}"
```
(Vault password is 12345)
It probably should be fixed, though, as all it will take to provoke a UnicodeError is some piece of code being changed to do ```'%s' % vault_encrypted_variable_with_non_ascii_chars```. The %s format string will use ```__str__()``` instead of ```__unicode__()``` and provoke the error.
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```paste below
```
|
https://github.com/ansible/ansible/issues/58351
|
https://github.com/ansible/ansible/pull/58503
|
e28bc463530abbaa4b6ae608f08876e94091ce5a
|
826f224f0293dc4e9264b44ecd2d8a07710e89c0
| 2019-06-25T17:51:55Z |
python
| 2019-06-28T17:23:15Z |
changelogs/fragments/58351-fix-non-ascii-vault.yml
| |
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,351 |
AnsibleVaultEncryptedUnicode.__str__() will traceback on python2 with non-ascii strings.
|
##### SUMMARY
This line of code will traceback on Python2 if a vaulted string contains non-ascii characters:
https://github.com/ansible/ansible/blob/devel/lib/ansible/parsing/yaml/objects.py#L131
The function should be defined like this:
``` python
def __str__(self):
return to_native(self.data, errors='surrogate_or_strict')
```
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
lib/ansible/parsing/yaml/objects.py
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
Current devel (2.9) and previous versions
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
##### STEPS TO REPRODUCE
I'm not sure if the current ```__str__()``` method ever gets called on Python2. A quick test by tracing the following playbook shows that ```__unicode__()``` gets called in that playbook.
```
---
- hosts: localhost
gather_facts: False
vars:
the_secret: !vault |
$ANSIBLE_VAULT;1.1;AES256
62666630343233373162323132363462633332356664636165616339303536333334366231303963
6433666337653864653163623063353932386130646530370a303234633037383966343366343037
39336433656461656261326165643431633363313562343764373136613338363039366136366439
6666633836343935660a396336393834326232383636613665316133666464393834623831326562
6165
tasks:
- debug: msg="{{ the_secret }}"
```
(Vault password is 12345)
It probably should be fixed, though, as all it will take to provoke a UnicodeError is some piece of code being changed to do ```'%s' % vault_encrypted_variable_with_non_ascii_chars```. The %s format string will use ```__str__()``` instead of ```__unicode__()``` and provoke the error.
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```paste below
```
|
https://github.com/ansible/ansible/issues/58351
|
https://github.com/ansible/ansible/pull/58503
|
e28bc463530abbaa4b6ae608f08876e94091ce5a
|
826f224f0293dc4e9264b44ecd2d8a07710e89c0
| 2019-06-25T17:51:55Z |
python
| 2019-06-28T17:23:15Z |
lib/ansible/parsing/yaml/objects.py
|
# (c) 2012-2014, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import yaml
from ansible.module_utils.six import text_type
from ansible.module_utils._text import to_bytes, to_text
class AnsibleBaseYAMLObject(object):
'''
the base class used to sub-class python built-in objects
so that we can add attributes to them during yaml parsing
'''
_data_source = None
_line_number = 0
_column_number = 0
def _get_ansible_position(self):
return (self._data_source, self._line_number, self._column_number)
def _set_ansible_position(self, obj):
try:
(src, line, col) = obj
except (TypeError, ValueError):
raise AssertionError(
'ansible_pos can only be set with a tuple/list '
'of three values: source, line number, column number'
)
self._data_source = src
self._line_number = line
self._column_number = col
ansible_pos = property(_get_ansible_position, _set_ansible_position)
class AnsibleMapping(AnsibleBaseYAMLObject, dict):
''' sub class for dictionaries '''
pass
class AnsibleUnicode(AnsibleBaseYAMLObject, text_type):
''' sub class for unicode objects '''
pass
class AnsibleSequence(AnsibleBaseYAMLObject, list):
''' sub class for lists '''
pass
# Unicode like object that is not evaluated (decrypted) until it needs to be
# TODO: is there a reason these objects are subclasses for YAMLObject?
class AnsibleVaultEncryptedUnicode(yaml.YAMLObject, AnsibleBaseYAMLObject):
__UNSAFE__ = True
__ENCRYPTED__ = True
yaml_tag = u'!vault'
@classmethod
def from_plaintext(cls, seq, vault, secret):
if not vault:
raise vault.AnsibleVaultError('Error creating AnsibleVaultEncryptedUnicode, invalid vault (%s) provided' % vault)
ciphertext = vault.encrypt(seq, secret)
avu = cls(ciphertext)
avu.vault = vault
return avu
def __init__(self, ciphertext):
'''A AnsibleUnicode with a Vault attribute that can decrypt it.
ciphertext is a byte string (str on PY2, bytestring on PY3).
The .data attribute is a property that returns the decrypted plaintext
of the ciphertext as a PY2 unicode or PY3 string object.
'''
super(AnsibleVaultEncryptedUnicode, self).__init__()
# after construction, calling code has to set the .vault attribute to a vaultlib object
self.vault = None
self._ciphertext = to_bytes(ciphertext)
@property
def data(self):
if not self.vault:
# FIXME: raise exception?
return self._ciphertext
return to_text(self.vault.decrypt(self._ciphertext))
@data.setter
def data(self, value):
self._ciphertext = value
def __repr__(self):
return repr(self.data)
# Compare a regular str/text_type with the decrypted hypertext
def __eq__(self, other):
if self.vault:
return other == self.data
return False
def __hash__(self):
return id(self)
def __ne__(self, other):
if self.vault:
return other != self.data
return True
def __str__(self):
return str(self.data)
def __unicode__(self):
return to_text(self.data, errors='surrogate_or_strict')
def encode(self, encoding=None, errors=None):
return self.data.encode(encoding, errors)
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,351 |
AnsibleVaultEncryptedUnicode.__str__() will traceback on python2 with non-ascii strings.
|
##### SUMMARY
This line of code will traceback on Python2 if a vaulted string contains non-ascii characters:
https://github.com/ansible/ansible/blob/devel/lib/ansible/parsing/yaml/objects.py#L131
The function should be defined like this:
``` python
def __str__(self):
return to_native(self.data, errors='surrogate_or_strict')
```
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
lib/ansible/parsing/yaml/objects.py
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
Current devel (2.9) and previous versions
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
##### STEPS TO REPRODUCE
I'm not sure if the current ```__str__()``` method ever gets called on Python2. A quick test by tracing the following playbook shows that ```__unicode__()``` gets called in that playbook.
```
---
- hosts: localhost
gather_facts: False
vars:
the_secret: !vault |
$ANSIBLE_VAULT;1.1;AES256
62666630343233373162323132363462633332356664636165616339303536333334366231303963
6433666337653864653163623063353932386130646530370a303234633037383966343366343037
39336433656461656261326165643431633363313562343764373136613338363039366136366439
6666633836343935660a396336393834326232383636613665316133666464393834623831326562
6165
tasks:
- debug: msg="{{ the_secret }}"
```
(Vault password is 12345)
It probably should be fixed, though, as all it will take to provoke a UnicodeError is some piece of code being changed to do ```'%s' % vault_encrypted_variable_with_non_ascii_chars```. The %s format string will use ```__str__()``` instead of ```__unicode__()``` and provoke the error.
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```paste below
```
|
https://github.com/ansible/ansible/issues/58351
|
https://github.com/ansible/ansible/pull/58503
|
e28bc463530abbaa4b6ae608f08876e94091ce5a
|
826f224f0293dc4e9264b44ecd2d8a07710e89c0
| 2019-06-25T17:51:55Z |
python
| 2019-06-28T17:23:15Z |
test/units/parsing/yaml/test_objects.py
|
# This file is part of Ansible
# -*- coding: utf-8 -*-
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2016, Adrian Likins <[email protected]>
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat import unittest
from ansible.errors import AnsibleError
from ansible.parsing import vault
from ansible.parsing.yaml.loader import AnsibleLoader
# module under test
from ansible.parsing.yaml import objects
from units.mock.yaml_helper import YamlTestUtils
from units.mock.vault_helper import TextVaultSecret
class TestAnsibleVaultUnicodeNoVault(unittest.TestCase, YamlTestUtils):
def test_empty_init(self):
self.assertRaises(TypeError, objects.AnsibleVaultEncryptedUnicode)
def test_empty_string_init(self):
seq = ''.encode('utf8')
self.assert_values(seq)
def test_empty_byte_string_init(self):
seq = b''
self.assert_values(seq)
def _assert_values(self, avu, seq):
self.assertIsInstance(avu, objects.AnsibleVaultEncryptedUnicode)
self.assertTrue(avu.vault is None)
# AnsibleVaultEncryptedUnicode without a vault should never == any string
self.assertNotEquals(avu, seq)
def assert_values(self, seq):
avu = objects.AnsibleVaultEncryptedUnicode(seq)
self._assert_values(avu, seq)
def test_single_char(self):
seq = 'a'.encode('utf8')
self.assert_values(seq)
def test_string(self):
seq = 'some letters'
self.assert_values(seq)
def test_byte_string(self):
seq = 'some letters'.encode('utf8')
self.assert_values(seq)
class TestAnsibleVaultEncryptedUnicode(unittest.TestCase, YamlTestUtils):
def setUp(self):
self.good_vault_password = "hunter42"
good_vault_secret = TextVaultSecret(self.good_vault_password)
self.good_vault_secrets = [('good_vault_password', good_vault_secret)]
self.good_vault = vault.VaultLib(self.good_vault_secrets)
# TODO: make this use two vault secret identities instead of two vaultSecrets
self.wrong_vault_password = 'not-hunter42'
wrong_vault_secret = TextVaultSecret(self.wrong_vault_password)
self.wrong_vault_secrets = [('wrong_vault_password', wrong_vault_secret)]
self.wrong_vault = vault.VaultLib(self.wrong_vault_secrets)
self.vault = self.good_vault
self.vault_secrets = self.good_vault_secrets
def _loader(self, stream):
return AnsibleLoader(stream, vault_secrets=self.vault_secrets)
def test_dump_load_cycle(self):
aveu = self._from_plaintext('the test string for TestAnsibleVaultEncryptedUnicode.test_dump_load_cycle')
self._dump_load_cycle(aveu)
def assert_values(self, avu, seq):
self.assertIsInstance(avu, objects.AnsibleVaultEncryptedUnicode)
self.assertEqual(avu, seq)
self.assertTrue(avu.vault is self.vault)
self.assertIsInstance(avu.vault, vault.VaultLib)
def _from_plaintext(self, seq):
id_secret = vault.match_encrypt_secret(self.good_vault_secrets)
return objects.AnsibleVaultEncryptedUnicode.from_plaintext(seq, vault=self.vault, secret=id_secret[1])
def _from_ciphertext(self, ciphertext):
avu = objects.AnsibleVaultEncryptedUnicode(ciphertext)
avu.vault = self.vault
return avu
def test_empty_init(self):
self.assertRaises(TypeError, objects.AnsibleVaultEncryptedUnicode)
def test_empty_string_init_from_plaintext(self):
seq = ''
avu = self._from_plaintext(seq)
self.assert_values(avu, seq)
def test_empty_unicode_init_from_plaintext(self):
seq = u''
avu = self._from_plaintext(seq)
self.assert_values(avu, seq)
def test_string_from_plaintext(self):
seq = 'some letters'
avu = self._from_plaintext(seq)
self.assert_values(avu, seq)
def test_unicode_from_plaintext(self):
seq = u'some letters'
avu = self._from_plaintext(seq)
self.assert_values(avu, seq)
def test_unicode_from_plaintext_encode(self):
seq = u'some text here'
avu = self._from_plaintext(seq)
b_avu = avu.encode('utf-8', 'strict')
self.assertIsInstance(avu, objects.AnsibleVaultEncryptedUnicode)
self.assertEqual(b_avu, seq.encode('utf-8', 'strict'))
self.assertTrue(avu.vault is self.vault)
self.assertIsInstance(avu.vault, vault.VaultLib)
# TODO/FIXME: make sure bad password fails differently than 'thats not encrypted'
def test_empty_string_wrong_password(self):
seq = ''
self.vault = self.wrong_vault
avu = self._from_plaintext(seq)
def compare(avu, seq):
return avu == seq
self.assertRaises(AnsibleError, compare, avu, seq)
def test_vaulted_utf8_value_37258(self):
seq = u"aöffü"
avu = self._from_plaintext(seq)
self.assert_values(avu, seq)
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,562 |
File module may crash when setting mode on a symlink, if it points to a read-only filesystem
|
##### SUMMARY
When using a module attempts to set the mode of a symlink, and the symlink target points to a read-only filesystem, then it may crash with an `OSError: [Errno 30] Read-only file system`.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
`file` module, due to `ansible/module_utils/basic.py` line 1117, in a `module.set_mode_if_different(…)` call.
https://github.com/ansible/ansible/blob/35dcd231be4f0afe2e1ee7a53769b3de1cc5222f/lib/ansible/module_utils/basic.py#L1101-L1122
##### ANSIBLE VERSION
```
ansible 2.8.1
python version = 3.7.3 (default, Mar 27 2019, 09:23:15) [Clang 10.0.1 (clang-1001.0.46.3)]
```
##### OS / ENVIRONMENT
OS on target host: Linux (or any platform where [`os.lchmod()` does not exist](https://mail.python.org/pipermail/docs/2011-February/003119.html)).
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```yaml
---
- hosts: all
tasks:
- copy:
dest: /tmp/fs.img
content: "{{ '_' * 1048576 }}"
- filesystem:
type: vfat
dev: /tmp/fs.img
- mount:
state: mounted
path: /mnt/readonly_fs
src: /tmp/fs.img
fstype: vfat
opts: ro
- name: This succeeds
file:
state: link
path: /tmp/some_symlink
src: /mnt/readonly_fs/nonexistent
follow: false
force: true
mode: 0757
- name: This crashes
file:
state: link
path: /tmp/some_other_symlink
src: /mnt/readonly_fs
follow: false
force: true
mode: 0757
```
##### EXPECTED RESULTS
The play should not fail, since `follow: false` should mean that the `chmod` only operates on `/tmp/some_symlink`, and never should never care about where it points.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```paste below
PLAY [all] ******************************************************************************************
TASK [Gathering Facts] ******************************************************************************
ok: [target.example.org]
TASK [copy] *****************************************************************************************
changed: [target.example.org]
TASK [filesystem] ***********************************************************************************
changed: [target.example.org]
TASK [mount] ****************************************************************************************
changed: [target.example.org]
TASK [This succeeds] ********************************************************************************
changed: [target.example.org]
TASK [This crashes] *********************************************************************************
fatal: [target.example.org]: FAILED! => {
"changed": false,
"module_stderr": "Shared connection to target.example.org closed.\r\n",
"module_stdout": "Traceback (most recent call last):\r\n File \"/root/.ansible/tmp/ansible-tmp-1561877445.915763-155915524570611/AnsiballZ_file.py\", line 114, in <module>\r\n _ansiballz_main()\r\n File \"/root/.ansible/tmp/ansible-tmp-1561877445.915763-155915524570611/AnsiballZ_file.py\", line 106, in _ansiballz_main\r\n invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n File \"/root/.ansible/tmp/ansible-tmp-1561877445.915763-155915524570611/AnsiballZ_file.py\", line 49, in invoke_module\r\n imp.load_module('__main__', mod, module, MOD_DESC)\r\n File \"/usr/lib/python3.6/imp.py\", line 235, in load_module\r\n return load_source(name, filename, file)\r\n File \"/usr/lib/python3.6/imp.py\", line 170, in load_source\r\n module = _exec(spec, sys.modules[name])\r\n File \"<frozen importlib._bootstrap>\", line 618, in _exec\r\n File \"<frozen importlib._bootstrap_external>\", line 678, in exec_module\r\n File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\r\n File \"/tmp/ansible_file_payload_r219es0e/__main__.py\", line 921, in <module>\r\n File \"/tmp/ansible_file_payload_r219es0e/__main__.py\", line 909, in main\r\n File \"/tmp/ansible_file_payload_r219es0e/__main__.py\", line 742, in ensure_symlink\r\n File \"/tmp/ansible_file_payload_r219es0e/ansible_file_payload.zip/ansible/module_utils/basic.py\", line 1339, in set_fs_attributes_if_different\r\n File \"/tmp/ansible_file_payload_r219es0e/ansible_file_payload.zip/ansible/module_utils/basic.py\", line 1112, in set_mode_if_different\r\nOSError: [Errno 30] Read-only file system: b'/tmp/some_other_symlink'\r\n",
"msg": "MODULE FAILURE\nSee stdout/stderr for the exact error",
"rc": 1
}
PLAY RECAP ******************************************************************************************
target.example.org : ok=5 changed=4 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
```
|
https://github.com/ansible/ansible/issues/58562
|
https://github.com/ansible/ansible/pull/58564
|
6e9bcc2579a988571abe1a83c6ca31ae1f2bd4d4
|
a9fcd1d197037387ccefec714b317e8034b396b1
| 2019-06-30T07:02:52Z |
python
| 2019-07-02T15:15:39Z |
lib/ansible/module_utils/basic.py
|
# Copyright (c), Michael DeHaan <[email protected]>, 2012-2013
# Copyright (c), Toshio Kuratomi <[email protected]> 2016
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
from __future__ import absolute_import, division, print_function
FILE_ATTRIBUTES = {
'A': 'noatime',
'a': 'append',
'c': 'compressed',
'C': 'nocow',
'd': 'nodump',
'D': 'dirsync',
'e': 'extents',
'E': 'encrypted',
'h': 'blocksize',
'i': 'immutable',
'I': 'indexed',
'j': 'journalled',
'N': 'inline',
's': 'zero',
'S': 'synchronous',
't': 'notail',
'T': 'blockroot',
'u': 'undelete',
'X': 'compressedraw',
'Z': 'compresseddirty',
}
# Ansible modules can be written in any language.
# The functions available here can be used to do many common tasks,
# to simplify development of Python modules.
import __main__
import atexit
import errno
import datetime
import grp
import fcntl
import locale
import os
import pwd
import platform
import re
import select
import shlex
import shutil
import signal
import stat
import subprocess
import sys
import tempfile
import time
import traceback
import types
from collections import deque
from itertools import chain, repeat
try:
import syslog
HAS_SYSLOG = True
except ImportError:
HAS_SYSLOG = False
try:
from systemd import journal
has_journal = True
except ImportError:
has_journal = False
HAVE_SELINUX = False
try:
import selinux
HAVE_SELINUX = True
except ImportError:
pass
# Python2 & 3 way to get NoneType
NoneType = type(None)
from ansible.module_utils._text import to_native, to_bytes, to_text
from ansible.module_utils.common.text.converters import (
jsonify,
container_to_bytes as json_dict_unicode_to_bytes,
container_to_text as json_dict_bytes_to_unicode,
)
from ansible.module_utils.common.text.formatters import (
lenient_lowercase,
bytes_to_human,
human_to_bytes,
SIZE_RANGES,
)
try:
from ansible.module_utils.common._json_compat import json
except ImportError as e:
print('\n{{"msg": "Error: ansible requires the stdlib json: {0}", "failed": true}}'.format(to_native(e)))
sys.exit(1)
AVAILABLE_HASH_ALGORITHMS = dict()
try:
import hashlib
# python 2.7.9+ and 2.7.0+
for attribute in ('available_algorithms', 'algorithms'):
algorithms = getattr(hashlib, attribute, None)
if algorithms:
break
if algorithms is None:
# python 2.5+
algorithms = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')
for algorithm in algorithms:
AVAILABLE_HASH_ALGORITHMS[algorithm] = getattr(hashlib, algorithm)
# we may have been able to import md5 but it could still not be available
try:
hashlib.md5()
except ValueError:
AVAILABLE_HASH_ALGORITHMS.pop('md5', None)
except Exception:
import sha
AVAILABLE_HASH_ALGORITHMS = {'sha1': sha.sha}
try:
import md5
AVAILABLE_HASH_ALGORITHMS['md5'] = md5.md5
except Exception:
pass
from ansible.module_utils.common._collections_compat import (
KeysView,
Mapping, MutableMapping,
Sequence, MutableSequence,
Set, MutableSet,
)
from ansible.module_utils.common.process import get_bin_path
from ansible.module_utils.common.file import (
_PERM_BITS as PERM_BITS,
_EXEC_PERM_BITS as EXEC_PERM_BITS,
_DEFAULT_PERM as DEFAULT_PERM,
is_executable,
format_attributes,
get_flags_from_attributes,
)
from ansible.module_utils.common.sys_info import (
get_distribution,
get_distribution_version,
get_platform_subclass,
)
from ansible.module_utils.pycompat24 import get_exception, literal_eval
from ansible.module_utils.common.parameters import (
handle_aliases,
list_deprecations,
list_no_log_values,
PASS_VARS,
PASS_BOOLS,
)
from ansible.module_utils.six import (
PY2,
PY3,
b,
binary_type,
integer_types,
iteritems,
string_types,
text_type,
)
from ansible.module_utils.six.moves import map, reduce, shlex_quote
from ansible.module_utils.common.validation import (
check_missing_parameters,
check_mutually_exclusive,
check_required_arguments,
check_required_by,
check_required_if,
check_required_one_of,
check_required_together,
count_terms,
check_type_bool,
check_type_bits,
check_type_bytes,
check_type_float,
check_type_int,
check_type_jsonarg,
check_type_list,
check_type_dict,
check_type_path,
check_type_raw,
check_type_str,
safe_eval,
)
from ansible.module_utils.common._utils import get_all_subclasses as _get_all_subclasses
from ansible.module_utils.parsing.convert_bool import BOOLEANS, BOOLEANS_FALSE, BOOLEANS_TRUE, boolean
# Note: When getting Sequence from collections, it matches with strings. If
# this matters, make sure to check for strings before checking for sequencetype
SEQUENCETYPE = frozenset, KeysView, Sequence
PASSWORD_MATCH = re.compile(r'^(?:.+[-_\s])?pass(?:[-_\s]?(?:word|phrase|wrd|wd)?)(?:[-_\s].+)?$', re.I)
imap = map
try:
# Python 2
unicode
except NameError:
# Python 3
unicode = text_type
try:
# Python 2
basestring
except NameError:
# Python 3
basestring = string_types
_literal_eval = literal_eval
# End of deprecated names
# Internal global holding passed in params. This is consulted in case
# multiple AnsibleModules are created. Otherwise each AnsibleModule would
# attempt to read from stdin. Other code should not use this directly as it
# is an internal implementation detail
_ANSIBLE_ARGS = None
FILE_COMMON_ARGUMENTS = dict(
# These are things we want. About setting metadata (mode, ownership, permissions in general) on
# created files (these are used by set_fs_attributes_if_different and included in
# load_file_common_arguments)
mode=dict(type='raw'),
owner=dict(),
group=dict(),
seuser=dict(),
serole=dict(),
selevel=dict(),
setype=dict(),
attributes=dict(aliases=['attr']),
# The following are not about perms and should not be in a rewritten file_common_args
src=dict(), # Maybe dest or path would be appropriate but src is not
follow=dict(type='bool', default=False), # Maybe follow is appropriate because it determines whether to follow symlinks for permission purposes too
force=dict(type='bool'),
# not taken by the file module, but other action plugins call the file module so this ignores
# them for now. In the future, the caller should take care of removing these from the module
# arguments before calling the file module.
content=dict(no_log=True), # used by copy
backup=dict(), # Used by a few modules to create a remote backup before updating the file
remote_src=dict(), # used by assemble
regexp=dict(), # used by assemble
delimiter=dict(), # used by assemble
directory_mode=dict(), # used by copy
unsafe_writes=dict(type='bool'), # should be available to any module using atomic_move
)
PASSWD_ARG_RE = re.compile(r'^[-]{0,2}pass[-]?(word|wd)?')
# Used for parsing symbolic file perms
MODE_OPERATOR_RE = re.compile(r'[+=-]')
USERS_RE = re.compile(r'[^ugo]')
PERMS_RE = re.compile(r'[^rwxXstugo]')
# Used for determining if the system is running a new enough python version
# and should only restrict on our documented minimum versions
_PY3_MIN = sys.version_info[:2] >= (3, 5)
_PY2_MIN = (2, 6) <= sys.version_info[:2] < (3,)
_PY_MIN = _PY3_MIN or _PY2_MIN
if not _PY_MIN:
print(
'\n{"failed": true, '
'"msg": "Ansible requires a minimum of Python2 version 2.6 or Python3 version 3.5. Current version: %s"}' % ''.join(sys.version.splitlines())
)
sys.exit(1)
#
# Deprecated functions
#
def get_platform():
'''
**Deprecated** Use :py:func:`platform.system` directly.
:returns: Name of the platform the module is running on in a native string
Returns a native string that labels the platform ("Linux", "Solaris", etc). Currently, this is
the result of calling :py:func:`platform.system`.
'''
return platform.system()
# End deprecated functions
#
# Compat shims
#
def load_platform_subclass(cls, *args, **kwargs):
"""**Deprecated**: Use ansible.module_utils.common.sys_info.get_platform_subclass instead"""
platform_cls = get_platform_subclass(cls)
return super(cls, platform_cls).__new__(platform_cls)
def get_all_subclasses(cls):
"""**Deprecated**: Use ansible.module_utils.common._utils.get_all_subclasses instead"""
return list(_get_all_subclasses(cls))
# End compat shims
def _remove_values_conditions(value, no_log_strings, deferred_removals):
"""
Helper function for :meth:`remove_values`.
:arg value: The value to check for strings that need to be stripped
:arg no_log_strings: set of strings which must be stripped out of any values
:arg deferred_removals: List which holds information about nested
containers that have to be iterated for removals. It is passed into
this function so that more entries can be added to it if value is
a container type. The format of each entry is a 2-tuple where the first
element is the ``value`` parameter and the second value is a new
container to copy the elements of ``value`` into once iterated.
:returns: if ``value`` is a scalar, returns ``value`` with two exceptions:
1. :class:`~datetime.datetime` objects which are changed into a string representation.
2. objects which are in no_log_strings are replaced with a placeholder
so that no sensitive data is leaked.
If ``value`` is a container type, returns a new empty container.
``deferred_removals`` is added to as a side-effect of this function.
.. warning:: It is up to the caller to make sure the order in which value
is passed in is correct. For instance, higher level containers need
to be passed in before lower level containers. For example, given
``{'level1': {'level2': 'level3': [True]} }`` first pass in the
dictionary for ``level1``, then the dict for ``level2``, and finally
the list for ``level3``.
"""
if isinstance(value, (text_type, binary_type)):
# Need native str type
native_str_value = value
if isinstance(value, text_type):
value_is_text = True
if PY2:
native_str_value = to_bytes(value, errors='surrogate_or_strict')
elif isinstance(value, binary_type):
value_is_text = False
if PY3:
native_str_value = to_text(value, errors='surrogate_or_strict')
if native_str_value in no_log_strings:
return 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER'
for omit_me in no_log_strings:
native_str_value = native_str_value.replace(omit_me, '*' * 8)
if value_is_text and isinstance(native_str_value, binary_type):
value = to_text(native_str_value, encoding='utf-8', errors='surrogate_then_replace')
elif not value_is_text and isinstance(native_str_value, text_type):
value = to_bytes(native_str_value, encoding='utf-8', errors='surrogate_then_replace')
else:
value = native_str_value
elif isinstance(value, Sequence):
if isinstance(value, MutableSequence):
new_value = type(value)()
else:
new_value = [] # Need a mutable value
deferred_removals.append((value, new_value))
value = new_value
elif isinstance(value, Set):
if isinstance(value, MutableSet):
new_value = type(value)()
else:
new_value = set() # Need a mutable value
deferred_removals.append((value, new_value))
value = new_value
elif isinstance(value, Mapping):
if isinstance(value, MutableMapping):
new_value = type(value)()
else:
new_value = {} # Need a mutable value
deferred_removals.append((value, new_value))
value = new_value
elif isinstance(value, tuple(chain(integer_types, (float, bool, NoneType)))):
stringy_value = to_native(value, encoding='utf-8', errors='surrogate_or_strict')
if stringy_value in no_log_strings:
return 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER'
for omit_me in no_log_strings:
if omit_me in stringy_value:
return 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER'
elif isinstance(value, datetime.datetime):
value = value.isoformat()
else:
raise TypeError('Value of unknown type: %s, %s' % (type(value), value))
return value
def remove_values(value, no_log_strings):
""" Remove strings in no_log_strings from value. If value is a container
type, then remove a lot more"""
deferred_removals = deque()
no_log_strings = [to_native(s, errors='surrogate_or_strict') for s in no_log_strings]
new_value = _remove_values_conditions(value, no_log_strings, deferred_removals)
while deferred_removals:
old_data, new_data = deferred_removals.popleft()
if isinstance(new_data, Mapping):
for old_key, old_elem in old_data.items():
new_elem = _remove_values_conditions(old_elem, no_log_strings, deferred_removals)
new_data[old_key] = new_elem
else:
for elem in old_data:
new_elem = _remove_values_conditions(elem, no_log_strings, deferred_removals)
if isinstance(new_data, MutableSequence):
new_data.append(new_elem)
elif isinstance(new_data, MutableSet):
new_data.add(new_elem)
else:
raise TypeError('Unknown container type encountered when removing private values from output')
return new_value
def heuristic_log_sanitize(data, no_log_values=None):
''' Remove strings that look like passwords from log messages '''
# Currently filters:
# user:pass@foo/whatever and http://username:pass@wherever/foo
# This code has false positives and consumes parts of logs that are
# not passwds
# begin: start of a passwd containing string
# end: end of a passwd containing string
# sep: char between user and passwd
# prev_begin: where in the overall string to start a search for
# a passwd
# sep_search_end: where in the string to end a search for the sep
data = to_native(data)
output = []
begin = len(data)
prev_begin = begin
sep = 1
while sep:
# Find the potential end of a passwd
try:
end = data.rindex('@', 0, begin)
except ValueError:
# No passwd in the rest of the data
output.insert(0, data[0:begin])
break
# Search for the beginning of a passwd
sep = None
sep_search_end = end
while not sep:
# URL-style username+password
try:
begin = data.rindex('://', 0, sep_search_end)
except ValueError:
# No url style in the data, check for ssh style in the
# rest of the string
begin = 0
# Search for separator
try:
sep = data.index(':', begin + 3, end)
except ValueError:
# No separator; choices:
if begin == 0:
# Searched the whole string so there's no password
# here. Return the remaining data
output.insert(0, data[0:begin])
break
# Search for a different beginning of the password field.
sep_search_end = begin
continue
if sep:
# Password was found; remove it.
output.insert(0, data[end:prev_begin])
output.insert(0, '********')
output.insert(0, data[begin:sep + 1])
prev_begin = begin
output = ''.join(output)
if no_log_values:
output = remove_values(output, no_log_values)
return output
def _load_params():
''' read the modules parameters and store them globally.
This function may be needed for certain very dynamic custom modules which
want to process the parameters that are being handed the module. Since
this is so closely tied to the implementation of modules we cannot
guarantee API stability for it (it may change between versions) however we
will try not to break it gratuitously. It is certainly more future-proof
to call this function and consume its outputs than to implement the logic
inside it as a copy in your own code.
'''
global _ANSIBLE_ARGS
if _ANSIBLE_ARGS is not None:
buffer = _ANSIBLE_ARGS
else:
# debug overrides to read args from file or cmdline
# Avoid tracebacks when locale is non-utf8
# We control the args and we pass them as utf8
if len(sys.argv) > 1:
if os.path.isfile(sys.argv[1]):
fd = open(sys.argv[1], 'rb')
buffer = fd.read()
fd.close()
else:
buffer = sys.argv[1]
if PY3:
buffer = buffer.encode('utf-8', errors='surrogateescape')
# default case, read from stdin
else:
if PY2:
buffer = sys.stdin.read()
else:
buffer = sys.stdin.buffer.read()
_ANSIBLE_ARGS = buffer
try:
params = json.loads(buffer.decode('utf-8'))
except ValueError:
# This helper used too early for fail_json to work.
print('\n{"msg": "Error: Module unable to decode valid JSON on stdin. Unable to figure out what parameters were passed", "failed": true}')
sys.exit(1)
if PY2:
params = json_dict_unicode_to_bytes(params)
try:
return params['ANSIBLE_MODULE_ARGS']
except KeyError:
# This helper does not have access to fail_json so we have to print
# json output on our own.
print('\n{"msg": "Error: Module unable to locate ANSIBLE_MODULE_ARGS in json data from stdin. Unable to figure out what parameters were passed", '
'"failed": true}')
sys.exit(1)
def env_fallback(*args, **kwargs):
''' Load value from environment '''
for arg in args:
if arg in os.environ:
return os.environ[arg]
raise AnsibleFallbackNotFound
def missing_required_lib(library, reason=None, url=None):
hostname = platform.node()
msg = "Failed to import the required Python library (%s) on %s's Python %s." % (library, hostname, sys.executable)
if reason:
msg += " This is required %s." % reason
if url:
msg += " See %s for more info." % url
return msg + " Please read module documentation and install in the appropriate location"
class AnsibleFallbackNotFound(Exception):
pass
class AnsibleModule(object):
def __init__(self, argument_spec, bypass_checks=False, no_log=False,
check_invalid_arguments=None, mutually_exclusive=None, required_together=None,
required_one_of=None, add_file_common_args=False, supports_check_mode=False,
required_if=None, required_by=None):
'''
Common code for quickly building an ansible module in Python
(although you can write modules with anything that can return JSON).
See :ref:`developing_modules_general` for a general introduction
and :ref:`developing_program_flow_modules` for more detailed explanation.
'''
self._name = os.path.basename(__file__) # initialize name until we can parse from options
self.argument_spec = argument_spec
self.supports_check_mode = supports_check_mode
self.check_mode = False
self.bypass_checks = bypass_checks
self.no_log = no_log
# Check whether code set this explicitly for deprecation purposes
if check_invalid_arguments is None:
check_invalid_arguments = True
module_set_check_invalid_arguments = False
else:
module_set_check_invalid_arguments = True
self.check_invalid_arguments = check_invalid_arguments
self.mutually_exclusive = mutually_exclusive
self.required_together = required_together
self.required_one_of = required_one_of
self.required_if = required_if
self.required_by = required_by
self.cleanup_files = []
self._debug = False
self._diff = False
self._socket_path = None
self._shell = None
self._verbosity = 0
# May be used to set modifications to the environment for any
# run_command invocation
self.run_command_environ_update = {}
self._warnings = []
self._deprecations = []
self._clean = {}
self._string_conversion_action = ''
self.aliases = {}
self._legal_inputs = []
self._options_context = list()
self._tmpdir = None
if add_file_common_args:
for k, v in FILE_COMMON_ARGUMENTS.items():
if k not in self.argument_spec:
self.argument_spec[k] = v
self._load_params()
self._set_fallbacks()
# append to legal_inputs and then possibly check against them
try:
self.aliases = self._handle_aliases()
except (ValueError, TypeError) as e:
# Use exceptions here because it isn't safe to call fail_json until no_log is processed
print('\n{"failed": true, "msg": "Module alias error: %s"}' % to_native(e))
sys.exit(1)
# Save parameter values that should never be logged
self.no_log_values = set()
self._handle_no_log_values()
# check the locale as set by the current environment, and reset to
# a known valid (LANG=C) if it's an invalid/unavailable locale
self._check_locale()
self._check_arguments(check_invalid_arguments)
# check exclusive early
if not bypass_checks:
self._check_mutually_exclusive(mutually_exclusive)
self._set_defaults(pre=True)
self._CHECK_ARGUMENT_TYPES_DISPATCHER = {
'str': self._check_type_str,
'list': self._check_type_list,
'dict': self._check_type_dict,
'bool': self._check_type_bool,
'int': self._check_type_int,
'float': self._check_type_float,
'path': self._check_type_path,
'raw': self._check_type_raw,
'jsonarg': self._check_type_jsonarg,
'json': self._check_type_jsonarg,
'bytes': self._check_type_bytes,
'bits': self._check_type_bits,
}
if not bypass_checks:
self._check_required_arguments()
self._check_argument_types()
self._check_argument_values()
self._check_required_together(required_together)
self._check_required_one_of(required_one_of)
self._check_required_if(required_if)
self._check_required_by(required_by)
self._set_defaults(pre=False)
# deal with options sub-spec
self._handle_options()
if not self.no_log:
self._log_invocation()
# finally, make sure we're in a sane working dir
self._set_cwd()
# Do this at the end so that logging parameters have been set up
# This is to warn third party module authors that the functionatlity is going away.
# We exclude uri and zfs as they have their own deprecation warnings for users and we'll
# make sure to update their code to stop using check_invalid_arguments when 2.9 rolls around
if module_set_check_invalid_arguments and self._name not in ('uri', 'zfs'):
self.deprecate('Setting check_invalid_arguments is deprecated and will be removed.'
' Update the code for this module In the future, AnsibleModule will'
' always check for invalid arguments.', version='2.9')
@property
def tmpdir(self):
# if _ansible_tmpdir was not set and we have a remote_tmp,
# the module needs to create it and clean it up once finished.
# otherwise we create our own module tmp dir from the system defaults
if self._tmpdir is None:
basedir = None
if self._remote_tmp is not None:
basedir = os.path.expanduser(os.path.expandvars(self._remote_tmp))
if basedir is not None and not os.path.exists(basedir):
try:
os.makedirs(basedir, mode=0o700)
except (OSError, IOError) as e:
self.warn("Unable to use %s as temporary directory, "
"failing back to system: %s" % (basedir, to_native(e)))
basedir = None
else:
self.warn("Module remote_tmp %s did not exist and was "
"created with a mode of 0700, this may cause"
" issues when running as another user. To "
"avoid this, create the remote_tmp dir with "
"the correct permissions manually" % basedir)
basefile = "ansible-moduletmp-%s-" % time.time()
try:
tmpdir = tempfile.mkdtemp(prefix=basefile, dir=basedir)
except (OSError, IOError) as e:
self.fail_json(
msg="Failed to create remote module tmp path at dir %s "
"with prefix %s: %s" % (basedir, basefile, to_native(e))
)
if not self._keep_remote_files:
atexit.register(shutil.rmtree, tmpdir)
self._tmpdir = tmpdir
return self._tmpdir
def warn(self, warning):
if isinstance(warning, string_types):
self._warnings.append(warning)
self.log('[WARNING] %s' % warning)
else:
raise TypeError("warn requires a string not a %s" % type(warning))
def deprecate(self, msg, version=None):
if isinstance(msg, string_types):
self._deprecations.append({
'msg': msg,
'version': version
})
self.log('[DEPRECATION WARNING] %s %s' % (msg, version))
else:
raise TypeError("deprecate requires a string not a %s" % type(msg))
def load_file_common_arguments(self, params):
'''
many modules deal with files, this encapsulates common
options that the file module accepts such that it is directly
available to all modules and they can share code.
'''
path = params.get('path', params.get('dest', None))
if path is None:
return {}
else:
path = os.path.expanduser(os.path.expandvars(path))
b_path = to_bytes(path, errors='surrogate_or_strict')
# if the path is a symlink, and we're following links, get
# the target of the link instead for testing
if params.get('follow', False) and os.path.islink(b_path):
b_path = os.path.realpath(b_path)
path = to_native(b_path)
mode = params.get('mode', None)
owner = params.get('owner', None)
group = params.get('group', None)
# selinux related options
seuser = params.get('seuser', None)
serole = params.get('serole', None)
setype = params.get('setype', None)
selevel = params.get('selevel', None)
secontext = [seuser, serole, setype]
if self.selinux_mls_enabled():
secontext.append(selevel)
default_secontext = self.selinux_default_context(path)
for i in range(len(default_secontext)):
if i is not None and secontext[i] == '_default':
secontext[i] = default_secontext[i]
attributes = params.get('attributes', None)
return dict(
path=path, mode=mode, owner=owner, group=group,
seuser=seuser, serole=serole, setype=setype,
selevel=selevel, secontext=secontext, attributes=attributes,
)
# Detect whether using selinux that is MLS-aware.
# While this means you can set the level/range with
# selinux.lsetfilecon(), it may or may not mean that you
# will get the selevel as part of the context returned
# by selinux.lgetfilecon().
def selinux_mls_enabled(self):
if not HAVE_SELINUX:
return False
if selinux.is_selinux_mls_enabled() == 1:
return True
else:
return False
def selinux_enabled(self):
if not HAVE_SELINUX:
seenabled = self.get_bin_path('selinuxenabled')
if seenabled is not None:
(rc, out, err) = self.run_command(seenabled)
if rc == 0:
self.fail_json(msg="Aborting, target uses selinux but python bindings (libselinux-python) aren't installed!")
return False
if selinux.is_selinux_enabled() == 1:
return True
else:
return False
# Determine whether we need a placeholder for selevel/mls
def selinux_initial_context(self):
context = [None, None, None]
if self.selinux_mls_enabled():
context.append(None)
return context
# If selinux fails to find a default, return an array of None
def selinux_default_context(self, path, mode=0):
context = self.selinux_initial_context()
if not HAVE_SELINUX or not self.selinux_enabled():
return context
try:
ret = selinux.matchpathcon(to_native(path, errors='surrogate_or_strict'), mode)
except OSError:
return context
if ret[0] == -1:
return context
# Limit split to 4 because the selevel, the last in the list,
# may contain ':' characters
context = ret[1].split(':', 3)
return context
def selinux_context(self, path):
context = self.selinux_initial_context()
if not HAVE_SELINUX or not self.selinux_enabled():
return context
try:
ret = selinux.lgetfilecon_raw(to_native(path, errors='surrogate_or_strict'))
except OSError as e:
if e.errno == errno.ENOENT:
self.fail_json(path=path, msg='path %s does not exist' % path)
else:
self.fail_json(path=path, msg='failed to retrieve selinux context')
if ret[0] == -1:
return context
# Limit split to 4 because the selevel, the last in the list,
# may contain ':' characters
context = ret[1].split(':', 3)
return context
def user_and_group(self, path, expand=True):
b_path = to_bytes(path, errors='surrogate_or_strict')
if expand:
b_path = os.path.expanduser(os.path.expandvars(b_path))
st = os.lstat(b_path)
uid = st.st_uid
gid = st.st_gid
return (uid, gid)
def find_mount_point(self, path):
path_is_bytes = False
if isinstance(path, binary_type):
path_is_bytes = True
b_path = os.path.realpath(to_bytes(os.path.expanduser(os.path.expandvars(path)), errors='surrogate_or_strict'))
while not os.path.ismount(b_path):
b_path = os.path.dirname(b_path)
if path_is_bytes:
return b_path
return to_text(b_path, errors='surrogate_or_strict')
def is_special_selinux_path(self, path):
"""
Returns a tuple containing (True, selinux_context) if the given path is on a
NFS or other 'special' fs mount point, otherwise the return will be (False, None).
"""
try:
f = open('/proc/mounts', 'r')
mount_data = f.readlines()
f.close()
except Exception:
return (False, None)
path_mount_point = self.find_mount_point(path)
for line in mount_data:
(device, mount_point, fstype, options, rest) = line.split(' ', 4)
if path_mount_point == mount_point:
for fs in self._selinux_special_fs:
if fs in fstype:
special_context = self.selinux_context(path_mount_point)
return (True, special_context)
return (False, None)
def set_default_selinux_context(self, path, changed):
if not HAVE_SELINUX or not self.selinux_enabled():
return changed
context = self.selinux_default_context(path)
return self.set_context_if_different(path, context, False)
def set_context_if_different(self, path, context, changed, diff=None):
if not HAVE_SELINUX or not self.selinux_enabled():
return changed
if self.check_file_absent_if_check_mode(path):
return True
cur_context = self.selinux_context(path)
new_context = list(cur_context)
# Iterate over the current context instead of the
# argument context, which may have selevel.
(is_special_se, sp_context) = self.is_special_selinux_path(path)
if is_special_se:
new_context = sp_context
else:
for i in range(len(cur_context)):
if len(context) > i:
if context[i] is not None and context[i] != cur_context[i]:
new_context[i] = context[i]
elif context[i] is None:
new_context[i] = cur_context[i]
if cur_context != new_context:
if diff is not None:
if 'before' not in diff:
diff['before'] = {}
diff['before']['secontext'] = cur_context
if 'after' not in diff:
diff['after'] = {}
diff['after']['secontext'] = new_context
try:
if self.check_mode:
return True
rc = selinux.lsetfilecon(to_native(path), ':'.join(new_context))
except OSError as e:
self.fail_json(path=path, msg='invalid selinux context: %s' % to_native(e),
new_context=new_context, cur_context=cur_context, input_was=context)
if rc != 0:
self.fail_json(path=path, msg='set selinux context failed')
changed = True
return changed
def set_owner_if_different(self, path, owner, changed, diff=None, expand=True):
if owner is None:
return changed
b_path = to_bytes(path, errors='surrogate_or_strict')
if expand:
b_path = os.path.expanduser(os.path.expandvars(b_path))
if self.check_file_absent_if_check_mode(b_path):
return True
orig_uid, orig_gid = self.user_and_group(b_path, expand)
try:
uid = int(owner)
except ValueError:
try:
uid = pwd.getpwnam(owner).pw_uid
except KeyError:
path = to_text(b_path)
self.fail_json(path=path, msg='chown failed: failed to look up user %s' % owner)
if orig_uid != uid:
if diff is not None:
if 'before' not in diff:
diff['before'] = {}
diff['before']['owner'] = orig_uid
if 'after' not in diff:
diff['after'] = {}
diff['after']['owner'] = uid
if self.check_mode:
return True
try:
os.lchown(b_path, uid, -1)
except (IOError, OSError) as e:
path = to_text(b_path)
self.fail_json(path=path, msg='chown failed: %s' % (to_text(e)))
changed = True
return changed
def set_group_if_different(self, path, group, changed, diff=None, expand=True):
if group is None:
return changed
b_path = to_bytes(path, errors='surrogate_or_strict')
if expand:
b_path = os.path.expanduser(os.path.expandvars(b_path))
if self.check_file_absent_if_check_mode(b_path):
return True
orig_uid, orig_gid = self.user_and_group(b_path, expand)
try:
gid = int(group)
except ValueError:
try:
gid = grp.getgrnam(group).gr_gid
except KeyError:
path = to_text(b_path)
self.fail_json(path=path, msg='chgrp failed: failed to look up group %s' % group)
if orig_gid != gid:
if diff is not None:
if 'before' not in diff:
diff['before'] = {}
diff['before']['group'] = orig_gid
if 'after' not in diff:
diff['after'] = {}
diff['after']['group'] = gid
if self.check_mode:
return True
try:
os.lchown(b_path, -1, gid)
except OSError:
path = to_text(b_path)
self.fail_json(path=path, msg='chgrp failed')
changed = True
return changed
def set_mode_if_different(self, path, mode, changed, diff=None, expand=True):
if mode is None:
return changed
b_path = to_bytes(path, errors='surrogate_or_strict')
if expand:
b_path = os.path.expanduser(os.path.expandvars(b_path))
path_stat = os.lstat(b_path)
if self.check_file_absent_if_check_mode(b_path):
return True
if not isinstance(mode, int):
try:
mode = int(mode, 8)
except Exception:
try:
mode = self._symbolic_mode_to_octal(path_stat, mode)
except Exception as e:
path = to_text(b_path)
self.fail_json(path=path,
msg="mode must be in octal or symbolic form",
details=to_native(e))
if mode != stat.S_IMODE(mode):
# prevent mode from having extra info orbeing invalid long number
path = to_text(b_path)
self.fail_json(path=path, msg="Invalid mode supplied, only permission info is allowed", details=mode)
prev_mode = stat.S_IMODE(path_stat.st_mode)
if prev_mode != mode:
if diff is not None:
if 'before' not in diff:
diff['before'] = {}
diff['before']['mode'] = '0%03o' % prev_mode
if 'after' not in diff:
diff['after'] = {}
diff['after']['mode'] = '0%03o' % mode
if self.check_mode:
return True
# FIXME: comparison against string above will cause this to be executed
# every time
try:
if hasattr(os, 'lchmod'):
os.lchmod(b_path, mode)
else:
if not os.path.islink(b_path):
os.chmod(b_path, mode)
else:
# Attempt to set the perms of the symlink but be
# careful not to change the perms of the underlying
# file while trying
underlying_stat = os.stat(b_path)
os.chmod(b_path, mode)
new_underlying_stat = os.stat(b_path)
if underlying_stat.st_mode != new_underlying_stat.st_mode:
os.chmod(b_path, stat.S_IMODE(underlying_stat.st_mode))
except OSError as e:
if os.path.islink(b_path) and e.errno == errno.EPERM: # Can't set mode on symbolic links
pass
elif e.errno in (errno.ENOENT, errno.ELOOP): # Can't set mode on broken symbolic links
pass
else:
raise
except Exception as e:
path = to_text(b_path)
self.fail_json(path=path, msg='chmod failed', details=to_native(e),
exception=traceback.format_exc())
path_stat = os.lstat(b_path)
new_mode = stat.S_IMODE(path_stat.st_mode)
if new_mode != prev_mode:
changed = True
return changed
def set_attributes_if_different(self, path, attributes, changed, diff=None, expand=True):
if attributes is None:
return changed
b_path = to_bytes(path, errors='surrogate_or_strict')
if expand:
b_path = os.path.expanduser(os.path.expandvars(b_path))
if self.check_file_absent_if_check_mode(b_path):
return True
existing = self.get_file_attributes(b_path)
attr_mod = '='
if attributes.startswith(('-', '+')):
attr_mod = attributes[0]
attributes = attributes[1:]
if existing.get('attr_flags', '') != attributes or attr_mod == '-':
attrcmd = self.get_bin_path('chattr')
if attrcmd:
attrcmd = [attrcmd, '%s%s' % (attr_mod, attributes), b_path]
changed = True
if diff is not None:
if 'before' not in diff:
diff['before'] = {}
diff['before']['attributes'] = existing.get('attr_flags')
if 'after' not in diff:
diff['after'] = {}
diff['after']['attributes'] = '%s%s' % (attr_mod, attributes)
if not self.check_mode:
try:
rc, out, err = self.run_command(attrcmd)
if rc != 0 or err:
raise Exception("Error while setting attributes: %s" % (out + err))
except Exception as e:
self.fail_json(path=to_text(b_path), msg='chattr failed',
details=to_native(e), exception=traceback.format_exc())
return changed
def get_file_attributes(self, path):
output = {}
attrcmd = self.get_bin_path('lsattr', False)
if attrcmd:
attrcmd = [attrcmd, '-vd', path]
try:
rc, out, err = self.run_command(attrcmd)
if rc == 0:
res = out.split()
output['attr_flags'] = res[1].replace('-', '').strip()
output['version'] = res[0].strip()
output['attributes'] = format_attributes(output['attr_flags'])
except Exception:
pass
return output
@classmethod
def _symbolic_mode_to_octal(cls, path_stat, symbolic_mode):
"""
This enables symbolic chmod string parsing as stated in the chmod man-page
This includes things like: "u=rw-x+X,g=r-x+X,o=r-x+X"
"""
new_mode = stat.S_IMODE(path_stat.st_mode)
# Now parse all symbolic modes
for mode in symbolic_mode.split(','):
# Per single mode. This always contains a '+', '-' or '='
# Split it on that
permlist = MODE_OPERATOR_RE.split(mode)
# And find all the operators
opers = MODE_OPERATOR_RE.findall(mode)
# The user(s) where it's all about is the first element in the
# 'permlist' list. Take that and remove it from the list.
# An empty user or 'a' means 'all'.
users = permlist.pop(0)
use_umask = (users == '')
if users == 'a' or users == '':
users = 'ugo'
# Check if there are illegal characters in the user list
# They can end up in 'users' because they are not split
if USERS_RE.match(users):
raise ValueError("bad symbolic permission for mode: %s" % mode)
# Now we have two list of equal length, one contains the requested
# permissions and one with the corresponding operators.
for idx, perms in enumerate(permlist):
# Check if there are illegal characters in the permissions
if PERMS_RE.match(perms):
raise ValueError("bad symbolic permission for mode: %s" % mode)
for user in users:
mode_to_apply = cls._get_octal_mode_from_symbolic_perms(path_stat, user, perms, use_umask)
new_mode = cls._apply_operation_to_mode(user, opers[idx], mode_to_apply, new_mode)
return new_mode
@staticmethod
def _apply_operation_to_mode(user, operator, mode_to_apply, current_mode):
if operator == '=':
if user == 'u':
mask = stat.S_IRWXU | stat.S_ISUID
elif user == 'g':
mask = stat.S_IRWXG | stat.S_ISGID
elif user == 'o':
mask = stat.S_IRWXO | stat.S_ISVTX
# mask out u, g, or o permissions from current_mode and apply new permissions
inverse_mask = mask ^ PERM_BITS
new_mode = (current_mode & inverse_mask) | mode_to_apply
elif operator == '+':
new_mode = current_mode | mode_to_apply
elif operator == '-':
new_mode = current_mode - (current_mode & mode_to_apply)
return new_mode
@staticmethod
def _get_octal_mode_from_symbolic_perms(path_stat, user, perms, use_umask):
prev_mode = stat.S_IMODE(path_stat.st_mode)
is_directory = stat.S_ISDIR(path_stat.st_mode)
has_x_permissions = (prev_mode & EXEC_PERM_BITS) > 0
apply_X_permission = is_directory or has_x_permissions
# Get the umask, if the 'user' part is empty, the effect is as if (a) were
# given, but bits that are set in the umask are not affected.
# We also need the "reversed umask" for masking
umask = os.umask(0)
os.umask(umask)
rev_umask = umask ^ PERM_BITS
# Permission bits constants documented at:
# http://docs.python.org/2/library/stat.html#stat.S_ISUID
if apply_X_permission:
X_perms = {
'u': {'X': stat.S_IXUSR},
'g': {'X': stat.S_IXGRP},
'o': {'X': stat.S_IXOTH},
}
else:
X_perms = {
'u': {'X': 0},
'g': {'X': 0},
'o': {'X': 0},
}
user_perms_to_modes = {
'u': {
'r': rev_umask & stat.S_IRUSR if use_umask else stat.S_IRUSR,
'w': rev_umask & stat.S_IWUSR if use_umask else stat.S_IWUSR,
'x': rev_umask & stat.S_IXUSR if use_umask else stat.S_IXUSR,
's': stat.S_ISUID,
't': 0,
'u': prev_mode & stat.S_IRWXU,
'g': (prev_mode & stat.S_IRWXG) << 3,
'o': (prev_mode & stat.S_IRWXO) << 6},
'g': {
'r': rev_umask & stat.S_IRGRP if use_umask else stat.S_IRGRP,
'w': rev_umask & stat.S_IWGRP if use_umask else stat.S_IWGRP,
'x': rev_umask & stat.S_IXGRP if use_umask else stat.S_IXGRP,
's': stat.S_ISGID,
't': 0,
'u': (prev_mode & stat.S_IRWXU) >> 3,
'g': prev_mode & stat.S_IRWXG,
'o': (prev_mode & stat.S_IRWXO) << 3},
'o': {
'r': rev_umask & stat.S_IROTH if use_umask else stat.S_IROTH,
'w': rev_umask & stat.S_IWOTH if use_umask else stat.S_IWOTH,
'x': rev_umask & stat.S_IXOTH if use_umask else stat.S_IXOTH,
's': 0,
't': stat.S_ISVTX,
'u': (prev_mode & stat.S_IRWXU) >> 6,
'g': (prev_mode & stat.S_IRWXG) >> 3,
'o': prev_mode & stat.S_IRWXO},
}
# Insert X_perms into user_perms_to_modes
for key, value in X_perms.items():
user_perms_to_modes[key].update(value)
def or_reduce(mode, perm):
return mode | user_perms_to_modes[user][perm]
return reduce(or_reduce, perms, 0)
def set_fs_attributes_if_different(self, file_args, changed, diff=None, expand=True):
# set modes owners and context as needed
changed = self.set_context_if_different(
file_args['path'], file_args['secontext'], changed, diff
)
changed = self.set_owner_if_different(
file_args['path'], file_args['owner'], changed, diff, expand
)
changed = self.set_group_if_different(
file_args['path'], file_args['group'], changed, diff, expand
)
changed = self.set_mode_if_different(
file_args['path'], file_args['mode'], changed, diff, expand
)
changed = self.set_attributes_if_different(
file_args['path'], file_args['attributes'], changed, diff, expand
)
return changed
def check_file_absent_if_check_mode(self, file_path):
return self.check_mode and not os.path.exists(file_path)
def set_directory_attributes_if_different(self, file_args, changed, diff=None, expand=True):
return self.set_fs_attributes_if_different(file_args, changed, diff, expand)
def set_file_attributes_if_different(self, file_args, changed, diff=None, expand=True):
return self.set_fs_attributes_if_different(file_args, changed, diff, expand)
def add_path_info(self, kwargs):
'''
for results that are files, supplement the info about the file
in the return path with stats about the file path.
'''
path = kwargs.get('path', kwargs.get('dest', None))
if path is None:
return kwargs
b_path = to_bytes(path, errors='surrogate_or_strict')
if os.path.exists(b_path):
(uid, gid) = self.user_and_group(path)
kwargs['uid'] = uid
kwargs['gid'] = gid
try:
user = pwd.getpwuid(uid)[0]
except KeyError:
user = str(uid)
try:
group = grp.getgrgid(gid)[0]
except KeyError:
group = str(gid)
kwargs['owner'] = user
kwargs['group'] = group
st = os.lstat(b_path)
kwargs['mode'] = '0%03o' % stat.S_IMODE(st[stat.ST_MODE])
# secontext not yet supported
if os.path.islink(b_path):
kwargs['state'] = 'link'
elif os.path.isdir(b_path):
kwargs['state'] = 'directory'
elif os.stat(b_path).st_nlink > 1:
kwargs['state'] = 'hard'
else:
kwargs['state'] = 'file'
if HAVE_SELINUX and self.selinux_enabled():
kwargs['secontext'] = ':'.join(self.selinux_context(path))
kwargs['size'] = st[stat.ST_SIZE]
return kwargs
def _check_locale(self):
'''
Uses the locale module to test the currently set locale
(per the LANG and LC_CTYPE environment settings)
'''
try:
# setting the locale to '' uses the default locale
# as it would be returned by locale.getdefaultlocale()
locale.setlocale(locale.LC_ALL, '')
except locale.Error:
# fallback to the 'C' locale, which may cause unicode
# issues but is preferable to simply failing because
# of an unknown locale
locale.setlocale(locale.LC_ALL, 'C')
os.environ['LANG'] = 'C'
os.environ['LC_ALL'] = 'C'
os.environ['LC_MESSAGES'] = 'C'
except Exception as e:
self.fail_json(msg="An unknown error was encountered while attempting to validate the locale: %s" %
to_native(e), exception=traceback.format_exc())
def _handle_aliases(self, spec=None, param=None):
if spec is None:
spec = self.argument_spec
if param is None:
param = self.params
# this uses exceptions as it happens before we can safely call fail_json
alias_results, self._legal_inputs = handle_aliases(spec, param)
return alias_results
def _handle_no_log_values(self, spec=None, param=None):
if spec is None:
spec = self.argument_spec
if param is None:
param = self.params
self.no_log_values.update(list_no_log_values(spec, param))
self._deprecations.extend(list_deprecations(spec, param))
def _check_arguments(self, check_invalid_arguments, spec=None, param=None, legal_inputs=None):
self._syslog_facility = 'LOG_USER'
unsupported_parameters = set()
if spec is None:
spec = self.argument_spec
if param is None:
param = self.params
if legal_inputs is None:
legal_inputs = self._legal_inputs
for k in list(param.keys()):
if check_invalid_arguments and k not in legal_inputs:
unsupported_parameters.add(k)
for k in PASS_VARS:
# handle setting internal properties from internal ansible vars
param_key = '_ansible_%s' % k
if param_key in param:
if k in PASS_BOOLS:
setattr(self, PASS_VARS[k][0], self.boolean(param[param_key]))
else:
setattr(self, PASS_VARS[k][0], param[param_key])
# clean up internal top level params:
if param_key in self.params:
del self.params[param_key]
else:
# use defaults if not already set
if not hasattr(self, PASS_VARS[k][0]):
setattr(self, PASS_VARS[k][0], PASS_VARS[k][1])
if unsupported_parameters:
msg = "Unsupported parameters for (%s) module: %s" % (self._name, ', '.join(sorted(list(unsupported_parameters))))
if self._options_context:
msg += " found in %s." % " -> ".join(self._options_context)
msg += " Supported parameters include: %s" % (', '.join(sorted(spec.keys())))
self.fail_json(msg=msg)
if self.check_mode and not self.supports_check_mode:
self.exit_json(skipped=True, msg="remote module (%s) does not support check mode" % self._name)
def _count_terms(self, check, param=None):
if param is None:
param = self.params
return count_terms(check, param)
def _check_mutually_exclusive(self, spec, param=None):
if param is None:
param = self.params
try:
check_mutually_exclusive(spec, param)
except TypeError as e:
msg = to_native(e)
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
def _check_required_one_of(self, spec, param=None):
if spec is None:
return
if param is None:
param = self.params
try:
check_required_one_of(spec, param)
except TypeError as e:
msg = to_native(e)
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
def _check_required_together(self, spec, param=None):
if spec is None:
return
if param is None:
param = self.params
try:
check_required_together(spec, param)
except TypeError as e:
msg = to_native(e)
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
def _check_required_by(self, spec, param=None):
if spec is None:
return
if param is None:
param = self.params
try:
check_required_by(spec, param)
except TypeError as e:
self.fail_json(msg=to_native(e))
def _check_required_arguments(self, spec=None, param=None):
if spec is None:
spec = self.argument_spec
if param is None:
param = self.params
try:
check_required_arguments(spec, param)
except TypeError as e:
msg = to_native(e)
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
def _check_required_if(self, spec, param=None):
''' ensure that parameters which conditionally required are present '''
if spec is None:
return
if param is None:
param = self.params
try:
check_required_if(spec, param)
except TypeError as e:
msg = to_native(e)
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
def _check_argument_values(self, spec=None, param=None):
''' ensure all arguments have the requested values, and there are no stray arguments '''
if spec is None:
spec = self.argument_spec
if param is None:
param = self.params
for (k, v) in spec.items():
choices = v.get('choices', None)
if choices is None:
continue
if isinstance(choices, SEQUENCETYPE) and not isinstance(choices, (binary_type, text_type)):
if k in param:
# Allow one or more when type='list' param with choices
if isinstance(param[k], list):
diff_list = ", ".join([item for item in param[k] if item not in choices])
if diff_list:
choices_str = ", ".join([to_native(c) for c in choices])
msg = "value of %s must be one or more of: %s. Got no match for: %s" % (k, choices_str, diff_list)
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
elif param[k] not in choices:
# PyYaml converts certain strings to bools. If we can unambiguously convert back, do so before checking
# the value. If we can't figure this out, module author is responsible.
lowered_choices = None
if param[k] == 'False':
lowered_choices = lenient_lowercase(choices)
overlap = BOOLEANS_FALSE.intersection(choices)
if len(overlap) == 1:
# Extract from a set
(param[k],) = overlap
if param[k] == 'True':
if lowered_choices is None:
lowered_choices = lenient_lowercase(choices)
overlap = BOOLEANS_TRUE.intersection(choices)
if len(overlap) == 1:
(param[k],) = overlap
if param[k] not in choices:
choices_str = ", ".join([to_native(c) for c in choices])
msg = "value of %s must be one of: %s, got: %s" % (k, choices_str, param[k])
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
else:
msg = "internal error: choices for argument %s are not iterable: %s" % (k, choices)
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
def safe_eval(self, value, locals=None, include_exceptions=False):
return safe_eval(value, locals, include_exceptions)
def _check_type_str(self, value):
opts = {
'error': False,
'warn': False,
'ignore': True
}
# Ignore, warn, or error when converting to a string.
allow_conversion = opts.get(self._string_conversion_action, True)
try:
return check_type_str(value, allow_conversion)
except TypeError:
common_msg = 'quote the entire value to ensure it does not change.'
if self._string_conversion_action == 'error':
msg = common_msg.capitalize()
raise TypeError(to_native(msg))
elif self._string_conversion_action == 'warn':
msg = ('The value {0!r} (type {0.__class__.__name__}) in a string field was converted to {1!r} (type string). '
'If this does not look like what you expect, {2}').format(value, to_text(value), common_msg)
self.warn(to_native(msg))
return to_native(value, errors='surrogate_or_strict')
def _check_type_list(self, value):
return check_type_list(value)
def _check_type_dict(self, value):
return check_type_dict(value)
def _check_type_bool(self, value):
return check_type_bool(value)
def _check_type_int(self, value):
return check_type_int(value)
def _check_type_float(self, value):
return check_type_float(value)
def _check_type_path(self, value):
return check_type_path(value)
def _check_type_jsonarg(self, value):
return check_type_jsonarg(value)
def _check_type_raw(self, value):
return check_type_raw(value)
def _check_type_bytes(self, value):
return check_type_bytes(value)
def _check_type_bits(self, value):
return check_type_bits(value)
def _handle_options(self, argument_spec=None, params=None):
''' deal with options to create sub spec '''
if argument_spec is None:
argument_spec = self.argument_spec
if params is None:
params = self.params
for (k, v) in argument_spec.items():
wanted = v.get('type', None)
if wanted == 'dict' or (wanted == 'list' and v.get('elements', '') == 'dict'):
spec = v.get('options', None)
if v.get('apply_defaults', False):
if spec is not None:
if params.get(k) is None:
params[k] = {}
else:
continue
elif spec is None or k not in params or params[k] is None:
continue
self._options_context.append(k)
if isinstance(params[k], dict):
elements = [params[k]]
else:
elements = params[k]
for param in elements:
if not isinstance(param, dict):
self.fail_json(msg="value of %s must be of type dict or list of dict" % k)
self._set_fallbacks(spec, param)
options_aliases = self._handle_aliases(spec, param)
self._handle_no_log_values(spec, param)
options_legal_inputs = list(spec.keys()) + list(options_aliases.keys())
self._check_arguments(self.check_invalid_arguments, spec, param, options_legal_inputs)
# check exclusive early
if not self.bypass_checks:
self._check_mutually_exclusive(v.get('mutually_exclusive', None), param)
self._set_defaults(pre=True, spec=spec, param=param)
if not self.bypass_checks:
self._check_required_arguments(spec, param)
self._check_argument_types(spec, param)
self._check_argument_values(spec, param)
self._check_required_together(v.get('required_together', None), param)
self._check_required_one_of(v.get('required_one_of', None), param)
self._check_required_if(v.get('required_if', None), param)
self._check_required_by(v.get('required_by', None), param)
self._set_defaults(pre=False, spec=spec, param=param)
# handle multi level options (sub argspec)
self._handle_options(spec, param)
self._options_context.pop()
def _get_wanted_type(self, wanted, k):
if not callable(wanted):
if wanted is None:
# Mostly we want to default to str.
# For values set to None explicitly, return None instead as
# that allows a user to unset a parameter
wanted = 'str'
try:
type_checker = self._CHECK_ARGUMENT_TYPES_DISPATCHER[wanted]
except KeyError:
self.fail_json(msg="implementation error: unknown type %s requested for %s" % (wanted, k))
else:
# set the type_checker to the callable, and reset wanted to the callable's name (or type if it doesn't have one, ala MagicMock)
type_checker = wanted
wanted = getattr(wanted, '__name__', to_native(type(wanted)))
return type_checker, wanted
def _handle_elements(self, wanted, param, values):
type_checker, wanted_name = self._get_wanted_type(wanted, param)
validated_params = []
for value in values:
try:
validated_params.append(type_checker(value))
except (TypeError, ValueError) as e:
msg = "Elements value for option %s" % param
if self._options_context:
msg += " found in '%s'" % " -> ".join(self._options_context)
msg += " is of type %s and we were unable to convert to %s: %s" % (type(value), wanted_name, to_native(e))
self.fail_json(msg=msg)
return validated_params
def _check_argument_types(self, spec=None, param=None):
''' ensure all arguments have the requested type '''
if spec is None:
spec = self.argument_spec
if param is None:
param = self.params
for (k, v) in spec.items():
wanted = v.get('type', None)
if k not in param:
continue
value = param[k]
if value is None:
continue
type_checker, wanted_name = self._get_wanted_type(wanted, k)
try:
param[k] = type_checker(value)
wanted_elements = v.get('elements', None)
if wanted_elements:
if wanted != 'list' or not isinstance(param[k], list):
msg = "Invalid type %s for option '%s'" % (wanted_name, param)
if self._options_context:
msg += " found in '%s'." % " -> ".join(self._options_context)
msg += ", elements value check is supported only with 'list' type"
self.fail_json(msg=msg)
param[k] = self._handle_elements(wanted_elements, k, param[k])
except (TypeError, ValueError) as e:
msg = "argument %s is of type %s" % (k, type(value))
if self._options_context:
msg += " found in '%s'." % " -> ".join(self._options_context)
msg += " and we were unable to convert to %s: %s" % (wanted_name, to_native(e))
self.fail_json(msg=msg)
def _set_defaults(self, pre=True, spec=None, param=None):
if spec is None:
spec = self.argument_spec
if param is None:
param = self.params
for (k, v) in spec.items():
default = v.get('default', None)
if pre is True:
# this prevents setting defaults on required items
if default is not None and k not in param:
param[k] = default
else:
# make sure things without a default still get set None
if k not in param:
param[k] = default
def _set_fallbacks(self, spec=None, param=None):
if spec is None:
spec = self.argument_spec
if param is None:
param = self.params
for (k, v) in spec.items():
fallback = v.get('fallback', (None,))
fallback_strategy = fallback[0]
fallback_args = []
fallback_kwargs = {}
if k not in param and fallback_strategy is not None:
for item in fallback[1:]:
if isinstance(item, dict):
fallback_kwargs = item
else:
fallback_args = item
try:
param[k] = fallback_strategy(*fallback_args, **fallback_kwargs)
except AnsibleFallbackNotFound:
continue
def _load_params(self):
''' read the input and set the params attribute.
This method is for backwards compatibility. The guts of the function
were moved out in 2.1 so that custom modules could read the parameters.
'''
# debug overrides to read args from file or cmdline
self.params = _load_params()
def _log_to_syslog(self, msg):
if HAS_SYSLOG:
module = 'ansible-%s' % self._name
facility = getattr(syslog, self._syslog_facility, syslog.LOG_USER)
syslog.openlog(str(module), 0, facility)
syslog.syslog(syslog.LOG_INFO, msg)
def debug(self, msg):
if self._debug:
self.log('[debug] %s' % msg)
def log(self, msg, log_args=None):
if not self.no_log:
if log_args is None:
log_args = dict()
module = 'ansible-%s' % self._name
if isinstance(module, binary_type):
module = module.decode('utf-8', 'replace')
# 6655 - allow for accented characters
if not isinstance(msg, (binary_type, text_type)):
raise TypeError("msg should be a string (got %s)" % type(msg))
# We want journal to always take text type
# syslog takes bytes on py2, text type on py3
if isinstance(msg, binary_type):
journal_msg = remove_values(msg.decode('utf-8', 'replace'), self.no_log_values)
else:
# TODO: surrogateescape is a danger here on Py3
journal_msg = remove_values(msg, self.no_log_values)
if PY3:
syslog_msg = journal_msg
else:
syslog_msg = journal_msg.encode('utf-8', 'replace')
if has_journal:
journal_args = [("MODULE", os.path.basename(__file__))]
for arg in log_args:
journal_args.append((arg.upper(), str(log_args[arg])))
try:
if HAS_SYSLOG:
# If syslog_facility specified, it needs to convert
# from the facility name to the facility code, and
# set it as SYSLOG_FACILITY argument of journal.send()
facility = getattr(syslog,
self._syslog_facility,
syslog.LOG_USER) >> 3
journal.send(MESSAGE=u"%s %s" % (module, journal_msg),
SYSLOG_FACILITY=facility,
**dict(journal_args))
else:
journal.send(MESSAGE=u"%s %s" % (module, journal_msg),
**dict(journal_args))
except IOError:
# fall back to syslog since logging to journal failed
self._log_to_syslog(syslog_msg)
else:
self._log_to_syslog(syslog_msg)
def _log_invocation(self):
''' log that ansible ran the module '''
# TODO: generalize a separate log function and make log_invocation use it
# Sanitize possible password argument when logging.
log_args = dict()
for param in self.params:
canon = self.aliases.get(param, param)
arg_opts = self.argument_spec.get(canon, {})
no_log = arg_opts.get('no_log', False)
if self.boolean(no_log):
log_args[param] = 'NOT_LOGGING_PARAMETER'
# try to capture all passwords/passphrase named fields missed by no_log
elif PASSWORD_MATCH.search(param) and arg_opts.get('type', 'str') != 'bool' and not arg_opts.get('choices', False):
# skip boolean and enums as they are about 'password' state
log_args[param] = 'NOT_LOGGING_PASSWORD'
self.warn('Module did not set no_log for %s' % param)
else:
param_val = self.params[param]
if not isinstance(param_val, (text_type, binary_type)):
param_val = str(param_val)
elif isinstance(param_val, text_type):
param_val = param_val.encode('utf-8')
log_args[param] = heuristic_log_sanitize(param_val, self.no_log_values)
msg = ['%s=%s' % (to_native(arg), to_native(val)) for arg, val in log_args.items()]
if msg:
msg = 'Invoked with %s' % ' '.join(msg)
else:
msg = 'Invoked'
self.log(msg, log_args=log_args)
def _set_cwd(self):
try:
cwd = os.getcwd()
if not os.access(cwd, os.F_OK | os.R_OK):
raise Exception()
return cwd
except Exception:
# we don't have access to the cwd, probably because of sudo.
# Try and move to a neutral location to prevent errors
for cwd in [self.tmpdir, os.path.expandvars('$HOME'), tempfile.gettempdir()]:
try:
if os.access(cwd, os.F_OK | os.R_OK):
os.chdir(cwd)
return cwd
except Exception:
pass
# we won't error here, as it may *not* be a problem,
# and we don't want to break modules unnecessarily
return None
def get_bin_path(self, arg, required=False, opt_dirs=None):
'''
Find system executable in PATH.
:param arg: The executable to find.
:param required: if executable is not found and required is ``True``, fail_json
:param opt_dirs: optional list of directories to search in addition to ``PATH``
:returns: if found return full path; otherwise return None
'''
bin_path = None
try:
bin_path = get_bin_path(arg, required, opt_dirs)
except ValueError as e:
self.fail_json(msg=to_text(e))
return bin_path
def boolean(self, arg):
'''Convert the argument to a boolean'''
if arg is None:
return arg
try:
return boolean(arg)
except TypeError as e:
self.fail_json(msg=to_native(e))
def jsonify(self, data):
try:
return jsonify(data)
except UnicodeError as e:
self.fail_json(msg=to_text(e))
def from_json(self, data):
return json.loads(data)
def add_cleanup_file(self, path):
if path not in self.cleanup_files:
self.cleanup_files.append(path)
def do_cleanup_files(self):
for path in self.cleanup_files:
self.cleanup(path)
def _return_formatted(self, kwargs):
self.add_path_info(kwargs)
if 'invocation' not in kwargs:
kwargs['invocation'] = {'module_args': self.params}
if 'warnings' in kwargs:
if isinstance(kwargs['warnings'], list):
for w in kwargs['warnings']:
self.warn(w)
else:
self.warn(kwargs['warnings'])
if self._warnings:
kwargs['warnings'] = self._warnings
if 'deprecations' in kwargs:
if isinstance(kwargs['deprecations'], list):
for d in kwargs['deprecations']:
if isinstance(d, SEQUENCETYPE) and len(d) == 2:
self.deprecate(d[0], version=d[1])
elif isinstance(d, Mapping):
self.deprecate(d['msg'], version=d.get('version', None))
else:
self.deprecate(d)
else:
self.deprecate(kwargs['deprecations'])
if self._deprecations:
kwargs['deprecations'] = self._deprecations
kwargs = remove_values(kwargs, self.no_log_values)
print('\n%s' % self.jsonify(kwargs))
def exit_json(self, **kwargs):
''' return from the module, without error '''
self.do_cleanup_files()
self._return_formatted(kwargs)
sys.exit(0)
def fail_json(self, **kwargs):
''' return from the module, with an error message '''
if 'msg' not in kwargs:
raise AssertionError("implementation error -- msg to explain the error is required")
kwargs['failed'] = True
# Add traceback if debug or high verbosity and it is missing
# NOTE: Badly named as exception, it really always has been a traceback
if 'exception' not in kwargs and sys.exc_info()[2] and (self._debug or self._verbosity >= 3):
if PY2:
# On Python 2 this is the last (stack frame) exception and as such may be unrelated to the failure
kwargs['exception'] = 'WARNING: The below traceback may *not* be related to the actual failure.\n' +\
''.join(traceback.format_tb(sys.exc_info()[2]))
else:
kwargs['exception'] = ''.join(traceback.format_tb(sys.exc_info()[2]))
self.do_cleanup_files()
self._return_formatted(kwargs)
sys.exit(1)
def fail_on_missing_params(self, required_params=None):
if not required_params:
return
try:
check_missing_parameters(self.params, required_params)
except TypeError as e:
self.fail_json(msg=to_native(e))
def digest_from_file(self, filename, algorithm):
''' Return hex digest of local file for a digest_method specified by name, or None if file is not present. '''
b_filename = to_bytes(filename, errors='surrogate_or_strict')
if not os.path.exists(b_filename):
return None
if os.path.isdir(b_filename):
self.fail_json(msg="attempted to take checksum of directory: %s" % filename)
# preserve old behaviour where the third parameter was a hash algorithm object
if hasattr(algorithm, 'hexdigest'):
digest_method = algorithm
else:
try:
digest_method = AVAILABLE_HASH_ALGORITHMS[algorithm]()
except KeyError:
self.fail_json(msg="Could not hash file '%s' with algorithm '%s'. Available algorithms: %s" %
(filename, algorithm, ', '.join(AVAILABLE_HASH_ALGORITHMS)))
blocksize = 64 * 1024
infile = open(os.path.realpath(b_filename), 'rb')
block = infile.read(blocksize)
while block:
digest_method.update(block)
block = infile.read(blocksize)
infile.close()
return digest_method.hexdigest()
def md5(self, filename):
''' Return MD5 hex digest of local file using digest_from_file().
Do not use this function unless you have no other choice for:
1) Optional backwards compatibility
2) Compatibility with a third party protocol
This function will not work on systems complying with FIPS-140-2.
Most uses of this function can use the module.sha1 function instead.
'''
if 'md5' not in AVAILABLE_HASH_ALGORITHMS:
raise ValueError('MD5 not available. Possibly running in FIPS mode')
return self.digest_from_file(filename, 'md5')
def sha1(self, filename):
''' Return SHA1 hex digest of local file using digest_from_file(). '''
return self.digest_from_file(filename, 'sha1')
def sha256(self, filename):
''' Return SHA-256 hex digest of local file using digest_from_file(). '''
return self.digest_from_file(filename, 'sha256')
def backup_local(self, fn):
'''make a date-marked backup of the specified file, return True or False on success or failure'''
backupdest = ''
if os.path.exists(fn):
# backups named basename.PID.YYYY-MM-DD@HH:MM:SS~
ext = time.strftime("%Y-%m-%d@%H:%M:%S~", time.localtime(time.time()))
backupdest = '%s.%s.%s' % (fn, os.getpid(), ext)
try:
self.preserved_copy(fn, backupdest)
except (shutil.Error, IOError) as e:
self.fail_json(msg='Could not make backup of %s to %s: %s' % (fn, backupdest, to_native(e)))
return backupdest
def cleanup(self, tmpfile):
if os.path.exists(tmpfile):
try:
os.unlink(tmpfile)
except OSError as e:
sys.stderr.write("could not cleanup %s: %s" % (tmpfile, to_native(e)))
def preserved_copy(self, src, dest):
"""Copy a file with preserved ownership, permissions and context"""
# shutil.copy2(src, dst)
# Similar to shutil.copy(), but metadata is copied as well - in fact,
# this is just shutil.copy() followed by copystat(). This is similar
# to the Unix command cp -p.
#
# shutil.copystat(src, dst)
# Copy the permission bits, last access time, last modification time,
# and flags from src to dst. The file contents, owner, and group are
# unaffected. src and dst are path names given as strings.
shutil.copy2(src, dest)
# Set the context
if self.selinux_enabled():
context = self.selinux_context(src)
self.set_context_if_different(dest, context, False)
# chown it
try:
dest_stat = os.stat(src)
tmp_stat = os.stat(dest)
if dest_stat and (tmp_stat.st_uid != dest_stat.st_uid or tmp_stat.st_gid != dest_stat.st_gid):
os.chown(dest, dest_stat.st_uid, dest_stat.st_gid)
except OSError as e:
if e.errno != errno.EPERM:
raise
# Set the attributes
current_attribs = self.get_file_attributes(src)
current_attribs = current_attribs.get('attr_flags', '')
self.set_attributes_if_different(dest, current_attribs, True)
def atomic_move(self, src, dest, unsafe_writes=False):
'''atomically move src to dest, copying attributes from dest, returns true on success
it uses os.rename to ensure this as it is an atomic operation, rest of the function is
to work around limitations, corner cases and ensure selinux context is saved if possible'''
context = None
dest_stat = None
b_src = to_bytes(src, errors='surrogate_or_strict')
b_dest = to_bytes(dest, errors='surrogate_or_strict')
if os.path.exists(b_dest):
try:
dest_stat = os.stat(b_dest)
# copy mode and ownership
os.chmod(b_src, dest_stat.st_mode & PERM_BITS)
os.chown(b_src, dest_stat.st_uid, dest_stat.st_gid)
# try to copy flags if possible
if hasattr(os, 'chflags') and hasattr(dest_stat, 'st_flags'):
try:
os.chflags(b_src, dest_stat.st_flags)
except OSError as e:
for err in 'EOPNOTSUPP', 'ENOTSUP':
if hasattr(errno, err) and e.errno == getattr(errno, err):
break
else:
raise
except OSError as e:
if e.errno != errno.EPERM:
raise
if self.selinux_enabled():
context = self.selinux_context(dest)
else:
if self.selinux_enabled():
context = self.selinux_default_context(dest)
creating = not os.path.exists(b_dest)
try:
# Optimistically try a rename, solves some corner cases and can avoid useless work, throws exception if not atomic.
os.rename(b_src, b_dest)
except (IOError, OSError) as e:
if e.errno not in [errno.EPERM, errno.EXDEV, errno.EACCES, errno.ETXTBSY, errno.EBUSY]:
# only try workarounds for errno 18 (cross device), 1 (not permitted), 13 (permission denied)
# and 26 (text file busy) which happens on vagrant synced folders and other 'exotic' non posix file systems
self.fail_json(msg='Could not replace file: %s to %s: %s' % (src, dest, to_native(e)),
exception=traceback.format_exc())
else:
# Use bytes here. In the shippable CI, this fails with
# a UnicodeError with surrogateescape'd strings for an unknown
# reason (doesn't happen in a local Ubuntu16.04 VM)
b_dest_dir = os.path.dirname(b_dest)
b_suffix = os.path.basename(b_dest)
error_msg = None
tmp_dest_name = None
try:
tmp_dest_fd, tmp_dest_name = tempfile.mkstemp(prefix=b'.ansible_tmp',
dir=b_dest_dir, suffix=b_suffix)
except (OSError, IOError) as e:
error_msg = 'The destination directory (%s) is not writable by the current user. Error was: %s' % (os.path.dirname(dest), to_native(e))
except TypeError:
# We expect that this is happening because python3.4.x and
# below can't handle byte strings in mkstemp(). Traceback
# would end in something like:
# file = _os.path.join(dir, pre + name + suf)
# TypeError: can't concat bytes to str
error_msg = ('Failed creating tmp file for atomic move. This usually happens when using Python3 less than Python3.5. '
'Please use Python2.x or Python3.5 or greater.')
finally:
if error_msg:
if unsafe_writes:
self._unsafe_writes(b_src, b_dest)
else:
self.fail_json(msg=error_msg, exception=traceback.format_exc())
if tmp_dest_name:
b_tmp_dest_name = to_bytes(tmp_dest_name, errors='surrogate_or_strict')
try:
try:
# close tmp file handle before file operations to prevent text file busy errors on vboxfs synced folders (windows host)
os.close(tmp_dest_fd)
# leaves tmp file behind when sudo and not root
try:
shutil.move(b_src, b_tmp_dest_name)
except OSError:
# cleanup will happen by 'rm' of tmpdir
# copy2 will preserve some metadata
shutil.copy2(b_src, b_tmp_dest_name)
if self.selinux_enabled():
self.set_context_if_different(
b_tmp_dest_name, context, False)
try:
tmp_stat = os.stat(b_tmp_dest_name)
if dest_stat and (tmp_stat.st_uid != dest_stat.st_uid or tmp_stat.st_gid != dest_stat.st_gid):
os.chown(b_tmp_dest_name, dest_stat.st_uid, dest_stat.st_gid)
except OSError as e:
if e.errno != errno.EPERM:
raise
try:
os.rename(b_tmp_dest_name, b_dest)
except (shutil.Error, OSError, IOError) as e:
if unsafe_writes and e.errno == errno.EBUSY:
self._unsafe_writes(b_tmp_dest_name, b_dest)
else:
self.fail_json(msg='Unable to make %s into to %s, failed final rename from %s: %s' %
(src, dest, b_tmp_dest_name, to_native(e)),
exception=traceback.format_exc())
except (shutil.Error, OSError, IOError) as e:
self.fail_json(msg='Failed to replace file: %s to %s: %s' % (src, dest, to_native(e)),
exception=traceback.format_exc())
finally:
self.cleanup(b_tmp_dest_name)
if creating:
# make sure the file has the correct permissions
# based on the current value of umask
umask = os.umask(0)
os.umask(umask)
os.chmod(b_dest, DEFAULT_PERM & ~umask)
try:
os.chown(b_dest, os.geteuid(), os.getegid())
except OSError:
# We're okay with trying our best here. If the user is not
# root (or old Unices) they won't be able to chown.
pass
if self.selinux_enabled():
# rename might not preserve context
self.set_context_if_different(dest, context, False)
def _unsafe_writes(self, src, dest):
# sadly there are some situations where we cannot ensure atomicity, but only if
# the user insists and we get the appropriate error we update the file unsafely
try:
out_dest = in_src = None
try:
out_dest = open(dest, 'wb')
in_src = open(src, 'rb')
shutil.copyfileobj(in_src, out_dest)
finally: # assuring closed files in 2.4 compatible way
if out_dest:
out_dest.close()
if in_src:
in_src.close()
except (shutil.Error, OSError, IOError) as e:
self.fail_json(msg='Could not write data to file (%s) from (%s): %s' % (dest, src, to_native(e)),
exception=traceback.format_exc())
def _read_from_pipes(self, rpipes, rfds, file_descriptor):
data = b('')
if file_descriptor in rfds:
data = os.read(file_descriptor.fileno(), self.get_buffer_size(file_descriptor))
if data == b(''):
rpipes.remove(file_descriptor)
return data
def _clean_args(self, args):
if not self._clean:
# create a printable version of the command for use in reporting later,
# which strips out things like passwords from the args list
to_clean_args = args
if PY2:
if isinstance(args, text_type):
to_clean_args = to_bytes(args)
else:
if isinstance(args, binary_type):
to_clean_args = to_text(args)
if isinstance(args, (text_type, binary_type)):
to_clean_args = shlex.split(to_clean_args)
clean_args = []
is_passwd = False
for arg in (to_native(a) for a in to_clean_args):
if is_passwd:
is_passwd = False
clean_args.append('********')
continue
if PASSWD_ARG_RE.match(arg):
sep_idx = arg.find('=')
if sep_idx > -1:
clean_args.append('%s=********' % arg[:sep_idx])
continue
else:
is_passwd = True
arg = heuristic_log_sanitize(arg, self.no_log_values)
clean_args.append(arg)
self._clean = ' '.join(shlex_quote(arg) for arg in clean_args)
return self._clean
def _restore_signal_handlers(self):
# Reset SIGPIPE to SIG_DFL, otherwise in Python2.7 it gets ignored in subprocesses.
if PY2 and sys.platform != 'win32':
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
def run_command(self, args, check_rc=False, close_fds=True, executable=None, data=None, binary_data=False, path_prefix=None, cwd=None,
use_unsafe_shell=False, prompt_regex=None, environ_update=None, umask=None, encoding='utf-8', errors='surrogate_or_strict',
expand_user_and_vars=True, pass_fds=None, before_communicate_callback=None):
'''
Execute a command, returns rc, stdout, and stderr.
:arg args: is the command to run
* If args is a list, the command will be run with shell=False.
* If args is a string and use_unsafe_shell=False it will split args to a list and run with shell=False
* If args is a string and use_unsafe_shell=True it runs with shell=True.
:kw check_rc: Whether to call fail_json in case of non zero RC.
Default False
:kw close_fds: See documentation for subprocess.Popen(). Default True
:kw executable: See documentation for subprocess.Popen(). Default None
:kw data: If given, information to write to the stdin of the command
:kw binary_data: If False, append a newline to the data. Default False
:kw path_prefix: If given, additional path to find the command in.
This adds to the PATH environment variable so helper commands in
the same directory can also be found
:kw cwd: If given, working directory to run the command inside
:kw use_unsafe_shell: See `args` parameter. Default False
:kw prompt_regex: Regex string (not a compiled regex) which can be
used to detect prompts in the stdout which would otherwise cause
the execution to hang (especially if no input data is specified)
:kw environ_update: dictionary to *update* os.environ with
:kw umask: Umask to be used when running the command. Default None
:kw encoding: Since we return native strings, on python3 we need to
know the encoding to use to transform from bytes to text. If you
want to always get bytes back, use encoding=None. The default is
"utf-8". This does not affect transformation of strings given as
args.
:kw errors: Since we return native strings, on python3 we need to
transform stdout and stderr from bytes to text. If the bytes are
undecodable in the ``encoding`` specified, then use this error
handler to deal with them. The default is ``surrogate_or_strict``
which means that the bytes will be decoded using the
surrogateescape error handler if available (available on all
python3 versions we support) otherwise a UnicodeError traceback
will be raised. This does not affect transformations of strings
given as args.
:kw expand_user_and_vars: When ``use_unsafe_shell=False`` this argument
dictates whether ``~`` is expanded in paths and environment variables
are expanded before running the command. When ``True`` a string such as
``$SHELL`` will be expanded regardless of escaping. When ``False`` and
``use_unsafe_shell=False`` no path or variable expansion will be done.
:kw pass_fds: When running on python3 this argument
dictates which file descriptors should be passed
to an underlying ``Popen`` constructor.
:kw before_communicate_callback: This function will be called
after ``Popen`` object will be created
but before communicating to the process.
(``Popen`` object will be passed to callback as a first argument)
:returns: A 3-tuple of return code (integer), stdout (native string),
and stderr (native string). On python2, stdout and stderr are both
byte strings. On python3, stdout and stderr are text strings converted
according to the encoding and errors parameters. If you want byte
strings on python3, use encoding=None to turn decoding to text off.
'''
# used by clean args later on
self._clean = None
if not isinstance(args, (list, binary_type, text_type)):
msg = "Argument 'args' to run_command must be list or string"
self.fail_json(rc=257, cmd=args, msg=msg)
shell = False
if use_unsafe_shell:
# stringify args for unsafe/direct shell usage
if isinstance(args, list):
args = " ".join([shlex_quote(x) for x in args])
# not set explicitly, check if set by controller
if executable:
args = [executable, '-c', args]
elif self._shell not in (None, '/bin/sh'):
args = [self._shell, '-c', args]
else:
shell = True
else:
# ensure args are a list
if isinstance(args, (binary_type, text_type)):
# On python2.6 and below, shlex has problems with text type
# On python3, shlex needs a text type.
if PY2:
args = to_bytes(args, errors='surrogate_or_strict')
elif PY3:
args = to_text(args, errors='surrogateescape')
args = shlex.split(args)
# expand ``~`` in paths, and all environment vars
if expand_user_and_vars:
args = [os.path.expanduser(os.path.expandvars(x)) for x in args if x is not None]
else:
args = [x for x in args if x is not None]
prompt_re = None
if prompt_regex:
if isinstance(prompt_regex, text_type):
if PY3:
prompt_regex = to_bytes(prompt_regex, errors='surrogateescape')
elif PY2:
prompt_regex = to_bytes(prompt_regex, errors='surrogate_or_strict')
try:
prompt_re = re.compile(prompt_regex, re.MULTILINE)
except re.error:
self.fail_json(msg="invalid prompt regular expression given to run_command")
rc = 0
msg = None
st_in = None
# Manipulate the environ we'll send to the new process
old_env_vals = {}
# We can set this from both an attribute and per call
for key, val in self.run_command_environ_update.items():
old_env_vals[key] = os.environ.get(key, None)
os.environ[key] = val
if environ_update:
for key, val in environ_update.items():
old_env_vals[key] = os.environ.get(key, None)
os.environ[key] = val
if path_prefix:
old_env_vals['PATH'] = os.environ['PATH']
os.environ['PATH'] = "%s:%s" % (path_prefix, os.environ['PATH'])
# If using test-module and explode, the remote lib path will resemble ...
# /tmp/test_module_scratch/debug_dir/ansible/module_utils/basic.py
# If using ansible or ansible-playbook with a remote system ...
# /tmp/ansible_vmweLQ/ansible_modlib.zip/ansible/module_utils/basic.py
# Clean out python paths set by ansiballz
if 'PYTHONPATH' in os.environ:
pypaths = os.environ['PYTHONPATH'].split(':')
pypaths = [x for x in pypaths
if not x.endswith('/ansible_modlib.zip') and
not x.endswith('/debug_dir')]
os.environ['PYTHONPATH'] = ':'.join(pypaths)
if not os.environ['PYTHONPATH']:
del os.environ['PYTHONPATH']
if data:
st_in = subprocess.PIPE
kwargs = dict(
executable=executable,
shell=shell,
close_fds=close_fds,
stdin=st_in,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
preexec_fn=self._restore_signal_handlers,
)
if PY3 and pass_fds:
kwargs["pass_fds"] = pass_fds
# store the pwd
prev_dir = os.getcwd()
# make sure we're in the right working directory
if cwd and os.path.isdir(cwd):
cwd = os.path.abspath(os.path.expanduser(cwd))
kwargs['cwd'] = cwd
try:
os.chdir(cwd)
except (OSError, IOError) as e:
self.fail_json(rc=e.errno, msg="Could not open %s, %s" % (cwd, to_native(e)),
exception=traceback.format_exc())
old_umask = None
if umask:
old_umask = os.umask(umask)
try:
if self._debug:
self.log('Executing: ' + self._clean_args(args))
cmd = subprocess.Popen(args, **kwargs)
if before_communicate_callback:
before_communicate_callback(cmd)
# the communication logic here is essentially taken from that
# of the _communicate() function in ssh.py
stdout = b('')
stderr = b('')
rpipes = [cmd.stdout, cmd.stderr]
if data:
if not binary_data:
data += '\n'
if isinstance(data, text_type):
data = to_bytes(data)
cmd.stdin.write(data)
cmd.stdin.close()
while True:
rfds, wfds, efds = select.select(rpipes, [], rpipes, 1)
stdout += self._read_from_pipes(rpipes, rfds, cmd.stdout)
stderr += self._read_from_pipes(rpipes, rfds, cmd.stderr)
# if we're checking for prompts, do it now
if prompt_re:
if prompt_re.search(stdout) and not data:
if encoding:
stdout = to_native(stdout, encoding=encoding, errors=errors)
return (257, stdout, "A prompt was encountered while running a command, but no input data was specified")
# only break out if no pipes are left to read or
# the pipes are completely read and
# the process is terminated
if (not rpipes or not rfds) and cmd.poll() is not None:
break
# No pipes are left to read but process is not yet terminated
# Only then it is safe to wait for the process to be finished
# NOTE: Actually cmd.poll() is always None here if rpipes is empty
elif not rpipes and cmd.poll() is None:
cmd.wait()
# The process is terminated. Since no pipes to read from are
# left, there is no need to call select() again.
break
cmd.stdout.close()
cmd.stderr.close()
rc = cmd.returncode
except (OSError, IOError) as e:
self.log("Error Executing CMD:%s Exception:%s" % (self._clean_args(args), to_native(e)))
self.fail_json(rc=e.errno, msg=to_native(e), cmd=self._clean_args(args))
except Exception as e:
self.log("Error Executing CMD:%s Exception:%s" % (self._clean_args(args), to_native(traceback.format_exc())))
self.fail_json(rc=257, msg=to_native(e), exception=traceback.format_exc(), cmd=self._clean_args(args))
# Restore env settings
for key, val in old_env_vals.items():
if val is None:
del os.environ[key]
else:
os.environ[key] = val
if old_umask:
os.umask(old_umask)
if rc != 0 and check_rc:
msg = heuristic_log_sanitize(stderr.rstrip(), self.no_log_values)
self.fail_json(cmd=self._clean_args(args), rc=rc, stdout=stdout, stderr=stderr, msg=msg)
# reset the pwd
os.chdir(prev_dir)
if encoding is not None:
return (rc, to_native(stdout, encoding=encoding, errors=errors),
to_native(stderr, encoding=encoding, errors=errors))
return (rc, stdout, stderr)
def append_to_file(self, filename, str):
filename = os.path.expandvars(os.path.expanduser(filename))
fh = open(filename, 'a')
fh.write(str)
fh.close()
def bytes_to_human(self, size):
return bytes_to_human(size)
# for backwards compatibility
pretty_bytes = bytes_to_human
def human_to_bytes(self, number, isbits=False):
return human_to_bytes(number, isbits)
#
# Backwards compat
#
# In 2.0, moved from inside the module to the toplevel
is_executable = is_executable
@staticmethod
def get_buffer_size(fd):
try:
# 1032 == FZ_GETPIPE_SZ
buffer_size = fcntl.fcntl(fd, 1032)
except Exception:
try:
# not as exact as above, but should be good enough for most platforms that fail the previous call
buffer_size = select.PIPE_BUF
except Exception:
buffer_size = 9000 # use sane default JIC
return buffer_size
def get_module_path():
return os.path.dirname(os.path.realpath(__file__))
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,691 |
win_get_url doesn't use the proxy even if proxy_url is specified
|
##### SUMMARY
`win_get_url` doesn't use the proxy even if `proxy_url` is specified. Therefore, if I execute a `win_get_url` task under a proxy restricted network, it fails with 407 error (Proxy Authentication Required).
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
win_get_url
##### ANSIBLE VERSION
```console
$ ansible --version
ansible 2.8.1
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/user/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.15+ (default, Nov 27 2018, 23:36:35) [GCC 7.3.0]
```
##### CONFIGURATION
```console
$ ansible-config dump --only-changed
ANSIBLE_NOCOWS(/mnt/c/Users/user/tmp/ansible-bug/ansible.cfg) = True
INJECT_FACTS_AS_VARS(/mnt/c/Users/user/tmp/ansible-bug/ansible.cfg) = False
RETRY_FILES_ENABLED(/mnt/c/Users/user/tmp/ansible-bug/ansible.cfg) = False
```
##### OS / ENVIRONMENT
Control machine is Ubuntu 18.04 on WSL.
```console
$ cat /etc/os-release
NAME="Ubuntu"
VERSION="18.04.2 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.2 LTS"
VERSION_ID="18.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=bionic
UBUNTU_CODENAME=bionic
```
Installed pip libraries
```console
$ pip list --format=columns
Package Version
------------- ---------
ansible 2.8.1
asn1crypto 0.24.0
certifi 2019.6.16
chardet 3.0.4
cryptography 2.1.4
enum34 1.1.6
gyp 0.1
httplib2 0.9.2
idna 2.6
ipaddress 1.0.17
Jinja2 2.10
keyring 10.6.0
keyrings.alt 3.0
MarkupSafe 1.0
ntlm-auth 1.3.0
paramiko 2.0.0
pip 9.0.1
pyasn1 0.4.2
pycrypto 2.6.1
pygobject 3.26.1
python-apt 1.6.4
pywinrm 0.3.0
pyxdg 0.25
PyYAML 3.12
requests 2.22.0
requests-ntlm 1.1.0
SecretStorage 2.3.1
setuptools 39.0.1
six 1.11.0
urllib3 1.25.3
wheel 0.30.0
xmltodict 0.12.0
```
Target machine is Windows 10.
- Edition: Windows 10 Pro
- Version: 1809
- Installation Date: 2019/02/07
- OS Build: 17763.379
##### STEPS TO REPRODUCE
Inventory file (`hosts`) is as below.
```ini
[windows10]
localhost
[windows10:vars]
ansible_port=5986
ansible_connection=winrm
ansible_winrm_server_cert_validation=ignore
ansible_user=domain\user
ansible_password=********
ansible_winrm_transport=ntlm
```
Playbook (`test.yml`) is as below.
```yaml
- hosts: windows10
gather_facts: no
tasks:
- name: Download file via proxy
win_get_url:
url: https://github.com/ansible/ansible/archive/v2.8.1.zip
dest: "%TEMP%"
proxy_url: http://proxy.example.com:8080
proxy_username: proxyuser
proxy_password: ********
```
I applied a playbook like this, it fails with 407 error.
```console
$ ansible-playbook -vvv -i hosts test.yml
ansible-playbook 2.8.1
config file = /mnt/c/Users/user/tmp/ansible-bug/ansible.cfg
configured module search path = [u'/home/user/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible-playbook
python version = 2.7.15+ (default, Nov 27 2018, 23:36:35) [GCC 7.3.0]
Using /mnt/c/Users/user/tmp/ansible-bug/ansible.cfg as config file
host_list declined parsing /mnt/c/Users/user/tmp/ansible-bug/hosts as it did not pass it's verify_file() method
script declined parsing /mnt/c/Users/user/tmp/ansible-bug/hosts as it did not pass it's verify_file() method
auto declined parsing /mnt/c/Users/user/tmp/ansible-bug/hosts as it did not pass it's verify_file() method
Parsed /mnt/c/Users/user/tmp/ansible-bug/hosts inventory source with ini plugin
PLAYBOOK: test.yml ************************************************************************************************************************************************************************************************
1 plays in test.yml
PLAY [windows10] **************************************************************************************************************************************************************************************************
META: ran handlers
TASK [Download file via proxy] ************************************************************************************************************************************************************************************
task path: /mnt/c/Users/user/tmp/ansible-bug/test.yml:4
Using module file /usr/lib/python2.7/dist-packages/ansible/modules/windows/win_get_url.ps1
Pipelining is enabled.
<localhost> ESTABLISH WINRM CONNECTION FOR USER: domain\user on PORT 5986 TO localhost
EXEC (via pipeline wrapper)
The full traceback is:
The remote server returned an error: (407) Proxy Authentication Required.
At line:107 char:9
+ $web_response = $web_request.GetResponse()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], WebException
+ FullyQualifiedErrorId : WebException
ScriptStackTrace:
at Invoke-AnsibleWebRequest, <No file>: line 107
at Invoke-DownloadFile, <No file>: line 311
at <ScriptBlock>, <No file>: line 406
fatal: [localhost]: FAILED! => {
"changed": false,
"dest": "C:\\Users\\user\\AppData\\Local\\Temp\\v2.8.1.zip",
"elapsed": 0,
"invocation": {
"module_args": {
"checksum": null,
"checksum_algorithm": "sha1",
"checksum_url": null,
"dest": "C:\\Users\\user\\AppData\\Local\\Temp",
"force": true,
"force_basic_auth": false,
"headers": {},
"proxy_password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"proxy_url": "http://proxy.example.com:8080",
"proxy_username": "proxyuser",
"timeout": 10,
"url": "https://github.com/ansible/ansible/archive/v2.8.1.zip",
"url_password": null,
"url_username": null,
"use_proxy": true,
"validate_certs": true
}
},
"msg": "Error requesting 'https://github.com/ansible/ansible/archive/v2.8.1.zip'. The remote server returned an error: (407) Proxy Authentication Required.",
"status_code": 407,
"url": "https://github.com/ansible/ansible/archive/v2.8.1.zip"
}
PLAY RECAP ********************************************************************************************************************************************************************************************************
localhost : ok=0 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
```
##### EXPECTED RESULTS
`win_get_url` uses a proxy configuration and download a file successfully.
##### ACTUAL RESULTS
`win_get_url` doesn't use a proxy configuration and fails with 407 error.
|
https://github.com/ansible/ansible/issues/58691
|
https://github.com/ansible/ansible/pull/58738
|
60fb9fc208adebdc10c8a0f5ff1b3d61f8d6516d
|
48a518d9a32aec2be834e88084e36a9924403115
| 2019-07-03T22:35:39Z |
python
| 2019-07-04T21:42:05Z |
changelogs/fragments/win_get_url-proxy-not-used.yml
| |
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,691 |
win_get_url doesn't use the proxy even if proxy_url is specified
|
##### SUMMARY
`win_get_url` doesn't use the proxy even if `proxy_url` is specified. Therefore, if I execute a `win_get_url` task under a proxy restricted network, it fails with 407 error (Proxy Authentication Required).
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
win_get_url
##### ANSIBLE VERSION
```console
$ ansible --version
ansible 2.8.1
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/user/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.15+ (default, Nov 27 2018, 23:36:35) [GCC 7.3.0]
```
##### CONFIGURATION
```console
$ ansible-config dump --only-changed
ANSIBLE_NOCOWS(/mnt/c/Users/user/tmp/ansible-bug/ansible.cfg) = True
INJECT_FACTS_AS_VARS(/mnt/c/Users/user/tmp/ansible-bug/ansible.cfg) = False
RETRY_FILES_ENABLED(/mnt/c/Users/user/tmp/ansible-bug/ansible.cfg) = False
```
##### OS / ENVIRONMENT
Control machine is Ubuntu 18.04 on WSL.
```console
$ cat /etc/os-release
NAME="Ubuntu"
VERSION="18.04.2 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.2 LTS"
VERSION_ID="18.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=bionic
UBUNTU_CODENAME=bionic
```
Installed pip libraries
```console
$ pip list --format=columns
Package Version
------------- ---------
ansible 2.8.1
asn1crypto 0.24.0
certifi 2019.6.16
chardet 3.0.4
cryptography 2.1.4
enum34 1.1.6
gyp 0.1
httplib2 0.9.2
idna 2.6
ipaddress 1.0.17
Jinja2 2.10
keyring 10.6.0
keyrings.alt 3.0
MarkupSafe 1.0
ntlm-auth 1.3.0
paramiko 2.0.0
pip 9.0.1
pyasn1 0.4.2
pycrypto 2.6.1
pygobject 3.26.1
python-apt 1.6.4
pywinrm 0.3.0
pyxdg 0.25
PyYAML 3.12
requests 2.22.0
requests-ntlm 1.1.0
SecretStorage 2.3.1
setuptools 39.0.1
six 1.11.0
urllib3 1.25.3
wheel 0.30.0
xmltodict 0.12.0
```
Target machine is Windows 10.
- Edition: Windows 10 Pro
- Version: 1809
- Installation Date: 2019/02/07
- OS Build: 17763.379
##### STEPS TO REPRODUCE
Inventory file (`hosts`) is as below.
```ini
[windows10]
localhost
[windows10:vars]
ansible_port=5986
ansible_connection=winrm
ansible_winrm_server_cert_validation=ignore
ansible_user=domain\user
ansible_password=********
ansible_winrm_transport=ntlm
```
Playbook (`test.yml`) is as below.
```yaml
- hosts: windows10
gather_facts: no
tasks:
- name: Download file via proxy
win_get_url:
url: https://github.com/ansible/ansible/archive/v2.8.1.zip
dest: "%TEMP%"
proxy_url: http://proxy.example.com:8080
proxy_username: proxyuser
proxy_password: ********
```
I applied a playbook like this, it fails with 407 error.
```console
$ ansible-playbook -vvv -i hosts test.yml
ansible-playbook 2.8.1
config file = /mnt/c/Users/user/tmp/ansible-bug/ansible.cfg
configured module search path = [u'/home/user/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible-playbook
python version = 2.7.15+ (default, Nov 27 2018, 23:36:35) [GCC 7.3.0]
Using /mnt/c/Users/user/tmp/ansible-bug/ansible.cfg as config file
host_list declined parsing /mnt/c/Users/user/tmp/ansible-bug/hosts as it did not pass it's verify_file() method
script declined parsing /mnt/c/Users/user/tmp/ansible-bug/hosts as it did not pass it's verify_file() method
auto declined parsing /mnt/c/Users/user/tmp/ansible-bug/hosts as it did not pass it's verify_file() method
Parsed /mnt/c/Users/user/tmp/ansible-bug/hosts inventory source with ini plugin
PLAYBOOK: test.yml ************************************************************************************************************************************************************************************************
1 plays in test.yml
PLAY [windows10] **************************************************************************************************************************************************************************************************
META: ran handlers
TASK [Download file via proxy] ************************************************************************************************************************************************************************************
task path: /mnt/c/Users/user/tmp/ansible-bug/test.yml:4
Using module file /usr/lib/python2.7/dist-packages/ansible/modules/windows/win_get_url.ps1
Pipelining is enabled.
<localhost> ESTABLISH WINRM CONNECTION FOR USER: domain\user on PORT 5986 TO localhost
EXEC (via pipeline wrapper)
The full traceback is:
The remote server returned an error: (407) Proxy Authentication Required.
At line:107 char:9
+ $web_response = $web_request.GetResponse()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], WebException
+ FullyQualifiedErrorId : WebException
ScriptStackTrace:
at Invoke-AnsibleWebRequest, <No file>: line 107
at Invoke-DownloadFile, <No file>: line 311
at <ScriptBlock>, <No file>: line 406
fatal: [localhost]: FAILED! => {
"changed": false,
"dest": "C:\\Users\\user\\AppData\\Local\\Temp\\v2.8.1.zip",
"elapsed": 0,
"invocation": {
"module_args": {
"checksum": null,
"checksum_algorithm": "sha1",
"checksum_url": null,
"dest": "C:\\Users\\user\\AppData\\Local\\Temp",
"force": true,
"force_basic_auth": false,
"headers": {},
"proxy_password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"proxy_url": "http://proxy.example.com:8080",
"proxy_username": "proxyuser",
"timeout": 10,
"url": "https://github.com/ansible/ansible/archive/v2.8.1.zip",
"url_password": null,
"url_username": null,
"use_proxy": true,
"validate_certs": true
}
},
"msg": "Error requesting 'https://github.com/ansible/ansible/archive/v2.8.1.zip'. The remote server returned an error: (407) Proxy Authentication Required.",
"status_code": 407,
"url": "https://github.com/ansible/ansible/archive/v2.8.1.zip"
}
PLAY RECAP ********************************************************************************************************************************************************************************************************
localhost : ok=0 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
```
##### EXPECTED RESULTS
`win_get_url` uses a proxy configuration and download a file successfully.
##### ACTUAL RESULTS
`win_get_url` doesn't use a proxy configuration and fails with 407 error.
|
https://github.com/ansible/ansible/issues/58691
|
https://github.com/ansible/ansible/pull/58738
|
60fb9fc208adebdc10c8a0f5ff1b3d61f8d6516d
|
48a518d9a32aec2be834e88084e36a9924403115
| 2019-07-03T22:35:39Z |
python
| 2019-07-04T21:42:05Z |
lib/ansible/modules/windows/win_get_url.ps1
|
#!powershell
# Copyright: (c) 2015, Paul Durivage <[email protected]>
# Copyright: (c) 2015, Tal Auslander <[email protected]>
# Copyright: (c) 2017, Dag Wieers <[email protected]>
# Copyright: (c) 2019, Viktor Utkin <[email protected]>
# Copyright: (c) 2019, Uladzimir Klybik <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#AnsibleRequires -CSharpUtil Ansible.Basic
#Requires -Module Ansible.ModuleUtils.AddType
#Requires -Module Ansible.ModuleUtils.FileUtil
$spec = @{
options = @{
url = @{ type='str'; required=$true }
dest = @{ type='path'; required=$true }
timeout = @{ type='int'; default=10 }
headers = @{ type='dict'; default=@{} }
validate_certs = @{ type='bool'; default=$true }
url_username = @{ type='str'; aliases=@( 'username' ) }
url_password = @{ type='str'; aliases=@( 'password' ); no_log=$true }
force_basic_auth = @{ type='bool'; default=$false }
use_proxy = @{ type='bool'; default=$true }
proxy_url = @{ type='str' }
proxy_username = @{ type='str' }
proxy_password = @{ type='str'; no_log=$true }
force = @{ type='bool'; default=$true }
checksum = @{ type='str' }
checksum_algorithm = @{ type='str'; default='sha1'; choices = @("md5", "sha1", "sha256", "sha384", "sha512") }
checksum_url = @{ type='str' }
}
mutually_exclusive = @(
,@('checksum', 'checksum_url')
)
supports_check_mode = $true
}
$module = [Ansible.Basic.AnsibleModule]::Create($args, $spec)
$url = $module.Params.url
$dest = $module.Params.dest
$timeout = $module.Params.timeout
$headers = $module.Params.headers
$validate_certs = $module.Params.validate_certs
$url_username = $module.Params.url_username
$url_password = $module.Params.url_password
$force_basic_auth = $module.Params.force_basic_auth
$use_proxy = $module.Params.use_proxy
$proxy_url = $module.Params.proxy_url
$proxy_username = $module.Params.proxy_username
$proxy_password = $module.Params.proxy_password
$force = $module.Params.force
$checksum = $module.Params.checksum
$checksum_algorithm = $module.Params.checksum_algorithm
$checksum_url = $module.Params.checksum_url
$module.Result.elapsed = 0
$module.Result.url = $url
Function Invoke-AnsibleWebRequest {
<#
.SYNOPSIS
Creates a WebRequest and invokes a ScriptBlock with the response passed in.
It handles the common module options like credential, timeout, proxy options
in a single location to reduce code duplication.
#>
param(
[Parameter(Mandatory=$true)][Ansible.Basic.AnsibleModule]$Module,
[Parameter(Mandatory=$true)][Uri]$Uri,
[Parameter(Mandatory=$true)][Hashtable]$Method,
[Parameter(Mandatory=$true)][ScriptBlock]$Script, # Invoked in this cmdlet
[System.Collections.IDictionary]$Headers,
[Int32]$Timeout,
[Switch]$UseProxy,
[System.Net.WebProxy]$Proxy,
$Credential # Either a String (force_basic_auth) or NetCredentials
)
$web_request = [System.Net.WebRequest]::Create($Uri)
$web_request.Method = $Method.($web_request.GetType().Name)
foreach ($header in $headers.GetEnumerator()) {
# some headers need to be set on the property itself
switch ($header.Key) {
Accept { $web_request.Accept = $header.Value }
Connection { $web_request.Connection = $header.Value }
Content-Length { $web_request.ContentLength = $header.Value }
Content-Type { $web_request.ContentType = $header.Value }
Expect { $web_request.Expect = $header.Value }
Date { $web_request.Date = $header.Value }
Host { $web_request.Host = $header.Value }
If-Modified-Since { $web_request.IfModifiedSince = $header.Value }
Range { $web_request.AddRange($header.Value) }
Referer { $web_request.Referer = $header.Value }
Transfer-Encoding {
$web_request.SendChunked = $true
$web_request.TransferEncoding = $header.Value
}
User-Agent { $web_request.UserAgent = $header.Value }
default { $web_request.Headers.Add($header.Key, $header.Value) }
}
}
if ($timeout) {
$web_request.Timeout = $timeout * 1000
}
if (-not $UseProxy) {
$web_request.Proxy = $null
} elseif ($ProxyUri) {
$web_request.Proxy = $Proxy
}
if ($Credential) {
if ($Credential -is [String]) {
# force_basic_auth=yes is set
$web_request.Headers.Add("Authorization", "Basic $Credential")
} else {
$web_request.Credentials = $Credential
}
}
try {
$web_response = $web_request.GetResponse()
$response_stream = $web_response.GetResponseStream()
try {
# Invoke the ScriptBlock and pass in the WebResponse and ResponseStream
&$Script -Response $web_response -Stream $response_stream
} finally {
$response_stream.Dispose()
}
if ($Uri.IsFile) {
# A FileWebResponse won't have these properties set
$module.Result.msg = "OK"
$module.Result.status_code = 200
} else {
$module.Result.msg = [string]$web_response.StatusDescription
$module.Result.status_code = [int]$web_response.StatusCode
}
} catch [System.Net.WebException] {
$module.Result.status_code = [int]$_.Exception.Response.StatusCode
$module.FailJson("Error requesting '$Uri'. $($_.Exception.Message)", $_)
} finally {
if ($web_response) {
$web_response.Close()
}
}
}
Function Get-ChecksumFromUri {
param(
[Parameter(Mandatory=$true)][Ansible.Basic.AnsibleModule]$Module,
[Parameter(Mandatory=$true)][Uri]$Uri,
[Uri]$SourceUri,
[Hashtable]$RequestParams
)
$script = {
param($Response, $Stream)
$read_stream = New-Object -TypeName System.IO.StreamReader -ArgumentList $Stream
$web_checksum = $read_stream.ReadToEnd()
$basename = (Split-Path -Path $SourceUri.LocalPath -Leaf)
$basename = [regex]::Escape($basename)
$web_checksum_str = $web_checksum -split '\r?\n' | Select-String -Pattern $("\s+\.?\/?\\?" + $basename + "\s*$")
if (-not $web_checksum_str) {
$Module.FailJson("Checksum record not found for file name '$basename' in file from url: '$Uri'")
}
$web_checksum_str_splitted = $web_checksum_str[0].ToString().split(" ", 2)
$hash_from_file = $web_checksum_str_splitted[0].Trim()
# Remove any non-alphanumeric characters
$hash_from_file = $hash_from_file -replace '\W+', ''
Write-Output -InputObject $hash_from_file
}
$invoke_args = @{
Module = $Module
Uri = $Uri
Method = @{
FileWebRequest = [System.Net.WebRequestMethods+File]::DownloadFile
FtpWebRequest = [System.Net.WebRequestMethods+Ftp]::DownloadFile
HttpWebRequest = [System.Net.WebRequestMethods+Http]::Get
}
Script = $script
}
try {
Invoke-AnsibleWebRequest @invoke_args @RequestParams
} catch {
$Module.FailJson("Error when getting the remote checksum from '$Uri'. $($_.Exception.Message)", $_)
}
}
Function Compare-ModifiedFile {
<#
.SYNOPSIS
Compares the remote URI resource against the local Dest resource. Will
return true if the LastWriteTime/LastModificationDate of the remote is
newer than the local resource date.
#>
param(
[Parameter(Mandatory=$true)][Ansible.Basic.AnsibleModule]$Module,
[Parameter(Mandatory=$true)][Uri]$Uri,
[Parameter(Mandatory=$true)][String]$Dest,
[Hashtable]$RequestParams
)
$dest_last_mod = (Get-AnsibleItem -Path $Dest).LastWriteTimeUtc
# If the URI is a file we don't need to go through the whole WebRequest
if ($Uri.IsFile) {
$src_last_mod = (Get-AnsibleItem -Path $Uri.AbsolutePath).LastWriteTimeUtc
} else {
$invoke_args = @{
Module = $Module
Uri = $Uri
Method = @{
FtpWebRequest = [System.Net.WebRequestMethods+Ftp]::GetDateTimestamp
HttpWebRequest = [System.Net.WebRequestMethods+Http]::Head
}
Script = { param($Response, $Stream); $Response.LastModified }
}
try {
$src_last_mod = Invoke-AnsibleWebRequest @invoke_args @RequestParams
} catch {
$Module.FailJson("Error when requesting 'Last-Modified' date from '$Uri'. $($_.Exception.Message)", $_)
}
}
# Return $true if the Uri LastModification date is newer than the Dest LastModification date
((Get-Date -Date $src_last_mod).ToUniversalTime() -gt $dest_last_mod)
}
Function Get-Checksum {
param(
[Parameter(Mandatory=$true)][String]$Path,
[String]$Algorithm = "sha1"
)
switch ($Algorithm) {
'md5' { $sp = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider }
'sha1' { $sp = New-Object -TypeName System.Security.Cryptography.SHA1CryptoServiceProvider }
'sha256' { $sp = New-Object -TypeName System.Security.Cryptography.SHA256CryptoServiceProvider }
'sha384' { $sp = New-Object -TypeName System.Security.Cryptography.SHA384CryptoServiceProvider }
'sha512' { $sp = New-Object -TypeName System.Security.Cryptography.SHA512CryptoServiceProvider }
}
$fs = [System.IO.File]::Open($Path, [System.IO.Filemode]::Open, [System.IO.FileAccess]::Read,
[System.IO.FileShare]::ReadWrite)
try {
$hash = [System.BitConverter]::ToString($sp.ComputeHash($fs)).Replace("-", "").ToLower()
} finally {
$fs.Dispose()
}
return $hash
}
Function Invoke-DownloadFile {
param(
[Parameter(Mandatory=$true)][Ansible.Basic.AnsibleModule]$Module,
[Parameter(Mandatory=$true)][Uri]$Uri,
[Parameter(Mandatory=$true)][String]$Dest,
[String]$Checksum,
[String]$ChecksumAlgorithm,
[Hashtable]$RequestParams
)
# Check $dest parent folder exists before attempting download, which avoids unhelpful generic error message.
$dest_parent = Split-Path -LiteralPath $Dest
if (-not (Test-Path -LiteralPath $dest_parent -PathType Container)) {
$module.FailJson("The path '$dest_parent' does not exist for destination '$Dest', or is not visible to the current user. Ensure download destination folder exists (perhaps using win_file state=directory) before win_get_url runs.")
}
$download_script = {
param($Response, $Stream)
# Download the file to a temporary directory so we can compare it
$tmp_dest = Join-Path -Path $Module.Tmpdir -ChildPath ([System.IO.Path]::GetRandomFileName())
$fs = [System.IO.File]::Create($tmp_dest)
try {
$Stream.CopyTo($fs)
$fs.Flush()
} finally {
$fs.Dispose()
}
$tmp_checksum = Get-Checksum -Path $tmp_dest -Algorithm $ChecksumAlgorithm
$Module.Result.checksum_src = $tmp_checksum
# If the checksum has been set, verify the checksum of the remote against the input checksum.
if ($Checksum -and $Checksum -ne $tmp_checksum) {
$Module.FailJson(("The checksum for {0} did not match '{1}', it was '{2}'" -f $Uri, $Checksum, $tmp_checksum))
}
$download = $true
if (Test-Path -LiteralPath $Dest) {
# Validate the remote checksum against the existing downloaded file
$dest_checksum = Get-Checksum -Path $Dest -Algorithm $ChecksumAlgorithm
# If we don't need to download anything, save the dest checksum so we don't waste time calculating it
# again at the end of the script
if ($dest_checksum -eq $tmp_checksum) {
$download = $false
$Module.Result.checksum_dest = $dest_checksum
$Module.Result.size = (Get-AnsibleItem -Path $Dest).Length
}
}
if ($download) {
Copy-Item -LiteralPath $tmp_dest -Destination $Dest -Force -WhatIf:$Module.CheckMode > $null
$Module.Result.changed = $true
}
}
$invoke_args = @{
Module = $Module
Uri = $Uri
Method = @{
FileWebRequest = [System.Net.WebRequestMethods+File]::DownloadFile
FtpWebRequest = [System.Net.WebRequestMethods+Ftp]::DownloadFile
HttpWebRequest = [System.Net.WebRequestMethods+Http]::Get
}
Script = $download_script
}
$module_start = Get-Date
try {
Invoke-AnsibleWebRequest @invoke_args @RequestParams
} catch {
$Module.FailJson("Unknown error downloading '$Uri' to '$Dest': $($_.Exception.Message)", $_)
} finally {
$Module.Result.elapsed = ((Get-Date) - $module_start).TotalSeconds
}
}
if (-not $use_proxy -and ($proxy_url -or $proxy_username -or $proxy_password)) {
$module.Warn("Not using a proxy on request, however a 'proxy_url', 'proxy_username' or 'proxy_password' was defined.")
}
$proxy = $null
if ($proxy_url) {
$proxy = New-Object System.Net.WebProxy($proxy_url, $true)
if ($proxy_username -and $proxy_password) {
$proxy_credential = New-Object System.Net.NetworkCredential($proxy_username, $proxy_password)
$proxy.Credentials = $proxy_credential
}
}
$credentials = $null
if ($url_username) {
if ($force_basic_auth) {
$credentials = [convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($url_username+":"+$url_password))
} else {
$credentials = New-Object System.Net.NetworkCredential($url_username, $url_password)
}
}
if (-not $validate_certs) {
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
}
# Use last part of url for dest file name if a directory is supplied for $dest
if (Test-Path -LiteralPath $dest -PathType Container) {
$uri = [System.Uri]$url
$basename = Split-Path -Path $uri.LocalPath -Leaf
if ($uri.LocalPath -and $uri.LocalPath -ne '/' -and $basename) {
$url_basename = Split-Path -Path $uri.LocalPath -Leaf
$dest = Join-Path -Path $dest -ChildPath $url_basename
} else {
$dest = Join-Path -Path $dest -ChildPath $uri.Host
}
# Ensure we have a string instead of a PS object to avoid serialization issues
$dest = $dest.ToString()
} elseif (([System.IO.Path]::GetFileName($dest)) -eq '') {
# We have a trailing path separator
$module.FailJson("The destination path '$dest' does not exist, or is not visible to the current user. Ensure download destination folder exists (perhaps using win_file state=directory) before win_get_url runs.")
}
$module.Result.dest = $dest
# Enable TLS1.1/TLS1.2 if they're available but disabled (eg. .NET 4.5)
$security_protocols = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::SystemDefault
if ([Net.SecurityProtocolType].GetMember("Tls11").Count -gt 0) {
$security_protocols = $security_protocols -bor [Net.SecurityProtocolType]::Tls11
}
if ([Net.SecurityProtocolType].GetMember("Tls12").Count -gt 0) {
$security_protocols = $security_protocols -bor [Net.SecurityProtocolType]::Tls12
}
[Net.ServicePointManager]::SecurityProtocol = $security_protocols
$request_params = @{
Credential = $credentials
Headers = $headers
Timeout = $timeout
UseProxy = $use_proxy
Proxy = $proxy
}
if ($checksum) {
$checksum = $checksum.Trim().ToLower()
}
if ($checksum_algorithm) {
$checksum_algorithm = $checksum_algorithm.Trim().ToLower()
}
if ($checksum_url) {
$checksum_url = $checksum_url.Trim()
}
# Check for case $checksum variable contain url. If yes, get file data from url and replace original value in $checksum
if ($checksum_url) {
$checksum_uri = [System.Uri]$checksum_url
if ($checksum_uri.Scheme -notin @("file", "ftp", "http", "https")) {
$module.FailJson("Unsupported 'checksum_url' value for '$dest': '$checksum_url'")
}
$checksum = Get-ChecksumFromUri -Module $Module -Uri $checksum_uri -SourceUri $url -RequestParams $request_params
}
if ($force -or -not (Test-Path -LiteralPath $dest)) {
# force=yes or dest does not exist, download the file
# Note: Invoke-DownloadFile will compare the checksums internally if dest exists
Invoke-DownloadFile -Module $module -Uri $url -Dest $dest -Checksum $checksum `
-ChecksumAlgorithm $checksum_algorithm -RequestParams $request_params
} else {
# force=no, we want to check the last modified dates and only download if they don't match
$is_modified = Compare-ModifiedFile -Module $module -Uri $url -Dest $dest -RequestParams $request_params
if ($is_modified) {
Invoke-DownloadFile -Module $module -Uri $url -Dest $dest -Checksum $checksum `
-ChecksumAlgorithm $checksum_algorithm -RequestParams $request_params
}
}
if ((-not $module.Result.ContainsKey("checksum_dest")) -and (Test-Path -LiteralPath $dest)) {
# Calculate the dest file checksum if it hasn't already been done
$module.Result.checksum_dest = Get-Checksum -Path $dest -Algorithm $checksum_algorithm
$module.Result.size = (Get-AnsibleItem -Path $dest).Length
}
$module.ExitJson()
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,493 |
cron does not allow to remove a cron_file without user anymore
|
##### SUMMARY
Removing a cron_file is no longer possible since 2.8 without specifying the user parameter.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
cron
##### ANSIBLE VERSION
```paste below
ansible 2.8.1
config file = /home/duck/OSPO/community-cage-infra-ansible/ansible.cfg
configured module search path = ['/home/duck/OSPO/community-cage-infra-ansible/library']
ansible python module location = /home/duck/.local/lib/python3.7/site-packages/ansible
executable location = /home/duck/.local/bin/ansible
python version = 3.7.3 (default, Apr 3 2019, 05:39:12) [GCC 8.3.0]
```
##### CONFIGURATION
```paste below
ANSIBLE_FORCE_COLOR(env: ANSIBLE_FORCE_COLOR) = True
ANSIBLE_PIPELINING(/home/duck/OSPO/community-cage-infra-ansible/ansible.cfg) = True
ANSIBLE_SSH_ARGS(/home/duck/OSPO/community-cage-infra-ansible/ansible.cfg) = -o ControlMaster=auto -o ControlPersist=30m
CACHE_PLUGIN(/home/duck/OSPO/community-cage-infra-ansible/ansible.cfg) = jsonfile
CACHE_PLUGIN_CONNECTION(/home/duck/OSPO/community-cage-infra-ansible/ansible.cfg) = ./facts_cache
CACHE_PLUGIN_TIMEOUT(/home/duck/OSPO/community-cage-infra-ansible/ansible.cfg) = 86400
DEFAULT_ACTION_PLUGIN_PATH(/home/duck/OSPO/community-cage-infra-ansible/ansible.cfg) = ['/home/duck/OSPO/community-cage-infra-ansible/plugins/actio
DEFAULT_CALLBACK_PLUGIN_PATH(/home/duck/OSPO/community-cage-infra-ansible/ansible.cfg) = ['/home/duck/OSPO/community-cage-infra-ansible/plugins/cal
DEFAULT_CONNECTION_PLUGIN_PATH(/home/duck/OSPO/community-cage-infra-ansible/ansible.cfg) = ['/home/duck/OSPO/community-cage-infra-ansible/plugins/c
DEFAULT_FILTER_PLUGIN_PATH(/home/duck/OSPO/community-cage-infra-ansible/ansible.cfg) = ['/home/duck/OSPO/community-cage-infra-ansible/plugins/filte
DEFAULT_FORKS(/home/duck/OSPO/community-cage-infra-ansible/ansible.cfg) = 10
DEFAULT_GATHERING(/home/duck/OSPO/community-cage-infra-ansible/ansible.cfg) = smart
DEFAULT_HASH_BEHAVIOUR(/home/duck/OSPO/community-cage-infra-ansible/ansible.cfg) = merge
DEFAULT_HOST_LIST(/home/duck/OSPO/community-cage-infra-ansible/ansible.cfg) = ['/home/duck/OSPO/community-cage-infra-ansible/hosts.yml']
DEFAULT_LOOKUP_PLUGIN_PATH(/home/duck/OSPO/community-cage-infra-ansible/ansible.cfg) = ['/home/duck/OSPO/community-cage-infra-ansible/plugins/looku
DEFAULT_MANAGED_STR(/home/duck/OSPO/community-cage-infra-ansible/ansible.cfg) = Ansible managed
DEFAULT_MODULE_PATH(/home/duck/OSPO/community-cage-infra-ansible/ansible.cfg) = ['/home/duck/OSPO/community-cage-infra-ansible/library']
DEFAULT_ROLES_PATH(/home/duck/OSPO/community-cage-infra-ansible/ansible.cfg) = ['/home/duck/OSPO/community-cage-infra-ansible/roles']
DEFAULT_STRATEGY_PLUGIN_PATH(/home/duck/OSPO/community-cage-infra-ansible/ansible.cfg) = ['/home/duck/OSPO/community-cage-infra-ansible/plugins/str
DEFAULT_TIMEOUT(/home/duck/OSPO/community-cage-infra-ansible/ansible.cfg) = 40
DEFAULT_VARS_PLUGIN_PATH(/home/duck/OSPO/community-cage-infra-ansible/ansible.cfg) = ['/home/duck/OSPO/community-cage-infra-ansible/plugins/vars']
DEFAULT_VAULT_PASSWORD_FILE(env: ANSIBLE_VAULT_PASSWORD_FILE) = /home/duck/.ansible_vault/cage.txt
ERROR_ON_MISSING_HANDLER(/home/duck/OSPO/community-cage-infra-ansible/ansible.cfg) = True
PARAMIKO_HOST_KEY_AUTO_ADD(/home/duck/OSPO/community-cage-infra-ansible/ansible.cfg) = True
PERSISTENT_CONNECT_TIMEOUT(/home/duck/OSPO/community-cage-infra-ansible/ansible.cfg) = 1800
```
##### OS / ENVIRONMENT
Ansible runs on Debian unstable and the node is using Debian Stretch.
##### STEPS TO REPRODUCE
The following worked before 2.8 and now fails.
```yaml
- name: remove useless backup cron
cron:
cron_file: backup-postgresql-databases
state: absent
```
##### EXPECTED RESULTS
There is no reason to request the user when deleting the contab file thus it should continue to work as before 2.8.
I would dare to say a test is missing here.
##### ACTUAL RESULTS
```paste below
fatal: [catton.osci.io]: FAILED! => {"changed": false, "msg": "missing parameter(s) required by 'cron_file': user"}
```
|
https://github.com/ansible/ansible/issues/58493
|
https://github.com/ansible/ansible/pull/58751
|
709fbcf8043c9fc636d2404e61de0f76ef5bad9d
|
61647731e28889cd5ebbf678e9f78aebae7ee812
| 2019-06-28T08:58:17Z |
python
| 2019-07-05T13:02:29Z |
lib/ansible/modules/system/cron.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2012, Dane Summers <[email protected]>
# Copyright: (c) 2013, Mike Grozak <[email protected]>
# Copyright: (c) 2013, Patrick Callahan <[email protected]>
# Copyright: (c) 2015, Evan Kaufman <[email protected]>
# Copyright: (c) 2015, Luca Berruti <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: cron
short_description: Manage cron.d and crontab entries
description:
- Use this module to manage crontab and environment variables entries. This module allows
you to create environment variables and named crontab entries, update, or delete them.
- 'When crontab jobs are managed: the module includes one line with the description of the
crontab entry C("#Ansible: <name>") corresponding to the "name" passed to the module,
which is used by future ansible/module calls to find/check the state. The "name"
parameter should be unique, and changing the "name" value will result in a new cron
task being created (or a different one being removed).'
- When environment variables are managed, no comment line is added, but, when the module
needs to find/check the state, it uses the "name" parameter to find the environment
variable definition line.
- When using symbols such as %, they must be properly escaped.
version_added: "0.9"
options:
name:
description:
- Description of a crontab entry or, if env is set, the name of environment variable.
- Required if C(state=absent).
- Note that if name is not set and C(state=present), then a
new crontab entry will always be created, regardless of existing ones.
- This parameter will always be required in future releases.
type: str
user:
description:
- The specific user whose crontab should be modified.
- When unset, this parameter defaults to using C(root).
type: str
job:
description:
- The command to execute or, if env is set, the value of environment variable.
- The command should not contain line breaks.
- Required if C(state=present).
type: str
aliases: [ value ]
state:
description:
- Whether to ensure the job or environment variable is present or absent.
type: str
choices: [ absent, present ]
default: present
cron_file:
description:
- If specified, uses this file instead of an individual user's crontab.
- If this is a relative path, it is interpreted with respect to I(/etc/cron.d).
- If it is absolute, it will typically be I(/etc/crontab).
- Many linux distros expect (and some require) the filename portion to consist solely
of upper- and lower-case letters, digits, underscores, and hyphens.
- To use the C(cron_file) parameter you must specify the C(user) as well.
type: str
backup:
description:
- If set, create a backup of the crontab before it is modified.
The location of the backup is returned in the C(backup_file) variable by this module.
type: bool
default: no
minute:
description:
- Minute when the job should run ( 0-59, *, */2, etc )
type: str
default: "*"
hour:
description:
- Hour when the job should run ( 0-23, *, */2, etc )
type: str
default: "*"
day:
description:
- Day of the month the job should run ( 1-31, *, */2, etc )
type: str
default: "*"
aliases: [ dom ]
month:
description:
- Month of the year the job should run ( 1-12, *, */2, etc )
type: str
default: "*"
weekday:
description:
- Day of the week that the job should run ( 0-6 for Sunday-Saturday, *, etc )
type: str
default: "*"
aliases: [ dow ]
reboot:
description:
- If the job should be run at reboot. This option is deprecated. Users should use special_time.
version_added: "1.0"
type: bool
default: no
special_time:
description:
- Special time specification nickname.
type: str
choices: [ annually, daily, hourly, monthly, reboot, weekly, yearly ]
version_added: "1.3"
disabled:
description:
- If the job should be disabled (commented out) in the crontab.
- Only has effect if C(state=present).
type: bool
default: no
version_added: "2.0"
env:
description:
- If set, manages a crontab's environment variable.
- New variables are added on top of crontab.
- C(name) and C(value) parameters are the name and the value of environment variable.
type: bool
default: no
version_added: "2.1"
insertafter:
description:
- Used with C(state=present) and C(env).
- If specified, the environment variable will be inserted after the declaration of specified environment variable.
type: str
version_added: "2.1"
insertbefore:
description:
- Used with C(state=present) and C(env).
- If specified, the environment variable will be inserted before the declaration of specified environment variable.
type: str
version_added: "2.1"
requirements:
- cron
author:
- Dane Summers (@dsummersl)
- Mike Grozak (@rhaido)
- Patrick Callahan (@dirtyharrycallahan)
- Evan Kaufman (@EvanK)
- Luca Berruti (@lberruti)
'''
EXAMPLES = r'''
- name: Ensure a job that runs at 2 and 5 exists. Creates an entry like "0 5,2 * * ls -alh > /dev/null"
cron:
name: "check dirs"
minute: "0"
hour: "5,2"
job: "ls -alh > /dev/null"
- name: 'Ensure an old job is no longer present. Removes any job that is prefixed by "#Ansible: an old job" from the crontab'
cron:
name: "an old job"
state: absent
- name: Creates an entry like "@reboot /some/job.sh"
cron:
name: "a job for reboot"
special_time: reboot
job: "/some/job.sh"
- name: Creates an entry like "PATH=/opt/bin" on top of crontab
cron:
name: PATH
env: yes
job: /opt/bin
- name: Creates an entry like "APP_HOME=/srv/app" and insert it after PATH declaration
cron:
name: APP_HOME
env: yes
job: /srv/app
insertafter: PATH
- name: Creates a cron file under /etc/cron.d
cron:
name: yum autoupdate
weekday: "2"
minute: "0"
hour: "12"
user: root
job: "YUMINTERACTIVE=0 /usr/sbin/yum-autoupdate"
cron_file: ansible_yum-autoupdate
- name: Removes a cron file from under /etc/cron.d
cron:
name: "yum autoupdate"
cron_file: ansible_yum-autoupdate
state: absent
- name: Removes "APP_HOME" environment variable from crontab
cron:
name: APP_HOME
env: yes
state: absent
'''
import os
import platform
import pwd
import re
import sys
import tempfile
from ansible.module_utils.basic import AnsibleModule, get_platform
from ansible.module_utils.six.moves import shlex_quote
CRONCMD = "/usr/bin/crontab"
class CronTabError(Exception):
pass
class CronTab(object):
"""
CronTab object to write time based crontab file
user - the user of the crontab (defaults to root)
cron_file - a cron file under /etc/cron.d, or an absolute path
"""
def __init__(self, module, user=None, cron_file=None):
self.module = module
self.user = user
self.root = (os.getuid() == 0)
self.lines = None
self.ansible = "#Ansible: "
self.existing = ''
if cron_file:
if os.path.isabs(cron_file):
self.cron_file = cron_file
else:
self.cron_file = os.path.join('/etc/cron.d', cron_file)
else:
self.cron_file = None
self.read()
def read(self):
# Read in the crontab from the system
self.lines = []
if self.cron_file:
# read the cronfile
try:
f = open(self.cron_file, 'r')
self.existing = f.read()
self.lines = self.existing.splitlines()
f.close()
except IOError:
# cron file does not exist
return
except Exception:
raise CronTabError("Unexpected error:", sys.exc_info()[0])
else:
# using safely quoted shell for now, but this really should be two non-shell calls instead. FIXME
(rc, out, err) = self.module.run_command(self._read_user_execute(), use_unsafe_shell=True)
if rc != 0 and rc != 1: # 1 can mean that there are no jobs.
raise CronTabError("Unable to read crontab")
self.existing = out
lines = out.splitlines()
count = 0
for l in lines:
if count > 2 or (not re.match(r'# DO NOT EDIT THIS FILE - edit the master and reinstall.', l) and
not re.match(r'# \(/tmp/.*installed on.*\)', l) and
not re.match(r'# \(.*version.*\)', l)):
self.lines.append(l)
else:
pattern = re.escape(l) + '[\r\n]?'
self.existing = re.sub(pattern, '', self.existing, 1)
count += 1
def is_empty(self):
if len(self.lines) == 0:
return True
else:
return False
def write(self, backup_file=None):
"""
Write the crontab to the system. Saves all information.
"""
if backup_file:
fileh = open(backup_file, 'w')
elif self.cron_file:
fileh = open(self.cron_file, 'w')
else:
filed, path = tempfile.mkstemp(prefix='crontab')
os.chmod(path, int('0644', 8))
fileh = os.fdopen(filed, 'w')
fileh.write(self.render())
fileh.close()
# return if making a backup
if backup_file:
return
# Add the entire crontab back to the user crontab
if not self.cron_file:
# quoting shell args for now but really this should be two non-shell calls. FIXME
(rc, out, err) = self.module.run_command(self._write_execute(path), use_unsafe_shell=True)
os.unlink(path)
if rc != 0:
self.module.fail_json(msg=err)
# set SELinux permissions
if self.module.selinux_enabled() and self.cron_file:
self.module.set_default_selinux_context(self.cron_file, False)
def do_comment(self, name):
return "%s%s" % (self.ansible, name)
def add_job(self, name, job):
# Add the comment
self.lines.append(self.do_comment(name))
# Add the job
self.lines.append("%s" % (job))
def update_job(self, name, job):
return self._update_job(name, job, self.do_add_job)
def do_add_job(self, lines, comment, job):
lines.append(comment)
lines.append("%s" % (job))
def remove_job(self, name):
return self._update_job(name, "", self.do_remove_job)
def do_remove_job(self, lines, comment, job):
return None
def add_env(self, decl, insertafter=None, insertbefore=None):
if not (insertafter or insertbefore):
self.lines.insert(0, decl)
return
if insertafter:
other_name = insertafter
elif insertbefore:
other_name = insertbefore
other_decl = self.find_env(other_name)
if len(other_decl) > 0:
if insertafter:
index = other_decl[0] + 1
elif insertbefore:
index = other_decl[0]
self.lines.insert(index, decl)
return
self.module.fail_json(msg="Variable named '%s' not found." % other_name)
def update_env(self, name, decl):
return self._update_env(name, decl, self.do_add_env)
def do_add_env(self, lines, decl):
lines.append(decl)
def remove_env(self, name):
return self._update_env(name, '', self.do_remove_env)
def do_remove_env(self, lines, decl):
return None
def remove_job_file(self):
try:
os.unlink(self.cron_file)
return True
except OSError:
# cron file does not exist
return False
except Exception:
raise CronTabError("Unexpected error:", sys.exc_info()[0])
def find_job(self, name, job=None):
# attempt to find job by 'Ansible:' header comment
comment = None
for l in self.lines:
if comment is not None:
if comment == name:
return [comment, l]
else:
comment = None
elif re.match(r'%s' % self.ansible, l):
comment = re.sub(r'%s' % self.ansible, '', l)
# failing that, attempt to find job by exact match
if job:
for i, l in enumerate(self.lines):
if l == job:
# if no leading ansible header, insert one
if not re.match(r'%s' % self.ansible, self.lines[i - 1]):
self.lines.insert(i, self.do_comment(name))
return [self.lines[i], l, True]
# if a leading blank ansible header AND job has a name, update header
elif name and self.lines[i - 1] == self.do_comment(None):
self.lines[i - 1] = self.do_comment(name)
return [self.lines[i - 1], l, True]
return []
def find_env(self, name):
for index, l in enumerate(self.lines):
if re.match(r'^%s=' % name, l):
return [index, l]
return []
def get_cron_job(self, minute, hour, day, month, weekday, job, special, disabled):
# normalize any leading/trailing newlines (ansible/ansible-modules-core#3791)
job = job.strip('\r\n')
if disabled:
disable_prefix = '#'
else:
disable_prefix = ''
if special:
if self.cron_file:
return "%s@%s %s %s" % (disable_prefix, special, self.user, job)
else:
return "%s@%s %s" % (disable_prefix, special, job)
else:
if self.cron_file:
return "%s%s %s %s %s %s %s %s" % (disable_prefix, minute, hour, day, month, weekday, self.user, job)
else:
return "%s%s %s %s %s %s %s" % (disable_prefix, minute, hour, day, month, weekday, job)
def get_jobnames(self):
jobnames = []
for l in self.lines:
if re.match(r'%s' % self.ansible, l):
jobnames.append(re.sub(r'%s' % self.ansible, '', l))
return jobnames
def get_envnames(self):
envnames = []
for l in self.lines:
if re.match(r'^\S+=', l):
envnames.append(l.split('=')[0])
return envnames
def _update_job(self, name, job, addlinesfunction):
ansiblename = self.do_comment(name)
newlines = []
comment = None
for l in self.lines:
if comment is not None:
addlinesfunction(newlines, comment, job)
comment = None
elif l == ansiblename:
comment = l
else:
newlines.append(l)
self.lines = newlines
if len(newlines) == 0:
return True
else:
return False # TODO add some more error testing
def _update_env(self, name, decl, addenvfunction):
newlines = []
for l in self.lines:
if re.match(r'^%s=' % name, l):
addenvfunction(newlines, decl)
else:
newlines.append(l)
self.lines = newlines
def render(self):
"""
Render this crontab as it would be in the crontab.
"""
crons = []
for cron in self.lines:
crons.append(cron)
result = '\n'.join(crons)
if result:
result = result.rstrip('\r\n') + '\n'
return result
def _read_user_execute(self):
"""
Returns the command line for reading a crontab
"""
user = ''
if self.user:
if platform.system() == 'SunOS':
return "su %s -c '%s -l'" % (shlex_quote(self.user), shlex_quote(CRONCMD))
elif platform.system() == 'AIX':
return "%s -l %s" % (shlex_quote(CRONCMD), shlex_quote(self.user))
elif platform.system() == 'HP-UX':
return "%s %s %s" % (CRONCMD, '-l', shlex_quote(self.user))
elif pwd.getpwuid(os.getuid())[0] != self.user:
user = '-u %s' % shlex_quote(self.user)
return "%s %s %s" % (CRONCMD, user, '-l')
def _write_execute(self, path):
"""
Return the command line for writing a crontab
"""
user = ''
if self.user:
if platform.system() in ['SunOS', 'HP-UX', 'AIX']:
return "chown %s %s ; su '%s' -c '%s %s'" % (shlex_quote(self.user), shlex_quote(path), shlex_quote(self.user), CRONCMD, shlex_quote(path))
elif pwd.getpwuid(os.getuid())[0] != self.user:
user = '-u %s' % shlex_quote(self.user)
return "%s %s %s" % (CRONCMD, user, shlex_quote(path))
def main():
# The following example playbooks:
#
# - cron: name="check dirs" hour="5,2" job="ls -alh > /dev/null"
#
# - name: do the job
# cron: name="do the job" hour="5,2" job="/some/dir/job.sh"
#
# - name: no job
# cron: name="an old job" state=absent
#
# - name: sets env
# cron: name="PATH" env=yes value="/bin:/usr/bin"
#
# Would produce:
# PATH=/bin:/usr/bin
# # Ansible: check dirs
# * * 5,2 * * ls -alh > /dev/null
# # Ansible: do the job
# * * 5,2 * * /some/dir/job.sh
module = AnsibleModule(
argument_spec=dict(
name=dict(type='str'),
user=dict(type='str'),
job=dict(type='str', aliases=['value']),
cron_file=dict(type='str'),
state=dict(type='str', default='present', choices=['present', 'absent']),
backup=dict(type='bool', default=False),
minute=dict(type='str', default='*'),
hour=dict(type='str', default='*'),
day=dict(type='str', default='*', aliases=['dom']),
month=dict(type='str', default='*'),
weekday=dict(type='str', default='*', aliases=['dow']),
reboot=dict(type='bool', default=False),
special_time=dict(type='str', choices=["reboot", "yearly", "annually", "monthly", "weekly", "daily", "hourly"]),
disabled=dict(type='bool', default=False),
env=dict(type='bool'),
insertafter=dict(type='str'),
insertbefore=dict(type='str'),
),
supports_check_mode=True,
mutually_exclusive=[
['reboot', 'special_time'],
['insertafter', 'insertbefore'],
],
required_by=dict(
cron_file=('user',),
),
required_if=(
('state', 'present', ('job',)),
),
)
name = module.params['name']
user = module.params['user']
job = module.params['job']
cron_file = module.params['cron_file']
state = module.params['state']
backup = module.params['backup']
minute = module.params['minute']
hour = module.params['hour']
day = module.params['day']
month = module.params['month']
weekday = module.params['weekday']
reboot = module.params['reboot']
special_time = module.params['special_time']
disabled = module.params['disabled']
env = module.params['env']
insertafter = module.params['insertafter']
insertbefore = module.params['insertbefore']
do_install = state == 'present'
changed = False
res_args = dict()
warnings = list()
if cron_file:
cron_file_basename = os.path.basename(cron_file)
if not re.search(r'^[A-Z0-9_-]+$', cron_file_basename, re.I):
warnings.append('Filename portion of cron_file ("%s") should consist' % cron_file_basename +
' solely of upper- and lower-case letters, digits, underscores, and hyphens')
# Ensure all files generated are only writable by the owning user. Primarily relevant for the cron_file option.
os.umask(int('022', 8))
crontab = CronTab(module, user, cron_file)
module.debug('cron instantiated - name: "%s"' % name)
if not name:
module.deprecate(
msg="The 'name' parameter will be required in future releases.",
version='2.12'
)
if reboot:
module.deprecate(
msg="The 'reboot' parameter will be removed in future releases. Use 'special_time' option instead.",
version='2.12'
)
if module._diff:
diff = dict()
diff['before'] = crontab.existing
if crontab.cron_file:
diff['before_header'] = crontab.cron_file
else:
if crontab.user:
diff['before_header'] = 'crontab for user "%s"' % crontab.user
else:
diff['before_header'] = 'crontab'
# --- user input validation ---
if (special_time or reboot) and \
(True in [(x != '*') for x in [minute, hour, day, month, weekday]]):
module.fail_json(msg="You must specify time and date fields or special time.")
# cannot support special_time on solaris
if (special_time or reboot) and get_platform() == 'SunOS':
module.fail_json(msg="Solaris does not support special_time=... or @reboot")
if (insertafter or insertbefore) and not env and do_install:
module.fail_json(msg="Insertafter and insertbefore parameters are valid only with env=yes")
if reboot:
special_time = "reboot"
# if requested make a backup before making a change
if backup and not module.check_mode:
(backuph, backup_file) = tempfile.mkstemp(prefix='crontab')
crontab.write(backup_file)
if crontab.cron_file and not name and not do_install:
if module._diff:
diff['after'] = ''
diff['after_header'] = '/dev/null'
else:
diff = dict()
if module.check_mode:
changed = os.path.isfile(crontab.cron_file)
else:
changed = crontab.remove_job_file()
module.exit_json(changed=changed, cron_file=cron_file, state=state, diff=diff)
if env:
if ' ' in name:
module.fail_json(msg="Invalid name for environment variable")
decl = '%s="%s"' % (name, job)
old_decl = crontab.find_env(name)
if do_install:
if len(old_decl) == 0:
crontab.add_env(decl, insertafter, insertbefore)
changed = True
if len(old_decl) > 0 and old_decl[1] != decl:
crontab.update_env(name, decl)
changed = True
else:
if len(old_decl) > 0:
crontab.remove_env(name)
changed = True
else:
if do_install:
for char in ['\r', '\n']:
if char in job.strip('\r\n'):
warnings.append('Job should not contain line breaks')
break
job = crontab.get_cron_job(minute, hour, day, month, weekday, job, special_time, disabled)
old_job = crontab.find_job(name, job)
if len(old_job) == 0:
crontab.add_job(name, job)
changed = True
if len(old_job) > 0 and old_job[1] != job:
crontab.update_job(name, job)
changed = True
if len(old_job) > 2:
crontab.update_job(name, job)
changed = True
else:
old_job = crontab.find_job(name)
if len(old_job) > 0:
crontab.remove_job(name)
changed = True
# no changes to env/job, but existing crontab needs a terminating newline
if not changed and crontab.existing != '':
if not (crontab.existing.endswith('\r') or crontab.existing.endswith('\n')):
changed = True
res_args = dict(
jobs=crontab.get_jobnames(),
envs=crontab.get_envnames(),
warnings=warnings,
changed=changed
)
if changed:
if not module.check_mode:
crontab.write()
if module._diff:
diff['after'] = crontab.render()
if crontab.cron_file:
diff['after_header'] = crontab.cron_file
else:
if crontab.user:
diff['after_header'] = 'crontab for user "%s"' % crontab.user
else:
diff['after_header'] = 'crontab'
res_args['diff'] = diff
# retain the backup only if crontab or cron file have changed
if backup and not module.check_mode:
if changed:
res_args['backup_file'] = backup_file
else:
os.unlink(backup_file)
if cron_file:
res_args['cron_file'] = cron_file
module.exit_json(**res_args)
# --- should never get here
module.exit_json(msg="Unable to execute cron task.")
if __name__ == '__main__':
main()
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,788 |
ios_bgp next-hop-self does not add command
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
<!--- Explain the problem briefly below -->
When setting `next_hop_self: true` within the AF Neighbors, this does not get set.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
ios_bgp
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.8.1
config file = None
configured module search path = ['/Users/joshv/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.7/site-packages/ansible
executable location = /usr/local/bin/ansible
python version = 3.7.2 (default, Feb 10 2019, 15:44:18) [Clang 10.0.0 (clang-1000.11.45.5)]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
➜ ansible-config dump --only-changed
Time: 0h:00m:15s
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
MacOS --> Cisco IOS
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
- Created a playbook with `next_hop_self` set to true, it was not added
- Output shows that the neighbor is activated twice
- Checked `neighbors.py` file, the `next_hop_self` section is just a copy of the `activate` section (lines 165-172)
``` python
def _render_next_hop_self(self, item, config=None):
cmd = 'neighbor %s activate' % item['neighbor']
if item['next_hop_self'] is False:
if not config or cmd in config:
cmd = 'no %s' % cmd
return cmd
elif not config or cmd not in config:
return cmd
```
<!--- Paste example playbooks or commands between quotes below -->
```yaml
- name: "PLAY 3: Setup R4"
hosts: r4
become: yes
become_method: enable
tags: router_setup
tasks:
- name: "TASK 1: Setup BGP Peers"
ios_bgp:
config:
bgp_as: 65500
router_id: 10.0.0.4
log_neighbor_changes: true
neighbors:
- neighbor: 192.0.2.5
remote_as: 65510
timers:
keepalive: 15
holdtime: 45
min_neighbor_holdtime: 5
description: R2 Uplink
- neighbor: 198.51.100.1
remote_as: 65500
timers:
keepalive: 15
holdtime: 45
min_neighbor_holdtime: 5
description: R3 conenction
networks:
- prefix: 0.0.0.0
masklen: 0
address_family:
- afi: ipv4
safi: unicast
redistribute:
- protocol: eigrp
id: "20"
metric: 10
neighbors:
- neighbor: 198.51.100.1
activate: yes
next_hop_self: yes
operation: override
register: output
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
I'd expect that the command `neighbor 198.51.100.1 next-hop-self` would be in the commands
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
`neighbor 198.51.100.1 activate` was sent twice
<!--- Paste verbatim command output between quotes -->
```paste below
ok: [r4] => {
"msg": {
"changed": true,
"commands": [
"no router bgp 65500",
"router bgp 65500",
"bgp router-id 10.0.0.4",
"bgp log-neighbor-changes",
"neighbor 192.0.2.5 remote-as 65510",
"neighbor 192.0.2.5 timers 15 45 5",
"neighbor 192.0.2.5 description R2 Uplink",
"neighbor 198.51.100.1 remote-as 65500",
"neighbor 198.51.100.1 timers 15 45 5",
"neighbor 198.51.100.1 description R3 conenction",
"network 0.0.0.0",
"address-family ipv4",
"redistribute eigrp 20 metric 10",
"neighbor 198.51.100.1 activate",
"neighbor 198.51.100.1 activate",
"exit-address-family",
"exit"
],
"failed": false
}
}
```
|
https://github.com/ansible/ansible/issues/58788
|
https://github.com/ansible/ansible/pull/58789
|
faf50dbace25d0236f8019d114c214c61fff3f55
|
73db7e290143c9b167fa9d5d7f801262347f713b
| 2019-07-06T18:24:00Z |
python
| 2019-07-06T20:39:10Z |
lib/ansible/module_utils/network/ios/providers/cli/config/bgp/neighbors.py
|
#
# (c) 2019, Ansible by Red Hat, inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
import re
from ansible.module_utils.six import iteritems
from ansible.module_utils.network.common.utils import to_list
from ansible.module_utils.network.ios.providers.providers import CliProvider
class Neighbors(CliProvider):
def render(self, config=None, nbr_list=None):
commands = list()
safe_list = list()
if not nbr_list:
nbr_list = self.get_value('config.neighbors')
for item in nbr_list:
neighbor_commands = list()
context = 'neighbor %s' % item['neighbor']
cmd = '%s remote-as %s' % (context, item['remote_as'])
if not config or cmd not in config:
neighbor_commands.append(cmd)
for key, value in iteritems(item):
if value is not None:
meth = getattr(self, '_render_%s' % key, None)
if meth:
resp = meth(item, config)
if resp:
neighbor_commands.extend(to_list(resp))
commands.extend(neighbor_commands)
safe_list.append(context)
if self.params['operation'] == 'replace':
if config and safe_list:
commands.extend(self._negate_config(config, safe_list))
return commands
def _negate_config(self, config, safe_list=None):
commands = list()
matches = re.findall(r'(neighbor \S+)', config, re.M)
for item in set(matches).difference(safe_list):
commands.append('no %s' % item)
return commands
def _render_local_as(self, item, config=None):
cmd = 'neighbor %s local-as %s' % (item['neighbor'], item['local_as'])
if not config or cmd not in config:
return cmd
def _render_port(self, item, config=None):
cmd = 'neighbor %s port %s' % (item['neighbor'], item['port'])
if not config or cmd not in config:
return cmd
def _render_description(self, item, config=None):
cmd = 'neighbor %s description %s' % (item['neighbor'], item['description'])
if not config or cmd not in config:
return cmd
def _render_enabled(self, item, config=None):
cmd = 'neighbor %s shutdown' % item['neighbor']
if item['enabled'] is True:
if not config or cmd in config:
cmd = 'no %s' % cmd
return cmd
elif not config or cmd not in config:
return cmd
def _render_update_source(self, item, config=None):
cmd = 'neighbor %s update-source %s' % (item['neighbor'], item['update_source'])
if not config or cmd not in config:
return cmd
def _render_password(self, item, config=None):
cmd = 'neighbor %s password %s' % (item['neighbor'], item['password'])
if not config or cmd not in config:
return cmd
def _render_ebgp_multihop(self, item, config=None):
cmd = 'neighbor %s ebgp-multihop %s' % (item['neighbor'], item['ebgp_multihop'])
if not config or cmd not in config:
return cmd
def _render_peer_group(self, item, config=None):
cmd = 'neighbor %s peer-group %s' % (item['neighbor'], item['peer_group'])
if not config or cmd not in config:
return cmd
def _render_timers(self, item, config):
"""generate bgp timer related configuration
"""
keepalive = item['timers']['keepalive']
holdtime = item['timers']['holdtime']
min_neighbor_holdtime = item['timers']['min_neighbor_holdtime']
neighbor = item['neighbor']
if keepalive and holdtime:
cmd = 'neighbor %s timers %s %s' % (neighbor, keepalive, holdtime)
if min_neighbor_holdtime:
cmd += ' %s' % min_neighbor_holdtime
if not config or cmd not in config:
return cmd
class AFNeighbors(CliProvider):
def render(self, config=None, nbr_list=None):
commands = list()
if not nbr_list:
return
for item in nbr_list:
neighbor_commands = list()
for key, value in iteritems(item):
if value is not None:
meth = getattr(self, '_render_%s' % key, None)
if meth:
resp = meth(item, config)
if resp:
neighbor_commands.extend(to_list(resp))
commands.extend(neighbor_commands)
return commands
def _render_advertisement_interval(self, item, config=None):
cmd = 'neighbor %s advertisement-interval %s' % (item['neighbor'], item['advertisement_interval'])
if not config or cmd not in config:
return cmd
def _render_route_reflector_client(self, item, config=None):
cmd = 'neighbor %s route-reflector-client' % item['neighbor']
if item['route_reflector_client'] is False:
if not config or cmd in config:
cmd = 'no %s' % cmd
return cmd
elif not config or cmd not in config:
return cmd
def _render_route_server_client(self, item, config=None):
cmd = 'neighbor %s route-server-client' % item['neighbor']
if item['route_server_client'] is False:
if not config or cmd in config:
cmd = 'no %s' % cmd
return cmd
elif not config or cmd not in config:
return cmd
def _render_remove_private_as(self, item, config=None):
cmd = 'neighbor %s remove-private-as' % item['neighbor']
if item['remove_private_as'] is False:
if not config or cmd in config:
cmd = 'no %s' % cmd
return cmd
elif not config or cmd not in config:
return cmd
def _render_next_hop_self(self, item, config=None):
cmd = 'neighbor %s activate' % item['neighbor']
if item['next_hop_self'] is False:
if not config or cmd in config:
cmd = 'no %s' % cmd
return cmd
elif not config or cmd not in config:
return cmd
def _render_activate(self, item, config=None):
cmd = 'neighbor %s activate' % item['neighbor']
if item['activate'] is False:
if not config or cmd in config:
cmd = 'no %s' % cmd
return cmd
elif not config or cmd not in config:
return cmd
def _render_maximum_prefix(self, item, config=None):
cmd = 'neighbor %s maximum-prefix %s' % (item['neighbor'], item['maximum_prefix'])
if not config or cmd not in config:
return cmd
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,813 |
udm_dns_record module has incorrect module info
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
udm_dns_record contains probably copy&paste info from udm_dns_zone module, see https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/cloud/univention/udm_dns_record.py#L64 Thus it's confusing how to use it, if one uses 'udm_dns_zone' in her playbook it would fail because invalid values.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
udm_dns_record module
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.7.7
config file = /home/jiri/awebsys/ansible/ansible.cfg
configured module search path = ['/home/jiri/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python3/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 3.7.3 (default, Apr 3 2019, 05:39:12) [GCC 8.3.0]
```
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
```
$ ansible-doc udm_dns_record | sed -n '/^EXAMPLES/,$p'
EXAMPLES:
# Create a DNS record on a UCS
- udm_dns_zone:
name: www
zone: example.com
type: host_record
data:
- a: 192.0.2.1
RETURN VALUES:
#
```
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
Should have valid example data.
|
https://github.com/ansible/ansible/issues/58813
|
https://github.com/ansible/ansible/pull/58814
|
88ec5e14cb9edd780d15e763ed89cad47e095174
|
1f427249d5ed66d597400cf719083bd4ce1848fb
| 2019-07-08T06:07:48Z |
python
| 2019-07-09T07:22:02Z |
lib/ansible/modules/cloud/univention/udm_dns_record.py
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Copyright: (c) 2016, Adfinis SyGroup AG
# Tobias Rueetschi <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: udm_dns_record
version_added: "2.2"
author:
- Tobias Rüetschi (@keachi)
short_description: Manage dns entries on a univention corporate server
description:
- "This module allows to manage dns records on a univention corporate server (UCS).
It uses the python API of the UCS to create a new object or edit it."
requirements:
- Python >= 2.6
- Univention
options:
state:
required: false
default: "present"
choices: [ present, absent ]
description:
- Whether the dns record is present or not.
name:
required: true
description:
- "Name of the record, this is also the DNS record. E.g. www for
www.example.com."
zone:
required: true
description:
- Corresponding DNS zone for this record, e.g. example.com.
type:
required: true
choices: [ host_record, alias, ptr_record, srv_record, txt_record ]
description:
- "Define the record type. C(host_record) is a A or AAAA record,
C(alias) is a CNAME, C(ptr_record) is a PTR record, C(srv_record)
is a SRV record and C(txt_record) is a TXT record."
data:
required: false
default: []
description:
- "Additional data for this record, e.g. ['a': '192.0.2.1'].
Required if C(state=present)."
'''
EXAMPLES = '''
# Create a DNS record on a UCS
- udm_dns_zone:
name: www
zone: example.com
type: host_record
data:
- a: 192.0.2.1
'''
RETURN = '''# '''
HAVE_UNIVENTION = False
try:
from univention.admin.handlers.dns import (
forward_zone,
reverse_zone,
)
HAVE_UNIVENTION = True
except ImportError:
pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.univention_umc import (
umc_module_for_add,
umc_module_for_edit,
ldap_search,
base_dn,
config,
uldap,
)
def main():
module = AnsibleModule(
argument_spec=dict(
type=dict(required=True,
type='str'),
zone=dict(required=True,
type='str'),
name=dict(required=True,
type='str'),
data=dict(default=[],
type='dict'),
state=dict(default='present',
choices=['present', 'absent'],
type='str')
),
supports_check_mode=True,
required_if=([
('state', 'present', ['data'])
])
)
if not HAVE_UNIVENTION:
module.fail_json(msg="This module requires univention python bindings")
type = module.params['type']
zone = module.params['zone']
name = module.params['name']
data = module.params['data']
state = module.params['state']
changed = False
diff = None
obj = list(ldap_search(
'(&(objectClass=dNSZone)(zoneName={0})(relativeDomainName={1}))'.format(zone, name),
attr=['dNSZone']
))
exists = bool(len(obj))
container = 'zoneName={0},cn=dns,{1}'.format(zone, base_dn())
dn = 'relativeDomainName={0},{1}'.format(name, container)
if state == 'present':
try:
if not exists:
so = forward_zone.lookup(
config(),
uldap(),
'(zone={0})'.format(zone),
scope='domain',
) or reverse_zone.lookup(
config(),
uldap(),
'(zone={0})'.format(zone),
scope='domain',
)
obj = umc_module_for_add('dns/{0}'.format(type), container, superordinate=so[0])
else:
obj = umc_module_for_edit('dns/{0}'.format(type), dn)
obj['name'] = name
for k, v in data.items():
obj[k] = v
diff = obj.diff()
changed = obj.diff() != []
if not module.check_mode:
if not exists:
obj.create()
else:
obj.modify()
except Exception as e:
module.fail_json(
msg='Creating/editing dns entry {0} in {1} failed: {2}'.format(name, container, e)
)
if state == 'absent' and exists:
try:
obj = umc_module_for_edit('dns/{0}'.format(type), dn)
if not module.check_mode:
obj.remove()
changed = True
except Exception as e:
module.fail_json(
msg='Removing dns entry {0} in {1} failed: {2}'.format(name, container, e)
)
module.exit_json(
changed=changed,
name=name,
diff=diff,
container=container
)
if __name__ == '__main__':
main()
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,834 |
Update default test container to Python 3.8.0b2
|
<!--- Verify first that your feature was not already discussed on GitHub -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
Python 3.8.0b2 is [released](https://www.python.org/downloads/release/python-380b2/). We should update the default test container with this version.
##### ISSUE TYPE
- Feature Idea
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
`shippable.yml`
##### ADDITIONAL INFORMATION
<!--- Describe how the feature would be used, why it is needed and what it would solve -->
This release [reverted a C API breaking change](https://github.com/python/cpython/pull/13959) in Beta 1.
|
https://github.com/ansible/ansible/issues/58834
|
https://github.com/ansible/ansible/pull/58877
|
0befccbeb96d388574249b65849c84cddeaae915
|
5ccd674dba810dbbe0622b764c4d06f2814cbb56
| 2019-07-08T17:18:37Z |
python
| 2019-07-09T21:44:16Z |
test/runner/completion/docker.txt
|
default name=quay.io/ansible/default-test-container:1.8.1 python=3.6,2.6,2.7,3.5,3.7,3.8 seccomp=unconfined
centos6 name=quay.io/ansible/centos6-test-container:1.8.0 python=2.6 seccomp=unconfined
centos7 name=quay.io/ansible/centos7-test-container:1.8.0 python=2.7 seccomp=unconfined
fedora29 name=quay.io/ansible/fedora29-test-container:1.8.0 python=3.7
fedora30 name=quay.io/ansible/fedora30-test-container:1.9.2 python=3.7
opensuse15py2 name=quay.io/ansible/opensuse15py2-test-container:1.8.0 python=2.7
opensuse15 name=quay.io/ansible/opensuse15-test-container:1.8.0 python=3.6
ubuntu1604 name=quay.io/ansible/ubuntu1604-test-container:1.8.0 python=2.7 seccomp=unconfined
ubuntu1804 name=quay.io/ansible/ubuntu1804-test-container:1.8.0 python=3.6 seccomp=unconfined
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,820 |
Templated loop_var not defined when looping include_tasks
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
<!--- Explain the problem briefly below -->
When looping `include_tasks`, the loop control `loop_var` property is not defined in the included task, when the `loop_var` property has been assigned with a template.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
- loop_var
- include_tasks
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.8.1
config file = /playbooks/ansible.cfg
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.7/site-packages/ansible
executable location = /usr/local/bin/ansible
python version = 3.7.3 (default, Jun 11 2019, 01:05:09) [GCC 6.3.0 20170516]
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
Redhat7
Archlinux
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```yaml
---
# main.yml
- hosts: localhost
vars:
loop_var_name: custom_var
tasks:
- include_tasks: looped-include.yml
loop:
- first
- second
loop_control:
loop_var: "{{ loop_var_name }}"
```
```yaml
---
# looped-include.yml
- name: Print looped var
debug:
var: custom_var
- name: Loop default item var
debug:
var: item
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
We expect the variabe `custom_var` to be the looped variable, and `item` to be undefined.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
Neither `custom_var` nor `item` are defined in the looped included task.
<!--- Paste verbatim command output between quotes -->
```paste below
PLAY [localhost] *****************************************************************************************
TASK [Gathering Facts] ***********************************************************************************
ok: [localhost]
included: /ansible-bug/looped-include.yml for localhost
included: /ansible-bug/looped-include.yml for localhost
TASK [Print looped var] **********************************************************************************
ok: [localhost] =>
custom_var: VARIABLE IS NOT DEFINED!
TASK [Loop default item var] *****************************************************************************
ok: [localhost] =>
item: VARIABLE IS NOT DEFINED!
TASK [Print looped var] **********************************************************************************
ok: [localhost] =>
custom_var: VARIABLE IS NOT DEFINED!
TASK [Loop default item var] *****************************************************************************
ok: [localhost] =>
item: VARIABLE IS NOT DEFINED!
```
|
https://github.com/ansible/ansible/issues/58820
|
https://github.com/ansible/ansible/pull/58866
|
ad490573306864f8596f9e9af49e69f70d8f15d0
|
7346b699eec99d7279da4175b99f07e08f0de283
| 2019-07-08T09:51:03Z |
python
| 2019-07-10T11:49:24Z |
changelogs/fragments/58820-use-templated-loop_var-in-include_tasks.yaml
| |
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,820 |
Templated loop_var not defined when looping include_tasks
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
<!--- Explain the problem briefly below -->
When looping `include_tasks`, the loop control `loop_var` property is not defined in the included task, when the `loop_var` property has been assigned with a template.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
- loop_var
- include_tasks
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.8.1
config file = /playbooks/ansible.cfg
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.7/site-packages/ansible
executable location = /usr/local/bin/ansible
python version = 3.7.3 (default, Jun 11 2019, 01:05:09) [GCC 6.3.0 20170516]
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
Redhat7
Archlinux
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```yaml
---
# main.yml
- hosts: localhost
vars:
loop_var_name: custom_var
tasks:
- include_tasks: looped-include.yml
loop:
- first
- second
loop_control:
loop_var: "{{ loop_var_name }}"
```
```yaml
---
# looped-include.yml
- name: Print looped var
debug:
var: custom_var
- name: Loop default item var
debug:
var: item
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
We expect the variabe `custom_var` to be the looped variable, and `item` to be undefined.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
Neither `custom_var` nor `item` are defined in the looped included task.
<!--- Paste verbatim command output between quotes -->
```paste below
PLAY [localhost] *****************************************************************************************
TASK [Gathering Facts] ***********************************************************************************
ok: [localhost]
included: /ansible-bug/looped-include.yml for localhost
included: /ansible-bug/looped-include.yml for localhost
TASK [Print looped var] **********************************************************************************
ok: [localhost] =>
custom_var: VARIABLE IS NOT DEFINED!
TASK [Loop default item var] *****************************************************************************
ok: [localhost] =>
item: VARIABLE IS NOT DEFINED!
TASK [Print looped var] **********************************************************************************
ok: [localhost] =>
custom_var: VARIABLE IS NOT DEFINED!
TASK [Loop default item var] *****************************************************************************
ok: [localhost] =>
item: VARIABLE IS NOT DEFINED!
```
|
https://github.com/ansible/ansible/issues/58820
|
https://github.com/ansible/ansible/pull/58866
|
ad490573306864f8596f9e9af49e69f70d8f15d0
|
7346b699eec99d7279da4175b99f07e08f0de283
| 2019-07-08T09:51:03Z |
python
| 2019-07-10T11:49:24Z |
lib/ansible/executor/task_executor.py
|
# (c) 2012-2014, Michael DeHaan <[email protected]>
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import re
import pty
import time
import json
import subprocess
import sys
import termios
import traceback
from ansible import constants as C
from ansible.errors import AnsibleError, AnsibleParserError, AnsibleUndefinedVariable, AnsibleConnectionFailure, AnsibleActionFail, AnsibleActionSkip
from ansible.executor.task_result import TaskResult
from ansible.executor.module_common import get_action_args_with_defaults
from ansible.module_utils.six import iteritems, string_types, binary_type
from ansible.module_utils.six.moves import xrange
from ansible.module_utils._text import to_text, to_native
from ansible.module_utils.connection import write_to_file_descriptor
from ansible.playbook.conditional import Conditional
from ansible.playbook.task import Task
from ansible.plugins.loader import become_loader, cliconf_loader, connection_loader, httpapi_loader, netconf_loader, terminal_loader
from ansible.template import Templar
from ansible.utils.listify import listify_lookup_plugin_terms
from ansible.utils.unsafe_proxy import UnsafeProxy, wrap_var
from ansible.vars.clean import namespace_facts, clean_facts
from ansible.utils.display import Display
from ansible.utils.vars import combine_vars, isidentifier
display = Display()
__all__ = ['TaskExecutor']
def remove_omit(task_args, omit_token):
'''
Remove args with a value equal to the ``omit_token`` recursively
to align with now having suboptions in the argument_spec
'''
if not isinstance(task_args, dict):
return task_args
new_args = {}
for i in iteritems(task_args):
if i[1] == omit_token:
continue
elif isinstance(i[1], dict):
new_args[i[0]] = remove_omit(i[1], omit_token)
elif isinstance(i[1], list):
new_args[i[0]] = [remove_omit(v, omit_token) for v in i[1]]
else:
new_args[i[0]] = i[1]
return new_args
class TaskExecutor:
'''
This is the main worker class for the executor pipeline, which
handles loading an action plugin to actually dispatch the task to
a given host. This class roughly corresponds to the old Runner()
class.
'''
# Modules that we optimize by squashing loop items into a single call to
# the module
SQUASH_ACTIONS = frozenset(C.DEFAULT_SQUASH_ACTIONS)
def __init__(self, host, task, job_vars, play_context, new_stdin, loader, shared_loader_obj, final_q):
self._host = host
self._task = task
self._job_vars = job_vars
self._play_context = play_context
self._new_stdin = new_stdin
self._loader = loader
self._shared_loader_obj = shared_loader_obj
self._connection = None
self._final_q = final_q
self._loop_eval_error = None
self._task.squash()
def run(self):
'''
The main executor entrypoint, where we determine if the specified
task requires looping and either runs the task with self._run_loop()
or self._execute(). After that, the returned results are parsed and
returned as a dict.
'''
display.debug("in run() - task %s" % self._task._uuid)
try:
try:
items = self._get_loop_items()
except AnsibleUndefinedVariable as e:
# save the error raised here for use later
items = None
self._loop_eval_error = e
if items is not None:
if len(items) > 0:
item_results = self._run_loop(items)
# create the overall result item
res = dict(results=item_results)
# loop through the item results, and set the global changed/failed result flags based on any item.
for item in item_results:
if 'changed' in item and item['changed'] and not res.get('changed'):
res['changed'] = True
if 'failed' in item and item['failed']:
item_ignore = item.pop('_ansible_ignore_errors')
if not res.get('failed'):
res['failed'] = True
res['msg'] = 'One or more items failed'
self._task.ignore_errors = item_ignore
elif self._task.ignore_errors and not item_ignore:
self._task.ignore_errors = item_ignore
# ensure to accumulate these
for array in ['warnings', 'deprecations']:
if array in item and item[array]:
if array not in res:
res[array] = []
if not isinstance(item[array], list):
item[array] = [item[array]]
res[array] = res[array] + item[array]
del item[array]
if not res.get('Failed', False):
res['msg'] = 'All items completed'
else:
res = dict(changed=False, skipped=True, skipped_reason='No items in the list', results=[])
else:
display.debug("calling self._execute()")
res = self._execute()
display.debug("_execute() done")
# make sure changed is set in the result, if it's not present
if 'changed' not in res:
res['changed'] = False
def _clean_res(res, errors='surrogate_or_strict'):
if isinstance(res, UnsafeProxy):
return res._obj
elif isinstance(res, binary_type):
return to_text(res, errors=errors)
elif isinstance(res, dict):
for k in res:
try:
res[k] = _clean_res(res[k], errors=errors)
except UnicodeError:
if k == 'diff':
# If this is a diff, substitute a replacement character if the value
# is undecodable as utf8. (Fix #21804)
display.warning("We were unable to decode all characters in the module return data."
" Replaced some in an effort to return as much as possible")
res[k] = _clean_res(res[k], errors='surrogate_then_replace')
else:
raise
elif isinstance(res, list):
for idx, item in enumerate(res):
res[idx] = _clean_res(item, errors=errors)
return res
display.debug("dumping result to json")
res = _clean_res(res)
display.debug("done dumping result, returning")
return res
except AnsibleError as e:
return dict(failed=True, msg=wrap_var(to_text(e, nonstring='simplerepr')), _ansible_no_log=self._play_context.no_log)
except Exception as e:
return dict(failed=True, msg='Unexpected failure during module execution.', exception=to_text(traceback.format_exc()),
stdout='', _ansible_no_log=self._play_context.no_log)
finally:
try:
self._connection.close()
except AttributeError:
pass
except Exception as e:
display.debug(u"error closing connection: %s" % to_text(e))
def _get_loop_items(self):
'''
Loads a lookup plugin to handle the with_* portion of a task (if specified),
and returns the items result.
'''
# save the play context variables to a temporary dictionary,
# so that we can modify the job vars without doing a full copy
# and later restore them to avoid modifying things too early
play_context_vars = dict()
self._play_context.update_vars(play_context_vars)
old_vars = dict()
for k in play_context_vars:
if k in self._job_vars:
old_vars[k] = self._job_vars[k]
self._job_vars[k] = play_context_vars[k]
# get search path for this task to pass to lookup plugins
self._job_vars['ansible_search_path'] = self._task.get_search_path()
# ensure basedir is always in (dwim already searches here but we need to display it)
if self._loader.get_basedir() not in self._job_vars['ansible_search_path']:
self._job_vars['ansible_search_path'].append(self._loader.get_basedir())
templar = Templar(loader=self._loader, shared_loader_obj=self._shared_loader_obj, variables=self._job_vars)
items = None
loop_cache = self._job_vars.get('_ansible_loop_cache')
if loop_cache is not None:
# _ansible_loop_cache may be set in `get_vars` when calculating `delegate_to`
# to avoid reprocessing the loop
items = loop_cache
elif self._task.loop_with:
if self._task.loop_with in self._shared_loader_obj.lookup_loader:
fail = True
if self._task.loop_with == 'first_found':
# first_found loops are special. If the item is undefined then we want to fall through to the next value rather than failing.
fail = False
loop_terms = listify_lookup_plugin_terms(terms=self._task.loop, templar=templar, loader=self._loader, fail_on_undefined=fail,
convert_bare=False)
if not fail:
loop_terms = [t for t in loop_terms if not templar.is_template(t)]
# get lookup
mylookup = self._shared_loader_obj.lookup_loader.get(self._task.loop_with, loader=self._loader, templar=templar)
# give lookup task 'context' for subdir (mostly needed for first_found)
for subdir in ['template', 'var', 'file']: # TODO: move this to constants?
if subdir in self._task.action:
break
setattr(mylookup, '_subdir', subdir + 's')
# run lookup
items = mylookup.run(terms=loop_terms, variables=self._job_vars, wantlist=True)
else:
raise AnsibleError("Unexpected failure in finding the lookup named '%s' in the available lookup plugins" % self._task.loop_with)
elif self._task.loop is not None:
items = templar.template(self._task.loop)
if not isinstance(items, list):
raise AnsibleError(
"Invalid data passed to 'loop', it requires a list, got this instead: %s."
" Hint: If you passed a list/dict of just one element,"
" try adding wantlist=True to your lookup invocation or use q/query instead of lookup." % items
)
# now we restore any old job variables that may have been modified,
# and delete them if they were in the play context vars but not in
# the old variables dictionary
for k in play_context_vars:
if k in old_vars:
self._job_vars[k] = old_vars[k]
else:
del self._job_vars[k]
if items:
for idx, item in enumerate(items):
if item is not None and not isinstance(item, UnsafeProxy):
items[idx] = UnsafeProxy(item)
return items
def _run_loop(self, items):
'''
Runs the task with the loop items specified and collates the result
into an array named 'results' which is inserted into the final result
along with the item for which the loop ran.
'''
results = []
# make copies of the job vars and task so we can add the item to
# the variables and re-validate the task with the item variable
# task_vars = self._job_vars.copy()
task_vars = self._job_vars
loop_var = 'item'
index_var = None
label = None
loop_pause = 0
extended = False
templar = Templar(loader=self._loader, shared_loader_obj=self._shared_loader_obj, variables=self._job_vars)
# FIXME: move this to the object itself to allow post_validate to take care of templating (loop_control.post_validate)
if self._task.loop_control:
loop_var = templar.template(self._task.loop_control.loop_var)
index_var = templar.template(self._task.loop_control.index_var)
loop_pause = templar.template(self._task.loop_control.pause)
extended = templar.template(self._task.loop_control.extended)
# This may be 'None',so it is templated below after we ensure a value and an item is assigned
label = self._task.loop_control.label
# ensure we always have a label
if label is None:
label = '{{' + loop_var + '}}'
if loop_var in task_vars:
display.warning(u"The loop variable '%s' is already in use. "
u"You should set the `loop_var` value in the `loop_control` option for the task"
u" to something else to avoid variable collisions and unexpected behavior." % loop_var)
ran_once = False
if self._task.loop_with:
# Only squash with 'with_:' not with the 'loop:', 'magic' squashing can be removed once with_ loops are
items = self._squash_items(items, loop_var, task_vars)
no_log = False
items_len = len(items)
for item_index, item in enumerate(items):
task_vars['ansible_loop_var'] = loop_var
task_vars[loop_var] = item
if index_var:
task_vars[index_var] = item_index
if extended:
task_vars['ansible_loop'] = {
'allitems': items,
'index': item_index + 1,
'index0': item_index,
'first': item_index == 0,
'last': item_index + 1 == items_len,
'length': items_len,
'revindex': items_len - item_index,
'revindex0': items_len - item_index - 1,
}
try:
task_vars['ansible_loop']['nextitem'] = items[item_index + 1]
except IndexError:
pass
if item_index - 1 >= 0:
task_vars['ansible_loop']['previtem'] = items[item_index - 1]
# Update template vars to reflect current loop iteration
templar.available_variables = task_vars
# pause between loop iterations
if loop_pause and ran_once:
try:
time.sleep(float(loop_pause))
except ValueError as e:
raise AnsibleError('Invalid pause value: %s, produced error: %s' % (loop_pause, to_native(e)))
else:
ran_once = True
try:
tmp_task = self._task.copy(exclude_parent=True, exclude_tasks=True)
tmp_task._parent = self._task._parent
tmp_play_context = self._play_context.copy()
except AnsibleParserError as e:
results.append(dict(failed=True, msg=to_text(e)))
continue
# now we swap the internal task and play context with their copies,
# execute, and swap them back so we can do the next iteration cleanly
(self._task, tmp_task) = (tmp_task, self._task)
(self._play_context, tmp_play_context) = (tmp_play_context, self._play_context)
res = self._execute(variables=task_vars)
task_fields = self._task.dump_attrs()
(self._task, tmp_task) = (tmp_task, self._task)
(self._play_context, tmp_play_context) = (tmp_play_context, self._play_context)
# update 'general no_log' based on specific no_log
no_log = no_log or tmp_task.no_log
# now update the result with the item info, and append the result
# to the list of results
res[loop_var] = item
res['ansible_loop_var'] = loop_var
if index_var:
res[index_var] = item_index
if extended:
res['ansible_loop'] = task_vars['ansible_loop']
res['_ansible_item_result'] = True
res['_ansible_ignore_errors'] = task_fields.get('ignore_errors')
# gets templated here unlike rest of loop_control fields, depends on loop_var above
try:
res['_ansible_item_label'] = templar.template(label, cache=False)
except AnsibleUndefinedVariable as e:
res.update({
'failed': True,
'msg': 'Failed to template loop_control.label: %s' % to_text(e)
})
self._final_q.put(
TaskResult(
self._host.name,
self._task._uuid,
res,
task_fields=task_fields,
),
block=False,
)
results.append(res)
del task_vars[loop_var]
self._task.no_log = no_log
return results
def _squash_items(self, items, loop_var, variables):
'''
Squash items down to a comma-separated list for certain modules which support it
(typically package management modules).
'''
name = None
try:
# _task.action could contain templatable strings (via action: and
# local_action:) Template it before comparing. If we don't end up
# optimizing it here, the templatable string might use template vars
# that aren't available until later (it could even use vars from the
# with_items loop) so don't make the templated string permanent yet.
templar = Templar(loader=self._loader, shared_loader_obj=self._shared_loader_obj, variables=variables)
task_action = self._task.action
if templar.is_template(task_action):
task_action = templar.template(task_action, fail_on_undefined=False)
if len(items) > 0 and task_action in self.SQUASH_ACTIONS:
if all(isinstance(o, string_types) for o in items):
final_items = []
found = None
for allowed in ['name', 'pkg', 'package']:
name = self._task.args.pop(allowed, None)
if name is not None:
found = allowed
break
# This gets the information to check whether the name field
# contains a template that we can squash for
template_no_item = template_with_item = None
if name:
if templar.is_template(name):
variables[loop_var] = '\0$'
template_no_item = templar.template(name, variables, cache=False)
variables[loop_var] = '\0@'
template_with_item = templar.template(name, variables, cache=False)
del variables[loop_var]
# Check if the user is doing some operation that doesn't take
# name/pkg or the name/pkg field doesn't have any variables
# and thus the items can't be squashed
if template_no_item != template_with_item:
if self._task.loop_with and self._task.loop_with not in ('items', 'list'):
value_text = "\"{{ query('%s', %r) }}\"" % (self._task.loop_with, self._task.loop)
else:
value_text = '%r' % self._task.loop
# Without knowing the data structure well, it's easiest to strip python2 unicode
# literals after stringifying
value_text = re.sub(r"\bu'", "'", value_text)
display.deprecated(
'Invoking "%s" only once while using a loop via squash_actions is deprecated. '
'Instead of using a loop to supply multiple items and specifying `%s: "%s"`, '
'please use `%s: %s` and remove the loop' % (self._task.action, found, name, found, value_text),
version='2.11'
)
for item in items:
variables[loop_var] = item
if self._task.evaluate_conditional(templar, variables):
new_item = templar.template(name, cache=False)
final_items.append(new_item)
self._task.args['name'] = final_items
# Wrap this in a list so that the calling function loop
# executes exactly once
return [final_items]
else:
# Restore the name parameter
self._task.args['name'] = name
# elif:
# Right now we only optimize single entries. In the future we
# could optimize more types:
# * lists can be squashed together
# * dicts could squash entries that match in all cases except the
# name or pkg field.
except Exception:
# Squashing is an optimization. If it fails for any reason,
# simply use the unoptimized list of items.
# Restore the name parameter
if name is not None:
self._task.args['name'] = name
return items
def _execute(self, variables=None):
'''
The primary workhorse of the executor system, this runs the task
on the specified host (which may be the delegated_to host) and handles
the retry/until and block rescue/always execution
'''
if variables is None:
variables = self._job_vars
templar = Templar(loader=self._loader, shared_loader_obj=self._shared_loader_obj, variables=variables)
context_validation_error = None
try:
# apply the given task's information to the connection info,
# which may override some fields already set by the play or
# the options specified on the command line
self._play_context = self._play_context.set_task_and_variable_override(task=self._task, variables=variables, templar=templar)
# fields set from the play/task may be based on variables, so we have to
# do the same kind of post validation step on it here before we use it.
self._play_context.post_validate(templar=templar)
# now that the play context is finalized, if the remote_addr is not set
# default to using the host's address field as the remote address
if not self._play_context.remote_addr:
self._play_context.remote_addr = self._host.address
# We also add "magic" variables back into the variables dict to make sure
# a certain subset of variables exist.
self._play_context.update_vars(variables)
# FIXME: update connection/shell plugin options
except AnsibleError as e:
# save the error, which we'll raise later if we don't end up
# skipping this task during the conditional evaluation step
context_validation_error = e
# Evaluate the conditional (if any) for this task, which we do before running
# the final task post-validation. We do this before the post validation due to
# the fact that the conditional may specify that the task be skipped due to a
# variable not being present which would otherwise cause validation to fail
try:
if not self._task.evaluate_conditional(templar, variables):
display.debug("when evaluation is False, skipping this task")
return dict(changed=False, skipped=True, skip_reason='Conditional result was False', _ansible_no_log=self._play_context.no_log)
except AnsibleError:
# loop error takes precedence
if self._loop_eval_error is not None:
raise self._loop_eval_error # pylint: disable=raising-bad-type
raise
# Not skipping, if we had loop error raised earlier we need to raise it now to halt the execution of this task
if self._loop_eval_error is not None:
raise self._loop_eval_error # pylint: disable=raising-bad-type
# if we ran into an error while setting up the PlayContext, raise it now
if context_validation_error is not None:
raise context_validation_error # pylint: disable=raising-bad-type
# if this task is a TaskInclude, we just return now with a success code so the
# main thread can expand the task list for the given host
if self._task.action in ('include', 'include_tasks'):
include_args = self._task.args.copy()
include_file = include_args.pop('_raw_params', None)
if not include_file:
return dict(failed=True, msg="No include file was specified to the include")
include_file = templar.template(include_file)
return dict(include=include_file, include_args=include_args)
# if this task is a IncludeRole, we just return now with a success code so the main thread can expand the task list for the given host
elif self._task.action == 'include_role':
include_args = self._task.args.copy()
return dict(include_args=include_args)
# Now we do final validation on the task, which sets all fields to their final values.
self._task.post_validate(templar=templar)
if '_variable_params' in self._task.args:
variable_params = self._task.args.pop('_variable_params')
if isinstance(variable_params, dict):
if C.INJECT_FACTS_AS_VARS:
display.warning("Using a variable for a task's 'args' is unsafe in some situations "
"(see https://docs.ansible.com/ansible/devel/reference_appendices/faq.html#argsplat-unsafe)")
variable_params.update(self._task.args)
self._task.args = variable_params
# get the connection and the handler for this execution
if (not self._connection or
not getattr(self._connection, 'connected', False) or
self._play_context.remote_addr != self._connection._play_context.remote_addr):
self._connection = self._get_connection(variables=variables, templar=templar)
else:
# if connection is reused, its _play_context is no longer valid and needs
# to be replaced with the one templated above, in case other data changed
self._connection._play_context = self._play_context
self._set_connection_options(variables, templar)
# get handler
self._handler = self._get_action_handler(connection=self._connection, templar=templar)
# Apply default params for action/module, if present
self._task.args = get_action_args_with_defaults(self._task.action, self._task.args, self._task.module_defaults, templar)
# And filter out any fields which were set to default(omit), and got the omit token value
omit_token = variables.get('omit')
if omit_token is not None:
self._task.args = remove_omit(self._task.args, omit_token)
# Read some values from the task, so that we can modify them if need be
if self._task.until:
retries = self._task.retries
if retries is None:
retries = 3
elif retries <= 0:
retries = 1
else:
retries += 1
else:
retries = 1
delay = self._task.delay
if delay < 0:
delay = 1
# make a copy of the job vars here, in case we need to update them
# with the registered variable value later on when testing conditions
vars_copy = variables.copy()
display.debug("starting attempt loop")
result = None
for attempt in xrange(1, retries + 1):
display.debug("running the handler")
try:
result = self._handler.run(task_vars=variables)
except AnsibleActionSkip as e:
return dict(skipped=True, msg=to_text(e))
except AnsibleActionFail as e:
return dict(failed=True, msg=to_text(e))
except AnsibleConnectionFailure as e:
return dict(unreachable=True, msg=to_text(e))
display.debug("handler run complete")
# preserve no log
result["_ansible_no_log"] = self._play_context.no_log
# update the local copy of vars with the registered value, if specified,
# or any facts which may have been generated by the module execution
if self._task.register:
if not isidentifier(self._task.register):
raise AnsibleError("Invalid variable name in 'register' specified: '%s'" % self._task.register)
vars_copy[self._task.register] = wrap_var(result)
if self._task.async_val > 0:
if self._task.poll > 0 and not result.get('skipped') and not result.get('failed'):
result = self._poll_async_result(result=result, templar=templar, task_vars=vars_copy)
# FIXME callback 'v2_runner_on_async_poll' here
# ensure no log is preserved
result["_ansible_no_log"] = self._play_context.no_log
# helper methods for use below in evaluating changed/failed_when
def _evaluate_changed_when_result(result):
if self._task.changed_when is not None and self._task.changed_when:
cond = Conditional(loader=self._loader)
cond.when = self._task.changed_when
result['changed'] = cond.evaluate_conditional(templar, vars_copy)
def _evaluate_failed_when_result(result):
if self._task.failed_when:
cond = Conditional(loader=self._loader)
cond.when = self._task.failed_when
failed_when_result = cond.evaluate_conditional(templar, vars_copy)
result['failed_when_result'] = result['failed'] = failed_when_result
else:
failed_when_result = False
return failed_when_result
if 'ansible_facts' in result:
if self._task.action in ('set_fact', 'include_vars'):
vars_copy.update(result['ansible_facts'])
else:
# TODO: cleaning of facts should eventually become part of taskresults instead of vars
af = wrap_var(result['ansible_facts'])
vars_copy.update(namespace_facts(af))
if C.INJECT_FACTS_AS_VARS:
vars_copy.update(clean_facts(af))
# set the failed property if it was missing.
if 'failed' not in result:
# rc is here for backwards compatibility and modules that use it instead of 'failed'
if 'rc' in result and result['rc'] not in [0, "0"]:
result['failed'] = True
else:
result['failed'] = False
# Make attempts and retries available early to allow their use in changed/failed_when
if self._task.until:
result['attempts'] = attempt
# set the changed property if it was missing.
if 'changed' not in result:
result['changed'] = False
# re-update the local copy of vars with the registered value, if specified,
# or any facts which may have been generated by the module execution
# This gives changed/failed_when access to additional recently modified
# attributes of result
if self._task.register:
vars_copy[self._task.register] = wrap_var(result)
# if we didn't skip this task, use the helpers to evaluate the changed/
# failed_when properties
if 'skipped' not in result:
_evaluate_changed_when_result(result)
_evaluate_failed_when_result(result)
if retries > 1:
cond = Conditional(loader=self._loader)
cond.when = self._task.until
if cond.evaluate_conditional(templar, vars_copy):
break
else:
# no conditional check, or it failed, so sleep for the specified time
if attempt < retries:
result['_ansible_retry'] = True
result['retries'] = retries
display.debug('Retrying task, attempt %d of %d' % (attempt, retries))
self._final_q.put(TaskResult(self._host.name, self._task._uuid, result, task_fields=self._task.dump_attrs()), block=False)
time.sleep(delay)
self._handler = self._get_action_handler(connection=self._connection, templar=templar)
else:
if retries > 1:
# we ran out of attempts, so mark the result as failed
result['attempts'] = retries - 1
result['failed'] = True
# do the final update of the local variables here, for both registered
# values and any facts which may have been created
if self._task.register:
variables[self._task.register] = wrap_var(result)
if 'ansible_facts' in result:
if self._task.action in ('set_fact', 'include_vars'):
variables.update(result['ansible_facts'])
else:
# TODO: cleaning of facts should eventually become part of taskresults instead of vars
af = wrap_var(result['ansible_facts'])
variables.update(namespace_facts(af))
if C.INJECT_FACTS_AS_VARS:
variables.update(clean_facts(af))
# save the notification target in the result, if it was specified, as
# this task may be running in a loop in which case the notification
# may be item-specific, ie. "notify: service {{item}}"
if self._task.notify is not None:
result['_ansible_notify'] = self._task.notify
# add the delegated vars to the result, so we can reference them
# on the results side without having to do any further templating
# FIXME: we only want a limited set of variables here, so this is currently
# hardcoded but should be possibly fixed if we want more or if
# there is another source of truth we can use
delegated_vars = variables.get('ansible_delegated_vars', dict()).get(self._task.delegate_to, dict()).copy()
if len(delegated_vars) > 0:
result["_ansible_delegated_vars"] = {'ansible_delegated_host': self._task.delegate_to}
for k in ('ansible_host', ):
result["_ansible_delegated_vars"][k] = delegated_vars.get(k)
# and return
display.debug("attempt loop complete, returning result")
return result
def _poll_async_result(self, result, templar, task_vars=None):
'''
Polls for the specified JID to be complete
'''
if task_vars is None:
task_vars = self._job_vars
async_jid = result.get('ansible_job_id')
if async_jid is None:
return dict(failed=True, msg="No job id was returned by the async task")
# Create a new pseudo-task to run the async_status module, and run
# that (with a sleep for "poll" seconds between each retry) until the
# async time limit is exceeded.
async_task = Task().load(dict(action='async_status jid=%s' % async_jid, environment=self._task.environment))
# FIXME: this is no longer the case, normal takes care of all, see if this can just be generalized
# Because this is an async task, the action handler is async. However,
# we need the 'normal' action handler for the status check, so get it
# now via the action_loader
async_handler = self._shared_loader_obj.action_loader.get(
'async_status',
task=async_task,
connection=self._connection,
play_context=self._play_context,
loader=self._loader,
templar=templar,
shared_loader_obj=self._shared_loader_obj,
)
time_left = self._task.async_val
while time_left > 0:
time.sleep(self._task.poll)
try:
async_result = async_handler.run(task_vars=task_vars)
# We do not bail out of the loop in cases where the failure
# is associated with a parsing error. The async_runner can
# have issues which result in a half-written/unparseable result
# file on disk, which manifests to the user as a timeout happening
# before it's time to timeout.
if (int(async_result.get('finished', 0)) == 1 or
('failed' in async_result and async_result.get('_ansible_parsed', False)) or
'skipped' in async_result):
break
except Exception as e:
# Connections can raise exceptions during polling (eg, network bounce, reboot); these should be non-fatal.
# On an exception, call the connection's reset method if it has one
# (eg, drop/recreate WinRM connection; some reused connections are in a broken state)
display.vvvv("Exception during async poll, retrying... (%s)" % to_text(e))
display.debug("Async poll exception was:\n%s" % to_text(traceback.format_exc()))
try:
async_handler._connection.reset()
except AttributeError:
pass
# Little hack to raise the exception if we've exhausted the timeout period
time_left -= self._task.poll
if time_left <= 0:
raise
else:
time_left -= self._task.poll
if int(async_result.get('finished', 0)) != 1:
if async_result.get('_ansible_parsed'):
return dict(failed=True, msg="async task did not complete within the requested time - %ss" % self._task.async_val)
else:
return dict(failed=True, msg="async task produced unparseable results", async_result=async_result)
else:
return async_result
def _get_become(self, name):
become = become_loader.get(name)
if not become:
raise AnsibleError("Invalid become method specified, could not find matching plugin: '%s'. "
"Use `ansible-doc -t become -l` to list available plugins." % name)
return become
def _get_connection(self, variables, templar):
'''
Reads the connection property for the host, and returns the
correct connection object from the list of connection plugins
'''
if self._task.delegate_to is not None:
# since we're delegating, we don't want to use interpreter values
# which would have been set for the original target host
for i in list(variables.keys()):
if isinstance(i, string_types) and i.startswith('ansible_') and i.endswith('_interpreter'):
del variables[i]
# now replace the interpreter values with those that may have come
# from the delegated-to host
delegated_vars = variables.get('ansible_delegated_vars', dict()).get(self._task.delegate_to, dict())
if isinstance(delegated_vars, dict):
for i in delegated_vars:
if isinstance(i, string_types) and i.startswith("ansible_") and i.endswith("_interpreter"):
variables[i] = delegated_vars[i]
# load connection
conn_type = self._play_context.connection
connection = self._shared_loader_obj.connection_loader.get(
conn_type,
self._play_context,
self._new_stdin,
task_uuid=self._task._uuid,
ansible_playbook_pid=to_text(os.getppid())
)
if not connection:
raise AnsibleError("the connection plugin '%s' was not found" % conn_type)
# load become plugin if needed
become_plugin = None
if self._play_context.become:
become_plugin = self._get_become(self._play_context.become_method)
if getattr(become_plugin, 'require_tty', False) and not getattr(connection, 'has_tty', False):
raise AnsibleError(
"The '%s' connection does not provide a tty which is required for the selected "
"become plugin: %s." % (conn_type, become_plugin.name)
)
try:
connection.set_become_plugin(become_plugin)
except AttributeError:
# Connection plugin does not support set_become_plugin
pass
# Backwards compat for connection plugins that don't support become plugins
# Just do this unconditionally for now, we could move it inside of the
# AttributeError above later
self._play_context.set_become_plugin(become_plugin)
# FIXME: remove once all plugins pull all data from self._options
self._play_context.set_attributes_from_plugin(connection)
if any(((connection.supports_persistence and C.USE_PERSISTENT_CONNECTIONS), connection.force_persistence)):
self._play_context.timeout = connection.get_option('persistent_command_timeout')
display.vvvv('attempting to start connection', host=self._play_context.remote_addr)
display.vvvv('using connection plugin %s' % connection.transport, host=self._play_context.remote_addr)
options = self._get_persistent_connection_options(connection, variables, templar)
socket_path = start_connection(self._play_context, options)
display.vvvv('local domain socket path is %s' % socket_path, host=self._play_context.remote_addr)
setattr(connection, '_socket_path', socket_path)
return connection
def _get_persistent_connection_options(self, connection, variables, templar):
final_vars = combine_vars(variables, variables.get('ansible_delegated_vars', dict()).get(self._task.delegate_to, dict()))
option_vars = C.config.get_plugin_vars('connection', connection._load_name)
plugin = connection._sub_plugin
if plugin['type'] != 'external':
option_vars.extend(C.config.get_plugin_vars(plugin['type'], plugin['name']))
options = {}
for k in option_vars:
if k in final_vars:
options[k] = templar.template(final_vars[k])
return options
def _set_plugin_options(self, plugin_type, variables, templar, task_keys):
try:
plugin = getattr(self._connection, '_%s' % plugin_type)
except AttributeError:
# Some plugins are assigned to private attrs, ``become`` is not
plugin = getattr(self._connection, plugin_type)
option_vars = C.config.get_plugin_vars(plugin_type, plugin._load_name)
options = {}
for k in option_vars:
if k in variables:
options[k] = templar.template(variables[k])
# TODO move to task method?
plugin.set_options(task_keys=task_keys, var_options=options)
def _set_connection_options(self, variables, templar):
# Keep the pre-delegate values for these keys
PRESERVE_ORIG = ('inventory_hostname',)
# create copy with delegation built in
final_vars = combine_vars(
variables,
variables.get('ansible_delegated_vars', {}).get(self._task.delegate_to, {})
)
# grab list of usable vars for this plugin
option_vars = C.config.get_plugin_vars('connection', self._connection._load_name)
# create dict of 'templated vars'
options = {'_extras': {}}
for k in option_vars:
if k in PRESERVE_ORIG:
options[k] = templar.template(variables[k])
elif k in final_vars:
options[k] = templar.template(final_vars[k])
# add extras if plugin supports them
if getattr(self._connection, 'allow_extras', False):
for k in final_vars:
if k.startswith('ansible_%s_' % self._connection._load_name) and k not in options:
options['_extras'][k] = templar.template(final_vars[k])
task_keys = self._task.dump_attrs()
# set options with 'templated vars' specific to this plugin and dependant ones
self._connection.set_options(task_keys=task_keys, var_options=options)
self._set_plugin_options('shell', final_vars, templar, task_keys)
if self._connection.become is not None:
# FIXME: find alternate route to provide passwords,
# keep out of play objects to avoid accidental disclosure
task_keys['become_pass'] = self._play_context.become_pass
self._set_plugin_options('become', final_vars, templar, task_keys)
# FOR BACKWARDS COMPAT:
for option in ('become_user', 'become_flags', 'become_exe'):
try:
setattr(self._play_context, option, self._connection.become.get_option(option))
except KeyError:
pass # some plugins don't support all base flags
self._play_context.prompt = self._connection.become.prompt
def _get_action_handler(self, connection, templar):
'''
Returns the correct action plugin to handle the requestion task action
'''
module_prefix = self._task.action.split('_')[0]
collections = self._task.collections
# let action plugin override module, fallback to 'normal' action plugin otherwise
if self._shared_loader_obj.action_loader.has_plugin(self._task.action, collection_list=collections):
handler_name = self._task.action
# FIXME: is this code path even live anymore? check w/ networking folks; it trips sometimes when it shouldn't
elif all((module_prefix in C.NETWORK_GROUP_MODULES, module_prefix in self._shared_loader_obj.action_loader)):
handler_name = module_prefix
else:
# FUTURE: once we're comfortable with collections impl, preface this action with ansible.builtin so it can't be hijacked
handler_name = 'normal'
collections = None # until then, we don't want the task's collection list to be consulted; use the builtin
handler = self._shared_loader_obj.action_loader.get(
handler_name,
task=self._task,
connection=connection,
play_context=self._play_context,
loader=self._loader,
templar=templar,
shared_loader_obj=self._shared_loader_obj,
collection_list=collections
)
if not handler:
raise AnsibleError("the handler '%s' was not found" % handler_name)
return handler
def start_connection(play_context, variables):
'''
Starts the persistent connection
'''
candidate_paths = [C.ANSIBLE_CONNECTION_PATH or os.path.dirname(sys.argv[0])]
candidate_paths.extend(os.environ['PATH'].split(os.pathsep))
for dirname in candidate_paths:
ansible_connection = os.path.join(dirname, 'ansible-connection')
if os.path.isfile(ansible_connection):
break
else:
raise AnsibleError("Unable to find location of 'ansible-connection'. "
"Please set or check the value of ANSIBLE_CONNECTION_PATH")
env = os.environ.copy()
env.update({
'ANSIBLE_BECOME_PLUGINS': become_loader.print_paths(),
'ANSIBLE_CLICONF_PLUGINS': cliconf_loader.print_paths(),
'ANSIBLE_CONNECTION_PLUGINS': connection_loader.print_paths(),
'ANSIBLE_HTTPAPI_PLUGINS': httpapi_loader.print_paths(),
'ANSIBLE_NETCONF_PLUGINS': netconf_loader.print_paths(),
'ANSIBLE_TERMINAL_PLUGINS': terminal_loader.print_paths(),
})
python = sys.executable
master, slave = pty.openpty()
p = subprocess.Popen(
[python, ansible_connection, to_text(os.getppid())],
stdin=slave, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env
)
os.close(slave)
# We need to set the pty into noncanonical mode. This ensures that we
# can receive lines longer than 4095 characters (plus newline) without
# truncating.
old = termios.tcgetattr(master)
new = termios.tcgetattr(master)
new[3] = new[3] & ~termios.ICANON
try:
termios.tcsetattr(master, termios.TCSANOW, new)
write_to_file_descriptor(master, variables)
write_to_file_descriptor(master, play_context.serialize())
(stdout, stderr) = p.communicate()
finally:
termios.tcsetattr(master, termios.TCSANOW, old)
os.close(master)
if p.returncode == 0:
result = json.loads(to_text(stdout, errors='surrogate_then_replace'))
else:
try:
result = json.loads(to_text(stderr, errors='surrogate_then_replace'))
except getattr(json.decoder, 'JSONDecodeError', ValueError):
# JSONDecodeError only available on Python 3.5+
result = {'error': to_text(stderr, errors='surrogate_then_replace')}
if 'messages' in result:
for level, message in result['messages']:
if level == 'log':
display.display(message, log_only=True)
elif level in ('debug', 'v', 'vv', 'vvv', 'vvvv', 'vvvvv', 'vvvvvv'):
getattr(display, level)(message, host=play_context.remote_addr)
else:
if hasattr(display, level):
getattr(display, level)(message)
else:
display.vvvv(message, host=play_context.remote_addr)
if 'error' in result:
if play_context.verbosity > 2:
if result.get('exception'):
msg = "The full traceback is:\n" + result['exception']
display.display(msg, color=C.COLOR_ERROR)
raise AnsibleError(result['error'])
return result['socket_path']
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,820 |
Templated loop_var not defined when looping include_tasks
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
<!--- Explain the problem briefly below -->
When looping `include_tasks`, the loop control `loop_var` property is not defined in the included task, when the `loop_var` property has been assigned with a template.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
- loop_var
- include_tasks
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.8.1
config file = /playbooks/ansible.cfg
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.7/site-packages/ansible
executable location = /usr/local/bin/ansible
python version = 3.7.3 (default, Jun 11 2019, 01:05:09) [GCC 6.3.0 20170516]
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
Redhat7
Archlinux
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```yaml
---
# main.yml
- hosts: localhost
vars:
loop_var_name: custom_var
tasks:
- include_tasks: looped-include.yml
loop:
- first
- second
loop_control:
loop_var: "{{ loop_var_name }}"
```
```yaml
---
# looped-include.yml
- name: Print looped var
debug:
var: custom_var
- name: Loop default item var
debug:
var: item
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
We expect the variabe `custom_var` to be the looped variable, and `item` to be undefined.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
Neither `custom_var` nor `item` are defined in the looped included task.
<!--- Paste verbatim command output between quotes -->
```paste below
PLAY [localhost] *****************************************************************************************
TASK [Gathering Facts] ***********************************************************************************
ok: [localhost]
included: /ansible-bug/looped-include.yml for localhost
included: /ansible-bug/looped-include.yml for localhost
TASK [Print looped var] **********************************************************************************
ok: [localhost] =>
custom_var: VARIABLE IS NOT DEFINED!
TASK [Loop default item var] *****************************************************************************
ok: [localhost] =>
item: VARIABLE IS NOT DEFINED!
TASK [Print looped var] **********************************************************************************
ok: [localhost] =>
custom_var: VARIABLE IS NOT DEFINED!
TASK [Loop default item var] *****************************************************************************
ok: [localhost] =>
item: VARIABLE IS NOT DEFINED!
```
|
https://github.com/ansible/ansible/issues/58820
|
https://github.com/ansible/ansible/pull/58866
|
ad490573306864f8596f9e9af49e69f70d8f15d0
|
7346b699eec99d7279da4175b99f07e08f0de283
| 2019-07-08T09:51:03Z |
python
| 2019-07-10T11:49:24Z |
lib/ansible/playbook/included_file.py
|
# (c) 2012-2014, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ansible.errors import AnsibleError
from ansible.module_utils._text import to_text
from ansible.playbook.task_include import TaskInclude
from ansible.playbook.role_include import IncludeRole
from ansible.template import Templar
from ansible.utils.display import Display
display = Display()
class IncludedFile:
def __init__(self, filename, args, vars, task, is_role=False):
self._filename = filename
self._args = args
self._vars = vars
self._task = task
self._hosts = []
self._is_role = is_role
def add_host(self, host):
if host not in self._hosts:
self._hosts.append(host)
return
raise ValueError()
def __eq__(self, other):
return (other._filename == self._filename and
other._args == self._args and
other._vars == self._vars and
other._task._parent._uuid == self._task._parent._uuid)
def __repr__(self):
return "%s (args=%s vars=%s): %s" % (self._filename, self._args, self._vars, self._hosts)
@staticmethod
def process_include_results(results, iterator, loader, variable_manager):
included_files = []
task_vars_cache = {}
for res in results:
original_host = res._host
original_task = res._task
if original_task.action in ('include', 'include_tasks', 'include_role'):
if original_task.loop:
if 'results' not in res._result:
continue
include_results = res._result['results']
else:
include_results = [res._result]
for include_result in include_results:
# if the task result was skipped or failed, continue
if 'skipped' in include_result and include_result['skipped'] or 'failed' in include_result and include_result['failed']:
continue
cache_key = (iterator._play, original_host, original_task)
try:
task_vars = task_vars_cache[cache_key]
except KeyError:
task_vars = task_vars_cache[cache_key] = variable_manager.get_vars(play=iterator._play, host=original_host, task=original_task)
include_args = include_result.get('include_args', dict())
special_vars = {}
loop_var = 'item'
index_var = None
if original_task.loop_control:
loop_var = original_task.loop_control.loop_var
index_var = original_task.loop_control.index_var
if loop_var in include_result:
task_vars[loop_var] = special_vars[loop_var] = include_result[loop_var]
if index_var and index_var in include_result:
task_vars[index_var] = special_vars[index_var] = include_result[index_var]
if '_ansible_item_label' in include_result:
task_vars['_ansible_item_label'] = special_vars['_ansible_item_label'] = include_result['_ansible_item_label']
if original_task.no_log and '_ansible_no_log' not in include_args:
task_vars['_ansible_no_log'] = special_vars['_ansible_no_log'] = original_task.no_log
# get search path for this task to pass to lookup plugins that may be used in pathing to
# the included file
task_vars['ansible_search_path'] = original_task.get_search_path()
# ensure basedir is always in (dwim already searches here but we need to display it)
if loader.get_basedir() not in task_vars['ansible_search_path']:
task_vars['ansible_search_path'].append(loader.get_basedir())
templar = Templar(loader=loader, variables=task_vars)
if original_task.action in ('include', 'include_tasks'):
include_file = None
if original_task:
if original_task.static:
continue
if original_task._parent:
# handle relative includes by walking up the list of parent include
# tasks and checking the relative result to see if it exists
parent_include = original_task._parent
cumulative_path = None
while parent_include is not None:
if not isinstance(parent_include, TaskInclude):
parent_include = parent_include._parent
continue
if isinstance(parent_include, IncludeRole):
parent_include_dir = parent_include._role_path
else:
try:
parent_include_dir = os.path.dirname(templar.template(parent_include.args.get('_raw_params')))
except AnsibleError as e:
parent_include_dir = ''
display.warning(
'Templating the path of the parent %s failed. The path to the '
'included file may not be found. '
'The error was: %s.' % (original_task.action, to_text(e))
)
if cumulative_path is not None and not os.path.isabs(cumulative_path):
cumulative_path = os.path.join(parent_include_dir, cumulative_path)
else:
cumulative_path = parent_include_dir
include_target = templar.template(include_result['include'])
if original_task._role:
new_basedir = os.path.join(original_task._role._role_path, 'tasks', cumulative_path)
candidates = [loader.path_dwim_relative(original_task._role._role_path, 'tasks', include_target),
loader.path_dwim_relative(new_basedir, 'tasks', include_target)]
for include_file in candidates:
try:
# may throw OSError
os.stat(include_file)
# or select the task file if it exists
break
except OSError:
pass
else:
include_file = loader.path_dwim_relative(loader.get_basedir(), cumulative_path, include_target)
if os.path.exists(include_file):
break
else:
parent_include = parent_include._parent
if include_file is None:
if original_task._role:
include_target = templar.template(include_result['include'])
include_file = loader.path_dwim_relative(original_task._role._role_path, 'tasks', include_target)
else:
include_file = loader.path_dwim(include_result['include'])
include_file = templar.template(include_file)
inc_file = IncludedFile(include_file, include_args, special_vars, original_task)
else:
# template the included role's name here
role_name = include_args.pop('name', include_args.pop('role', None))
if role_name is not None:
role_name = templar.template(role_name)
new_task = original_task.copy()
new_task._role_name = role_name
for from_arg in new_task.FROM_ARGS:
if from_arg in include_args:
from_key = from_arg.replace('_from', '')
new_task._from_files[from_key] = templar.template(include_args.pop(from_arg))
inc_file = IncludedFile(role_name, include_args, special_vars, new_task, is_role=True)
idx = 0
orig_inc_file = inc_file
while 1:
try:
pos = included_files[idx:].index(orig_inc_file)
# pos is relative to idx since we are slicing
# use idx + pos due to relative indexing
inc_file = included_files[idx + pos]
except ValueError:
included_files.append(orig_inc_file)
inc_file = orig_inc_file
try:
inc_file.add_host(original_host)
except ValueError:
# The host already exists for this include, advance forward, this is a new include
idx += pos + 1
else:
break
return included_files
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,820 |
Templated loop_var not defined when looping include_tasks
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
<!--- Explain the problem briefly below -->
When looping `include_tasks`, the loop control `loop_var` property is not defined in the included task, when the `loop_var` property has been assigned with a template.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
- loop_var
- include_tasks
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.8.1
config file = /playbooks/ansible.cfg
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.7/site-packages/ansible
executable location = /usr/local/bin/ansible
python version = 3.7.3 (default, Jun 11 2019, 01:05:09) [GCC 6.3.0 20170516]
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
Redhat7
Archlinux
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```yaml
---
# main.yml
- hosts: localhost
vars:
loop_var_name: custom_var
tasks:
- include_tasks: looped-include.yml
loop:
- first
- second
loop_control:
loop_var: "{{ loop_var_name }}"
```
```yaml
---
# looped-include.yml
- name: Print looped var
debug:
var: custom_var
- name: Loop default item var
debug:
var: item
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
We expect the variabe `custom_var` to be the looped variable, and `item` to be undefined.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
Neither `custom_var` nor `item` are defined in the looped included task.
<!--- Paste verbatim command output between quotes -->
```paste below
PLAY [localhost] *****************************************************************************************
TASK [Gathering Facts] ***********************************************************************************
ok: [localhost]
included: /ansible-bug/looped-include.yml for localhost
included: /ansible-bug/looped-include.yml for localhost
TASK [Print looped var] **********************************************************************************
ok: [localhost] =>
custom_var: VARIABLE IS NOT DEFINED!
TASK [Loop default item var] *****************************************************************************
ok: [localhost] =>
item: VARIABLE IS NOT DEFINED!
TASK [Print looped var] **********************************************************************************
ok: [localhost] =>
custom_var: VARIABLE IS NOT DEFINED!
TASK [Loop default item var] *****************************************************************************
ok: [localhost] =>
item: VARIABLE IS NOT DEFINED!
```
|
https://github.com/ansible/ansible/issues/58820
|
https://github.com/ansible/ansible/pull/58866
|
ad490573306864f8596f9e9af49e69f70d8f15d0
|
7346b699eec99d7279da4175b99f07e08f0de283
| 2019-07-08T09:51:03Z |
python
| 2019-07-10T11:49:24Z |
test/integration/targets/loops/tasks/main.yml
|
#
# loop_control/pause
#
- name: Measure time before
shell: date +%s
register: before
- debug:
var: i
with_sequence: count=3
loop_control:
loop_var: i
pause: 2
- name: Measure time after
shell: date +%s
register: after
# since there is 3 rounds, and 2 seconds between, it should last 4 seconds
# we do not test the upper bound, since CI can lag significantly
- assert:
that:
- '(after.stdout |int) - (before.stdout|int) >= 4'
- name: test subsecond pause
block:
- name: Measure time before loop with .5s pause
set_fact:
times: "{{times|default([]) + [ lookup('pipe','date +%s.%3N') ]}}"
with_sequence: count=3
loop_control:
pause: 0.6
- name: ensure lag, since there is 3 rounds, and 0.5 seconds between, it should last 1.2 seconds, but allowing leeway due to CI lag
assert:
that:
- tdiff|float >= 1.2
- tdiff|int < 3
vars:
tdiff: '{{ times[2]|float - times[0]|float }}'
when:
- ansible_facts['distribution'] not in ("MacOSX", "FreeBSD")
#
# Tests of loop syntax with args
#
- name: Test that with_list works with a list
ping:
data: '{{ item }}'
with_list:
- 'Hello World'
- 'Olá Mundo'
register: results
- name: Assert that we ran the module twice with the correct strings
assert:
that:
- 'results["results"][0]["ping"] == "Hello World"'
- 'results["results"][1]["ping"] == "Olá Mundo"'
- name: Test that with_list works with a list inside a variable
ping:
data: '{{ item }}'
with_list: '{{ phrases }}'
register: results2
- name: Assert that we ran the module twice with the correct strings
assert:
that:
- 'results2["results"][0]["ping"] == "Hello World"'
- 'results2["results"][1]["ping"] == "Olá Mundo"'
- name: Test that loop works with a manual list
ping:
data: '{{ item }}'
loop:
- 'Hello World'
- 'Olá Mundo'
register: results3
- name: Assert that we ran the module twice with the correct strings
assert:
that:
- 'results3["results"][0]["ping"] == "Hello World"'
- 'results3["results"][1]["ping"] == "Olá Mundo"'
- name: Test that loop works with a list in a variable
ping:
data: '{{ item }}'
loop: '{{ phrases }}'
register: results4
- name: Assert that we ran the module twice with the correct strings
assert:
that:
- 'results4["results"][0]["ping"] == "Hello World"'
- 'results4["results"][1]["ping"] == "Olá Mundo"'
- name: Test that loop works with a list via the list lookup
ping:
data: '{{ item }}'
loop: '{{ lookup("list", "Hello World", "Olá Mundo", wantlist=True) }}'
register: results5
- name: Assert that we ran the module twice with the correct strings
assert:
that:
- 'results5["results"][0]["ping"] == "Hello World"'
- 'results5["results"][1]["ping"] == "Olá Mundo"'
- name: Test that loop works with a list in a variable via the list lookup
ping:
data: '{{ item }}'
loop: '{{ lookup("list", wantlist=True, *phrases) }}'
register: results6
- name: Assert that we ran the module twice with the correct strings
assert:
that:
- 'results6["results"][0]["ping"] == "Hello World"'
- 'results6["results"][1]["ping"] == "Olá Mundo"'
- name: Test that loop works with a list via the query lookup
ping:
data: '{{ item }}'
loop: '{{ query("list", "Hello World", "Olá Mundo") }}'
register: results7
- name: Assert that we ran the module twice with the correct strings
assert:
that:
- 'results7["results"][0]["ping"] == "Hello World"'
- 'results7["results"][1]["ping"] == "Olá Mundo"'
- name: Test that loop works with a list in a variable via the query lookup
ping:
data: '{{ item }}'
loop: '{{ q("list", *phrases) }}'
register: results8
- name: Assert that we ran the module twice with the correct strings
assert:
that:
- 'results8["results"][0]["ping"] == "Hello World"'
- 'results8["results"][1]["ping"] == "Olá Mundo"'
- name: Test that loop works with a list and keyword args
ping:
data: '{{ item }}'
loop: '{{ q("file", "data1.txt", "data2.txt", lstrip=True) }}'
register: results9
- name: Assert that we ran the module twice with the correct strings
assert:
that:
- 'results9["results"][0]["ping"] == "Hello World"'
- 'results9["results"][1]["ping"] == "Olá Mundo"'
- name: Test that loop works with a list in variable and keyword args
ping:
data: '{{ item }}'
loop: '{{ q("file", lstrip=True, *filenames) }}'
register: results10
- name: Assert that we ran the module twice with the correct strings
assert:
that:
- 'results10["results"][0]["ping"] == "Hello World"'
- 'results10["results"][1]["ping"] == "Olá Mundo"'
#
# loop_control/index_var
#
- name: check that the index var is created and increments as expected
assert:
that: my_idx == item|int
with_sequence: start=0 count=3
loop_control:
index_var: my_idx
- name: check that value of index var matches position of current item in source list
assert:
that: 'test_var.index(item) == my_idx'
vars:
test_var: ['a', 'b', 'c']
with_items: "{{ test_var }}"
loop_control:
index_var: my_idx
- name: check index var with included tasks file
include_tasks: index_var_tasks.yml
with_sequence: start=0 count=3
loop_control:
index_var: my_idx
# The following test cases are to ensure that we don't have a regression on
# GitHub Issue https://github.com/ansible/ansible/issues/35481
#
# This should execute and not cause a RuntimeError
- debug:
msg: "with_dict passed a list: {{item}}"
with_dict: "{{ a_list }}"
register: with_dict_passed_a_list
ignore_errors: True
- assert:
that:
- with_dict_passed_a_list is failed
- debug:
msg: "with_list passed a dict: {{item}}"
with_list: "{{ a_dict }}"
register: with_list_passed_a_dict
ignore_errors: True
- assert:
that:
- with_list_passed_a_dict is failed
- debug:
var: "item"
loop:
- "{{ ansible_search_path }}"
register: loop_search_path
- assert:
that:
- ansible_search_path == loop_search_path.results.0.item
# https://github.com/ansible/ansible/issues/45189
- name: with_X conditional delegate_to shortcircuit on templating error
debug:
msg: "loop"
when: false
delegate_to: localhost
with_list: "{{ fake_var }}"
register: result
failed_when: result is not skipped
- name: loop conditional delegate_to shortcircuit on templating error
debug:
msg: "loop"
when: false
delegate_to: localhost
loop: "{{ fake_var }}"
register: result
failed_when: result is not skipped
- name: Loop on literal empty list
debug:
loop: []
register: literal_empty_list
failed_when: literal_empty_list is not skipped
# https://github.com/ansible/ansible/issues/47372
- name: Loop unsafe list
debug:
var: item
with_items: "{{ things|list|unique }}"
vars:
things:
- !unsafe foo
- !unsafe bar
- name: extended loop info
assert:
that:
- ansible_loop.nextitem == 'orange'
- ansible_loop.index == 1
- ansible_loop.index0 == 0
- ansible_loop.first
- not ansible_loop.last
- ansible_loop.previtem is undefined
- ansible_loop.allitems == ['apple', 'orange', 'banana']
- ansible_loop.revindex == 3
- ansible_loop.revindex0 == 2
- ansible_loop.length == 3
loop:
- apple
- orange
- banana
loop_control:
extended: true
when: item == 'apple'
- name: extended loop info 2
assert:
that:
- ansible_loop.nextitem == 'banana'
- ansible_loop.index == 2
- ansible_loop.index0 == 1
- not ansible_loop.first
- not ansible_loop.last
- ansible_loop.previtem == 'apple'
- ansible_loop.allitems == ['apple', 'orange', 'banana']
- ansible_loop.revindex == 2
- ansible_loop.revindex0 == 1
- ansible_loop.length == 3
loop:
- apple
- orange
- banana
loop_control:
extended: true
when: item == 'orange'
- name: extended loop info 3
assert:
that:
- ansible_loop.nextitem is undefined
- ansible_loop.index == 3
- ansible_loop.index0 == 2
- not ansible_loop.first
- ansible_loop.last
- ansible_loop.previtem == 'orange'
- ansible_loop.allitems == ['apple', 'orange', 'banana']
- ansible_loop.revindex == 1
- ansible_loop.revindex0 == 0
- ansible_loop.length == 3
loop:
- apple
- orange
- banana
loop_control:
extended: true
when: item == 'banana'
- name: Validate the loop_var name
assert:
that:
- ansible_loop_var == 'alvin'
loop:
- 1
loop_control:
loop_var: alvin
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,820 |
Templated loop_var not defined when looping include_tasks
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
<!--- Explain the problem briefly below -->
When looping `include_tasks`, the loop control `loop_var` property is not defined in the included task, when the `loop_var` property has been assigned with a template.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
- loop_var
- include_tasks
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.8.1
config file = /playbooks/ansible.cfg
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.7/site-packages/ansible
executable location = /usr/local/bin/ansible
python version = 3.7.3 (default, Jun 11 2019, 01:05:09) [GCC 6.3.0 20170516]
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
Redhat7
Archlinux
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```yaml
---
# main.yml
- hosts: localhost
vars:
loop_var_name: custom_var
tasks:
- include_tasks: looped-include.yml
loop:
- first
- second
loop_control:
loop_var: "{{ loop_var_name }}"
```
```yaml
---
# looped-include.yml
- name: Print looped var
debug:
var: custom_var
- name: Loop default item var
debug:
var: item
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
We expect the variabe `custom_var` to be the looped variable, and `item` to be undefined.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
Neither `custom_var` nor `item` are defined in the looped included task.
<!--- Paste verbatim command output between quotes -->
```paste below
PLAY [localhost] *****************************************************************************************
TASK [Gathering Facts] ***********************************************************************************
ok: [localhost]
included: /ansible-bug/looped-include.yml for localhost
included: /ansible-bug/looped-include.yml for localhost
TASK [Print looped var] **********************************************************************************
ok: [localhost] =>
custom_var: VARIABLE IS NOT DEFINED!
TASK [Loop default item var] *****************************************************************************
ok: [localhost] =>
item: VARIABLE IS NOT DEFINED!
TASK [Print looped var] **********************************************************************************
ok: [localhost] =>
custom_var: VARIABLE IS NOT DEFINED!
TASK [Loop default item var] *****************************************************************************
ok: [localhost] =>
item: VARIABLE IS NOT DEFINED!
```
|
https://github.com/ansible/ansible/issues/58820
|
https://github.com/ansible/ansible/pull/58866
|
ad490573306864f8596f9e9af49e69f70d8f15d0
|
7346b699eec99d7279da4175b99f07e08f0de283
| 2019-07-08T09:51:03Z |
python
| 2019-07-10T11:49:24Z |
test/integration/targets/loops/tasks/templated_loop_var_tasks.yml
| |
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,933 |
azure_rm_loadbalancer intergration test target causing resource leakage on azure cloud
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
azure_rm_loadbalancer intergration test target causing resource leakage on azure cloud
The specific task to create lb with multiple options is for some reason causing resource leakage on azure cloud account used for ansible-ci testing
The exact reason is still unknown but I want to try to make sure it can get fixed with same task doing operation on two separate lb instead on named ^lbname
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
azure_rm_loadbalancer integration test
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.8.0
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/abehl/.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
python version = 2.7.16 (default, Apr 30 2019, 15:54:43) [GCC 9.0.1 20190312 (Red Hat 9.0.1-0.10)]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```yaml
Running ansible-ci on azure_rm_loadbalancer integration target causes this
In this case PublicIP is is tried to be deleted while LB attached to it
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
Systematic deletion of LB > PublicIP should happen and allow LB and PublicIP to be deleted
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```paste below
Public IP address /subscriptions/6d22db98-3e5f-4ab9-bdf9-2f911a2775f7/resourceGroups/ansible-core-ci-prod-a50bbaf0-0315-4286-815e-2c877e8d4b64-1/providers/Microsoft.Network/publicIPAddresses/pipa26c0a5f585 can not be deleted since it is still allocated to resource /subscriptions/6d22db98-3e5f-4ab9-bdf9-2f911a2775f7/resourceGroups/ansible-core-ci-prod-a50bbaf0-0315-4286-815e-2c877e8d4b64-1/providers/Microsoft.Network/loadBalancers/lbc26c0a5f581/frontendIPConfigurations/frontendipconf0.
```
|
https://github.com/ansible/ansible/issues/58933
|
https://github.com/ansible/ansible/pull/58936
|
15d76d97a94b50d9764cbdf4e5353625f41dc1a5
|
00d7aed56bdbc554dc26b4a32c77e4e9f92cc4ad
| 2019-07-10T15:47:17Z |
python
| 2019-07-10T18:20:35Z |
test/integration/targets/azure_rm_loadbalancer/tasks/main.yml
|
- name: Prepare random number
set_fact:
pipaname: "pipa{{ resource_group | hash('md5') | truncate(7, True, '') }}{{ 1000 | random }}"
pipbname: "pipb{{ resource_group | hash('md5') | truncate(7, True, '') }}{{ 1000 | random }}"
lbvnname: "lbvn{{ resource_group | hash('md5') | truncate(7, True, '') }}{{ 1000 | random }}"
lbname_a: "lba{{ resource_group | hash('md5') | truncate(7, True, '') }}{{ 1000 | random }}"
lbname_b: "lbb{{ resource_group | hash('md5') | truncate(7, True, '') }}{{ 1000 | random }}"
lbname_c: "lbc{{ resource_group | hash('md5') | truncate(7, True, '') }}{{ 1000 | random }}"
lbname_d: "lbd{{ resource_group | hash('md5') | truncate(7, True, '') }}{{ 1000 | random }}"
run_once: yes
- name: create public ip
azure_rm_publicipaddress:
name: "{{ pipbname }}"
sku: Standard
allocation_method: Static
resource_group: '{{ resource_group }}'
- name: create public ip
azure_rm_publicipaddress:
name: "{{ pipaname }}"
resource_group: '{{ resource_group }}'
- name: clear load balancer
azure_rm_loadbalancer:
resource_group: '{{ resource_group }}'
name: "{{ lbname_a }}"
state: absent
- name: create load balancer
azure_rm_loadbalancer:
resource_group: '{{ resource_group }}'
name: "{{ lbname_a }}"
public_ip: "{{ pipaname }}"
register: output
- name: assert load balancer created
assert:
that: output.changed
- name: delete load balancer
azure_rm_loadbalancer:
resource_group: '{{ resource_group }}'
name: "{{ lbname_a }}"
state: absent
register: output
- name: assert load balancer deleted
assert:
that: output.changed
- name: delete load balancer (idempotent)
azure_rm_loadbalancer:
resource_group: '{{ resource_group }}'
name: "{{ lbname_a }}"
state: absent
register: output
- name: assert load balancer deleted (idempotent)
assert:
that: not output.changed
- name: create another load balancer with more options
azure_rm_loadbalancer:
resource_group: '{{ resource_group }}'
name: "{{ lbname_b }}"
sku: Standard
public_ip_address: "{{ pipbname }}"
probe_protocol: Tcp
probe_port: 80
probe_interval: 10
probe_fail_count: 3
protocol: Tcp
load_distribution: Default
frontend_port: 80
backend_port: 8080
idle_timeout: 4
natpool_frontend_port_start: 30
natpool_frontend_port_end: 40
natpool_backend_port: 80
natpool_protocol: Tcp
register: output
- name: assert complex load balancer created
assert:
that:
- output.changed
- output.state.sku.name == 'Standard'
- name: create load balancer again to check idempotency
azure_rm_loadbalancer:
resource_group: '{{ resource_group }}'
name: "{{ lbname_b }}"
sku: Standard
public_ip_address: "{{ pipbname }}"
probe_protocol: Tcp
probe_port: 80
probe_interval: 10
probe_fail_count: 3
protocol: Tcp
load_distribution: Default
frontend_port: 80
backend_port: 8080
idle_timeout: 4
natpool_frontend_port_start: 30
natpool_frontend_port_end: 40
natpool_backend_port: 80
natpool_protocol: Tcp
register: output
- name: assert that output has not changed
assert:
that:
- not output.changed
- name: create load balancer again to check idempotency - change something
azure_rm_loadbalancer:
resource_group: '{{ resource_group }}'
name: "{{ lbname_b }}"
sku: Standard
public_ip_address: "{{ pipbname }}"
probe_protocol: Tcp
probe_port: 80
probe_interval: 10
probe_fail_count: 3
protocol: Tcp
load_distribution: Default
frontend_port: 81
backend_port: 8080
idle_timeout: 4
natpool_frontend_port_start: 30
natpool_frontend_port_end: 40
natpool_backend_port: 80
natpool_protocol: Tcp
register: output
- name: assert that output has changed
assert:
that:
- output.changed
- name: delete load balancer
azure_rm_loadbalancer:
resource_group: '{{ resource_group }}'
name: "{{ lbname_b }}"
state: absent
- name: create load balancer with multiple parameters
azure_rm_loadbalancer:
resource_group: '{{ resource_group }}'
name: "{{ lbname_c }}"
frontend_ip_configurations:
- name: frontendipconf0
public_ip_address: "{{ pipaname }}"
backend_address_pools:
- name: backendaddrpool0
probes:
- name: prob0
port: 80
inbound_nat_pools:
- name: inboundnatpool0
frontend_ip_configuration_name: frontendipconf0
protocol: Tcp
frontend_port_range_start: 80
frontend_port_range_end: 81
backend_port: 8080
load_balancing_rules:
- name: lbrbalancingrule0
frontend_ip_configuration: frontendipconf0
backend_address_pool: backendaddrpool0
frontend_port: 80
backend_port: 80
probe: prob0
register: output
- name: assert complex load balancer created
assert:
that: output.changed
- name: delete load balancer
azure_rm_loadbalancer:
resource_group: '{{ resource_group }}'
name: "{{ lbname_c }}"
state: absent
- name: create load balancer with multiple parameters
azure_rm_loadbalancer:
resource_group: '{{ resource_group }}'
name: "{{ lbname_c }}"
frontend_ip_configurations:
- name: frontendipconf0
public_ip_address: "{{ pipaname }}"
backend_address_pools:
- name: backendaddrpool0
probes:
- name: prob0
port: 80
load_balancing_rules:
- name: lbrbalancingrule0
frontend_ip_configuration: frontendipconf0
backend_address_pool: backendaddrpool0
frontend_port: 80
backend_port: 80
probe: prob0
inbound_nat_rules:
- name: inboundnatrule0
backend_port: 8080
protocol: Tcp
frontend_port: 8080
frontend_ip_configuration: frontendipconf0
register: output
- name: assert complex load balancer created
assert:
that: output.changed
- name: delete load balancer
azure_rm_loadbalancer:
resource_group: '{{ resource_group }}'
name: "{{ lbname_c }}"
state: absent
- name: Create virtual network
azure_rm_virtualnetwork:
resource_group: "{{ resource_group }}"
name: "{{ lbvnname }}"
address_prefixes: "10.10.0.0/16"
- name: Add subnet
azure_rm_subnet:
resource_group: "{{ resource_group }}"
name: "lb{{ resource_group | hash('md5') | truncate(7, True, '') }}{{ 1000 | random }}sb"
address_prefix: "10.10.0.0/24"
virtual_network: "{{ lbvnname }}"
register: subnet
- name: create internal loadbalancer
azure_rm_loadbalancer:
resource_group: '{{ resource_group }}'
name: "{{ lbname_d }}"
frontend_ip_configurations:
- name: frontendipconf0
private_ip_address: 10.10.0.10
private_ip_allocation_method: Static
subnet: "{{ subnet.state.id }}"
backend_address_pools:
- name: backendaddrpool0
probes:
- name: prob0
port: 80
inbound_nat_pools:
- name: inboundnatpool0
frontend_ip_configuration_name: frontendipconf0
protocol: Tcp
frontend_port_range_start: 80
frontend_port_range_end: 81
backend_port: 8080
load_balancing_rules:
- name: lbrbalancingrule0
frontend_ip_configuration: frontendipconf0
backend_address_pool: backendaddrpool0
frontend_port: 80
backend_port: 80
probe: prob0
register: output
- name: assert complex load balancer created
assert:
that: output.changed
- name: delete load balancer
azure_rm_loadbalancer:
resource_group: '{{ resource_group }}'
name: "{{ lbname_d }}"
state: absent
- name: cleanup public ip
azure_rm_publicipaddress:
name: "{{ item }}"
resource_group: '{{ resource_group }}'
state: absent
with_items:
- "{{ pipaname }}"
- "{{ pipbname }}"
- name: cleanup subnet
azure_rm_subnet:
resource_group: "{{ resource_group }}"
name: "lb{{ resource_group | hash('md5') | truncate(7, True, '') }}{{ 1000 | random }}sb"
virtual_network: "{{ lbvnname }}"
state: absent
- name: cleanup virtual network
azure_rm_virtualnetwork:
resource_group: "{{ resource_group }}"
name: "{{ lbvnname }}"
state: absent
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,769 |
Hang while executing handler when handler is included and notifies another handler
|
##### SUMMARY
I'll start by saying that this is a bit of a weird one. It seems that when a handler task is included from another handler and notifies yet another handler, ansible generates spurious warnings and then hangs.
Just to confuse things even more, if you remove the variable reference in `name` OR the `notify` from `bar_handler_tasks.yml`, ansible executes normally.
Another thing to note is that this code (or something very much like it) apparently worked properly in Ansible 2.7.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
handlers
##### ANSIBLE VERSION
```
ansible 2.8.1
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/agaffney/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.12 (default, Nov 12 2018, 14:36:49) [GCC 5.4.0 20160609]
```
##### CONFIGURATION
N/A
##### OS / ENVIRONMENT
N/A
##### STEPS TO REPRODUCE
`bar.yml`:
```yaml
- hosts: localhost
gather_facts: no
handlers:
- name: play handler 1
include_tasks: bar_handler_tasks.yml
- name: play handler 2
debug:
msg: play handler 2
tasks:
- name: trigger handler 1
debug:
msg: trigger handler 1
changed_when: true
notify: play handler 1
```
`bar_handler_tasks.yml`:
```yaml
- name: included handler 1 {{ inventory_hostname }}
debug:
msg: included handler 1
- name: included handler 2
debug:
msg: whatever
changed_when: true
notify: play handler 2
```
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
##### ACTUAL RESULTS
```
PLAY [localhost] **************************************************************************************************************************************************************************************************************************************************************
TASK [trigger handler 1] ******************************************************************************************************************************************************************************************************************************************************
changed: [localhost] => {
"msg": "trigger handler 1"
}
RUNNING HANDLER [play handler 1] **********************************************************************************************************************************************************************************************************************************************
included: /tmp/ansible_test/kiwiirc/bar_handler_tasks.yml for localhost
RUNNING HANDLER [included handler 1 {{ inventory_hostname }}] *****************************************************************************************************************************************************************************************************************
ok: [localhost] => {
"msg": "included handler 1"
}
RUNNING HANDLER [included handler 2] ******************************************************************************************************************************************************************************************************************************************
[WARNING]: 'inventory_hostname' is undefined
RUNNING HANDLER [included handler 2] ******************************************************************************************************************************************************************************************************************************************
[ERROR]: User interrupted execution
```
|
https://github.com/ansible/ansible/issues/58769
|
https://github.com/ansible/ansible/pull/58780
|
982a36c915cd776536092b593f06ae2a1ef2462a
|
d1afcbced1c7c2de63a5b01d9fbd59e98d7fb117
| 2019-07-05T14:58:43Z |
python
| 2019-07-10T18:53:56Z |
changelogs/fragments/58769-template-included-handler-names.yml
| |
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,769 |
Hang while executing handler when handler is included and notifies another handler
|
##### SUMMARY
I'll start by saying that this is a bit of a weird one. It seems that when a handler task is included from another handler and notifies yet another handler, ansible generates spurious warnings and then hangs.
Just to confuse things even more, if you remove the variable reference in `name` OR the `notify` from `bar_handler_tasks.yml`, ansible executes normally.
Another thing to note is that this code (or something very much like it) apparently worked properly in Ansible 2.7.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
handlers
##### ANSIBLE VERSION
```
ansible 2.8.1
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/agaffney/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.12 (default, Nov 12 2018, 14:36:49) [GCC 5.4.0 20160609]
```
##### CONFIGURATION
N/A
##### OS / ENVIRONMENT
N/A
##### STEPS TO REPRODUCE
`bar.yml`:
```yaml
- hosts: localhost
gather_facts: no
handlers:
- name: play handler 1
include_tasks: bar_handler_tasks.yml
- name: play handler 2
debug:
msg: play handler 2
tasks:
- name: trigger handler 1
debug:
msg: trigger handler 1
changed_when: true
notify: play handler 1
```
`bar_handler_tasks.yml`:
```yaml
- name: included handler 1 {{ inventory_hostname }}
debug:
msg: included handler 1
- name: included handler 2
debug:
msg: whatever
changed_when: true
notify: play handler 2
```
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
##### ACTUAL RESULTS
```
PLAY [localhost] **************************************************************************************************************************************************************************************************************************************************************
TASK [trigger handler 1] ******************************************************************************************************************************************************************************************************************************************************
changed: [localhost] => {
"msg": "trigger handler 1"
}
RUNNING HANDLER [play handler 1] **********************************************************************************************************************************************************************************************************************************************
included: /tmp/ansible_test/kiwiirc/bar_handler_tasks.yml for localhost
RUNNING HANDLER [included handler 1 {{ inventory_hostname }}] *****************************************************************************************************************************************************************************************************************
ok: [localhost] => {
"msg": "included handler 1"
}
RUNNING HANDLER [included handler 2] ******************************************************************************************************************************************************************************************************************************************
[WARNING]: 'inventory_hostname' is undefined
RUNNING HANDLER [included handler 2] ******************************************************************************************************************************************************************************************************************************************
[ERROR]: User interrupted execution
```
|
https://github.com/ansible/ansible/issues/58769
|
https://github.com/ansible/ansible/pull/58780
|
982a36c915cd776536092b593f06ae2a1ef2462a
|
d1afcbced1c7c2de63a5b01d9fbd59e98d7fb117
| 2019-07-05T14:58:43Z |
python
| 2019-07-10T18:53:56Z |
lib/ansible/plugins/strategy/__init__.py
|
# (c) 2012-2014, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import cmd
import functools
import os
import pprint
import sys
import threading
import time
from collections import deque
from multiprocessing import Lock
from jinja2.exceptions import UndefinedError
from ansible import constants as C
from ansible import context
from ansible.errors import AnsibleError, AnsibleFileNotFound, AnsibleParserError, AnsibleUndefinedVariable
from ansible.executor import action_write_locks
from ansible.executor.process.worker import WorkerProcess
from ansible.executor.task_result import TaskResult
from ansible.inventory.host import Host
from ansible.module_utils.six.moves import queue as Queue
from ansible.module_utils.six import iteritems, itervalues, string_types
from ansible.module_utils._text import to_text
from ansible.module_utils.connection import Connection, ConnectionError
from ansible.playbook.helpers import load_list_of_blocks
from ansible.playbook.included_file import IncludedFile
from ansible.playbook.task_include import TaskInclude
from ansible.plugins.loader import action_loader, connection_loader, filter_loader, lookup_loader, module_loader, test_loader
from ansible.template import Templar
from ansible.utils.display import Display
from ansible.utils.vars import combine_vars
from ansible.vars.clean import strip_internal_keys, module_response_deepcopy
display = Display()
__all__ = ['StrategyBase']
class StrategySentinel:
pass
# TODO: this should probably be in the plugins/__init__.py, with
# a smarter mechanism to set all of the attributes based on
# the loaders created there
class SharedPluginLoaderObj:
'''
A simple object to make pass the various plugin loaders to
the forked processes over the queue easier
'''
def __init__(self):
self.action_loader = action_loader
self.connection_loader = connection_loader
self.filter_loader = filter_loader
self.test_loader = test_loader
self.lookup_loader = lookup_loader
self.module_loader = module_loader
_sentinel = StrategySentinel()
def results_thread_main(strategy):
while True:
try:
result = strategy._final_q.get()
if isinstance(result, StrategySentinel):
break
else:
strategy._results_lock.acquire()
strategy._results.append(result)
strategy._results_lock.release()
except (IOError, EOFError):
break
except Queue.Empty:
pass
def debug_closure(func):
"""Closure to wrap ``StrategyBase._process_pending_results`` and invoke the task debugger"""
@functools.wraps(func)
def inner(self, iterator, one_pass=False, max_passes=None):
status_to_stats_map = (
('is_failed', 'failures'),
('is_unreachable', 'dark'),
('is_changed', 'changed'),
('is_skipped', 'skipped'),
)
# We don't know the host yet, copy the previous states, for lookup after we process new results
prev_host_states = iterator._host_states.copy()
results = func(self, iterator, one_pass=one_pass, max_passes=max_passes)
_processed_results = []
for result in results:
task = result._task
host = result._host
_queued_task_args = self._queued_task_cache.pop((host.name, task._uuid), None)
task_vars = _queued_task_args['task_vars']
play_context = _queued_task_args['play_context']
# Try to grab the previous host state, if it doesn't exist use get_host_state to generate an empty state
try:
prev_host_state = prev_host_states[host.name]
except KeyError:
prev_host_state = iterator.get_host_state(host)
while result.needs_debugger(globally_enabled=self.debugger_active):
next_action = NextAction()
dbg = Debugger(task, host, task_vars, play_context, result, next_action)
dbg.cmdloop()
if next_action.result == NextAction.REDO:
# rollback host state
self._tqm.clear_failed_hosts()
iterator._host_states[host.name] = prev_host_state
for method, what in status_to_stats_map:
if getattr(result, method)():
self._tqm._stats.decrement(what, host.name)
self._tqm._stats.decrement('ok', host.name)
# redo
self._queue_task(host, task, task_vars, play_context)
_processed_results.extend(debug_closure(func)(self, iterator, one_pass))
break
elif next_action.result == NextAction.CONTINUE:
_processed_results.append(result)
break
elif next_action.result == NextAction.EXIT:
# Matches KeyboardInterrupt from bin/ansible
sys.exit(99)
else:
_processed_results.append(result)
return _processed_results
return inner
class StrategyBase:
'''
This is the base class for strategy plugins, which contains some common
code useful to all strategies like running handlers, cleanup actions, etc.
'''
def __init__(self, tqm):
self._tqm = tqm
self._inventory = tqm.get_inventory()
self._workers = tqm.get_workers()
self._variable_manager = tqm.get_variable_manager()
self._loader = tqm.get_loader()
self._final_q = tqm._final_q
self._step = context.CLIARGS.get('step', False)
self._diff = context.CLIARGS.get('diff', False)
self.flush_cache = context.CLIARGS.get('flush_cache', False)
# the task cache is a dictionary of tuples of (host.name, task._uuid)
# used to find the original task object of in-flight tasks and to store
# the task args/vars and play context info used to queue the task.
self._queued_task_cache = {}
# Backwards compat: self._display isn't really needed, just import the global display and use that.
self._display = display
# internal counters
self._pending_results = 0
self._cur_worker = 0
# this dictionary is used to keep track of hosts that have
# outstanding tasks still in queue
self._blocked_hosts = dict()
# this dictionary is used to keep track of hosts that have
# flushed handlers
self._flushed_hosts = dict()
self._results = deque()
self._results_lock = threading.Condition(threading.Lock())
# create the result processing thread for reading results in the background
self._results_thread = threading.Thread(target=results_thread_main, args=(self,))
self._results_thread.daemon = True
self._results_thread.start()
# holds the list of active (persistent) connections to be shutdown at
# play completion
self._active_connections = dict()
self.debugger_active = C.ENABLE_TASK_DEBUGGER
def cleanup(self):
# close active persistent connections
for sock in itervalues(self._active_connections):
try:
conn = Connection(sock)
conn.reset()
except ConnectionError as e:
# most likely socket is already closed
display.debug("got an error while closing persistent connection: %s" % e)
self._final_q.put(_sentinel)
self._results_thread.join()
def run(self, iterator, play_context, result=0):
# execute one more pass through the iterator without peeking, to
# make sure that all of the hosts are advanced to their final task.
# This should be safe, as everything should be ITERATING_COMPLETE by
# this point, though the strategy may not advance the hosts itself.
inv_hosts = self._inventory.get_hosts(iterator._play.hosts, order=iterator._play.order)
[iterator.get_next_task_for_host(host) for host in inv_hosts if host.name not in self._tqm._unreachable_hosts]
# save the failed/unreachable hosts, as the run_handlers()
# method will clear that information during its execution
failed_hosts = iterator.get_failed_hosts()
unreachable_hosts = self._tqm._unreachable_hosts.keys()
display.debug("running handlers")
handler_result = self.run_handlers(iterator, play_context)
if isinstance(handler_result, bool) and not handler_result:
result |= self._tqm.RUN_ERROR
elif not handler_result:
result |= handler_result
# now update with the hosts (if any) that failed or were
# unreachable during the handler execution phase
failed_hosts = set(failed_hosts).union(iterator.get_failed_hosts())
unreachable_hosts = set(unreachable_hosts).union(self._tqm._unreachable_hosts.keys())
# return the appropriate code, depending on the status hosts after the run
if not isinstance(result, bool) and result != self._tqm.RUN_OK:
return result
elif len(unreachable_hosts) > 0:
return self._tqm.RUN_UNREACHABLE_HOSTS
elif len(failed_hosts) > 0:
return self._tqm.RUN_FAILED_HOSTS
else:
return self._tqm.RUN_OK
def get_hosts_remaining(self, play):
return [host for host in self._inventory.get_hosts(play.hosts)
if host.name not in self._tqm._failed_hosts and host.name not in self._tqm._unreachable_hosts]
def get_failed_hosts(self, play):
return [host for host in self._inventory.get_hosts(play.hosts) if host.name in self._tqm._failed_hosts]
def add_tqm_variables(self, vars, play):
'''
Base class method to add extra variables/information to the list of task
vars sent through the executor engine regarding the task queue manager state.
'''
vars['ansible_current_hosts'] = [h.name for h in self.get_hosts_remaining(play)]
vars['ansible_failed_hosts'] = [h.name for h in self.get_failed_hosts(play)]
def _queue_task(self, host, task, task_vars, play_context):
''' handles queueing the task up to be sent to a worker '''
display.debug("entering _queue_task() for %s/%s" % (host.name, task.action))
# Add a write lock for tasks.
# Maybe this should be added somewhere further up the call stack but
# this is the earliest in the code where we have task (1) extracted
# into its own variable and (2) there's only a single code path
# leading to the module being run. This is called by three
# functions: __init__.py::_do_handler_run(), linear.py::run(), and
# free.py::run() so we'd have to add to all three to do it there.
# The next common higher level is __init__.py::run() and that has
# tasks inside of play_iterator so we'd have to extract them to do it
# there.
if task.action not in action_write_locks.action_write_locks:
display.debug('Creating lock for %s' % task.action)
action_write_locks.action_write_locks[task.action] = Lock()
# and then queue the new task
try:
# create a dummy object with plugin loaders set as an easier
# way to share them with the forked processes
shared_loader_obj = SharedPluginLoaderObj()
queued = False
starting_worker = self._cur_worker
while True:
worker_prc = self._workers[self._cur_worker]
if worker_prc is None or not worker_prc.is_alive():
self._queued_task_cache[(host.name, task._uuid)] = {
'host': host,
'task': task,
'task_vars': task_vars,
'play_context': play_context
}
worker_prc = WorkerProcess(self._final_q, task_vars, host, task, play_context, self._loader, self._variable_manager, shared_loader_obj)
self._workers[self._cur_worker] = worker_prc
self._tqm.send_callback('v2_runner_on_start', host, task)
worker_prc.start()
display.debug("worker is %d (out of %d available)" % (self._cur_worker + 1, len(self._workers)))
queued = True
self._cur_worker += 1
if self._cur_worker >= len(self._workers):
self._cur_worker = 0
if queued:
break
elif self._cur_worker == starting_worker:
time.sleep(0.0001)
self._pending_results += 1
except (EOFError, IOError, AssertionError) as e:
# most likely an abort
display.debug("got an error while queuing: %s" % e)
return
display.debug("exiting _queue_task() for %s/%s" % (host.name, task.action))
def get_task_hosts(self, iterator, task_host, task):
if task.run_once:
host_list = [host for host in self._inventory.get_hosts(iterator._play.hosts) if host.name not in self._tqm._unreachable_hosts]
else:
host_list = [task_host]
return host_list
def get_delegated_hosts(self, result, task):
host_name = result.get('_ansible_delegated_vars', {}).get('ansible_delegated_host', None)
if host_name is not None:
actual_host = self._inventory.get_host(host_name)
if actual_host is None:
actual_host = Host(name=host_name)
else:
actual_host = Host(name=task.delegate_to)
return [actual_host]
def get_handler_templar(self, handler_task, iterator):
handler_vars = self._variable_manager.get_vars(play=iterator._play, task=handler_task)
return Templar(loader=self._loader, variables=handler_vars)
@debug_closure
def _process_pending_results(self, iterator, one_pass=False, max_passes=None):
'''
Reads results off the final queue and takes appropriate action
based on the result (executing callbacks, updating state, etc.).
'''
ret_results = []
def get_original_host(host_name):
# FIXME: this should not need x2 _inventory
host_name = to_text(host_name)
if host_name in self._inventory.hosts:
return self._inventory.hosts[host_name]
else:
return self._inventory.get_host(host_name)
def search_handler_blocks_by_name(handler_name, handler_blocks):
# iterate in reversed order since last handler loaded with the same name wins
for handler_block in reversed(handler_blocks):
for handler_task in handler_block.block:
if handler_task.name:
if not handler_task.cached_name:
templar = self.get_handler_templar(handler_task, iterator)
handler_task.name = templar.template(handler_task.name)
handler_task.cached_name = True
try:
# first we check with the full result of get_name(), which may
# include the role name (if the handler is from a role). If that
# is not found, we resort to the simple name field, which doesn't
# have anything extra added to it.
if handler_task.name == handler_name:
return handler_task
else:
if handler_task.get_name() == handler_name:
return handler_task
except (UndefinedError, AnsibleUndefinedVariable):
# We skip this handler due to the fact that it may be using
# a variable in the name that was conditionally included via
# set_fact or some other method, and we don't want to error
# out unnecessarily
continue
return None
cur_pass = 0
while True:
try:
self._results_lock.acquire()
task_result = self._results.popleft()
except IndexError:
break
finally:
self._results_lock.release()
# get the original host and task. We then assign them to the TaskResult for use in callbacks/etc.
original_host = get_original_host(task_result._host)
queue_cache_entry = (original_host.name, task_result._task)
found_task = self._queued_task_cache.get(queue_cache_entry)['task']
original_task = found_task.copy(exclude_parent=True, exclude_tasks=True)
original_task._parent = found_task._parent
original_task.from_attrs(task_result._task_fields)
task_result._host = original_host
task_result._task = original_task
# send callbacks for 'non final' results
if '_ansible_retry' in task_result._result:
self._tqm.send_callback('v2_runner_retry', task_result)
continue
elif '_ansible_item_result' in task_result._result:
if task_result.is_failed() or task_result.is_unreachable():
self._tqm.send_callback('v2_runner_item_on_failed', task_result)
elif task_result.is_skipped():
self._tqm.send_callback('v2_runner_item_on_skipped', task_result)
else:
if 'diff' in task_result._result:
if self._diff or getattr(original_task, 'diff', False):
self._tqm.send_callback('v2_on_file_diff', task_result)
self._tqm.send_callback('v2_runner_item_on_ok', task_result)
continue
if original_task.register:
host_list = self.get_task_hosts(iterator, original_host, original_task)
clean_copy = strip_internal_keys(module_response_deepcopy(task_result._result))
if 'invocation' in clean_copy:
del clean_copy['invocation']
for target_host in host_list:
self._variable_manager.set_nonpersistent_facts(target_host, {original_task.register: clean_copy})
# all host status messages contain 2 entries: (msg, task_result)
role_ran = False
if task_result.is_failed():
role_ran = True
ignore_errors = original_task.ignore_errors
if not ignore_errors:
display.debug("marking %s as failed" % original_host.name)
if original_task.run_once:
# if we're using run_once, we have to fail every host here
for h in self._inventory.get_hosts(iterator._play.hosts):
if h.name not in self._tqm._unreachable_hosts:
state, _ = iterator.get_next_task_for_host(h, peek=True)
iterator.mark_host_failed(h)
state, new_task = iterator.get_next_task_for_host(h, peek=True)
else:
iterator.mark_host_failed(original_host)
# grab the current state and if we're iterating on the rescue portion
# of a block then we save the failed task in a special var for use
# within the rescue/always
state, _ = iterator.get_next_task_for_host(original_host, peek=True)
if iterator.is_failed(original_host) and state and state.run_state == iterator.ITERATING_COMPLETE:
self._tqm._failed_hosts[original_host.name] = True
if state and iterator.get_active_state(state).run_state == iterator.ITERATING_RESCUE:
self._tqm._stats.increment('rescued', original_host.name)
self._variable_manager.set_nonpersistent_facts(
original_host,
dict(
ansible_failed_task=original_task.serialize(),
ansible_failed_result=task_result._result,
),
)
else:
self._tqm._stats.increment('failures', original_host.name)
else:
self._tqm._stats.increment('ok', original_host.name)
self._tqm._stats.increment('ignored', original_host.name)
if 'changed' in task_result._result and task_result._result['changed']:
self._tqm._stats.increment('changed', original_host.name)
self._tqm.send_callback('v2_runner_on_failed', task_result, ignore_errors=ignore_errors)
elif task_result.is_unreachable():
ignore_unreachable = original_task.ignore_unreachable
if not ignore_unreachable:
self._tqm._unreachable_hosts[original_host.name] = True
iterator._play._removed_hosts.append(original_host.name)
else:
self._tqm._stats.increment('skipped', original_host.name)
task_result._result['skip_reason'] = 'Host %s is unreachable' % original_host.name
self._tqm._stats.increment('dark', original_host.name)
self._tqm.send_callback('v2_runner_on_unreachable', task_result)
elif task_result.is_skipped():
self._tqm._stats.increment('skipped', original_host.name)
self._tqm.send_callback('v2_runner_on_skipped', task_result)
else:
role_ran = True
if original_task.loop:
# this task had a loop, and has more than one result, so
# loop over all of them instead of a single result
result_items = task_result._result.get('results', [])
else:
result_items = [task_result._result]
for result_item in result_items:
if '_ansible_notify' in result_item:
if task_result.is_changed():
# The shared dictionary for notified handlers is a proxy, which
# does not detect when sub-objects within the proxy are modified.
# So, per the docs, we reassign the list so the proxy picks up and
# notifies all other threads
for handler_name in result_item['_ansible_notify']:
found = False
# Find the handler using the above helper. First we look up the
# dependency chain of the current task (if it's from a role), otherwise
# we just look through the list of handlers in the current play/all
# roles and use the first one that matches the notify name
target_handler = search_handler_blocks_by_name(handler_name, iterator._play.handlers)
if target_handler is not None:
found = True
if target_handler.notify_host(original_host):
self._tqm.send_callback('v2_playbook_on_notify', target_handler, original_host)
for listening_handler_block in iterator._play.handlers:
for listening_handler in listening_handler_block.block:
listeners = getattr(listening_handler, 'listen', []) or []
templar = self.get_handler_templar(listening_handler, iterator)
listeners = listening_handler.get_validated_value(
'listen', listening_handler._valid_attrs['listen'], listeners, templar
)
if handler_name not in listeners:
continue
else:
found = True
if listening_handler.notify_host(original_host):
self._tqm.send_callback('v2_playbook_on_notify', listening_handler, original_host)
# and if none were found, then we raise an error
if not found:
msg = ("The requested handler '%s' was not found in either the main handlers list nor in the listening "
"handlers list" % handler_name)
if C.ERROR_ON_MISSING_HANDLER:
raise AnsibleError(msg)
else:
display.warning(msg)
if 'add_host' in result_item:
# this task added a new host (add_host module)
new_host_info = result_item.get('add_host', dict())
self._add_host(new_host_info, iterator)
elif 'add_group' in result_item:
# this task added a new group (group_by module)
self._add_group(original_host, result_item)
if 'ansible_facts' in result_item:
# if delegated fact and we are delegating facts, we need to change target host for them
if original_task.delegate_to is not None and original_task.delegate_facts:
host_list = self.get_delegated_hosts(result_item, original_task)
else:
host_list = self.get_task_hosts(iterator, original_host, original_task)
if original_task.action == 'include_vars':
for (var_name, var_value) in iteritems(result_item['ansible_facts']):
# find the host we're actually referring too here, which may
# be a host that is not really in inventory at all
for target_host in host_list:
self._variable_manager.set_host_variable(target_host, var_name, var_value)
else:
cacheable = result_item.pop('_ansible_facts_cacheable', False)
for target_host in host_list:
# so set_fact is a misnomer but 'cacheable = true' was meant to create an 'actual fact'
# to avoid issues with precedence and confusion with set_fact normal operation,
# we set BOTH fact and nonpersistent_facts (aka hostvar)
# when fact is retrieved from cache in subsequent operations it will have the lower precedence,
# but for playbook setting it the 'higher' precedence is kept
if original_task.action != 'set_fact' or cacheable:
self._variable_manager.set_host_facts(target_host, result_item['ansible_facts'].copy())
if original_task.action == 'set_fact':
self._variable_manager.set_nonpersistent_facts(target_host, result_item['ansible_facts'].copy())
if 'ansible_stats' in result_item and 'data' in result_item['ansible_stats'] and result_item['ansible_stats']['data']:
if 'per_host' not in result_item['ansible_stats'] or result_item['ansible_stats']['per_host']:
host_list = self.get_task_hosts(iterator, original_host, original_task)
else:
host_list = [None]
data = result_item['ansible_stats']['data']
aggregate = 'aggregate' in result_item['ansible_stats'] and result_item['ansible_stats']['aggregate']
for myhost in host_list:
for k in data.keys():
if aggregate:
self._tqm._stats.update_custom_stats(k, data[k], myhost)
else:
self._tqm._stats.set_custom_stats(k, data[k], myhost)
if 'diff' in task_result._result:
if self._diff or getattr(original_task, 'diff', False):
self._tqm.send_callback('v2_on_file_diff', task_result)
if not isinstance(original_task, TaskInclude):
self._tqm._stats.increment('ok', original_host.name)
if 'changed' in task_result._result and task_result._result['changed']:
self._tqm._stats.increment('changed', original_host.name)
# finally, send the ok for this task
self._tqm.send_callback('v2_runner_on_ok', task_result)
self._pending_results -= 1
if original_host.name in self._blocked_hosts:
del self._blocked_hosts[original_host.name]
# If this is a role task, mark the parent role as being run (if
# the task was ok or failed, but not skipped or unreachable)
if original_task._role is not None and role_ran: # TODO: and original_task.action != 'include_role':?
# lookup the role in the ROLE_CACHE to make sure we're dealing
# with the correct object and mark it as executed
for (entry, role_obj) in iteritems(iterator._play.ROLE_CACHE[original_task._role._role_name]):
if role_obj._uuid == original_task._role._uuid:
role_obj._had_task_run[original_host.name] = True
ret_results.append(task_result)
if one_pass or max_passes is not None and (cur_pass + 1) >= max_passes:
break
cur_pass += 1
return ret_results
def _wait_on_handler_results(self, iterator, handler, notified_hosts):
'''
Wait for the handler tasks to complete, using a short sleep
between checks to ensure we don't spin lock
'''
ret_results = []
handler_results = 0
display.debug("waiting for handler results...")
while (self._pending_results > 0 and
handler_results < len(notified_hosts) and
not self._tqm._terminated):
if self._tqm.has_dead_workers():
raise AnsibleError("A worker was found in a dead state")
results = self._process_pending_results(iterator)
ret_results.extend(results)
handler_results += len([
r._host for r in results if r._host in notified_hosts and
r.task_name == handler.name])
if self._pending_results > 0:
time.sleep(C.DEFAULT_INTERNAL_POLL_INTERVAL)
display.debug("no more pending handlers, returning what we have")
return ret_results
def _wait_on_pending_results(self, iterator):
'''
Wait for the shared counter to drop to zero, using a short sleep
between checks to ensure we don't spin lock
'''
ret_results = []
display.debug("waiting for pending results...")
while self._pending_results > 0 and not self._tqm._terminated:
if self._tqm.has_dead_workers():
raise AnsibleError("A worker was found in a dead state")
results = self._process_pending_results(iterator)
ret_results.extend(results)
if self._pending_results > 0:
time.sleep(C.DEFAULT_INTERNAL_POLL_INTERVAL)
display.debug("no more pending results, returning what we have")
return ret_results
def _add_host(self, host_info, iterator):
'''
Helper function to add a new host to inventory based on a task result.
'''
if host_info:
host_name = host_info.get('host_name')
# Check if host in inventory, add if not
if host_name not in self._inventory.hosts:
self._inventory.add_host(host_name, 'all')
new_host = self._inventory.hosts.get(host_name)
# Set/update the vars for this host
new_host.vars = combine_vars(new_host.get_vars(), host_info.get('host_vars', dict()))
new_groups = host_info.get('groups', [])
for group_name in new_groups:
if group_name not in self._inventory.groups:
self._inventory.add_group(group_name)
new_group = self._inventory.groups[group_name]
new_group.add_host(self._inventory.hosts[host_name])
# reconcile inventory, ensures inventory rules are followed
self._inventory.reconcile_inventory()
def _add_group(self, host, result_item):
'''
Helper function to add a group (if it does not exist), and to assign the
specified host to that group.
'''
changed = False
# the host here is from the executor side, which means it was a
# serialized/cloned copy and we'll need to look up the proper
# host object from the master inventory
real_host = self._inventory.hosts.get(host.name)
if real_host is None:
if host.name == self._inventory.localhost.name:
real_host = self._inventory.localhost
else:
raise AnsibleError('%s cannot be matched in inventory' % host.name)
group_name = result_item.get('add_group')
parent_group_names = result_item.get('parent_groups', [])
for name in [group_name] + parent_group_names:
if name not in self._inventory.groups:
# create the new group and add it to inventory
self._inventory.add_group(name)
changed = True
group = self._inventory.groups[group_name]
for parent_group_name in parent_group_names:
parent_group = self._inventory.groups[parent_group_name]
parent_group.add_child_group(group)
if real_host.name not in group.get_hosts():
group.add_host(real_host)
changed = True
if group_name not in host.get_groups():
real_host.add_group(group)
changed = True
if changed:
self._inventory.reconcile_inventory()
return changed
def _copy_included_file(self, included_file):
'''
A proven safe and performant way to create a copy of an included file
'''
ti_copy = included_file._task.copy(exclude_parent=True)
ti_copy._parent = included_file._task._parent
temp_vars = ti_copy.vars.copy()
temp_vars.update(included_file._vars)
ti_copy.vars = temp_vars
return ti_copy
def _load_included_file(self, included_file, iterator, is_handler=False):
'''
Loads an included YAML file of tasks, applying the optional set of variables.
'''
display.debug("loading included file: %s" % included_file._filename)
try:
data = self._loader.load_from_file(included_file._filename)
if data is None:
return []
elif not isinstance(data, list):
raise AnsibleError("included task files must contain a list of tasks")
ti_copy = self._copy_included_file(included_file)
# pop tags out of the include args, if they were specified there, and assign
# them to the include. If the include already had tags specified, we raise an
# error so that users know not to specify them both ways
tags = included_file._task.vars.pop('tags', [])
if isinstance(tags, string_types):
tags = tags.split(',')
if len(tags) > 0:
if len(included_file._task.tags) > 0:
raise AnsibleParserError("Include tasks should not specify tags in more than one way (both via args and directly on the task). "
"Mixing tag specify styles is prohibited for whole import hierarchy, not only for single import statement",
obj=included_file._task._ds)
display.deprecated("You should not specify tags in the include parameters. All tags should be specified using the task-level option",
version='2.12')
included_file._task.tags = tags
block_list = load_list_of_blocks(
data,
play=iterator._play,
parent_block=ti_copy.build_parent_block(),
role=included_file._task._role,
use_handlers=is_handler,
loader=self._loader,
variable_manager=self._variable_manager,
)
# since we skip incrementing the stats when the task result is
# first processed, we do so now for each host in the list
for host in included_file._hosts:
self._tqm._stats.increment('ok', host.name)
except AnsibleError as e:
if isinstance(e, AnsibleFileNotFound):
reason = "Could not find or access '%s' on the Ansible Controller." % to_text(e.file_name)
else:
reason = to_text(e)
# mark all of the hosts including this file as failed, send callbacks,
# and increment the stats for this host
for host in included_file._hosts:
tr = TaskResult(host=host, task=included_file._task, return_data=dict(failed=True, reason=reason))
iterator.mark_host_failed(host)
self._tqm._failed_hosts[host.name] = True
self._tqm._stats.increment('failures', host.name)
self._tqm.send_callback('v2_runner_on_failed', tr)
return []
# finally, send the callback and return the list of blocks loaded
self._tqm.send_callback('v2_playbook_on_include', included_file)
display.debug("done processing included file")
return block_list
def run_handlers(self, iterator, play_context):
'''
Runs handlers on those hosts which have been notified.
'''
result = self._tqm.RUN_OK
for handler_block in iterator._play.handlers:
# FIXME: handlers need to support the rescue/always portions of blocks too,
# but this may take some work in the iterator and gets tricky when
# we consider the ability of meta tasks to flush handlers
for handler in handler_block.block:
if handler.notified_hosts:
result = self._do_handler_run(handler, handler.get_name(), iterator=iterator, play_context=play_context)
if not result:
break
return result
def _do_handler_run(self, handler, handler_name, iterator, play_context, notified_hosts=None):
# FIXME: need to use iterator.get_failed_hosts() instead?
# if not len(self.get_hosts_remaining(iterator._play)):
# self._tqm.send_callback('v2_playbook_on_no_hosts_remaining')
# result = False
# break
if notified_hosts is None:
notified_hosts = handler.notified_hosts[:]
notified_hosts = self._filter_notified_hosts(notified_hosts)
if len(notified_hosts) > 0:
saved_name = handler.name
handler.name = handler_name
self._tqm.send_callback('v2_playbook_on_handler_task_start', handler)
handler.name = saved_name
bypass_host_loop = False
try:
action = action_loader.get(handler.action, class_only=True)
if getattr(action, 'BYPASS_HOST_LOOP', False):
bypass_host_loop = True
except KeyError:
# we don't care here, because the action may simply not have a
# corresponding action plugin
pass
host_results = []
for host in notified_hosts:
if not iterator.is_failed(host) or iterator._play.force_handlers:
task_vars = self._variable_manager.get_vars(play=iterator._play, host=host, task=handler)
self.add_tqm_variables(task_vars, play=iterator._play)
self._queue_task(host, handler, task_vars, play_context)
templar = Templar(loader=self._loader, variables=task_vars)
if templar.template(handler.run_once) or bypass_host_loop:
break
# collect the results from the handler run
host_results = self._wait_on_handler_results(iterator, handler, notified_hosts)
included_files = IncludedFile.process_include_results(
host_results,
iterator=iterator,
loader=self._loader,
variable_manager=self._variable_manager
)
result = True
if len(included_files) > 0:
for included_file in included_files:
try:
new_blocks = self._load_included_file(included_file, iterator=iterator, is_handler=True)
# for every task in each block brought in by the include, add the list
# of hosts which included the file to the notified_handlers dict
for block in new_blocks:
iterator._play.handlers.append(block)
for task in block.block:
task_name = task.get_name()
display.debug("adding task '%s' included in handler '%s'" % (task_name, handler_name))
task.notified_hosts = included_file._hosts[:]
result = self._do_handler_run(
handler=task,
handler_name=task_name,
iterator=iterator,
play_context=play_context,
notified_hosts=included_file._hosts[:],
)
if not result:
break
except AnsibleError as e:
for host in included_file._hosts:
iterator.mark_host_failed(host)
self._tqm._failed_hosts[host.name] = True
display.warning(to_text(e))
continue
# remove hosts from notification list
handler.notified_hosts = [
h for h in handler.notified_hosts
if h not in notified_hosts]
display.debug("done running handlers, result is: %s" % result)
return result
def _filter_notified_hosts(self, notified_hosts):
'''
Filter notified hosts accordingly to strategy
'''
# As main strategy is linear, we do not filter hosts
# We return a copy to avoid race conditions
return notified_hosts[:]
def _take_step(self, task, host=None):
ret = False
msg = u'Perform task: %s ' % task
if host:
msg += u'on %s ' % host
msg += u'(N)o/(y)es/(c)ontinue: '
resp = display.prompt(msg)
if resp.lower() in ['y', 'yes']:
display.debug("User ran task")
ret = True
elif resp.lower() in ['c', 'continue']:
display.debug("User ran task and canceled step mode")
self._step = False
ret = True
else:
display.debug("User skipped task")
display.banner(msg)
return ret
def _cond_not_supported_warn(self, task_name):
display.warning("%s task does not support when conditional" % task_name)
def _execute_meta(self, task, play_context, iterator, target_host):
# meta tasks store their args in the _raw_params field of args,
# since they do not use k=v pairs, so get that
meta_action = task.args.get('_raw_params')
def _evaluate_conditional(h):
all_vars = self._variable_manager.get_vars(play=iterator._play, host=h, task=task)
templar = Templar(loader=self._loader, variables=all_vars)
return task.evaluate_conditional(templar, all_vars)
skipped = False
msg = ''
if meta_action == 'noop':
# FIXME: issue a callback for the noop here?
if task.when:
self._cond_not_supported_warn(meta_action)
msg = "noop"
elif meta_action == 'flush_handlers':
if task.when:
self._cond_not_supported_warn(meta_action)
self._flushed_hosts[target_host] = True
self.run_handlers(iterator, play_context)
self._flushed_hosts[target_host] = False
msg = "ran handlers"
elif meta_action == 'refresh_inventory' or self.flush_cache:
if task.when:
self._cond_not_supported_warn(meta_action)
self._inventory.refresh_inventory()
msg = "inventory successfully refreshed"
elif meta_action == 'clear_facts':
if _evaluate_conditional(target_host):
for host in self._inventory.get_hosts(iterator._play.hosts):
hostname = host.get_name()
self._variable_manager.clear_facts(hostname)
msg = "facts cleared"
else:
skipped = True
elif meta_action == 'clear_host_errors':
if _evaluate_conditional(target_host):
for host in self._inventory.get_hosts(iterator._play.hosts):
self._tqm._failed_hosts.pop(host.name, False)
self._tqm._unreachable_hosts.pop(host.name, False)
iterator._host_states[host.name].fail_state = iterator.FAILED_NONE
msg = "cleared host errors"
else:
skipped = True
elif meta_action == 'end_play':
if _evaluate_conditional(target_host):
for host in self._inventory.get_hosts(iterator._play.hosts):
if host.name not in self._tqm._unreachable_hosts:
iterator._host_states[host.name].run_state = iterator.ITERATING_COMPLETE
msg = "ending play"
elif meta_action == 'end_host':
if _evaluate_conditional(target_host):
iterator._host_states[target_host.name].run_state = iterator.ITERATING_COMPLETE
msg = "ending play for %s" % target_host.name
else:
skipped = True
msg = "end_host conditional evaluated to false, continuing execution for %s" % target_host.name
elif meta_action == 'reset_connection':
all_vars = self._variable_manager.get_vars(play=iterator._play, host=target_host, task=task)
templar = Templar(loader=self._loader, variables=all_vars)
# apply the given task's information to the connection info,
# which may override some fields already set by the play or
# the options specified on the command line
play_context = play_context.set_task_and_variable_override(task=task, variables=all_vars, templar=templar)
# fields set from the play/task may be based on variables, so we have to
# do the same kind of post validation step on it here before we use it.
play_context.post_validate(templar=templar)
# now that the play context is finalized, if the remote_addr is not set
# default to using the host's address field as the remote address
if not play_context.remote_addr:
play_context.remote_addr = target_host.address
# We also add "magic" variables back into the variables dict to make sure
# a certain subset of variables exist.
play_context.update_vars(all_vars)
if task.when:
self._cond_not_supported_warn(meta_action)
if target_host in self._active_connections:
connection = Connection(self._active_connections[target_host])
del self._active_connections[target_host]
else:
connection = connection_loader.get(play_context.connection, play_context, os.devnull)
play_context.set_attributes_from_plugin(connection)
if connection:
try:
connection.reset()
msg = 'reset connection'
except ConnectionError as e:
# most likely socket is already closed
display.debug("got an error while closing persistent connection: %s" % e)
else:
msg = 'no connection, nothing to reset'
else:
raise AnsibleError("invalid meta action requested: %s" % meta_action, obj=task._ds)
result = {'msg': msg}
if skipped:
result['skipped'] = True
else:
result['changed'] = False
display.vv("META: %s" % msg)
return [TaskResult(target_host, task, result)]
def get_hosts_left(self, iterator):
''' returns list of available hosts for this iterator by filtering out unreachables '''
hosts_left = []
for host in self._inventory.get_hosts(iterator._play.hosts, order=iterator._play.order):
if host.name not in self._tqm._unreachable_hosts:
hosts_left.append(host)
return hosts_left
def update_active_connections(self, results):
''' updates the current active persistent connections '''
for r in results:
if 'args' in r._task_fields:
socket_path = r._task_fields['args'].get('_ansible_socket')
if socket_path:
if r._host not in self._active_connections:
self._active_connections[r._host] = socket_path
class NextAction(object):
""" The next action after an interpreter's exit. """
REDO = 1
CONTINUE = 2
EXIT = 3
def __init__(self, result=EXIT):
self.result = result
class Debugger(cmd.Cmd):
prompt_continuous = '> ' # multiple lines
def __init__(self, task, host, task_vars, play_context, result, next_action):
# cmd.Cmd is old-style class
cmd.Cmd.__init__(self)
self.prompt = '[%s] %s (debug)> ' % (host, task)
self.intro = None
self.scope = {}
self.scope['task'] = task
self.scope['task_vars'] = task_vars
self.scope['host'] = host
self.scope['play_context'] = play_context
self.scope['result'] = result
self.next_action = next_action
def cmdloop(self):
try:
cmd.Cmd.cmdloop(self)
except KeyboardInterrupt:
pass
do_h = cmd.Cmd.do_help
def do_EOF(self, args):
"""Quit"""
return self.do_quit(args)
def do_quit(self, args):
"""Quit"""
display.display('User interrupted execution')
self.next_action.result = NextAction.EXIT
return True
do_q = do_quit
def do_continue(self, args):
"""Continue to next result"""
self.next_action.result = NextAction.CONTINUE
return True
do_c = do_continue
def do_redo(self, args):
"""Schedule task for re-execution. The re-execution may not be the next result"""
self.next_action.result = NextAction.REDO
return True
do_r = do_redo
def do_update_task(self, args):
"""Recreate the task from ``task._ds``, and template with updated ``task_vars``"""
templar = Templar(None, shared_loader_obj=None, variables=self.scope['task_vars'])
task = self.scope['task']
task = task.load_data(task._ds)
task.post_validate(templar)
self.scope['task'] = task
do_u = do_update_task
def evaluate(self, args):
try:
return eval(args, globals(), self.scope)
except Exception:
t, v = sys.exc_info()[:2]
if isinstance(t, str):
exc_type_name = t
else:
exc_type_name = t.__name__
display.display('***%s:%s' % (exc_type_name, repr(v)))
raise
def do_pprint(self, args):
"""Pretty Print"""
try:
result = self.evaluate(args)
display.display(pprint.pformat(result))
except Exception:
pass
do_p = do_pprint
def execute(self, args):
try:
code = compile(args + '\n', '<stdin>', 'single')
exec(code, globals(), self.scope)
except Exception:
t, v = sys.exc_info()[:2]
if isinstance(t, str):
exc_type_name = t
else:
exc_type_name = t.__name__
display.display('***%s:%s' % (exc_type_name, repr(v)))
raise
def default(self, line):
try:
self.execute(line)
except Exception:
pass
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,980 |
force_valid_group_names throws unexpected exception if invalid names used with add_host/group_by
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
<!--- Explain the problem briefly below -->
While using a simple reproducer with either force_valid_group_names=silently or force_valid_group_names=always an unexpected exception is thrown:
Sample playbook:
```
---
- hosts: localhost
connection: local
gather_facts: false
tasks:
- name: add a host to a group
add_host:
name: localhost
groups: Not-Working
```
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
inventory
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```
ansible --version
ansible 2.9.0.dev0
config file = /opt/gmuniz/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /opt/ansible-devel/ansible/lib/ansible
executable location = /opt/ansible-devel/ansible/bin/ansible
python version = 2.7.5 (default, Apr 9 2019, 14:30:50) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```
ansible-config dump --only-changed
TRANSFORM_INVALID_GROUP_CHARS(/opt/gmuniz/ansible.cfg) = always
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
CentOs-7
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```
- hosts: localhost
connection: local
gather_facts: false
tasks:
- name: add a host to a group
add_host:
name: localhost
groups: Not-Working
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
I expect the host to be added to the group either with the originally provided name or the replaced underscore name.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```
TASK [add a host to a group] *************************************************************************************************************************************************************************************
task path: /opt/gmuniz/add_host.yml:6
creating host via 'add_host': hostname=localhost
[WARNING]: A duplicate localhost-like entry was found (localhost). First found localhost was localhost
[WARNING]: Invalid characters were found in group names and automatically replaced, use -vvvv to see details
ERROR! Unexpected Exception, this is probably a bug: u'Not-Working'
```
|
https://github.com/ansible/ansible/issues/58980
|
https://github.com/ansible/ansible/pull/58982
|
b0f38931b0e0b55db30a012e81683d380ea7a670
|
a7b14ec1becb947cc290deebe309ef06a12d1f7e
| 2019-07-11T13:32:26Z |
python
| 2019-07-11T17:49:49Z |
changelogs/fragments/fix_strategy_inv_up.yml
| |
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,980 |
force_valid_group_names throws unexpected exception if invalid names used with add_host/group_by
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
<!--- Explain the problem briefly below -->
While using a simple reproducer with either force_valid_group_names=silently or force_valid_group_names=always an unexpected exception is thrown:
Sample playbook:
```
---
- hosts: localhost
connection: local
gather_facts: false
tasks:
- name: add a host to a group
add_host:
name: localhost
groups: Not-Working
```
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
inventory
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```
ansible --version
ansible 2.9.0.dev0
config file = /opt/gmuniz/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /opt/ansible-devel/ansible/lib/ansible
executable location = /opt/ansible-devel/ansible/bin/ansible
python version = 2.7.5 (default, Apr 9 2019, 14:30:50) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```
ansible-config dump --only-changed
TRANSFORM_INVALID_GROUP_CHARS(/opt/gmuniz/ansible.cfg) = always
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
CentOs-7
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```
- hosts: localhost
connection: local
gather_facts: false
tasks:
- name: add a host to a group
add_host:
name: localhost
groups: Not-Working
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
I expect the host to be added to the group either with the originally provided name or the replaced underscore name.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```
TASK [add a host to a group] *************************************************************************************************************************************************************************************
task path: /opt/gmuniz/add_host.yml:6
creating host via 'add_host': hostname=localhost
[WARNING]: A duplicate localhost-like entry was found (localhost). First found localhost was localhost
[WARNING]: Invalid characters were found in group names and automatically replaced, use -vvvv to see details
ERROR! Unexpected Exception, this is probably a bug: u'Not-Working'
```
|
https://github.com/ansible/ansible/issues/58980
|
https://github.com/ansible/ansible/pull/58982
|
b0f38931b0e0b55db30a012e81683d380ea7a670
|
a7b14ec1becb947cc290deebe309ef06a12d1f7e
| 2019-07-11T13:32:26Z |
python
| 2019-07-11T17:49:49Z |
lib/ansible/plugins/strategy/__init__.py
|
# (c) 2012-2014, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import cmd
import functools
import os
import pprint
import sys
import threading
import time
from collections import deque
from multiprocessing import Lock
from jinja2.exceptions import UndefinedError
from ansible import constants as C
from ansible import context
from ansible.errors import AnsibleError, AnsibleFileNotFound, AnsibleParserError, AnsibleUndefinedVariable
from ansible.executor import action_write_locks
from ansible.executor.process.worker import WorkerProcess
from ansible.executor.task_result import TaskResult
from ansible.inventory.host import Host
from ansible.module_utils.six.moves import queue as Queue
from ansible.module_utils.six import iteritems, itervalues, string_types
from ansible.module_utils._text import to_text
from ansible.module_utils.connection import Connection, ConnectionError
from ansible.playbook.helpers import load_list_of_blocks
from ansible.playbook.included_file import IncludedFile
from ansible.playbook.task_include import TaskInclude
from ansible.plugins.loader import action_loader, connection_loader, filter_loader, lookup_loader, module_loader, test_loader
from ansible.template import Templar
from ansible.utils.display import Display
from ansible.utils.vars import combine_vars
from ansible.vars.clean import strip_internal_keys, module_response_deepcopy
display = Display()
__all__ = ['StrategyBase']
class StrategySentinel:
pass
# TODO: this should probably be in the plugins/__init__.py, with
# a smarter mechanism to set all of the attributes based on
# the loaders created there
class SharedPluginLoaderObj:
'''
A simple object to make pass the various plugin loaders to
the forked processes over the queue easier
'''
def __init__(self):
self.action_loader = action_loader
self.connection_loader = connection_loader
self.filter_loader = filter_loader
self.test_loader = test_loader
self.lookup_loader = lookup_loader
self.module_loader = module_loader
_sentinel = StrategySentinel()
def results_thread_main(strategy):
while True:
try:
result = strategy._final_q.get()
if isinstance(result, StrategySentinel):
break
else:
strategy._results_lock.acquire()
strategy._results.append(result)
strategy._results_lock.release()
except (IOError, EOFError):
break
except Queue.Empty:
pass
def debug_closure(func):
"""Closure to wrap ``StrategyBase._process_pending_results`` and invoke the task debugger"""
@functools.wraps(func)
def inner(self, iterator, one_pass=False, max_passes=None):
status_to_stats_map = (
('is_failed', 'failures'),
('is_unreachable', 'dark'),
('is_changed', 'changed'),
('is_skipped', 'skipped'),
)
# We don't know the host yet, copy the previous states, for lookup after we process new results
prev_host_states = iterator._host_states.copy()
results = func(self, iterator, one_pass=one_pass, max_passes=max_passes)
_processed_results = []
for result in results:
task = result._task
host = result._host
_queued_task_args = self._queued_task_cache.pop((host.name, task._uuid), None)
task_vars = _queued_task_args['task_vars']
play_context = _queued_task_args['play_context']
# Try to grab the previous host state, if it doesn't exist use get_host_state to generate an empty state
try:
prev_host_state = prev_host_states[host.name]
except KeyError:
prev_host_state = iterator.get_host_state(host)
while result.needs_debugger(globally_enabled=self.debugger_active):
next_action = NextAction()
dbg = Debugger(task, host, task_vars, play_context, result, next_action)
dbg.cmdloop()
if next_action.result == NextAction.REDO:
# rollback host state
self._tqm.clear_failed_hosts()
iterator._host_states[host.name] = prev_host_state
for method, what in status_to_stats_map:
if getattr(result, method)():
self._tqm._stats.decrement(what, host.name)
self._tqm._stats.decrement('ok', host.name)
# redo
self._queue_task(host, task, task_vars, play_context)
_processed_results.extend(debug_closure(func)(self, iterator, one_pass))
break
elif next_action.result == NextAction.CONTINUE:
_processed_results.append(result)
break
elif next_action.result == NextAction.EXIT:
# Matches KeyboardInterrupt from bin/ansible
sys.exit(99)
else:
_processed_results.append(result)
return _processed_results
return inner
class StrategyBase:
'''
This is the base class for strategy plugins, which contains some common
code useful to all strategies like running handlers, cleanup actions, etc.
'''
def __init__(self, tqm):
self._tqm = tqm
self._inventory = tqm.get_inventory()
self._workers = tqm.get_workers()
self._variable_manager = tqm.get_variable_manager()
self._loader = tqm.get_loader()
self._final_q = tqm._final_q
self._step = context.CLIARGS.get('step', False)
self._diff = context.CLIARGS.get('diff', False)
self.flush_cache = context.CLIARGS.get('flush_cache', False)
# the task cache is a dictionary of tuples of (host.name, task._uuid)
# used to find the original task object of in-flight tasks and to store
# the task args/vars and play context info used to queue the task.
self._queued_task_cache = {}
# Backwards compat: self._display isn't really needed, just import the global display and use that.
self._display = display
# internal counters
self._pending_results = 0
self._cur_worker = 0
# this dictionary is used to keep track of hosts that have
# outstanding tasks still in queue
self._blocked_hosts = dict()
# this dictionary is used to keep track of hosts that have
# flushed handlers
self._flushed_hosts = dict()
self._results = deque()
self._results_lock = threading.Condition(threading.Lock())
# create the result processing thread for reading results in the background
self._results_thread = threading.Thread(target=results_thread_main, args=(self,))
self._results_thread.daemon = True
self._results_thread.start()
# holds the list of active (persistent) connections to be shutdown at
# play completion
self._active_connections = dict()
self.debugger_active = C.ENABLE_TASK_DEBUGGER
def cleanup(self):
# close active persistent connections
for sock in itervalues(self._active_connections):
try:
conn = Connection(sock)
conn.reset()
except ConnectionError as e:
# most likely socket is already closed
display.debug("got an error while closing persistent connection: %s" % e)
self._final_q.put(_sentinel)
self._results_thread.join()
def run(self, iterator, play_context, result=0):
# execute one more pass through the iterator without peeking, to
# make sure that all of the hosts are advanced to their final task.
# This should be safe, as everything should be ITERATING_COMPLETE by
# this point, though the strategy may not advance the hosts itself.
inv_hosts = self._inventory.get_hosts(iterator._play.hosts, order=iterator._play.order)
[iterator.get_next_task_for_host(host) for host in inv_hosts if host.name not in self._tqm._unreachable_hosts]
# save the failed/unreachable hosts, as the run_handlers()
# method will clear that information during its execution
failed_hosts = iterator.get_failed_hosts()
unreachable_hosts = self._tqm._unreachable_hosts.keys()
display.debug("running handlers")
handler_result = self.run_handlers(iterator, play_context)
if isinstance(handler_result, bool) and not handler_result:
result |= self._tqm.RUN_ERROR
elif not handler_result:
result |= handler_result
# now update with the hosts (if any) that failed or were
# unreachable during the handler execution phase
failed_hosts = set(failed_hosts).union(iterator.get_failed_hosts())
unreachable_hosts = set(unreachable_hosts).union(self._tqm._unreachable_hosts.keys())
# return the appropriate code, depending on the status hosts after the run
if not isinstance(result, bool) and result != self._tqm.RUN_OK:
return result
elif len(unreachable_hosts) > 0:
return self._tqm.RUN_UNREACHABLE_HOSTS
elif len(failed_hosts) > 0:
return self._tqm.RUN_FAILED_HOSTS
else:
return self._tqm.RUN_OK
def get_hosts_remaining(self, play):
return [host for host in self._inventory.get_hosts(play.hosts)
if host.name not in self._tqm._failed_hosts and host.name not in self._tqm._unreachable_hosts]
def get_failed_hosts(self, play):
return [host for host in self._inventory.get_hosts(play.hosts) if host.name in self._tqm._failed_hosts]
def add_tqm_variables(self, vars, play):
'''
Base class method to add extra variables/information to the list of task
vars sent through the executor engine regarding the task queue manager state.
'''
vars['ansible_current_hosts'] = [h.name for h in self.get_hosts_remaining(play)]
vars['ansible_failed_hosts'] = [h.name for h in self.get_failed_hosts(play)]
def _queue_task(self, host, task, task_vars, play_context):
''' handles queueing the task up to be sent to a worker '''
display.debug("entering _queue_task() for %s/%s" % (host.name, task.action))
# Add a write lock for tasks.
# Maybe this should be added somewhere further up the call stack but
# this is the earliest in the code where we have task (1) extracted
# into its own variable and (2) there's only a single code path
# leading to the module being run. This is called by three
# functions: __init__.py::_do_handler_run(), linear.py::run(), and
# free.py::run() so we'd have to add to all three to do it there.
# The next common higher level is __init__.py::run() and that has
# tasks inside of play_iterator so we'd have to extract them to do it
# there.
if task.action not in action_write_locks.action_write_locks:
display.debug('Creating lock for %s' % task.action)
action_write_locks.action_write_locks[task.action] = Lock()
# and then queue the new task
try:
# create a dummy object with plugin loaders set as an easier
# way to share them with the forked processes
shared_loader_obj = SharedPluginLoaderObj()
queued = False
starting_worker = self._cur_worker
while True:
worker_prc = self._workers[self._cur_worker]
if worker_prc is None or not worker_prc.is_alive():
self._queued_task_cache[(host.name, task._uuid)] = {
'host': host,
'task': task,
'task_vars': task_vars,
'play_context': play_context
}
worker_prc = WorkerProcess(self._final_q, task_vars, host, task, play_context, self._loader, self._variable_manager, shared_loader_obj)
self._workers[self._cur_worker] = worker_prc
self._tqm.send_callback('v2_runner_on_start', host, task)
worker_prc.start()
display.debug("worker is %d (out of %d available)" % (self._cur_worker + 1, len(self._workers)))
queued = True
self._cur_worker += 1
if self._cur_worker >= len(self._workers):
self._cur_worker = 0
if queued:
break
elif self._cur_worker == starting_worker:
time.sleep(0.0001)
self._pending_results += 1
except (EOFError, IOError, AssertionError) as e:
# most likely an abort
display.debug("got an error while queuing: %s" % e)
return
display.debug("exiting _queue_task() for %s/%s" % (host.name, task.action))
def get_task_hosts(self, iterator, task_host, task):
if task.run_once:
host_list = [host for host in self._inventory.get_hosts(iterator._play.hosts) if host.name not in self._tqm._unreachable_hosts]
else:
host_list = [task_host]
return host_list
def get_delegated_hosts(self, result, task):
host_name = result.get('_ansible_delegated_vars', {}).get('ansible_delegated_host', None)
if host_name is not None:
actual_host = self._inventory.get_host(host_name)
if actual_host is None:
actual_host = Host(name=host_name)
else:
actual_host = Host(name=task.delegate_to)
return [actual_host]
def get_handler_templar(self, handler_task, iterator):
handler_vars = self._variable_manager.get_vars(play=iterator._play, task=handler_task)
return Templar(loader=self._loader, variables=handler_vars)
@debug_closure
def _process_pending_results(self, iterator, one_pass=False, max_passes=None):
'''
Reads results off the final queue and takes appropriate action
based on the result (executing callbacks, updating state, etc.).
'''
ret_results = []
def get_original_host(host_name):
# FIXME: this should not need x2 _inventory
host_name = to_text(host_name)
if host_name in self._inventory.hosts:
return self._inventory.hosts[host_name]
else:
return self._inventory.get_host(host_name)
def search_handler_blocks_by_name(handler_name, handler_blocks):
# iterate in reversed order since last handler loaded with the same name wins
for handler_block in reversed(handler_blocks):
for handler_task in handler_block.block:
if handler_task.name:
if not handler_task.cached_name:
templar = self.get_handler_templar(handler_task, iterator)
handler_task.name = templar.template(handler_task.name)
handler_task.cached_name = True
try:
# first we check with the full result of get_name(), which may
# include the role name (if the handler is from a role). If that
# is not found, we resort to the simple name field, which doesn't
# have anything extra added to it.
if handler_task.name == handler_name:
return handler_task
else:
if handler_task.get_name() == handler_name:
return handler_task
except (UndefinedError, AnsibleUndefinedVariable):
# We skip this handler due to the fact that it may be using
# a variable in the name that was conditionally included via
# set_fact or some other method, and we don't want to error
# out unnecessarily
continue
return None
cur_pass = 0
while True:
try:
self._results_lock.acquire()
task_result = self._results.popleft()
except IndexError:
break
finally:
self._results_lock.release()
# get the original host and task. We then assign them to the TaskResult for use in callbacks/etc.
original_host = get_original_host(task_result._host)
queue_cache_entry = (original_host.name, task_result._task)
found_task = self._queued_task_cache.get(queue_cache_entry)['task']
original_task = found_task.copy(exclude_parent=True, exclude_tasks=True)
original_task._parent = found_task._parent
original_task.from_attrs(task_result._task_fields)
task_result._host = original_host
task_result._task = original_task
# send callbacks for 'non final' results
if '_ansible_retry' in task_result._result:
self._tqm.send_callback('v2_runner_retry', task_result)
continue
elif '_ansible_item_result' in task_result._result:
if task_result.is_failed() or task_result.is_unreachable():
self._tqm.send_callback('v2_runner_item_on_failed', task_result)
elif task_result.is_skipped():
self._tqm.send_callback('v2_runner_item_on_skipped', task_result)
else:
if 'diff' in task_result._result:
if self._diff or getattr(original_task, 'diff', False):
self._tqm.send_callback('v2_on_file_diff', task_result)
self._tqm.send_callback('v2_runner_item_on_ok', task_result)
continue
if original_task.register:
host_list = self.get_task_hosts(iterator, original_host, original_task)
clean_copy = strip_internal_keys(module_response_deepcopy(task_result._result))
if 'invocation' in clean_copy:
del clean_copy['invocation']
for target_host in host_list:
self._variable_manager.set_nonpersistent_facts(target_host, {original_task.register: clean_copy})
# all host status messages contain 2 entries: (msg, task_result)
role_ran = False
if task_result.is_failed():
role_ran = True
ignore_errors = original_task.ignore_errors
if not ignore_errors:
display.debug("marking %s as failed" % original_host.name)
if original_task.run_once:
# if we're using run_once, we have to fail every host here
for h in self._inventory.get_hosts(iterator._play.hosts):
if h.name not in self._tqm._unreachable_hosts:
state, _ = iterator.get_next_task_for_host(h, peek=True)
iterator.mark_host_failed(h)
state, new_task = iterator.get_next_task_for_host(h, peek=True)
else:
iterator.mark_host_failed(original_host)
# grab the current state and if we're iterating on the rescue portion
# of a block then we save the failed task in a special var for use
# within the rescue/always
state, _ = iterator.get_next_task_for_host(original_host, peek=True)
if iterator.is_failed(original_host) and state and state.run_state == iterator.ITERATING_COMPLETE:
self._tqm._failed_hosts[original_host.name] = True
if state and iterator.get_active_state(state).run_state == iterator.ITERATING_RESCUE:
self._tqm._stats.increment('rescued', original_host.name)
self._variable_manager.set_nonpersistent_facts(
original_host,
dict(
ansible_failed_task=original_task.serialize(),
ansible_failed_result=task_result._result,
),
)
else:
self._tqm._stats.increment('failures', original_host.name)
else:
self._tqm._stats.increment('ok', original_host.name)
self._tqm._stats.increment('ignored', original_host.name)
if 'changed' in task_result._result and task_result._result['changed']:
self._tqm._stats.increment('changed', original_host.name)
self._tqm.send_callback('v2_runner_on_failed', task_result, ignore_errors=ignore_errors)
elif task_result.is_unreachable():
ignore_unreachable = original_task.ignore_unreachable
if not ignore_unreachable:
self._tqm._unreachable_hosts[original_host.name] = True
iterator._play._removed_hosts.append(original_host.name)
else:
self._tqm._stats.increment('skipped', original_host.name)
task_result._result['skip_reason'] = 'Host %s is unreachable' % original_host.name
self._tqm._stats.increment('dark', original_host.name)
self._tqm.send_callback('v2_runner_on_unreachable', task_result)
elif task_result.is_skipped():
self._tqm._stats.increment('skipped', original_host.name)
self._tqm.send_callback('v2_runner_on_skipped', task_result)
else:
role_ran = True
if original_task.loop:
# this task had a loop, and has more than one result, so
# loop over all of them instead of a single result
result_items = task_result._result.get('results', [])
else:
result_items = [task_result._result]
for result_item in result_items:
if '_ansible_notify' in result_item:
if task_result.is_changed():
# The shared dictionary for notified handlers is a proxy, which
# does not detect when sub-objects within the proxy are modified.
# So, per the docs, we reassign the list so the proxy picks up and
# notifies all other threads
for handler_name in result_item['_ansible_notify']:
found = False
# Find the handler using the above helper. First we look up the
# dependency chain of the current task (if it's from a role), otherwise
# we just look through the list of handlers in the current play/all
# roles and use the first one that matches the notify name
target_handler = search_handler_blocks_by_name(handler_name, iterator._play.handlers)
if target_handler is not None:
found = True
if target_handler.notify_host(original_host):
self._tqm.send_callback('v2_playbook_on_notify', target_handler, original_host)
for listening_handler_block in iterator._play.handlers:
for listening_handler in listening_handler_block.block:
listeners = getattr(listening_handler, 'listen', []) or []
templar = self.get_handler_templar(listening_handler, iterator)
listeners = listening_handler.get_validated_value(
'listen', listening_handler._valid_attrs['listen'], listeners, templar
)
if handler_name not in listeners:
continue
else:
found = True
if listening_handler.notify_host(original_host):
self._tqm.send_callback('v2_playbook_on_notify', listening_handler, original_host)
# and if none were found, then we raise an error
if not found:
msg = ("The requested handler '%s' was not found in either the main handlers list nor in the listening "
"handlers list" % handler_name)
if C.ERROR_ON_MISSING_HANDLER:
raise AnsibleError(msg)
else:
display.warning(msg)
if 'add_host' in result_item:
# this task added a new host (add_host module)
new_host_info = result_item.get('add_host', dict())
self._add_host(new_host_info, iterator)
elif 'add_group' in result_item:
# this task added a new group (group_by module)
self._add_group(original_host, result_item)
if 'ansible_facts' in result_item:
# if delegated fact and we are delegating facts, we need to change target host for them
if original_task.delegate_to is not None and original_task.delegate_facts:
host_list = self.get_delegated_hosts(result_item, original_task)
else:
host_list = self.get_task_hosts(iterator, original_host, original_task)
if original_task.action == 'include_vars':
for (var_name, var_value) in iteritems(result_item['ansible_facts']):
# find the host we're actually referring too here, which may
# be a host that is not really in inventory at all
for target_host in host_list:
self._variable_manager.set_host_variable(target_host, var_name, var_value)
else:
cacheable = result_item.pop('_ansible_facts_cacheable', False)
for target_host in host_list:
# so set_fact is a misnomer but 'cacheable = true' was meant to create an 'actual fact'
# to avoid issues with precedence and confusion with set_fact normal operation,
# we set BOTH fact and nonpersistent_facts (aka hostvar)
# when fact is retrieved from cache in subsequent operations it will have the lower precedence,
# but for playbook setting it the 'higher' precedence is kept
if original_task.action != 'set_fact' or cacheable:
self._variable_manager.set_host_facts(target_host, result_item['ansible_facts'].copy())
if original_task.action == 'set_fact':
self._variable_manager.set_nonpersistent_facts(target_host, result_item['ansible_facts'].copy())
if 'ansible_stats' in result_item and 'data' in result_item['ansible_stats'] and result_item['ansible_stats']['data']:
if 'per_host' not in result_item['ansible_stats'] or result_item['ansible_stats']['per_host']:
host_list = self.get_task_hosts(iterator, original_host, original_task)
else:
host_list = [None]
data = result_item['ansible_stats']['data']
aggregate = 'aggregate' in result_item['ansible_stats'] and result_item['ansible_stats']['aggregate']
for myhost in host_list:
for k in data.keys():
if aggregate:
self._tqm._stats.update_custom_stats(k, data[k], myhost)
else:
self._tqm._stats.set_custom_stats(k, data[k], myhost)
if 'diff' in task_result._result:
if self._diff or getattr(original_task, 'diff', False):
self._tqm.send_callback('v2_on_file_diff', task_result)
if not isinstance(original_task, TaskInclude):
self._tqm._stats.increment('ok', original_host.name)
if 'changed' in task_result._result and task_result._result['changed']:
self._tqm._stats.increment('changed', original_host.name)
# finally, send the ok for this task
self._tqm.send_callback('v2_runner_on_ok', task_result)
self._pending_results -= 1
if original_host.name in self._blocked_hosts:
del self._blocked_hosts[original_host.name]
# If this is a role task, mark the parent role as being run (if
# the task was ok or failed, but not skipped or unreachable)
if original_task._role is not None and role_ran: # TODO: and original_task.action != 'include_role':?
# lookup the role in the ROLE_CACHE to make sure we're dealing
# with the correct object and mark it as executed
for (entry, role_obj) in iteritems(iterator._play.ROLE_CACHE[original_task._role._role_name]):
if role_obj._uuid == original_task._role._uuid:
role_obj._had_task_run[original_host.name] = True
ret_results.append(task_result)
if one_pass or max_passes is not None and (cur_pass + 1) >= max_passes:
break
cur_pass += 1
return ret_results
def _wait_on_handler_results(self, iterator, handler, notified_hosts):
'''
Wait for the handler tasks to complete, using a short sleep
between checks to ensure we don't spin lock
'''
ret_results = []
handler_results = 0
display.debug("waiting for handler results...")
while (self._pending_results > 0 and
handler_results < len(notified_hosts) and
not self._tqm._terminated):
if self._tqm.has_dead_workers():
raise AnsibleError("A worker was found in a dead state")
results = self._process_pending_results(iterator)
ret_results.extend(results)
handler_results += len([
r._host for r in results if r._host in notified_hosts and
r.task_name == handler.name])
if self._pending_results > 0:
time.sleep(C.DEFAULT_INTERNAL_POLL_INTERVAL)
display.debug("no more pending handlers, returning what we have")
return ret_results
def _wait_on_pending_results(self, iterator):
'''
Wait for the shared counter to drop to zero, using a short sleep
between checks to ensure we don't spin lock
'''
ret_results = []
display.debug("waiting for pending results...")
while self._pending_results > 0 and not self._tqm._terminated:
if self._tqm.has_dead_workers():
raise AnsibleError("A worker was found in a dead state")
results = self._process_pending_results(iterator)
ret_results.extend(results)
if self._pending_results > 0:
time.sleep(C.DEFAULT_INTERNAL_POLL_INTERVAL)
display.debug("no more pending results, returning what we have")
return ret_results
def _add_host(self, host_info, iterator):
'''
Helper function to add a new host to inventory based on a task result.
'''
if host_info:
host_name = host_info.get('host_name')
# Check if host in inventory, add if not
if host_name not in self._inventory.hosts:
self._inventory.add_host(host_name, 'all')
new_host = self._inventory.hosts.get(host_name)
# Set/update the vars for this host
new_host.vars = combine_vars(new_host.get_vars(), host_info.get('host_vars', dict()))
new_groups = host_info.get('groups', [])
for group_name in new_groups:
if group_name not in self._inventory.groups:
self._inventory.add_group(group_name)
new_group = self._inventory.groups[group_name]
new_group.add_host(self._inventory.hosts[host_name])
# reconcile inventory, ensures inventory rules are followed
self._inventory.reconcile_inventory()
def _add_group(self, host, result_item):
'''
Helper function to add a group (if it does not exist), and to assign the
specified host to that group.
'''
changed = False
# the host here is from the executor side, which means it was a
# serialized/cloned copy and we'll need to look up the proper
# host object from the master inventory
real_host = self._inventory.hosts.get(host.name)
if real_host is None:
if host.name == self._inventory.localhost.name:
real_host = self._inventory.localhost
else:
raise AnsibleError('%s cannot be matched in inventory' % host.name)
group_name = result_item.get('add_group')
parent_group_names = result_item.get('parent_groups', [])
for name in [group_name] + parent_group_names:
if name not in self._inventory.groups:
# create the new group and add it to inventory
self._inventory.add_group(name)
changed = True
group = self._inventory.groups[group_name]
for parent_group_name in parent_group_names:
parent_group = self._inventory.groups[parent_group_name]
parent_group.add_child_group(group)
if real_host.name not in group.get_hosts():
group.add_host(real_host)
changed = True
if group_name not in host.get_groups():
real_host.add_group(group)
changed = True
if changed:
self._inventory.reconcile_inventory()
return changed
def _copy_included_file(self, included_file):
'''
A proven safe and performant way to create a copy of an included file
'''
ti_copy = included_file._task.copy(exclude_parent=True)
ti_copy._parent = included_file._task._parent
temp_vars = ti_copy.vars.copy()
temp_vars.update(included_file._vars)
ti_copy.vars = temp_vars
return ti_copy
def _load_included_file(self, included_file, iterator, is_handler=False):
'''
Loads an included YAML file of tasks, applying the optional set of variables.
'''
display.debug("loading included file: %s" % included_file._filename)
try:
data = self._loader.load_from_file(included_file._filename)
if data is None:
return []
elif not isinstance(data, list):
raise AnsibleError("included task files must contain a list of tasks")
ti_copy = self._copy_included_file(included_file)
# pop tags out of the include args, if they were specified there, and assign
# them to the include. If the include already had tags specified, we raise an
# error so that users know not to specify them both ways
tags = included_file._task.vars.pop('tags', [])
if isinstance(tags, string_types):
tags = tags.split(',')
if len(tags) > 0:
if len(included_file._task.tags) > 0:
raise AnsibleParserError("Include tasks should not specify tags in more than one way (both via args and directly on the task). "
"Mixing tag specify styles is prohibited for whole import hierarchy, not only for single import statement",
obj=included_file._task._ds)
display.deprecated("You should not specify tags in the include parameters. All tags should be specified using the task-level option",
version='2.12')
included_file._task.tags = tags
block_list = load_list_of_blocks(
data,
play=iterator._play,
parent_block=ti_copy.build_parent_block(),
role=included_file._task._role,
use_handlers=is_handler,
loader=self._loader,
variable_manager=self._variable_manager,
)
# since we skip incrementing the stats when the task result is
# first processed, we do so now for each host in the list
for host in included_file._hosts:
self._tqm._stats.increment('ok', host.name)
except AnsibleError as e:
if isinstance(e, AnsibleFileNotFound):
reason = "Could not find or access '%s' on the Ansible Controller." % to_text(e.file_name)
else:
reason = to_text(e)
# mark all of the hosts including this file as failed, send callbacks,
# and increment the stats for this host
for host in included_file._hosts:
tr = TaskResult(host=host, task=included_file._task, return_data=dict(failed=True, reason=reason))
iterator.mark_host_failed(host)
self._tqm._failed_hosts[host.name] = True
self._tqm._stats.increment('failures', host.name)
self._tqm.send_callback('v2_runner_on_failed', tr)
return []
# finally, send the callback and return the list of blocks loaded
self._tqm.send_callback('v2_playbook_on_include', included_file)
display.debug("done processing included file")
return block_list
def run_handlers(self, iterator, play_context):
'''
Runs handlers on those hosts which have been notified.
'''
result = self._tqm.RUN_OK
for handler_block in iterator._play.handlers:
# FIXME: handlers need to support the rescue/always portions of blocks too,
# but this may take some work in the iterator and gets tricky when
# we consider the ability of meta tasks to flush handlers
for handler in handler_block.block:
if handler.notified_hosts:
result = self._do_handler_run(handler, handler.get_name(), iterator=iterator, play_context=play_context)
if not result:
break
return result
def _do_handler_run(self, handler, handler_name, iterator, play_context, notified_hosts=None):
# FIXME: need to use iterator.get_failed_hosts() instead?
# if not len(self.get_hosts_remaining(iterator._play)):
# self._tqm.send_callback('v2_playbook_on_no_hosts_remaining')
# result = False
# break
if notified_hosts is None:
notified_hosts = handler.notified_hosts[:]
notified_hosts = self._filter_notified_hosts(notified_hosts)
if len(notified_hosts) > 0:
saved_name = handler.name
handler.name = handler_name
self._tqm.send_callback('v2_playbook_on_handler_task_start', handler)
handler.name = saved_name
bypass_host_loop = False
try:
action = action_loader.get(handler.action, class_only=True)
if getattr(action, 'BYPASS_HOST_LOOP', False):
bypass_host_loop = True
except KeyError:
# we don't care here, because the action may simply not have a
# corresponding action plugin
pass
host_results = []
for host in notified_hosts:
if not iterator.is_failed(host) or iterator._play.force_handlers:
task_vars = self._variable_manager.get_vars(play=iterator._play, host=host, task=handler)
self.add_tqm_variables(task_vars, play=iterator._play)
templar = Templar(loader=self._loader, variables=task_vars)
if not handler.cached_name:
handler.name = templar.template(handler.name)
handler.cached_name = True
self._queue_task(host, handler, task_vars, play_context)
if templar.template(handler.run_once) or bypass_host_loop:
break
# collect the results from the handler run
host_results = self._wait_on_handler_results(iterator, handler, notified_hosts)
included_files = IncludedFile.process_include_results(
host_results,
iterator=iterator,
loader=self._loader,
variable_manager=self._variable_manager
)
result = True
if len(included_files) > 0:
for included_file in included_files:
try:
new_blocks = self._load_included_file(included_file, iterator=iterator, is_handler=True)
# for every task in each block brought in by the include, add the list
# of hosts which included the file to the notified_handlers dict
for block in new_blocks:
iterator._play.handlers.append(block)
for task in block.block:
task_name = task.get_name()
display.debug("adding task '%s' included in handler '%s'" % (task_name, handler_name))
task.notified_hosts = included_file._hosts[:]
result = self._do_handler_run(
handler=task,
handler_name=task_name,
iterator=iterator,
play_context=play_context,
notified_hosts=included_file._hosts[:],
)
if not result:
break
except AnsibleError as e:
for host in included_file._hosts:
iterator.mark_host_failed(host)
self._tqm._failed_hosts[host.name] = True
display.warning(to_text(e))
continue
# remove hosts from notification list
handler.notified_hosts = [
h for h in handler.notified_hosts
if h not in notified_hosts]
display.debug("done running handlers, result is: %s" % result)
return result
def _filter_notified_hosts(self, notified_hosts):
'''
Filter notified hosts accordingly to strategy
'''
# As main strategy is linear, we do not filter hosts
# We return a copy to avoid race conditions
return notified_hosts[:]
def _take_step(self, task, host=None):
ret = False
msg = u'Perform task: %s ' % task
if host:
msg += u'on %s ' % host
msg += u'(N)o/(y)es/(c)ontinue: '
resp = display.prompt(msg)
if resp.lower() in ['y', 'yes']:
display.debug("User ran task")
ret = True
elif resp.lower() in ['c', 'continue']:
display.debug("User ran task and canceled step mode")
self._step = False
ret = True
else:
display.debug("User skipped task")
display.banner(msg)
return ret
def _cond_not_supported_warn(self, task_name):
display.warning("%s task does not support when conditional" % task_name)
def _execute_meta(self, task, play_context, iterator, target_host):
# meta tasks store their args in the _raw_params field of args,
# since they do not use k=v pairs, so get that
meta_action = task.args.get('_raw_params')
def _evaluate_conditional(h):
all_vars = self._variable_manager.get_vars(play=iterator._play, host=h, task=task)
templar = Templar(loader=self._loader, variables=all_vars)
return task.evaluate_conditional(templar, all_vars)
skipped = False
msg = ''
if meta_action == 'noop':
# FIXME: issue a callback for the noop here?
if task.when:
self._cond_not_supported_warn(meta_action)
msg = "noop"
elif meta_action == 'flush_handlers':
if task.when:
self._cond_not_supported_warn(meta_action)
self._flushed_hosts[target_host] = True
self.run_handlers(iterator, play_context)
self._flushed_hosts[target_host] = False
msg = "ran handlers"
elif meta_action == 'refresh_inventory' or self.flush_cache:
if task.when:
self._cond_not_supported_warn(meta_action)
self._inventory.refresh_inventory()
msg = "inventory successfully refreshed"
elif meta_action == 'clear_facts':
if _evaluate_conditional(target_host):
for host in self._inventory.get_hosts(iterator._play.hosts):
hostname = host.get_name()
self._variable_manager.clear_facts(hostname)
msg = "facts cleared"
else:
skipped = True
elif meta_action == 'clear_host_errors':
if _evaluate_conditional(target_host):
for host in self._inventory.get_hosts(iterator._play.hosts):
self._tqm._failed_hosts.pop(host.name, False)
self._tqm._unreachable_hosts.pop(host.name, False)
iterator._host_states[host.name].fail_state = iterator.FAILED_NONE
msg = "cleared host errors"
else:
skipped = True
elif meta_action == 'end_play':
if _evaluate_conditional(target_host):
for host in self._inventory.get_hosts(iterator._play.hosts):
if host.name not in self._tqm._unreachable_hosts:
iterator._host_states[host.name].run_state = iterator.ITERATING_COMPLETE
msg = "ending play"
elif meta_action == 'end_host':
if _evaluate_conditional(target_host):
iterator._host_states[target_host.name].run_state = iterator.ITERATING_COMPLETE
msg = "ending play for %s" % target_host.name
else:
skipped = True
msg = "end_host conditional evaluated to false, continuing execution for %s" % target_host.name
elif meta_action == 'reset_connection':
all_vars = self._variable_manager.get_vars(play=iterator._play, host=target_host, task=task)
templar = Templar(loader=self._loader, variables=all_vars)
# apply the given task's information to the connection info,
# which may override some fields already set by the play or
# the options specified on the command line
play_context = play_context.set_task_and_variable_override(task=task, variables=all_vars, templar=templar)
# fields set from the play/task may be based on variables, so we have to
# do the same kind of post validation step on it here before we use it.
play_context.post_validate(templar=templar)
# now that the play context is finalized, if the remote_addr is not set
# default to using the host's address field as the remote address
if not play_context.remote_addr:
play_context.remote_addr = target_host.address
# We also add "magic" variables back into the variables dict to make sure
# a certain subset of variables exist.
play_context.update_vars(all_vars)
if task.when:
self._cond_not_supported_warn(meta_action)
if target_host in self._active_connections:
connection = Connection(self._active_connections[target_host])
del self._active_connections[target_host]
else:
connection = connection_loader.get(play_context.connection, play_context, os.devnull)
play_context.set_attributes_from_plugin(connection)
if connection:
try:
connection.reset()
msg = 'reset connection'
except ConnectionError as e:
# most likely socket is already closed
display.debug("got an error while closing persistent connection: %s" % e)
else:
msg = 'no connection, nothing to reset'
else:
raise AnsibleError("invalid meta action requested: %s" % meta_action, obj=task._ds)
result = {'msg': msg}
if skipped:
result['skipped'] = True
else:
result['changed'] = False
display.vv("META: %s" % msg)
return [TaskResult(target_host, task, result)]
def get_hosts_left(self, iterator):
''' returns list of available hosts for this iterator by filtering out unreachables '''
hosts_left = []
for host in self._inventory.get_hosts(iterator._play.hosts, order=iterator._play.order):
if host.name not in self._tqm._unreachable_hosts:
hosts_left.append(host)
return hosts_left
def update_active_connections(self, results):
''' updates the current active persistent connections '''
for r in results:
if 'args' in r._task_fields:
socket_path = r._task_fields['args'].get('_ansible_socket')
if socket_path:
if r._host not in self._active_connections:
self._active_connections[r._host] = socket_path
class NextAction(object):
""" The next action after an interpreter's exit. """
REDO = 1
CONTINUE = 2
EXIT = 3
def __init__(self, result=EXIT):
self.result = result
class Debugger(cmd.Cmd):
prompt_continuous = '> ' # multiple lines
def __init__(self, task, host, task_vars, play_context, result, next_action):
# cmd.Cmd is old-style class
cmd.Cmd.__init__(self)
self.prompt = '[%s] %s (debug)> ' % (host, task)
self.intro = None
self.scope = {}
self.scope['task'] = task
self.scope['task_vars'] = task_vars
self.scope['host'] = host
self.scope['play_context'] = play_context
self.scope['result'] = result
self.next_action = next_action
def cmdloop(self):
try:
cmd.Cmd.cmdloop(self)
except KeyboardInterrupt:
pass
do_h = cmd.Cmd.do_help
def do_EOF(self, args):
"""Quit"""
return self.do_quit(args)
def do_quit(self, args):
"""Quit"""
display.display('User interrupted execution')
self.next_action.result = NextAction.EXIT
return True
do_q = do_quit
def do_continue(self, args):
"""Continue to next result"""
self.next_action.result = NextAction.CONTINUE
return True
do_c = do_continue
def do_redo(self, args):
"""Schedule task for re-execution. The re-execution may not be the next result"""
self.next_action.result = NextAction.REDO
return True
do_r = do_redo
def do_update_task(self, args):
"""Recreate the task from ``task._ds``, and template with updated ``task_vars``"""
templar = Templar(None, shared_loader_obj=None, variables=self.scope['task_vars'])
task = self.scope['task']
task = task.load_data(task._ds)
task.post_validate(templar)
self.scope['task'] = task
do_u = do_update_task
def evaluate(self, args):
try:
return eval(args, globals(), self.scope)
except Exception:
t, v = sys.exc_info()[:2]
if isinstance(t, str):
exc_type_name = t
else:
exc_type_name = t.__name__
display.display('***%s:%s' % (exc_type_name, repr(v)))
raise
def do_pprint(self, args):
"""Pretty Print"""
try:
result = self.evaluate(args)
display.display(pprint.pformat(result))
except Exception:
pass
do_p = do_pprint
def execute(self, args):
try:
code = compile(args + '\n', '<stdin>', 'single')
exec(code, globals(), self.scope)
except Exception:
t, v = sys.exc_info()[:2]
if isinstance(t, str):
exc_type_name = t
else:
exc_type_name = t.__name__
display.display('***%s:%s' % (exc_type_name, repr(v)))
raise
def default(self, line):
try:
self.execute(line)
except Exception:
pass
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,980 |
force_valid_group_names throws unexpected exception if invalid names used with add_host/group_by
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
<!--- Explain the problem briefly below -->
While using a simple reproducer with either force_valid_group_names=silently or force_valid_group_names=always an unexpected exception is thrown:
Sample playbook:
```
---
- hosts: localhost
connection: local
gather_facts: false
tasks:
- name: add a host to a group
add_host:
name: localhost
groups: Not-Working
```
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
inventory
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```
ansible --version
ansible 2.9.0.dev0
config file = /opt/gmuniz/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /opt/ansible-devel/ansible/lib/ansible
executable location = /opt/ansible-devel/ansible/bin/ansible
python version = 2.7.5 (default, Apr 9 2019, 14:30:50) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```
ansible-config dump --only-changed
TRANSFORM_INVALID_GROUP_CHARS(/opt/gmuniz/ansible.cfg) = always
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
CentOs-7
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```
- hosts: localhost
connection: local
gather_facts: false
tasks:
- name: add a host to a group
add_host:
name: localhost
groups: Not-Working
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
I expect the host to be added to the group either with the originally provided name or the replaced underscore name.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```
TASK [add a host to a group] *************************************************************************************************************************************************************************************
task path: /opt/gmuniz/add_host.yml:6
creating host via 'add_host': hostname=localhost
[WARNING]: A duplicate localhost-like entry was found (localhost). First found localhost was localhost
[WARNING]: Invalid characters were found in group names and automatically replaced, use -vvvv to see details
ERROR! Unexpected Exception, this is probably a bug: u'Not-Working'
```
|
https://github.com/ansible/ansible/issues/58980
|
https://github.com/ansible/ansible/pull/58982
|
b0f38931b0e0b55db30a012e81683d380ea7a670
|
a7b14ec1becb947cc290deebe309ef06a12d1f7e
| 2019-07-11T13:32:26Z |
python
| 2019-07-11T17:49:49Z |
test/integration/targets/inventory/runme.sh
|
#!/usr/bin/env bash
set -x
# https://github.com/ansible/ansible/issues/52152
# Ensure that non-matching limit causes failure with rc 1
ansible-playbook -i ../../inventory --limit foo playbook.yml
if [ "$?" != "1" ]; then
echo "Non-matching limit should cause failure"
exit 1
fi
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,980 |
force_valid_group_names throws unexpected exception if invalid names used with add_host/group_by
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
<!--- Explain the problem briefly below -->
While using a simple reproducer with either force_valid_group_names=silently or force_valid_group_names=always an unexpected exception is thrown:
Sample playbook:
```
---
- hosts: localhost
connection: local
gather_facts: false
tasks:
- name: add a host to a group
add_host:
name: localhost
groups: Not-Working
```
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
inventory
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```
ansible --version
ansible 2.9.0.dev0
config file = /opt/gmuniz/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /opt/ansible-devel/ansible/lib/ansible
executable location = /opt/ansible-devel/ansible/bin/ansible
python version = 2.7.5 (default, Apr 9 2019, 14:30:50) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```
ansible-config dump --only-changed
TRANSFORM_INVALID_GROUP_CHARS(/opt/gmuniz/ansible.cfg) = always
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
CentOs-7
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```
- hosts: localhost
connection: local
gather_facts: false
tasks:
- name: add a host to a group
add_host:
name: localhost
groups: Not-Working
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
I expect the host to be added to the group either with the originally provided name or the replaced underscore name.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```
TASK [add a host to a group] *************************************************************************************************************************************************************************************
task path: /opt/gmuniz/add_host.yml:6
creating host via 'add_host': hostname=localhost
[WARNING]: A duplicate localhost-like entry was found (localhost). First found localhost was localhost
[WARNING]: Invalid characters were found in group names and automatically replaced, use -vvvv to see details
ERROR! Unexpected Exception, this is probably a bug: u'Not-Working'
```
|
https://github.com/ansible/ansible/issues/58980
|
https://github.com/ansible/ansible/pull/58982
|
b0f38931b0e0b55db30a012e81683d380ea7a670
|
a7b14ec1becb947cc290deebe309ef06a12d1f7e
| 2019-07-11T13:32:26Z |
python
| 2019-07-11T17:49:49Z |
test/integration/targets/inventory/strategy.yml
| |
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,609 |
aix_filesystem.py - fail_json() missing msg=
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
When passed invalid data, a number of functions in `lib/ansible/modules/system/aix_filesystem.py` are running fail_json() without `msg=` on the error message itself, generating: `TypeError: exit_json() takes exactly 1 argument (4 given)` when attempting to fail.
ie:
```python2
def resize_fs(module, filesystem, size):
....
module.fail_json("Failed to run chfs.", rc=rc, err=err)
....
def mount_fs(module, filesystem):
...
module.fail_json("Failed to run mount.", rc=rc, err=err)
...
def unmount_fs(module, filesystem):
...
module.fail_json("Failed to run unmount.", rc=rc, err=err)
...
```
To fulfil function requirements, kwargs should be:
```python2
def resize_fs(module, filesystem, size):
....
module.fail_json(msg="Failed to run chfs.", rc=rc, err=err)
....
def mount_fs(module, filesystem):
...
module.fail_json(msg="Failed to run mount.", rc=rc, err=err)
...
def unmount_fs(module, filesystem):
...
module.fail_json(msg="Failed to run unmount.", rc=rc, err=err)
...
```
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
aix_filesystem.py
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.8.0
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 = /bin/ansible
python version = 2.7.5 (default, Apr 9 2019, 14:30:50) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
ANSIBLE_PIPELINING(/etc/ansible/ansible.cfg) = True
ANSIBLE_SSH_ARGS(/etc/ansible/ansible.cfg) = -o ForwardAgent=no
COMMAND_WARNINGS(/etc/ansible/ansible.cfg) = True
DEFAULT_BECOME(/etc/ansible/ansible.cfg) = True
DEFAULT_FORCE_HANDLERS(/etc/ansible/ansible.cfg) = True
DEFAULT_FORKS(/etc/ansible/ansible.cfg) = 50
DEFAULT_KEEP_REMOTE_FILES(env: ANSIBLE_KEEP_REMOTE_FILES) = True
DEFAULT_MANAGED_STR(/etc/ansible/ansible.cfg) = This file is managed by ansible - local changes will be lost! - Last Updated {{ now(fmt='%Y/%m/%d - %H:%M:%S %z(%Z)') }}
DEFAULT_REMOTE_USER(/etc/ansible/ansible.cfg) = root
DEFAULT_ROLES_PATH(/etc/ansible/ansible.cfg) = [u'/etc/ansible/roles/internal', u'/etc/ansible/roles/external']
DEFAULT_TRANSPORT(/etc/ansible/ansible.cfg) = ssh
DEPRECATION_WARNINGS(/etc/ansible/ansible.cfg) = True
RETRY_FILES_ENABLED(/etc/ansible/ansible.cfg) = True
SYSTEM_WARNINGS(/etc/ansible/ansible.cfg) = True
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
AIX
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
Run module with the above invalid data, such as mounting a filesystem which does not exist.
<!--- Paste example playbooks or commands between quotes below -->
```yaml
ansible HOSTNAME -i /etc/ansible/test.ini -m aix_filesystem -a "filesystem=/mnt/exp1 state=mounted"
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
With a fix in place in `mount_fs()` :
```
if rc != 0:
module.fail_json(msg="Failed to run mount.", rc=rc, err=err)
```
```
{"msg": "Failed to run mount.", "failed": true, "rc": 1, "err": "mount: /mnt/exp1 is not a known file system\n", "invocation": {"module_args": {"size": null, "vg": null, "rm_mount_point": false, "auto_mount": true, "account_subsystem": false, "mount_group": null, "state": "mounted", "fs_type": "jfs2", "filesystem": "/mnt/exp1", "device": "lv_exp1", "nfs_server": null, "attributes": ["agblksize='4096'", "isnapshot='no'"], "permissions": "rw"}}}
```
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
Using current code:
```
if rc != 0:
print(err)
module.fail_json("Failed to run mount.", rc=rc, err=err)
```
<!--- Paste verbatim command output between quotes -->
```paste below
Traceback (most recent call last):
File "__main__.py", line 579, in <module>
main()
File "__main__.py", line 561, in main
result['changed'], result['msg'] = mount_fs(module, filesystem)
File "__main__.py", line 430, in mount_fs
module.fail_json("Failed to run mount.", rc=rc, err=err)
TypeError: fail_json() takes exactly 1 argument (4 given)
```
|
https://github.com/ansible/ansible/issues/58609
|
https://github.com/ansible/ansible/pull/58642
|
adea964c3e58a30118a6b4a5a45a835b4f3b68a8
|
75724bb7cabcdd78eed0ee3435b056e75db315ee
| 2019-07-01T21:12:46Z |
python
| 2019-07-11T18:23:18Z |
lib/ansible/modules/system/aix_filesystem.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2017, Kairo Araujo <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
author:
- Kairo Araujo (@kairoaraujo)
module: aix_filesystem
short_description: Configure LVM and NFS file systems for AIX
description:
- This module creates, removes, mount and unmount LVM and NFS file system for
AIX using C(/etc/filesystems).
- For LVM file systems is possible to resize a file system.
version_added: '2.8'
options:
account_subsystem:
description:
- Specifies whether the file system is to be processed by the accounting subsystem.
type: bool
default: no
attributes:
description:
- Specifies attributes for files system separated by comma.
type: list
default: agblksize='4096',isnapshot='no'
auto_mount:
description:
- File system is automatically mounted at system restart.
type: bool
default: yes
device:
description:
- Logical volume (LV) device name or remote export device to create a NFS file system.
- It is used to create a file system on an already existing logical volume or the exported NFS file system.
- If not mentioned a new logical volume name will be created following AIX standards (LVM).
type: str
fs_type:
description:
- Specifies the virtual file system type.
type: str
default: jfs2
permissions:
description:
- Set file system permissions. C(rw) (read-write) or C(ro) (read-only).
type: str
choices: [ ro, rw ]
default: rw
mount_group:
description:
- Specifies the mount group.
type: str
filesystem:
description:
- Specifies the mount point, which is the directory where the file system will be mounted.
type: str
required: true
nfs_server:
description:
- Specifies a Network File System (NFS) server.
type: str
rm_mount_point:
description:
- Removes the mount point directory when used with state C(absent).
type: bool
default: no
size:
description:
- Specifies the file system size.
- For already C(present) it will be resized.
- 512-byte blocks, Megabytes or Gigabytes. If the value has M specified
it will be in Megabytes. If the value has G specified it will be in
Gigabytes.
- If no M or G the value will be 512-byte blocks.
- If "+" is specified in begin of value, the value will be added.
- If "-" is specified in begin of value, the value will be removed.
- If "+" or "-" is not specified, the total value will be the specified.
- Size will respects the LVM AIX standards.
type: str
state:
description:
- Controls the file system state.
- C(present) check if file system exists, creates or resize.
- C(absent) removes existing file system if already C(unmounted).
- C(mounted) checks if the file system is mounted or mount the file system.
- C(unmounted) check if the file system is unmounted or unmount the file system.
type: str
required: true
choices: [ absent, mounted, present, unmounted ]
default: present
vg:
description:
- Specifies an existing volume group (VG).
type: str
notes:
- For more C(attributes), please check "crfs" AIX manual.
'''
EXAMPLES = r'''
- name: Create filesystem in a previously defined logical volume.
aix_filesystem:
device: testlv
filesystem: /testfs
state: present
- name: Creating NFS filesystem from nfshost.
aix_filesystem:
device: /home/ftp
nfs_server: nfshost
filesystem: /home/ftp
state: present
- name: Creating a new file system without a previously logical volume.
aix_filesystem:
filesystem: /newfs
size: 1G
state: present
vg: datavg
- name: Unmounting /testfs.
aix_filesystem:
filesystem: /testfs
state: unmounted
- name: Resizing /mksysb to +512M.
aix_filesystem:
filesystem: /mksysb
size: +512M
state: present
- name: Resizing /mksysb to 11G.
aix_filesystem:
filesystem: /mksysb
size: 11G
state: present
- name: Resizing /mksysb to -2G.
aix_filesystem:
filesystem: /mksysb
size: -2G
state: present
- name: Remove NFS filesystem /home/ftp.
aix_filesystem:
filesystem: /home/ftp
rm_mount_point: yes
state: absent
- name: Remove /newfs.
aix_filesystem:
filesystem: /newfs
rm_mount_point: yes
state: absent
'''
RETURN = r'''
changed:
description: Return changed for aix_filesystems actions as true or false.
returned: always
type: bool
msg:
description: Return message regarding the action.
returned: always
type: str
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ismount import ismount
import re
def _fs_exists(module, filesystem):
"""
Check if file system already exists on /etc/filesystems.
:param module: Ansible module.
:param filesystem: filesystem name.
:return: True or False.
"""
lsfs_cmd = module.get_bin_path('lsfs', True)
rc, lsfs_out, err = module.run_command("%s -l %s" % (lsfs_cmd, filesystem))
if rc == 1:
if re.findall("No record matching", err):
return False
else:
module.fail_json(msg="Failed to run lsfs.", rc=rc, err=err)
else:
return True
def _check_nfs_device(module, nfs_host, device):
"""
Validate if NFS server is exporting the device (remote export).
:param module: Ansible module.
:param nfs_host: nfs_host parameter, NFS server.
:param device: device parameter, remote export.
:return: True or False.
"""
showmount_cmd = module.get_bin_path('showmount', True)
rc, showmount_out, err = module.run_command(
"%s -a %s" % (showmount_cmd, nfs_host))
if rc != 0:
module.fail_json(msg="Failed to run showmount.", rc=rc, err=err)
else:
showmount_data = showmount_out.splitlines()
for line in showmount_data:
if line.split(':')[1] == device:
return True
return False
def _validate_vg(module, vg):
"""
Check the current state of volume group.
:param module: Ansible module argument spec.
:param vg: Volume Group name.
:return: True (VG in varyon state) or False (VG in varyoff state) or
None (VG does not exist), message.
"""
lsvg_cmd = module.get_bin_path('lsvg', True)
rc, current_active_vgs, err = module.run_command("%s -o" % lsvg_cmd)
if rc != 0:
module.fail_json(msg="Failed executing %s command." % lsvg_cmd)
rc, current_all_vgs, err = module.run_command("%s" % lsvg_cmd)
if rc != 0:
module.fail_json(msg="Failed executing %s command." % lsvg_cmd)
if vg in current_all_vgs and vg not in current_active_vgs:
msg = "Volume group %s is in varyoff state." % vg
return False, msg
elif vg in current_active_vgs:
msg = "Volume group %s is in varyon state." % vg
return True, msg
else:
msg = "Volume group %s does not exist." % vg
return None, msg
def resize_fs(module, filesystem, size):
""" Resize LVM file system. """
chfs_cmd = module.get_bin_path('chfs', True)
if not module.check_mode:
rc, chfs_out, err = module.run_command('%s -a size="%s" %s' % (chfs_cmd, size, filesystem))
if rc == 28:
changed = False
return changed, chfs_out
elif rc != 0:
if re.findall('Maximum allocation for logical', err):
changed = False
return changed, err
else:
module.fail_json("Failed to run chfs.", rc=rc, err=err)
else:
if re.findall('The filesystem size is already', chfs_out):
changed = False
else:
changed = True
return changed, chfs_out
else:
changed = True
msg = ''
return changed, msg
def create_fs(
module, fs_type, filesystem, vg, device, size, mount_group, auto_mount,
account_subsystem, permissions, nfs_server, attributes):
""" Create LVM file system or NFS remote mount point. """
attributes = ' -a '.join(attributes)
# Parameters definition.
account_subsys_opt = {
True: '-t yes',
False: '-t no'
}
if nfs_server is not None:
auto_mount_opt = {
True: '-A',
False: '-a'
}
else:
auto_mount_opt = {
True: '-A yes',
False: '-A no'
}
if size is None:
size = ''
else:
size = "-a size=%s" % size
if device is None:
device = ''
else:
device = "-d %s" % device
if vg is None:
vg = ''
else:
vg_state, msg = _validate_vg(module, vg)
if vg_state:
vg = "-g %s" % vg
else:
changed = False
return changed, msg
if mount_group is None:
mount_group = ''
else:
mount_group = "-u %s" % mount_group
auto_mount = auto_mount_opt[auto_mount]
account_subsystem = account_subsys_opt[account_subsystem]
if nfs_server is not None:
# Creates a NFS file system.
mknfsmnt_cmd = module.get_bin_path('mknfsmnt', True)
if not module.check_mode:
rc, mknfsmnt_out, err = module.run_command('%s -f "%s" %s -h "%s" -t "%s" "%s" -w "bg"' % (
mknfsmnt_cmd, filesystem, device, nfs_server, permissions, auto_mount))
if rc != 0:
module.fail_json(msg="Failed to run mknfsmnt.", rc=rc, err=err)
else:
changed = True
msg = "NFS file system %s created." % filesystem
return changed, msg
else:
changed = True
msg = ''
return changed, msg
else:
# Creates a LVM file system.
crfs_cmd = module.get_bin_path('crfs', True)
if not module.check_mode:
rc, crfs_out, err = module.run_command(
"%s -v %s -m %s %s %s %s %s %s -p %s %s -a %s" % (
crfs_cmd, fs_type, filesystem, vg, device, mount_group, auto_mount, account_subsystem, permissions, size, attributes))
if rc == 10:
module.exit_json(
msg="Using a existent previously defined logical volume, "
"volume group needs to be empty. %s" % err)
elif rc != 0:
module.fail_json(msg="Failed to run crfs.", rc=rc, err=err)
else:
changed = True
return changed, crfs_out
else:
changed = True
msg = ''
return changed, msg
def remove_fs(module, filesystem, rm_mount_point):
""" Remove an LVM file system or NFS entry. """
# Command parameters.
rm_mount_point_opt = {
True: '-r',
False: ''
}
rm_mount_point = rm_mount_point_opt[rm_mount_point]
rmfs_cmd = module.get_bin_path('rmfs', True)
if not module.check_mode:
rc, rmfs_out, err = module.run_command("%s -r %s %s" % (rmfs_cmd, rm_mount_point, filesystem))
if rc != 0:
module.fail_json(msg="Failed to run rmfs.", rc=rc, err=err)
else:
changed = True
msg = rmfs_out
if not rmfs_out:
msg = "File system %s removed." % filesystem
return changed, msg
else:
changed = True
msg = ''
return changed, msg
def mount_fs(module, filesystem):
""" Mount a file system. """
mount_cmd = module.get_bin_path('mount', True)
if not module.check_mode:
rc, mount_out, err = module.run_command(
"%s %s" % (mount_cmd, filesystem))
if rc != 0:
module.fail_json("Failed to run mount.", rc=rc, err=err)
else:
changed = True
msg = "File system %s mounted." % filesystem
return changed, msg
else:
changed = True
msg = ''
return changed, msg
def unmount_fs(module, filesystem):
""" Unmount a file system."""
unmount_cmd = module.get_bin_path('unmount', True)
if not module.check_mode:
rc, unmount_out, err = module.run_command("%s %s" % (unmount_cmd, filesystem))
if rc != 0:
module.fail_json("Failed to run unmount.", rc=rc, err=err)
else:
changed = True
msg = "File system %s unmounted." % filesystem
return changed, msg
else:
changed = True
msg = ''
return changed, msg
def main():
module = AnsibleModule(
argument_spec=dict(
account_subsystem=dict(type='bool', default=False),
attributes=dict(type='list', default=["agblksize='4096'", "isnapshot='no'"]),
auto_mount=dict(type='bool', default=True),
device=dict(type='str'),
filesystem=dict(type='str', required=True),
fs_type=dict(type='str', default='jfs2'),
permissions=dict(type='str', default='rw', choices=['rw', 'ro']),
mount_group=dict(type='str'),
nfs_server=dict(type='str'),
rm_mount_point=dict(type='bool', default=False),
size=dict(type='str'),
state=dict(type='str', default='present', choices=['absent', 'mounted', 'present', 'unmounted']),
vg=dict(type='str'),
),
supports_check_mode=True,
)
account_subsystem = module.params['account_subsystem']
attributes = module.params['attributes']
auto_mount = module.params['auto_mount']
device = module.params['device']
fs_type = module.params['fs_type']
permissions = module.params['permissions']
mount_group = module.params['mount_group']
filesystem = module.params['filesystem']
nfs_server = module.params['nfs_server']
rm_mount_point = module.params['rm_mount_point']
size = module.params['size']
state = module.params['state']
vg = module.params['vg']
result = dict(
changed=False,
msg='',
)
if state == 'present':
fs_mounted = ismount(filesystem)
fs_exists = _fs_exists(module, filesystem)
# Check if fs is mounted or exists.
if fs_mounted or fs_exists:
result['msg'] = "File system %s already exists." % filesystem
result['changed'] = False
# If parameter size was passed, resize fs.
if size is not None:
result['changed'], result['msg'] = resize_fs(module, filesystem, size)
# If fs doesn't exist, create it.
else:
# Check if fs will be a NFS device.
if nfs_server is not None:
if device is None:
result['msg'] = 'Parameter "device" is required when "nfs_server" is defined.'
module.fail_json(**result)
else:
# Create a fs from NFS export.
if _check_nfs_device(module, nfs_server, device):
result['changed'], result['msg'] = create_fs(
module, fs_type, filesystem, vg, device, size, mount_group, auto_mount, account_subsystem, permissions, nfs_server, attributes)
if device is None:
if vg is None:
module.fail_json(**result)
else:
# Create a fs from
result['changed'], result['msg'] = create_fs(
module, fs_type, filesystem, vg, device, size, mount_group, auto_mount, account_subsystem, permissions, nfs_server, attributes)
if device is not None and nfs_server is None:
# Create a fs from a previously lv device.
result['changed'], result['msg'] = create_fs(
module, fs_type, filesystem, vg, device, size, mount_group, auto_mount, account_subsystem, permissions, nfs_server, attributes)
elif state == 'absent':
if ismount(filesystem):
result['msg'] = "File system %s mounted." % filesystem
else:
fs_status = _fs_exists(module, filesystem)
if not fs_status:
result['msg'] = "File system %s does not exist." % filesystem
else:
result['changed'], result['msg'] = remove_fs(module, filesystem, rm_mount_point)
elif state == 'mounted':
if ismount(filesystem):
result['changed'] = False
result['msg'] = "File system %s already mounted." % filesystem
else:
result['changed'], result['msg'] = mount_fs(module, filesystem)
elif state == 'unmounted':
if not ismount(filesystem):
result['changed'] = False
result['msg'] = "File system %s already unmounted." % filesystem
else:
result['changed'], result['msg'] = unmount_fs(module, filesystem)
else:
# Unreachable codeblock
result['msg'] = "Unexpected state %s." % state
module.fail_json(**result)
module.exit_json(**result)
if __name__ == '__main__':
main()
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,337 |
nmcli conn_name description
|
<!--- Verify first that your improvement is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
<!--- Explain the problem briefly below, add suggestions to wording or structure -->
nmcli docs state, for the conn_name option: when not provided a default name is generated: `<type>[-<ifname>][-<num>]`
am I misunderstanding something or does this imply that the option isn't actually required?
<!--- HINT: Did you know the documentation has an "Edit on GitHub" link on every page ? -->
##### ISSUE TYPE
- Documentation Report
##### COMPONENT NAME
<!--- Write the short name of the rst file, module, plugin, task or feature below, use your best guess if unsure -->
nmcli
|
https://github.com/ansible/ansible/issues/58337
|
https://github.com/ansible/ansible/pull/59034
|
343acd76d459993de64cf8e7a519f9d344b81620
|
fec314febb63185151dfae7386c29f0623894288
| 2019-06-25T14:30:42Z |
python
| 2019-07-12T20:07:55Z |
lib/ansible/modules/net_tools/nmcli.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2015, Chris Long <[email protected]> <[email protected]>
# Copyright: (c) 2017, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: nmcli
author:
- Chris Long (@alcamie101)
short_description: Manage Networking
requirements:
- dbus
- NetworkManager-glib
- nmcli
version_added: "2.0"
description:
- Manage the network devices. Create, modify and manage various connection and device type e.g., ethernet, teams, bonds, vlans etc.
- 'On CentOS and Fedora like systems, the requirements can be met by installing the following packages: NetworkManager-glib,
libnm-qt-devel.x86_64, nm-connection-editor.x86_64, libsemanage-python, policycoreutils-python.'
- 'On Ubuntu and Debian like systems, the requirements can be met by installing the following packages: network-manager,
python-dbus (or python3-dbus, depending on the Python version in use), libnm-glib-dev.'
- 'On openSUSE, the requirements can be met by installing the following packages: NetworkManager, python2-dbus-python (or
python3-dbus-python), typelib-1_0-NMClient-1_0 and typelib-1_0-NetworkManager-1_0.'
options:
state:
description:
- Whether the device should exist or not, taking action if the state is different from what is stated.
type: str
required: true
choices: [ absent, present ]
autoconnect:
description:
- Whether the connection should start on boot.
- Whether the connection profile can be automatically activated
type: bool
default: yes
conn_name:
description:
- 'Where conn_name will be the name used to call the connection. when not provided a default name is generated: <type>[-<ifname>][-<num>]'
type: str
required: true
ifname:
description:
- The interface to bind the connection to.
- The connection will only be applicable to this interface name.
- A special value of C('*') can be used for interface-independent connections.
- The ifname argument is mandatory for all connection types except bond, team, bridge and vlan.
- This parameter defaults to C(conn_name) when left unset.
type: str
type:
description:
- This is the type of device or network connection that you wish to create or modify.
- Type C(generic) is added in Ansible 2.5.
type: str
choices: [ bond, bond-slave, bridge, bridge-slave, ethernet, generic, ipip, sit, team, team-slave, vlan, vxlan ]
mode:
description:
- This is the type of device or network connection that you wish to create for a bond, team or bridge.
type: str
choices: [ 802.3ad, active-backup, balance-alb, balance-rr, balance-tlb, balance-xor, broadcast ]
default: balance-rr
master:
description:
- Master <master (ifname, or connection UUID or conn_name) of bridge, team, bond master connection profile.
type: str
ip4:
description:
- The IPv4 address to this interface.
- Use the format C(192.0.2.24/24).
type: str
gw4:
description:
- The IPv4 gateway for this interface.
- Use the format C(192.0.2.1).
type: str
dns4:
description:
- A list of up to 3 dns servers.
- IPv4 format e.g. to add two IPv4 DNS server addresses, use C(192.0.2.53 198.51.100.53).
type: list
dns4_search:
description:
- A list of DNS search domains.
type: list
version_added: '2.5'
ip6:
description:
- The IPv6 address to this interface.
- Use the format C(abbe::cafe).
type: str
gw6:
description:
- The IPv6 gateway for this interface.
- Use the format C(2001:db8::1).
type: str
dns6:
description:
- A list of up to 3 dns servers.
- IPv6 format e.g. to add two IPv6 DNS server addresses, use C(2001:4860:4860::8888 2001:4860:4860::8844).
type: list
dns6_search:
description:
- A list of DNS search domains.
type: list
version_added: '2.5'
mtu:
description:
- The connection MTU, e.g. 9000. This can't be applied when creating the interface and is done once the interface has been created.
- Can be used when modifying Team, VLAN, Ethernet (Future plans to implement wifi, pppoe, infiniband)
- This parameter defaults to C(1500) when unset.
type: int
dhcp_client_id:
description:
- DHCP Client Identifier sent to the DHCP server.
type: str
version_added: "2.5"
primary:
description:
- This is only used with bond and is the primary interface name (for "active-backup" mode), this is the usually the 'ifname'.
type: str
miimon:
description:
- This is only used with bond - miimon.
- This parameter defaults to C(100) when unset.
type: int
downdelay:
description:
- This is only used with bond - downdelay.
type: int
updelay:
description:
- This is only used with bond - updelay.
type: int
arp_interval:
description:
- This is only used with bond - ARP interval.
type: int
arp_ip_target:
description:
- This is only used with bond - ARP IP target.
type: str
stp:
description:
- This is only used with bridge and controls whether Spanning Tree Protocol (STP) is enabled for this bridge.
type: bool
default: yes
priority:
description:
- This is only used with 'bridge' - sets STP priority.
type: int
default: 128
forwarddelay:
description:
- This is only used with bridge - [forward-delay <2-30>] STP forwarding delay, in seconds.
type: int
default: 15
hellotime:
description:
- This is only used with bridge - [hello-time <1-10>] STP hello time, in seconds.
type: int
default: 2
maxage:
description:
- This is only used with bridge - [max-age <6-42>] STP maximum message age, in seconds.
type: int
default: 20
ageingtime:
description:
- This is only used with bridge - [ageing-time <0-1000000>] the Ethernet MAC address aging time, in seconds.
type: int
default: 300
mac:
description:
- This is only used with bridge - MAC address of the bridge.
- Note this requires a recent kernel feature, originally introduced in 3.15 upstream kernel.
slavepriority:
description:
- This is only used with 'bridge-slave' - [<0-63>] - STP priority of this slave.
type: int
default: 32
path_cost:
description:
- This is only used with 'bridge-slave' - [<1-65535>] - STP port cost for destinations via this slave.
type: int
default: 100
hairpin:
description:
- This is only used with 'bridge-slave' - 'hairpin mode' for the slave, which allows frames to be sent back out through the slave the
frame was received on.
type: bool
default: yes
vlanid:
description:
- This is only used with VLAN - VLAN ID in range <0-4095>.
type: int
vlandev:
description:
- This is only used with VLAN - parent device this VLAN is on, can use ifname.
type: str
flags:
description:
- This is only used with VLAN - flags.
type: str
ingress:
description:
- This is only used with VLAN - VLAN ingress priority mapping.
type: str
egress:
description:
- This is only used with VLAN - VLAN egress priority mapping.
type: str
vxlan_id:
description:
- This is only used with VXLAN - VXLAN ID.
type: int
version_added: "2.8"
vxlan_remote:
description:
- This is only used with VXLAN - VXLAN destination IP address.
type: str
version_added: "2.8"
vxlan_local:
description:
- This is only used with VXLAN - VXLAN local IP address.
type: str
version_added: "2.8"
ip_tunnel_dev:
description:
- This is used with IPIP/SIT - parent device this IPIP/SIT tunnel, can use ifname.
type: str
version_added: "2.8"
ip_tunnel_remote:
description:
- This is used with IPIP/SIT - IPIP/SIT destination IP address.
type: str
version_added: "2.8"
ip_tunnel_local:
description:
- This is used with IPIP/SIT - IPIP/SIT local IP address.
type: str
version_added: "2.8"
'''
EXAMPLES = r'''
# These examples are using the following inventory:
#
# ## Directory layout:
#
# |_/inventory/cloud-hosts
# | /group_vars/openstack-stage.yml
# | /host_vars/controller-01.openstack.host.com
# | /host_vars/controller-02.openstack.host.com
# |_/playbook/library/nmcli.py
# | /playbook-add.yml
# | /playbook-del.yml
# ```
#
# ## inventory examples
# ### groups_vars
# ```yml
# ---
# #devops_os_define_network
# storage_gw: "192.0.2.254"
# external_gw: "198.51.100.254"
# tenant_gw: "203.0.113.254"
#
# #Team vars
# nmcli_team:
# - conn_name: tenant
# ip4: '{{ tenant_ip }}'
# gw4: '{{ tenant_gw }}'
# - conn_name: external
# ip4: '{{ external_ip }}'
# gw4: '{{ external_gw }}'
# - conn_name: storage
# ip4: '{{ storage_ip }}'
# gw4: '{{ storage_gw }}'
# nmcli_team_slave:
# - conn_name: em1
# ifname: em1
# master: tenant
# - conn_name: em2
# ifname: em2
# master: tenant
# - conn_name: p2p1
# ifname: p2p1
# master: storage
# - conn_name: p2p2
# ifname: p2p2
# master: external
#
# #bond vars
# nmcli_bond:
# - conn_name: tenant
# ip4: '{{ tenant_ip }}'
# gw4: ''
# mode: balance-rr
# - conn_name: external
# ip4: '{{ external_ip }}'
# gw4: ''
# mode: balance-rr
# - conn_name: storage
# ip4: '{{ storage_ip }}'
# gw4: '{{ storage_gw }}'
# mode: balance-rr
# nmcli_bond_slave:
# - conn_name: em1
# ifname: em1
# master: tenant
# - conn_name: em2
# ifname: em2
# master: tenant
# - conn_name: p2p1
# ifname: p2p1
# master: storage
# - conn_name: p2p2
# ifname: p2p2
# master: external
#
# #ethernet vars
# nmcli_ethernet:
# - conn_name: em1
# ifname: em1
# ip4: '{{ tenant_ip }}'
# gw4: '{{ tenant_gw }}'
# - conn_name: em2
# ifname: em2
# ip4: '{{ tenant_ip1 }}'
# gw4: '{{ tenant_gw }}'
# - conn_name: p2p1
# ifname: p2p1
# ip4: '{{ storage_ip }}'
# gw4: '{{ storage_gw }}'
# - conn_name: p2p2
# ifname: p2p2
# ip4: '{{ external_ip }}'
# gw4: '{{ external_gw }}'
# ```
#
# ### host_vars
# ```yml
# ---
# storage_ip: "192.0.2.91/23"
# external_ip: "198.51.100.23/21"
# tenant_ip: "203.0.113.77/23"
# ```
## playbook-add.yml example
---
- hosts: openstack-stage
remote_user: root
tasks:
- name: install needed network manager libs
package:
name:
- NetworkManager-glib
- nm-connection-editor
- libsemanage-python
- policycoreutils-python
state: present
##### Working with all cloud nodes - Teaming
- name: Try nmcli add team - conn_name only & ip4 gw4
nmcli:
type: team
conn_name: '{{ item.conn_name }}'
ip4: '{{ item.ip4 }}'
gw4: '{{ item.gw4 }}'
state: present
with_items:
- '{{ nmcli_team }}'
- name: Try nmcli add teams-slave
nmcli:
type: team-slave
conn_name: '{{ item.conn_name }}'
ifname: '{{ item.ifname }}'
master: '{{ item.master }}'
state: present
with_items:
- '{{ nmcli_team_slave }}'
###### Working with all cloud nodes - Bonding
- name: Try nmcli add bond - conn_name only & ip4 gw4 mode
nmcli:
type: bond
conn_name: '{{ item.conn_name }}'
ip4: '{{ item.ip4 }}'
gw4: '{{ item.gw4 }}'
mode: '{{ item.mode }}'
state: present
with_items:
- '{{ nmcli_bond }}'
- name: Try nmcli add bond-slave
nmcli:
type: bond-slave
conn_name: '{{ item.conn_name }}'
ifname: '{{ item.ifname }}'
master: '{{ item.master }}'
state: present
with_items:
- '{{ nmcli_bond_slave }}'
##### Working with all cloud nodes - Ethernet
- name: Try nmcli add Ethernet - conn_name only & ip4 gw4
nmcli:
type: ethernet
conn_name: '{{ item.conn_name }}'
ip4: '{{ item.ip4 }}'
gw4: '{{ item.gw4 }}'
state: present
with_items:
- '{{ nmcli_ethernet }}'
## playbook-del.yml example
- hosts: openstack-stage
remote_user: root
tasks:
- name: Try nmcli del team - multiple
nmcli:
conn_name: '{{ item.conn_name }}'
state: absent
with_items:
- conn_name: em1
- conn_name: em2
- conn_name: p1p1
- conn_name: p1p2
- conn_name: p2p1
- conn_name: p2p2
- conn_name: tenant
- conn_name: storage
- conn_name: external
- conn_name: team-em1
- conn_name: team-em2
- conn_name: team-p1p1
- conn_name: team-p1p2
- conn_name: team-p2p1
- conn_name: team-p2p2
- name: Add an Ethernet connection with static IP configuration
nmcli:
conn_name: my-eth1
ifname: eth1
type: ethernet
ip4: 192.0.2.100/24
gw4: 192.0.2.1
state: present
- name: Add an Team connection with static IP configuration
nmcli:
conn_name: my-team1
ifname: my-team1
type: team
ip4: 192.0.2.100/24
gw4: 192.0.2.1
state: present
autoconnect: yes
- name: Optionally, at the same time specify IPv6 addresses for the device
nmcli:
conn_name: my-eth1
ifname: eth1
type: ethernet
ip4: 192.0.2.100/24
gw4: 192.0.2.1
ip6: 2001:db8::cafe
gw6: 2001:db8::1
state: present
- name: Add two IPv4 DNS server addresses
nmcli:
conn_name: my-eth1
type: ethernet
dns4:
- 192.0.2.53
- 198.51.100.53
state: present
- name: Make a profile usable for all compatible Ethernet interfaces
nmcli:
ctype: ethernet
name: my-eth1
ifname: '*'
state: present
- name: Change the property of a setting e.g. MTU
nmcli:
conn_name: my-eth1
mtu: 9000
type: ethernet
state: present
- name: Add VxLan
nmcli:
type: vxlan
conn_name: vxlan_test1
vxlan_id: 16
vxlan_local: 192.168.1.2
vxlan_remote: 192.168.1.5
- name: Add ipip
nmcli:
type: ipip
conn_name: ipip_test1
ip_tunnel_dev: eth0
ip_tunnel_local: 192.168.1.2
ip_tunnel_remote: 192.168.1.5
- name: Add sit
nmcli:
type: sit
conn_name: sit_test1
ip_tunnel_dev: eth0
ip_tunnel_local: 192.168.1.2
ip_tunnel_remote: 192.168.1.5
# nmcli exits with status 0 if it succeeds and exits with a status greater
# than zero when there is a failure. The following list of status codes may be
# returned:
#
# - 0 Success - indicates the operation succeeded
# - 1 Unknown or unspecified error
# - 2 Invalid user input, wrong nmcli invocation
# - 3 Timeout expired (see --wait option)
# - 4 Connection activation failed
# - 5 Connection deactivation failed
# - 6 Disconnecting device failed
# - 7 Connection deletion failed
# - 8 NetworkManager is not running
# - 9 nmcli and NetworkManager versions mismatch
# - 10 Connection, device, or access point does not exist.
'''
RETURN = r"""#
"""
import traceback
DBUS_IMP_ERR = None
try:
import dbus
HAVE_DBUS = True
except ImportError:
DBUS_IMP_ERR = traceback.format_exc()
HAVE_DBUS = False
NM_CLIENT_IMP_ERR = None
try:
import gi
gi.require_version('NMClient', '1.0')
gi.require_version('NetworkManager', '1.0')
from gi.repository import NetworkManager, NMClient
HAVE_NM_CLIENT = True
except (ImportError, ValueError):
NM_CLIENT_IMP_ERR = traceback.format_exc()
HAVE_NM_CLIENT = False
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils._text import to_native
class Nmcli(object):
"""
This is the generic nmcli manipulation class that is subclassed based on platform.
A subclass may wish to override the following action methods:-
- create_connection()
- delete_connection()
- modify_connection()
- show_connection()
- up_connection()
- down_connection()
All subclasses MUST define platform and distribution (which may be None).
"""
platform = 'Generic'
distribution = None
if HAVE_DBUS:
bus = dbus.SystemBus()
# The following is going to be used in dbus code
DEVTYPES = {
1: "Ethernet",
2: "Wi-Fi",
5: "Bluetooth",
6: "OLPC",
7: "WiMAX",
8: "Modem",
9: "InfiniBand",
10: "Bond",
11: "VLAN",
12: "ADSL",
13: "Bridge",
14: "Generic",
15: "Team",
16: "VxLan",
17: "ipip",
18: "sit",
}
STATES = {
0: "Unknown",
10: "Unmanaged",
20: "Unavailable",
30: "Disconnected",
40: "Prepare",
50: "Config",
60: "Need Auth",
70: "IP Config",
80: "IP Check",
90: "Secondaries",
100: "Activated",
110: "Deactivating",
120: "Failed"
}
def __init__(self, module):
self.module = module
self.state = module.params['state']
self.autoconnect = module.params['autoconnect']
self.conn_name = module.params['conn_name']
self.master = module.params['master']
self.ifname = module.params['ifname']
self.type = module.params['type']
self.ip4 = module.params['ip4']
self.gw4 = module.params['gw4']
self.dns4 = ' '.join(module.params['dns4']) if module.params.get('dns4') else None
self.dns4_search = ' '.join(module.params['dns4_search']) if module.params.get('dns4_search') else None
self.ip6 = module.params['ip6']
self.gw6 = module.params['gw6']
self.dns6 = ' '.join(module.params['dns6']) if module.params.get('dns6') else None
self.dns6_search = ' '.join(module.params['dns6_search']) if module.params.get('dns6_search') else None
self.mtu = module.params['mtu']
self.stp = module.params['stp']
self.priority = module.params['priority']
self.mode = module.params['mode']
self.miimon = module.params['miimon']
self.primary = module.params['primary']
self.downdelay = module.params['downdelay']
self.updelay = module.params['updelay']
self.arp_interval = module.params['arp_interval']
self.arp_ip_target = module.params['arp_ip_target']
self.slavepriority = module.params['slavepriority']
self.forwarddelay = module.params['forwarddelay']
self.hellotime = module.params['hellotime']
self.maxage = module.params['maxage']
self.ageingtime = module.params['ageingtime']
self.hairpin = module.params['hairpin']
self.path_cost = module.params['path_cost']
self.mac = module.params['mac']
self.vlanid = module.params['vlanid']
self.vlandev = module.params['vlandev']
self.flags = module.params['flags']
self.ingress = module.params['ingress']
self.egress = module.params['egress']
self.vxlan_id = module.params['vxlan_id']
self.vxlan_local = module.params['vxlan_local']
self.vxlan_remote = module.params['vxlan_remote']
self.ip_tunnel_dev = module.params['ip_tunnel_dev']
self.ip_tunnel_local = module.params['ip_tunnel_local']
self.ip_tunnel_remote = module.params['ip_tunnel_remote']
self.nmcli_bin = self.module.get_bin_path('nmcli', True)
self.dhcp_client_id = module.params['dhcp_client_id']
def execute_command(self, cmd, use_unsafe_shell=False, data=None):
return self.module.run_command(cmd, use_unsafe_shell=use_unsafe_shell, data=data)
def merge_secrets(self, proxy, config, setting_name):
try:
# returns a dict of dicts mapping name::setting, where setting is a dict
# mapping key::value. Each member of the 'setting' dict is a secret
secrets = proxy.GetSecrets(setting_name)
# Copy the secrets into our connection config
for setting in secrets:
for key in secrets[setting]:
config[setting_name][key] = secrets[setting][key]
except Exception:
pass
def dict_to_string(self, d):
# Try to trivially translate a dictionary's elements into nice string
# formatting.
dstr = ""
for key in d:
val = d[key]
str_val = ""
add_string = True
if isinstance(val, dbus.Array):
for elt in val:
if isinstance(elt, dbus.Byte):
str_val += "%s " % int(elt)
elif isinstance(elt, dbus.String):
str_val += "%s" % elt
elif isinstance(val, dbus.Dictionary):
dstr += self.dict_to_string(val)
add_string = False
else:
str_val = val
if add_string:
dstr += "%s: %s\n" % (key, str_val)
return dstr
def connection_to_string(self, config):
# dump a connection configuration to use in list_connection_info
setting_list = []
for setting_name in config:
setting_list.append(self.dict_to_string(config[setting_name]))
return setting_list
@staticmethod
def bool_to_string(boolean):
if boolean:
return "yes"
else:
return "no"
def list_connection_info(self):
# Ask the settings service for the list of connections it provides
bus = dbus.SystemBus()
service_name = "org.freedesktop.NetworkManager"
settings = None
try:
proxy = bus.get_object(service_name, "/org/freedesktop/NetworkManager/Settings")
settings = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings")
except dbus.exceptions.DBusException as e:
self.module.fail_json(msg="Unable to read Network Manager settings from DBus system bus: %s" % to_native(e),
details="Please check if NetworkManager is installed and"
"service network-manager is started.")
connection_paths = settings.ListConnections()
connection_list = []
# List each connection's name, UUID, and type
for path in connection_paths:
con_proxy = bus.get_object(service_name, path)
settings_connection = dbus.Interface(con_proxy, "org.freedesktop.NetworkManager.Settings.Connection")
config = settings_connection.GetSettings()
# Now get secrets too; we grab the secrets for each type of connection
# (since there isn't a "get all secrets" call because most of the time
# you only need 'wifi' secrets or '802.1x' secrets, not everything) and
# merge that into the configuration data - To use at a later stage
self.merge_secrets(settings_connection, config, '802-11-wireless')
self.merge_secrets(settings_connection, config, '802-11-wireless-security')
self.merge_secrets(settings_connection, config, '802-1x')
self.merge_secrets(settings_connection, config, 'gsm')
self.merge_secrets(settings_connection, config, 'cdma')
self.merge_secrets(settings_connection, config, 'ppp')
# Get the details of the 'connection' setting
s_con = config['connection']
connection_list.append(s_con['id'])
connection_list.append(s_con['uuid'])
connection_list.append(s_con['type'])
connection_list.append(self.connection_to_string(config))
return connection_list
def connection_exists(self):
# we are going to use name and type in this instance to find if that connection exists and is of type x
connections = self.list_connection_info()
for con_item in connections:
if self.conn_name == con_item:
return True
def down_connection(self):
cmd = [self.nmcli_bin, 'con', 'down', self.conn_name]
return self.execute_command(cmd)
def up_connection(self):
cmd = [self.nmcli_bin, 'con', 'up', self.conn_name]
return self.execute_command(cmd)
def create_connection_team(self):
cmd = [self.nmcli_bin, 'con', 'add', 'type', 'team', 'con-name']
# format for creating team interface
if self.conn_name is not None:
cmd.append(self.conn_name)
elif self.ifname is not None:
cmd.append(self.ifname)
cmd.append('ifname')
if self.ifname is not None:
cmd.append(self.ifname)
elif self.conn_name is not None:
cmd.append(self.conn_name)
options = {
'ipv4.address': self.ip4,
'ipv4.gateway': self.gw4,
'ipv6.address': self.ip6,
'ipv6.gateway': self.gw6,
'autoconnect': self.bool_to_string(self.autoconnect),
'ipv4.dns-search': self.dns4_search,
'ipv6.dns-search': self.dns6_search,
'ipv4.dhcp-client-id': self.dhcp_client_id,
}
for key, value in options.items():
if value is not None:
cmd.extend([key, value])
return cmd
def modify_connection_team(self):
cmd = [self.nmcli_bin, 'con', 'mod', self.conn_name]
options = {
'ipv4.address': self.ip4,
'ipv4.gateway': self.gw4,
'ipv4.dns': self.dns4,
'ipv6.address': self.ip6,
'ipv6.gateway': self.gw6,
'ipv6.dns': self.dns6,
'autoconnect': self.bool_to_string(self.autoconnect),
'ipv4.dns-search': self.dns4_search,
'ipv6.dns-search': self.dns6_search,
'ipv4.dhcp-client-id': self.dhcp_client_id,
}
for key, value in options.items():
if value is not None:
cmd.extend([key, value])
return cmd
def create_connection_team_slave(self):
cmd = [self.nmcli_bin, 'connection', 'add', 'type', self.type, 'con-name']
# format for creating team-slave interface
if self.conn_name is not None:
cmd.append(self.conn_name)
elif self.ifname is not None:
cmd.append(self.ifname)
cmd.append('ifname')
if self.ifname is not None:
cmd.append(self.ifname)
elif self.conn_name is not None:
cmd.append(self.conn_name)
cmd.append('master')
if self.conn_name is not None:
cmd.append(self.master)
return cmd
def modify_connection_team_slave(self):
cmd = [self.nmcli_bin, 'con', 'mod', self.conn_name, 'connection.master', self.master]
# format for modifying team-slave interface
if self.mtu is not None:
cmd.append('802-3-ethernet.mtu')
cmd.append(self.mtu)
return cmd
def create_connection_bond(self):
cmd = [self.nmcli_bin, 'con', 'add', 'type', 'bond', 'con-name']
# format for creating bond interface
if self.conn_name is not None:
cmd.append(self.conn_name)
elif self.ifname is not None:
cmd.append(self.ifname)
cmd.append('ifname')
if self.ifname is not None:
cmd.append(self.ifname)
elif self.conn_name is not None:
cmd.append(self.conn_name)
options = {
'mode': self.mode,
'ipv4.address': self.ip4,
'ipv4.gateway': self.gw4,
'ipv6.address': self.ip6,
'ipv6.gateway': self.gw6,
'autoconnect': self.bool_to_string(self.autoconnect),
'ipv4.dns-search': self.dns4_search,
'ipv6.dns-search': self.dns6_search,
'miimon': self.miimon,
'downdelay': self.downdelay,
'updelay': self.updelay,
'arp-interval': self.arp_interval,
'arp-ip-target': self.arp_ip_target,
'primary': self.primary,
'ipv4.dhcp-client-id': self.dhcp_client_id,
}
for key, value in options.items():
if value is not None:
cmd.extend([key, value])
return cmd
def modify_connection_bond(self):
cmd = [self.nmcli_bin, 'con', 'mod', self.conn_name]
# format for modifying bond interface
options = {
'ipv4.address': self.ip4,
'ipv4.gateway': self.gw4,
'ipv4.dns': self.dns4,
'ipv6.address': self.ip6,
'ipv6.gateway': self.gw6,
'ipv6.dns': self.dns6,
'autoconnect': self.bool_to_string(self.autoconnect),
'ipv4.dns-search': self.dns4_search,
'ipv6.dns-search': self.dns6_search,
'miimon': self.miimon,
'downdelay': self.downdelay,
'updelay': self.updelay,
'arp-interval': self.arp_interval,
'arp-ip-target': self.arp_ip_target,
'ipv4.dhcp-client-id': self.dhcp_client_id,
}
for key, value in options.items():
if value is not None:
cmd.extend([key, value])
return cmd
def create_connection_bond_slave(self):
cmd = [self.nmcli_bin, 'connection', 'add', 'type', 'bond-slave', 'con-name']
# format for creating bond-slave interface
if self.conn_name is not None:
cmd.append(self.conn_name)
elif self.ifname is not None:
cmd.append(self.ifname)
cmd.append('ifname')
if self.ifname is not None:
cmd.append(self.ifname)
elif self.conn_name is not None:
cmd.append(self.conn_name)
cmd.append('master')
if self.conn_name is not None:
cmd.append(self.master)
return cmd
def modify_connection_bond_slave(self):
cmd = [self.nmcli_bin, 'con', 'mod', self.conn_name, 'connection.master', self.master]
# format for modifying bond-slave interface
return cmd
def create_connection_ethernet(self, conn_type='ethernet'):
# format for creating ethernet interface
# To add an Ethernet connection with static IP configuration, issue a command as follows
# - nmcli: name=add conn_name=my-eth1 ifname=eth1 type=ethernet ip4=192.0.2.100/24 gw4=192.0.2.1 state=present
# nmcli con add con-name my-eth1 ifname eth1 type ethernet ip4 192.0.2.100/24 gw4 192.0.2.1
cmd = [self.nmcli_bin, 'con', 'add', 'type']
if conn_type == 'ethernet':
cmd.append('ethernet')
elif conn_type == 'generic':
cmd.append('generic')
cmd.append('con-name')
if self.conn_name is not None:
cmd.append(self.conn_name)
elif self.ifname is not None:
cmd.append(self.ifname)
cmd.append('ifname')
if self.ifname is not None:
cmd.append(self.ifname)
elif self.conn_name is not None:
cmd.append(self.conn_name)
options = {
'ipv4.address': self.ip4,
'ipv4.gateway': self.gw4,
'ipv6.address': self.ip6,
'ipv6.gateway': self.gw6,
'autoconnect': self.bool_to_string(self.autoconnect),
'ipv4.dns-search': self.dns4_search,
'ipv6.dns-search': self.dns6_search,
'ipv4.dhcp-client-id': self.dhcp_client_id,
}
for key, value in options.items():
if value is not None:
cmd.extend([key, value])
return cmd
def modify_connection_ethernet(self, conn_type='ethernet'):
cmd = [self.nmcli_bin, 'con', 'mod', self.conn_name]
# format for modifying ethernet interface
# To modify an Ethernet connection with static IP configuration, issue a command as follows
# - nmcli: conn_name=my-eth1 ifname=eth1 type=ethernet ip4=192.0.2.100/24 gw4=192.0.2.1 state=present
# nmcli con mod con-name my-eth1 ifname eth1 type ethernet ip4 192.0.2.100/24 gw4 192.0.2.1
options = {
'ipv4.address': self.ip4,
'ipv4.gateway': self.gw4,
'ipv4.dns': self.dns4,
'ipv6.address': self.ip6,
'ipv6.gateway': self.gw6,
'ipv6.dns': self.dns6,
'autoconnect': self.bool_to_string(self.autoconnect),
'ipv4.dns-search': self.dns4_search,
'ipv6.dns-search': self.dns6_search,
'802-3-ethernet.mtu': self.mtu,
'ipv4.dhcp-client-id': self.dhcp_client_id,
}
for key, value in options.items():
if value is not None:
if key == '802-3-ethernet.mtu' and conn_type != 'ethernet':
continue
cmd.extend([key, value])
return cmd
def create_connection_bridge(self):
# format for creating bridge interface
# To add an Bridge connection with static IP configuration, issue a command as follows
# - nmcli: name=add conn_name=my-eth1 ifname=eth1 type=bridge ip4=192.0.2.100/24 gw4=192.0.2.1 state=present
# nmcli con add con-name my-eth1 ifname eth1 type bridge ip4 192.0.2.100/24 gw4 192.0.2.1
cmd = [self.nmcli_bin, 'con', 'add', 'type', 'bridge', 'con-name']
if self.conn_name is not None:
cmd.append(self.conn_name)
elif self.ifname is not None:
cmd.append(self.ifname)
cmd.append('ifname')
if self.ifname is not None:
cmd.append(self.ifname)
elif self.conn_name is not None:
cmd.append(self.conn_name)
options = {
'ip4': self.ip4,
'gw4': self.gw4,
'ip6': self.ip6,
'gw6': self.gw6,
'autoconnect': self.bool_to_string(self.autoconnect),
'bridge.ageing-time': self.ageingtime,
'bridge.forward-delay': self.forwarddelay,
'bridge.hello-time': self.hellotime,
'bridge.mac-address': self.mac,
'bridge.max-age': self.maxage,
'bridge.priority': self.priority,
'bridge.stp': self.bool_to_string(self.stp)
}
for key, value in options.items():
if value is not None:
cmd.extend([key, value])
return cmd
def modify_connection_bridge(self):
# format for modifying bridge interface
# To add an Bridge connection with static IP configuration, issue a command as follows
# - nmcli: name=mod conn_name=my-eth1 ifname=eth1 type=bridge ip4=192.0.2.100/24 gw4=192.0.2.1 state=present
# nmcli con mod my-eth1 ifname eth1 type bridge ip4 192.0.2.100/24 gw4 192.0.2.1
cmd = [self.nmcli_bin, 'con', 'mod', self.conn_name]
options = {
'ip4': self.ip4,
'gw4': self.gw4,
'ip6': self.ip6,
'gw6': self.gw6,
'autoconnect': self.bool_to_string(self.autoconnect),
'bridge.ageing-time': self.ageingtime,
'bridge.forward-delay': self.forwarddelay,
'bridge.hello-time': self.hellotime,
'bridge.mac-address': self.mac,
'bridge.max-age': self.maxage,
'bridge.priority': self.priority,
'bridge.stp': self.bool_to_string(self.stp)
}
for key, value in options.items():
if value is not None:
cmd.extend([key, value])
return cmd
def create_connection_bridge_slave(self):
# format for creating bond-slave interface
cmd = [self.nmcli_bin, 'con', 'add', 'type', 'bridge-slave', 'con-name']
if self.conn_name is not None:
cmd.append(self.conn_name)
elif self.ifname is not None:
cmd.append(self.ifname)
cmd.append('ifname')
if self.ifname is not None:
cmd.append(self.ifname)
elif self.conn_name is not None:
cmd.append(self.conn_name)
options = {
'master': self.master,
'bridge-port.path-cost': self.path_cost,
'bridge-port.hairpin': self.bool_to_string(self.hairpin),
'bridge-port.priority': self.slavepriority,
}
for key, value in options.items():
if value is not None:
cmd.extend([key, value])
return cmd
def modify_connection_bridge_slave(self):
# format for modifying bond-slave interface
cmd = [self.nmcli_bin, 'con', 'mod', self.conn_name]
options = {
'master': self.master,
'bridge-port.path-cost': self.path_cost,
'bridge-port.hairpin': self.bool_to_string(self.hairpin),
'bridge-port.priority': self.slavepriority,
}
for key, value in options.items():
if value is not None:
cmd.extend([key, value])
return cmd
def create_connection_vlan(self):
cmd = [self.nmcli_bin]
cmd.append('con')
cmd.append('add')
cmd.append('type')
cmd.append('vlan')
cmd.append('con-name')
if self.conn_name is not None:
cmd.append(self.conn_name)
elif self.ifname is not None:
cmd.append(self.ifname)
else:
cmd.append('vlan%s' % self.vlanid)
cmd.append('ifname')
if self.ifname is not None:
cmd.append(self.ifname)
elif self.conn_name is not None:
cmd.append(self.conn_name)
else:
cmd.append('vlan%s' % self.vlanid)
params = {'dev': self.vlandev,
'id': str(self.vlanid),
'ip4': self.ip4 or '',
'gw4': self.gw4 or '',
'ip6': self.ip6 or '',
'gw6': self.gw6 or '',
'autoconnect': self.bool_to_string(self.autoconnect)
}
for k, v in params.items():
cmd.extend([k, v])
return cmd
def modify_connection_vlan(self):
cmd = [self.nmcli_bin]
cmd.append('con')
cmd.append('mod')
if self.conn_name is not None:
cmd.append(self.conn_name)
elif self.ifname is not None:
cmd.append(self.ifname)
else:
cmd.append('vlan%s' % self.vlanid)
params = {'vlan.parent': self.vlandev,
'vlan.id': str(self.vlanid),
'ipv4.address': self.ip4 or '',
'ipv4.gateway': self.gw4 or '',
'ipv4.dns': self.dns4 or '',
'ipv6.address': self.ip6 or '',
'ipv6.gateway': self.gw6 or '',
'ipv6.dns': self.dns6 or '',
'autoconnect': self.bool_to_string(self.autoconnect)
}
for k, v in params.items():
cmd.extend([k, v])
return cmd
def create_connection_vxlan(self):
cmd = [self.nmcli_bin, 'con', 'add', 'type', 'vxlan', 'con-name']
if self.conn_name is not None:
cmd.append(self.conn_name)
elif self.ifname is not None:
cmd.append(self.ifname)
else:
cmd.append('vxlan%s' % self.vxlanid)
cmd.append('ifname')
if self.ifname is not None:
cmd.append(self.ifname)
elif self.conn_name is not None:
cmd.append(self.conn_name)
else:
cmd.append('vxan%s' % self.vxlanid)
params = {'vxlan.id': self.vxlan_id,
'vxlan.local': self.vxlan_local,
'vxlan.remote': self.vxlan_remote,
'autoconnect': self.bool_to_string(self.autoconnect)
}
for k, v in params.items():
cmd.extend([k, v])
return cmd
def modify_connection_vxlan(self):
cmd = [self.nmcli_bin, 'con', 'mod']
if self.conn_name is not None:
cmd.append(self.conn_name)
elif self.ifname is not None:
cmd.append(self.ifname)
else:
cmd.append('vxlan%s' % self.vxlanid)
params = {'vxlan.id': self.vxlan_id,
'vxlan.local': self.vxlan_local,
'vxlan.remote': self.vxlan_remote,
'autoconnect': self.bool_to_string(self.autoconnect)
}
for k, v in params.items():
cmd.extend([k, v])
return cmd
def create_connection_ipip(self):
cmd = [self.nmcli_bin, 'con', 'add', 'type', 'ip-tunnel', 'mode', 'ipip', 'con-name']
if self.conn_name is not None:
cmd.append(self.conn_name)
elif self.ifname is not None:
cmd.append(self.ifname)
elif self.ip_tunnel_dev is not None:
cmd.append('ipip%s' % self.ip_tunnel_dev)
cmd.append('ifname')
if self.ifname is not None:
cmd.append(self.ifname)
elif self.conn_name is not None:
cmd.append(self.conn_name)
else:
cmd.append('ipip%s' % self.ipip_dev)
if self.ip_tunnel_dev is not None:
cmd.append('dev')
cmd.append(self.ip_tunnel_dev)
params = {'ip-tunnel.local': self.ip_tunnel_local,
'ip-tunnel.remote': self.ip_tunnel_remote,
'autoconnect': self.bool_to_string(self.autoconnect)
}
for k, v in params.items():
cmd.extend([k, v])
return cmd
def modify_connection_ipip(self):
cmd = [self.nmcli_bin, 'con', 'mod']
if self.conn_name is not None:
cmd.append(self.conn_name)
elif self.ifname is not None:
cmd.append(self.ifname)
elif self.ip_tunnel_dev is not None:
cmd.append('ipip%s' % self.ip_tunnel_dev)
params = {'ip-tunnel.local': self.ip_tunnel_local,
'ip-tunnel.remote': self.ip_tunnel_remote,
'autoconnect': self.bool_to_string(self.autoconnect)
}
for k, v in params.items():
cmd.extend([k, v])
return cmd
def create_connection_sit(self):
cmd = [self.nmcli_bin, 'con', 'add', 'type', 'ip-tunnel', 'mode', 'sit', 'con-name']
if self.conn_name is not None:
cmd.append(self.conn_name)
elif self.ifname is not None:
cmd.append(self.ifname)
elif self.ip_tunnel_dev is not None:
cmd.append('sit%s' % self.ip_tunnel_dev)
cmd.append('ifname')
if self.ifname is not None:
cmd.append(self.ifname)
elif self.conn_name is not None:
cmd.append(self.conn_name)
else:
cmd.append('sit%s' % self.ipip_dev)
if self.ip_tunnel_dev is not None:
cmd.append('dev')
cmd.append(self.ip_tunnel_dev)
params = {'ip-tunnel.local': self.ip_tunnel_local,
'ip-tunnel.remote': self.ip_tunnel_remote,
'autoconnect': self.bool_to_string(self.autoconnect)
}
for k, v in params.items():
cmd.extend([k, v])
return cmd
def modify_connection_sit(self):
cmd = [self.nmcli_bin, 'con', 'mod']
if self.conn_name is not None:
cmd.append(self.conn_name)
elif self.ifname is not None:
cmd.append(self.ifname)
elif self.ip_tunnel_dev is not None:
cmd.append('sit%s' % self.ip_tunnel_dev)
params = {'ip-tunnel.local': self.ip_tunnel_local,
'ip-tunnel.remote': self.ip_tunnel_remote,
'autoconnect': self.bool_to_string(self.autoconnect)
}
for k, v in params.items():
cmd.extend([k, v])
return cmd
def create_connection(self):
cmd = []
if self.type == 'team':
if (self.dns4 is not None) or (self.dns6 is not None):
cmd = self.create_connection_team()
self.execute_command(cmd)
cmd = self.modify_connection_team()
self.execute_command(cmd)
return self.up_connection()
elif (self.dns4 is None) or (self.dns6 is None):
cmd = self.create_connection_team()
elif self.type == 'team-slave':
if self.mtu is not None:
cmd = self.create_connection_team_slave()
self.execute_command(cmd)
cmd = self.modify_connection_team_slave()
return self.execute_command(cmd)
else:
cmd = self.create_connection_team_slave()
elif self.type == 'bond':
if (self.mtu is not None) or (self.dns4 is not None) or (self.dns6 is not None):
cmd = self.create_connection_bond()
self.execute_command(cmd)
cmd = self.modify_connection_bond()
self.execute_command(cmd)
return self.up_connection()
else:
cmd = self.create_connection_bond()
elif self.type == 'bond-slave':
cmd = self.create_connection_bond_slave()
elif self.type == 'ethernet':
if (self.mtu is not None) or (self.dns4 is not None) or (self.dns6 is not None):
cmd = self.create_connection_ethernet()
self.execute_command(cmd)
cmd = self.modify_connection_ethernet()
self.execute_command(cmd)
return self.up_connection()
else:
cmd = self.create_connection_ethernet()
elif self.type == 'bridge':
cmd = self.create_connection_bridge()
elif self.type == 'bridge-slave':
cmd = self.create_connection_bridge_slave()
elif self.type == 'vlan':
cmd = self.create_connection_vlan()
elif self.type == 'vxlan':
cmd = self.create_connection_vxlan()
elif self.type == 'ipip':
cmd = self.create_connection_ipip()
elif self.type == 'sit':
cmd = self.create_connection_sit()
elif self.type == 'generic':
cmd = self.create_connection_ethernet(conn_type='generic')
if cmd:
return self.execute_command(cmd)
else:
self.module.fail_json(msg="Type of device or network connection is required "
"while performing 'create' operation. Please specify 'type' as an argument.")
def remove_connection(self):
# self.down_connection()
cmd = [self.nmcli_bin, 'con', 'del', self.conn_name]
return self.execute_command(cmd)
def modify_connection(self):
cmd = []
if self.type == 'team':
cmd = self.modify_connection_team()
elif self.type == 'team-slave':
cmd = self.modify_connection_team_slave()
elif self.type == 'bond':
cmd = self.modify_connection_bond()
elif self.type == 'bond-slave':
cmd = self.modify_connection_bond_slave()
elif self.type == 'ethernet':
cmd = self.modify_connection_ethernet()
elif self.type == 'bridge':
cmd = self.modify_connection_bridge()
elif self.type == 'bridge-slave':
cmd = self.modify_connection_bridge_slave()
elif self.type == 'vlan':
cmd = self.modify_connection_vlan()
elif self.type == 'vxlan':
cmd = self.modify_connection_vxlan()
elif self.type == 'ipip':
cmd = self.modify_connection_ipip()
elif self.type == 'sit':
cmd = self.modify_connection_sit()
elif self.type == 'generic':
cmd = self.modify_connection_ethernet(conn_type='generic')
if cmd:
return self.execute_command(cmd)
else:
self.module.fail_json(msg="Type of device or network connection is required "
"while performing 'modify' operation. Please specify 'type' as an argument.")
def main():
# Parsing argument file
module = AnsibleModule(
argument_spec=dict(
autoconnect=dict(type='bool', default=True),
state=dict(type='str', required=True, choices=['absent', 'present']),
conn_name=dict(type='str', required=True),
master=dict(type='str'),
ifname=dict(type='str'),
type=dict(type='str',
choices=['bond', 'bond-slave', 'bridge', 'bridge-slave', 'ethernet', 'generic', 'ipip', 'sit', 'team', 'team-slave', 'vlan', 'vxlan']),
ip4=dict(type='str'),
gw4=dict(type='str'),
dns4=dict(type='list'),
dns4_search=dict(type='list'),
dhcp_client_id=dict(type='str'),
ip6=dict(type='str'),
gw6=dict(type='str'),
dns6=dict(type='list'),
dns6_search=dict(type='list'),
# Bond Specific vars
mode=dict(type='str', default='balance-rr',
choices=['802.3ad', 'active-backup', 'balance-alb', 'balance-rr', 'balance-tlb', 'balance-xor', 'broadcast']),
miimon=dict(type='int'),
downdelay=dict(type='int'),
updelay=dict(type='int'),
arp_interval=dict(type='int'),
arp_ip_target=dict(type='str'),
primary=dict(type='str'),
# general usage
mtu=dict(type='int'),
mac=dict(type='str'),
# bridge specific vars
stp=dict(type='bool', default=True),
priority=dict(type='int', default=128),
slavepriority=dict(type='int', default=32),
forwarddelay=dict(type='int', default=15),
hellotime=dict(type='int', default=2),
maxage=dict(type='int', default=20),
ageingtime=dict(type='int', default=300),
hairpin=dict(type='bool', default=True),
path_cost=dict(type='int', default=100),
# vlan specific vars
vlanid=dict(type='int'),
vlandev=dict(type='str'),
flags=dict(type='str'),
ingress=dict(type='str'),
egress=dict(type='str'),
# vxlan specific vars
vxlan_id=dict(type='int'),
vxlan_local=dict(type='str'),
vxlan_remote=dict(type='str'),
# ip-tunnel specific vars
ip_tunnel_dev=dict(type='str'),
ip_tunnel_local=dict(type='str'),
ip_tunnel_remote=dict(type='str'),
),
supports_check_mode=True,
)
if not HAVE_DBUS:
module.fail_json(msg=missing_required_lib('dbus'), exception=DBUS_IMP_ERR)
if not HAVE_NM_CLIENT:
module.fail_json(msg=missing_required_lib('NetworkManager glib API'), exception=NM_CLIENT_IMP_ERR)
nmcli = Nmcli(module)
(rc, out, err) = (None, '', '')
result = {'conn_name': nmcli.conn_name, 'state': nmcli.state}
# check for issues
if nmcli.conn_name is None:
nmcli.module.fail_json(msg="Please specify a name for the connection")
# team-slave checks
if nmcli.type == 'team-slave' and nmcli.master is None:
nmcli.module.fail_json(msg="Please specify a name for the master")
if nmcli.type == 'team-slave' and nmcli.ifname is None:
nmcli.module.fail_json(msg="Please specify an interface name for the connection")
if nmcli.state == 'absent':
if nmcli.connection_exists():
if module.check_mode:
module.exit_json(changed=True)
(rc, out, err) = nmcli.down_connection()
(rc, out, err) = nmcli.remove_connection()
if rc != 0:
module.fail_json(name=('No Connection named %s exists' % nmcli.conn_name), msg=err, rc=rc)
elif nmcli.state == 'present':
if nmcli.connection_exists():
# modify connection (note: this function is check mode aware)
# result['Connection']=('Connection %s of Type %s is not being added' % (nmcli.conn_name, nmcli.type))
result['Exists'] = 'Connections do exist so we are modifying them'
if module.check_mode:
module.exit_json(changed=True)
(rc, out, err) = nmcli.modify_connection()
if not nmcli.connection_exists():
result['Connection'] = ('Connection %s of Type %s is being added' % (nmcli.conn_name, nmcli.type))
if module.check_mode:
module.exit_json(changed=True)
(rc, out, err) = nmcli.create_connection()
if rc is not None and rc != 0:
module.fail_json(name=nmcli.conn_name, msg=err, rc=rc)
if rc is None:
result['changed'] = False
else:
result['changed'] = True
if out:
result['stdout'] = out
if err:
result['stderr'] = err
module.exit_json(**result)
if __name__ == '__main__':
main()
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,976 |
[docker_container][ansible 2.8] - missing Mount modes on volumes
|
##### SUMMARY
Unable to use the mount mode :nocopy on volume
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
docker_container
##### ANSIBLE VERSION
```
ansible 2.8.1
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 = /var/lib/awx/venv/venv-Ansible-28-python27/lib/python2.7/site-packages/ansible
executable location = /var/lib/awx/venv/venv-Ansible-28-python27/bin/ansible
python version = 2.7.5 (default, Jun 20 2019, 20:27:34) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```
N/A
```
##### OS / ENVIRONMENT
AWX 3.0/docker 1.13/ RHEL7.4
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```yaml
- name: start nexus_ihm services
docker_container:
name: nexus_ihm
image: '{{ docker_images.nexus_ihm.image }}:{{ docker_images.nexus_ihm.version }}'
state: started
recreate: yes
log_driver: json-file
restart_policy: 'unless-stopped'
hostname: nexus_ihm
env:
TZ: Europe/Paris
volumes:
- 'nfsdata:/nexus-data:nocopy'
- 'nfsbackup:/backup'
```
##### EXPECTED RESULTS
Beeing able to access the volume within the container like in :
```sh
[root@LX01665L ~]# docker run --rm -ti -v nfsdata:/test --name test alpine /bin/sh
/ # ls /test/
config.json init-stdin init-stdout
/ # exit
[root@LX01665L ~]# docker run --rm -ti -v nfsdata:/test:nocopy --name test alpine /bin/sh
/ # ls /test/
backup etc kar port
blobs generated-bundles keystores restore-from-backup
cache health-check lock tmp
db instances log upgrades
elasticsearch javaprefs orient
/ #
```
##### ACTUAL RESULTS
The task crash with (NB, accordingly to the documentation in https://docs.ansible.com/ansible/latest/modules/docker_container_module.html where it's not specified beeing usable ) :
```
fatal: [lx01665l.tb.uro.equant.com]: FAILED! => {"changed": false, "msg": "Found invalid volumes mode: nocopy"}
```
|
https://github.com/ansible/ansible/issues/58976
|
https://github.com/ansible/ansible/pull/59043
|
34a68fa0fb52128ec443830c49549adcf5d0edc6
|
fa7c387f9b975aa3214d958732ed77824a0e2fcc
| 2019-07-11T13:09:48Z |
python
| 2019-07-13T18:50:32Z |
changelogs/fragments/59043-docker_container-nocopy.yml
| |
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,976 |
[docker_container][ansible 2.8] - missing Mount modes on volumes
|
##### SUMMARY
Unable to use the mount mode :nocopy on volume
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
docker_container
##### ANSIBLE VERSION
```
ansible 2.8.1
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 = /var/lib/awx/venv/venv-Ansible-28-python27/lib/python2.7/site-packages/ansible
executable location = /var/lib/awx/venv/venv-Ansible-28-python27/bin/ansible
python version = 2.7.5 (default, Jun 20 2019, 20:27:34) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```
N/A
```
##### OS / ENVIRONMENT
AWX 3.0/docker 1.13/ RHEL7.4
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```yaml
- name: start nexus_ihm services
docker_container:
name: nexus_ihm
image: '{{ docker_images.nexus_ihm.image }}:{{ docker_images.nexus_ihm.version }}'
state: started
recreate: yes
log_driver: json-file
restart_policy: 'unless-stopped'
hostname: nexus_ihm
env:
TZ: Europe/Paris
volumes:
- 'nfsdata:/nexus-data:nocopy'
- 'nfsbackup:/backup'
```
##### EXPECTED RESULTS
Beeing able to access the volume within the container like in :
```sh
[root@LX01665L ~]# docker run --rm -ti -v nfsdata:/test --name test alpine /bin/sh
/ # ls /test/
config.json init-stdin init-stdout
/ # exit
[root@LX01665L ~]# docker run --rm -ti -v nfsdata:/test:nocopy --name test alpine /bin/sh
/ # ls /test/
backup etc kar port
blobs generated-bundles keystores restore-from-backup
cache health-check lock tmp
db instances log upgrades
elasticsearch javaprefs orient
/ #
```
##### ACTUAL RESULTS
The task crash with (NB, accordingly to the documentation in https://docs.ansible.com/ansible/latest/modules/docker_container_module.html where it's not specified beeing usable ) :
```
fatal: [lx01665l.tb.uro.equant.com]: FAILED! => {"changed": false, "msg": "Found invalid volumes mode: nocopy"}
```
|
https://github.com/ansible/ansible/issues/58976
|
https://github.com/ansible/ansible/pull/59043
|
34a68fa0fb52128ec443830c49549adcf5d0edc6
|
fa7c387f9b975aa3214d958732ed77824a0e2fcc
| 2019-07-11T13:09:48Z |
python
| 2019-07-13T18:50:32Z |
lib/ansible/modules/cloud/docker/docker_container.py
|
#!/usr/bin/python
#
# Copyright 2016 Red Hat | Ansible
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: docker_container
short_description: manage docker containers
description:
- Manage the life cycle of docker containers.
- Supports check mode. Run with --check and --diff to view config difference and list of actions to be taken.
version_added: "2.1"
options:
auto_remove:
description:
- enable auto-removal of the container on daemon side when the container's process exits
type: bool
default: no
version_added: "2.4"
blkio_weight:
description:
- Block IO (relative weight), between 10 and 1000.
type: int
capabilities:
description:
- List of capabilities to add to the container.
type: list
cap_drop:
description:
- List of capabilities to drop from the container.
type: list
version_added: "2.7"
cleanup:
description:
- Use with I(detach=false) to remove the container after successful execution.
type: bool
default: no
version_added: "2.2"
command:
description:
- Command to execute when the container starts.
A command may be either a string or a list.
- Prior to version 2.4, strings were split on commas.
type: raw
comparisons:
description:
- Allows to specify how properties of existing containers are compared with
module options to decide whether the container should be recreated / updated
or not. Only options which correspond to the state of a container as handled
by the Docker daemon can be specified, as well as C(networks).
- Must be a dictionary specifying for an option one of the keys C(strict), C(ignore)
and C(allow_more_present).
- If C(strict) is specified, values are tested for equality, and changes always
result in updating or restarting. If C(ignore) is specified, changes are ignored.
- C(allow_more_present) is allowed only for lists, sets and dicts. If it is
specified for lists or sets, the container will only be updated or restarted if
the module option contains a value which is not present in the container's
options. If the option is specified for a dict, the container will only be updated
or restarted if the module option contains a key which isn't present in the
container's option, or if the value of a key present differs.
- The wildcard option C(*) can be used to set one of the default values C(strict)
or C(ignore) to I(all) comparisons.
- See the examples for details.
type: dict
version_added: "2.8"
cpu_period:
description:
- Limit CPU CFS (Completely Fair Scheduler) period
type: int
cpu_quota:
description:
- Limit CPU CFS (Completely Fair Scheduler) quota
type: int
cpuset_cpus:
description:
- CPUs in which to allow execution C(1,3) or C(1-3).
type: str
cpuset_mems:
description:
- Memory nodes (MEMs) in which to allow execution C(0-3) or C(0,1)
type: str
cpu_shares:
description:
- CPU shares (relative weight).
type: int
detach:
description:
- Enable detached mode to leave the container running in background.
If disabled, the task will reflect the status of the container run (failed if the command failed).
type: bool
default: yes
devices:
description:
- "List of host device bindings to add to the container. Each binding is a mapping expressed
in the format: <path_on_host>:<path_in_container>:<cgroup_permissions>"
type: list
device_read_bps:
description:
- "List of device path and read rate (bytes per second) from device."
type: list
suboptions:
path:
description:
- Device path in the container.
type: str
required: yes
rate:
description:
- "Device read limit. Format: <number>[<unit>]"
- "Number is a positive integer. Unit can be one of C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte),
C(T) (tebibyte), or C(P) (pebibyte)"
- "Omitting the unit defaults to bytes."
type: str
required: yes
version_added: "2.8"
device_write_bps:
description:
- "List of device and write rate (bytes per second) to device."
type: list
suboptions:
path:
description:
- Device path in the container.
type: str
required: yes
rate:
description:
- "Device read limit. Format: <number>[<unit>]"
- "Number is a positive integer. Unit can be one of C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte),
C(T) (tebibyte), or C(P) (pebibyte)"
- "Omitting the unit defaults to bytes."
type: str
required: yes
version_added: "2.8"
device_read_iops:
description:
- "List of device and read rate (IO per second) from device."
type: list
suboptions:
path:
description:
- Device path in the container.
type: str
required: yes
rate:
description:
- "Device read limit."
- "Must be a positive integer."
type: int
required: yes
version_added: "2.8"
device_write_iops:
description:
- "List of device and write rate (IO per second) to device."
type: list
suboptions:
path:
description:
- Device path in the container.
type: str
required: yes
rate:
description:
- "Device read limit."
- "Must be a positive integer."
type: int
required: yes
version_added: "2.8"
dns_opts:
description:
- list of DNS options
type: list
dns_servers:
description:
- List of custom DNS servers.
type: list
dns_search_domains:
description:
- List of custom DNS search domains.
type: list
domainname:
description:
- Container domainname.
type: str
version_added: "2.5"
env:
description:
- Dictionary of key,value pairs.
- Values which might be parsed as numbers, booleans or other types by the YAML parser must be quoted (e.g. C("true")) in order to avoid data loss.
type: dict
env_file:
description:
- Path to a file, present on the target, containing environment variables I(FOO=BAR).
- If variable also present in C(env), then C(env) value will override.
type: path
version_added: "2.2"
entrypoint:
description:
- Command that overwrites the default ENTRYPOINT of the image.
type: list
etc_hosts:
description:
- Dict of host-to-IP mappings, where each host name is a key in the dictionary.
Each host name will be added to the container's /etc/hosts file.
type: dict
exposed_ports:
description:
- List of additional container ports which informs Docker that the container
listens on the specified network ports at runtime.
If the port is already exposed using EXPOSE in a Dockerfile, it does not
need to be exposed again.
type: list
aliases:
- exposed
- expose
force_kill:
description:
- Use the kill command when stopping a running container.
type: bool
default: no
aliases:
- forcekill
groups:
description:
- List of additional group names and/or IDs that the container process will run as.
type: list
healthcheck:
description:
- 'Configure a check that is run to determine whether or not containers for this service are "healthy".
See the docs for the L(HEALTHCHECK Dockerfile instruction,https://docs.docker.com/engine/reference/builder/#healthcheck)
for details on how healthchecks work.'
- 'I(interval), I(timeout) and I(start_period) are specified as durations. They accept duration as a string in a format
that look like: C(5h34m56s), C(1m30s) etc. The supported units are C(us), C(ms), C(s), C(m) and C(h)'
type: dict
suboptions:
test:
description:
- Command to run to check health.
- Must be either a string or a list. If it is a list, the first item must be one of C(NONE), C(CMD) or C(CMD-SHELL).
type: raw
interval:
description:
- 'Time between running the check. (default: 30s)'
type: str
timeout:
description:
- 'Maximum time to allow one check to run. (default: 30s)'
type: str
retries:
description:
- 'Consecutive failures needed to report unhealthy. It accept integer value. (default: 3)'
type: int
start_period:
description:
- 'Start period for the container to initialize before starting health-retries countdown. (default: 0s)'
type: str
version_added: "2.8"
hostname:
description:
- Container hostname.
type: str
ignore_image:
description:
- When C(state) is I(present) or I(started) the module compares the configuration of an existing
container to requested configuration. The evaluation includes the image version. If
the image version in the registry does not match the container, the container will be
recreated. Stop this behavior by setting C(ignore_image) to I(True).
- I(Warning:) This option is ignored if C(image) or C(*) is used for the C(comparisons) option.
type: bool
default: no
version_added: "2.2"
image:
description:
- Repository path and tag used to create the container. If an image is not found or pull is true, the image
will be pulled from the registry. If no tag is included, C(latest) will be used.
- Can also be an image ID. If this is the case, the image is assumed to be available locally.
The C(pull) option is ignored for this case.
type: str
init:
description:
- Run an init inside the container that forwards signals and reaps processes.
This option requires Docker API >= 1.25.
type: bool
default: no
version_added: "2.6"
interactive:
description:
- Keep stdin open after a container is launched, even if not attached.
type: bool
default: no
ipc_mode:
description:
- Set the IPC mode for the container. Can be one of 'container:<name|id>' to reuse another
container's IPC namespace or 'host' to use the host's IPC namespace within the container.
type: str
keep_volumes:
description:
- Retain volumes associated with a removed container.
type: bool
default: yes
kill_signal:
description:
- Override default signal used to kill a running container.
type: str
kernel_memory:
description:
- "Kernel memory limit (format: C(<number>[<unit>])). Number is a positive integer.
Unit can be C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte),
C(T) (tebibyte), or C(P) (pebibyte). Minimum is C(4M)."
- Omitting the unit defaults to bytes.
type: str
labels:
description:
- Dictionary of key value pairs.
type: dict
links:
description:
- List of name aliases for linked containers in the format C(container_name:alias).
- Setting this will force container to be restarted.
type: list
log_driver:
description:
- Specify the logging driver. Docker uses I(json-file) by default.
- See L(here,https://docs.docker.com/config/containers/logging/configure/) for possible choices.
type: str
log_options:
description:
- Dictionary of options specific to the chosen log_driver. See https://docs.docker.com/engine/admin/logging/overview/
for details.
type: dict
aliases:
- log_opt
mac_address:
description:
- Container MAC address (e.g. 92:d0:c6:0a:29:33)
type: str
memory:
description:
- "Memory limit (format: C(<number>[<unit>])). Number is a positive integer.
Unit can be C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte),
C(T) (tebibyte), or C(P) (pebibyte)."
- Omitting the unit defaults to bytes.
type: str
default: '0'
memory_reservation:
description:
- "Memory soft limit (format: C(<number>[<unit>])). Number is a positive integer.
Unit can be C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte),
C(T) (tebibyte), or C(P) (pebibyte)."
- Omitting the unit defaults to bytes.
type: str
memory_swap:
description:
- "Total memory limit (memory + swap, format: C(<number>[<unit>])).
Number is a positive integer. Unit can be C(B) (byte), C(K) (kibibyte, 1024B),
C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte)."
- Omitting the unit defaults to bytes.
type: str
memory_swappiness:
description:
- Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100.
- If not set, the value will be remain the same if container exists and will be inherited from the host machine if it is (re-)created.
type: int
name:
description:
- Assign a name to a new container or match an existing container.
- When identifying an existing container name may be a name or a long or short container ID.
type: str
required: yes
network_mode:
description:
- Connect the container to a network. Choices are "bridge", "host", "none" or "container:<name|id>"
type: str
userns_mode:
description:
- Set the user namespace mode for the container. Currently, the only valid value is C(host).
type: str
version_added: "2.5"
networks:
description:
- List of networks the container belongs to.
- For examples of the data structure and usage see EXAMPLES below.
- To remove a container from one or more networks, use the C(purge_networks) option.
- Note that as opposed to C(docker run ...), M(docker_container) does not remove the default
network if C(networks) is specified. You need to explicity use C(purge_networks) to enforce
the removal of the default network (and all other networks not explicitly mentioned in C(networks)).
type: list
suboptions:
name:
description:
- The network's name.
type: str
required: yes
ipv4_address:
description:
- The container's IPv4 address in this network.
type: str
ipv6_address:
description:
- The container's IPv6 address in this network.
type: str
links:
description:
- A list of containers to link to.
type: list
aliases:
description:
- List of aliases for this container in this network. These names
can be used in the network to reach this container.
type: list
version_added: "2.2"
networks_cli_compatible:
description:
- "When networks are provided to the module via the I(networks) option, the module
behaves differently than C(docker run --network): C(docker run --network other)
will create a container with network C(other) attached, but the default network
not attached. This module with C(networks: {name: other}) will create a container
with both C(default) and C(other) attached. If I(purge_networks) is set to C(yes),
the C(default) network will be removed afterwards."
- "If I(networks_cli_compatible) is set to C(yes), this module will behave as
C(docker run --network) and will I(not) add the default network if C(networks) is
specified. If C(networks) is not specified, the default network will be attached."
- "Note that docker CLI also sets C(network_mode) to the name of the first network
added if C(--network) is specified. For more compatibility with docker CLI, you
explicitly have to set C(network_mode) to the name of the first network you're
adding."
- Current value is C(no). A new default of C(yes) will be set in Ansible 2.12.
type: bool
version_added: "2.8"
oom_killer:
description:
- Whether or not to disable OOM Killer for the container.
type: bool
oom_score_adj:
description:
- An integer value containing the score given to the container in order to tune
OOM killer preferences.
type: int
version_added: "2.2"
output_logs:
description:
- If set to true, output of the container command will be printed (only effective
when log_driver is set to json-file or journald.
type: bool
default: no
version_added: "2.7"
paused:
description:
- Use with the started state to pause running processes inside the container.
type: bool
default: no
pid_mode:
description:
- Set the PID namespace mode for the container.
- Note that Docker SDK for Python < 2.0 only supports 'host'. Newer versions of the
Docker SDK for Python (docker) allow all values supported by the docker daemon.
type: str
pids_limit:
description:
- Set PIDs limit for the container. It accepts an integer value.
- Set -1 for unlimited PIDs.
type: int
version_added: "2.8"
privileged:
description:
- Give extended privileges to the container.
type: bool
default: no
published_ports:
description:
- List of ports to publish from the container to the host.
- "Use docker CLI syntax: C(8000), C(9000:8000), or C(0.0.0.0:9000:8000), where 8000 is a
container port, 9000 is a host port, and 0.0.0.0 is a host interface."
- Port ranges can be used for source and destination ports. If two ranges with
different lengths are specified, the shorter range will be used.
- "Bind addresses must be either IPv4 or IPv6 addresses. Hostnames are I(not) allowed. This
is different from the C(docker) command line utility. Use the L(dig lookup,../lookup/dig.html)
to resolve hostnames."
- A value of C(all) will publish all exposed container ports to random host ports, ignoring
any other mappings.
- If C(networks) parameter is provided, will inspect each network to see if there exists
a bridge network with optional parameter com.docker.network.bridge.host_binding_ipv4.
If such a network is found, then published ports where no host IP address is specified
will be bound to the host IP pointed to by com.docker.network.bridge.host_binding_ipv4.
Note that the first bridge network with a com.docker.network.bridge.host_binding_ipv4
value encountered in the list of C(networks) is the one that will be used.
type: list
aliases:
- ports
pull:
description:
- If true, always pull the latest version of an image. Otherwise, will only pull an image
when missing.
- I(Note) that images are only pulled when specified by name. If the image is specified
as a image ID (hash), it cannot be pulled.
type: bool
default: no
purge_networks:
description:
- Remove the container from ALL networks not included in C(networks) parameter.
- Any default networks such as I(bridge), if not found in C(networks), will be removed as well.
type: bool
default: no
version_added: "2.2"
read_only:
description:
- Mount the container's root file system as read-only.
type: bool
default: no
recreate:
description:
- Use with present and started states to force the re-creation of an existing container.
type: bool
default: no
restart:
description:
- Use with started state to force a matching container to be stopped and restarted.
type: bool
default: no
restart_policy:
description:
- Container restart policy. Place quotes around I(no) option.
type: str
choices:
- 'no'
- 'on-failure'
- 'always'
- 'unless-stopped'
restart_retries:
description:
- Use with restart policy to control maximum number of restart attempts.
type: int
runtime:
description:
- Runtime to use for the container.
type: str
version_added: "2.8"
shm_size:
description:
- "Size of C(/dev/shm) (format: C(<number>[<unit>])). Number is positive integer.
Unit can be C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte),
C(T) (tebibyte), or C(P) (pebibyte)."
- Omitting the unit defaults to bytes. If you omit the size entirely, the system uses C(64M).
type: str
security_opts:
description:
- List of security options in the form of C("label:user:User")
type: list
state:
description:
- 'I(absent) - A container matching the specified name will be stopped and removed. Use force_kill to kill the container
rather than stopping it. Use keep_volumes to retain volumes associated with the removed container.'
- 'I(present) - Asserts the existence of a container matching the name and any provided configuration parameters. If no
container matches the name, a container will be created. If a container matches the name but the provided configuration
does not match, the container will be updated, if it can be. If it cannot be updated, it will be removed and re-created
with the requested config. Image version will be taken into account when comparing configuration. To ignore image
version use the ignore_image option. Use the recreate option to force the re-creation of the matching container. Use
force_kill to kill the container rather than stopping it. Use keep_volumes to retain volumes associated with a removed
container.'
- 'I(started) - Asserts there is a running container matching the name and any provided configuration. If no container
matches the name, a container will be created and started. If a container matching the name is found but the
configuration does not match, the container will be updated, if it can be. If it cannot be updated, it will be removed
and a new container will be created with the requested configuration and started. Image version will be taken into
account when comparing configuration. To ignore image version use the ignore_image option. Use recreate to always
re-create a matching container, even if it is running. Use restart to force a matching container to be stopped and
restarted. Use force_kill to kill a container rather than stopping it. Use keep_volumes to retain volumes associated
with a removed container.'
- 'I(stopped) - Asserts that the container is first I(present), and then if the container is running moves it to a stopped
state. Use force_kill to kill a container rather than stopping it.'
type: str
default: started
choices:
- absent
- present
- stopped
- started
stop_signal:
description:
- Override default signal used to stop the container.
type: str
stop_timeout:
description:
- Number of seconds to wait for the container to stop before sending SIGKILL.
When the container is created by this module, its C(StopTimeout) configuration
will be set to this value.
- When the container is stopped, will be used as a timeout for stopping the
container. In case the container has a custom C(StopTimeout) configuration,
the behavior depends on the version of the docker daemon. New versions of
the docker daemon will always use the container's configured C(StopTimeout)
value if it has been configured.
type: int
trust_image_content:
description:
- If C(yes), skip image verification.
type: bool
default: no
tmpfs:
description:
- Mount a tmpfs directory
type: list
version_added: 2.4
tty:
description:
- Allocate a pseudo-TTY.
type: bool
default: no
ulimits:
description:
- "List of ulimit options. A ulimit is specified as C(nofile:262144:262144)"
type: list
sysctls:
description:
- Dictionary of key,value pairs.
type: dict
version_added: 2.4
user:
description:
- Sets the username or UID used and optionally the groupname or GID for the specified command.
- "Can be [ user | user:group | uid | uid:gid | user:gid | uid:group ]"
type: str
uts:
description:
- Set the UTS namespace mode for the container.
type: str
volumes:
description:
- List of volumes to mount within the container.
- "Use docker CLI-style syntax: C(/host:/container[:mode])"
- "Mount modes can be a comma-separated list of various modes such as C(ro), C(rw), C(consistent),
C(delegated), C(cached), C(rprivate), C(private), C(rshared), C(shared), C(rslave), C(slave).
Note that the docker daemon might not support all modes and combinations of such modes."
- SELinux hosts can additionally use C(z) or C(Z) to use a shared or
private label for the volume.
- "Note that Ansible 2.7 and earlier only supported one mode, which had to be one of C(ro), C(rw),
C(z), and C(Z)."
type: list
volume_driver:
description:
- The container volume driver.
type: str
volumes_from:
description:
- List of container names or Ids to get volumes from.
type: list
working_dir:
description:
- Path to the working directory.
type: str
version_added: "2.4"
extends_documentation_fragment:
- docker
- docker.docker_py_1_documentation
author:
- "Cove Schneider (@cove)"
- "Joshua Conner (@joshuaconner)"
- "Pavel Antonov (@softzilla)"
- "Thomas Steinbach (@ThomasSteinbach)"
- "Philippe Jandot (@zfil)"
- "Daan Oosterveld (@dusdanig)"
- "Chris Houseknecht (@chouseknecht)"
- "Kassian Sun (@kassiansun)"
- "Felix Fontein (@felixfontein)"
requirements:
- "L(Docker SDK for Python,https://docker-py.readthedocs.io/en/stable/) >= 1.8.0 (use L(docker-py,https://pypi.org/project/docker-py/) for Python 2.6)"
- "Docker API >= 1.20"
'''
EXAMPLES = '''
- name: Create a data container
docker_container:
name: mydata
image: busybox
volumes:
- /data
- name: Re-create a redis container
docker_container:
name: myredis
image: redis
command: redis-server --appendonly yes
state: present
recreate: yes
exposed_ports:
- 6379
volumes_from:
- mydata
- name: Restart a container
docker_container:
name: myapplication
image: someuser/appimage
state: started
restart: yes
links:
- "myredis:aliasedredis"
devices:
- "/dev/sda:/dev/xvda:rwm"
ports:
- "8080:9000"
- "127.0.0.1:8081:9001/udp"
env:
SECRET_KEY: "ssssh"
# Values which might be parsed as numbers, booleans or other types by the YAML parser need to be quoted
BOOLEAN_KEY: "yes"
- name: Container present
docker_container:
name: mycontainer
state: present
image: ubuntu:14.04
command: sleep infinity
- name: Stop a container
docker_container:
name: mycontainer
state: stopped
- name: Start 4 load-balanced containers
docker_container:
name: "container{{ item }}"
recreate: yes
image: someuser/anotherappimage
command: sleep 1d
with_sequence: count=4
- name: remove container
docker_container:
name: ohno
state: absent
- name: Syslogging output
docker_container:
name: myservice
image: busybox
log_driver: syslog
log_options:
syslog-address: tcp://my-syslog-server:514
syslog-facility: daemon
# NOTE: in Docker 1.13+ the "syslog-tag" option was renamed to "tag" for
# older docker installs, use "syslog-tag" instead
tag: myservice
- name: Create db container and connect to network
docker_container:
name: db_test
image: "postgres:latest"
networks:
- name: "{{ docker_network_name }}"
- name: Start container, connect to network and link
docker_container:
name: sleeper
image: ubuntu:14.04
networks:
- name: TestingNet
ipv4_address: "172.1.1.100"
aliases:
- sleepyzz
links:
- db_test:db
- name: TestingNet2
- name: Start a container with a command
docker_container:
name: sleepy
image: ubuntu:14.04
command: ["sleep", "infinity"]
- name: Add container to networks
docker_container:
name: sleepy
networks:
- name: TestingNet
ipv4_address: 172.1.1.18
links:
- sleeper
- name: TestingNet2
ipv4_address: 172.1.10.20
- name: Update network with aliases
docker_container:
name: sleepy
networks:
- name: TestingNet
aliases:
- sleepyz
- zzzz
- name: Remove container from one network
docker_container:
name: sleepy
networks:
- name: TestingNet2
purge_networks: yes
- name: Remove container from all networks
docker_container:
name: sleepy
purge_networks: yes
- name: Start a container and use an env file
docker_container:
name: agent
image: jenkinsci/ssh-slave
env_file: /var/tmp/jenkins/agent.env
- name: Create a container with limited capabilities
docker_container:
name: sleepy
image: ubuntu:16.04
command: sleep infinity
capabilities:
- sys_time
cap_drop:
- all
- name: Finer container restart/update control
docker_container:
name: test
image: ubuntu:18.04
env:
arg1: "true"
arg2: "whatever"
volumes:
- /tmp:/tmp
comparisons:
image: ignore # don't restart containers with older versions of the image
env: strict # we want precisely this environment
volumes: allow_more_present # if there are more volumes, that's ok, as long as `/tmp:/tmp` is there
- name: Finer container restart/update control II
docker_container:
name: test
image: ubuntu:18.04
env:
arg1: "true"
arg2: "whatever"
comparisons:
'*': ignore # by default, ignore *all* options (including image)
env: strict # except for environment variables; there, we want to be strict
- name: Start container with healthstatus
docker_container:
name: nginx-proxy
image: nginx:1.13
state: started
healthcheck:
# Check if nginx server is healthy by curl'ing the server.
# If this fails or timeouts, the healthcheck fails.
test: ["CMD", "curl", "--fail", "http://nginx.host.com"]
interval: 1m30s
timeout: 10s
retries: 3
start_period: 30s
- name: Remove healthcheck from container
docker_container:
name: nginx-proxy
image: nginx:1.13
state: started
healthcheck:
# The "NONE" check needs to be specified
test: ["NONE"]
- name: start container with block device read limit
docker_container:
name: test
image: ubuntu:18.04
state: started
device_read_bps:
# Limit read rate for /dev/sda to 20 mebibytes per second
- path: /dev/sda
rate: 20M
device_read_iops:
# Limit read rate for /dev/sdb to 300 IO per second
- path: /dev/sdb
rate: 300
'''
RETURN = '''
container:
description:
- Facts representing the current state of the container. Matches the docker inspection output.
- Note that facts are part of the registered vars since Ansible 2.8. For compatibility reasons, the facts
are also accessible directly as C(docker_container). Note that the returned fact will be removed in Ansible 2.12.
- Before 2.3 this was C(ansible_docker_container) but was renamed in 2.3 to C(docker_container) due to
conflicts with the connection plugin.
- Empty if C(state) is I(absent)
- If detached is I(False), will include Output attribute containing any output from container run.
returned: always
type: dict
sample: '{
"AppArmorProfile": "",
"Args": [],
"Config": {
"AttachStderr": false,
"AttachStdin": false,
"AttachStdout": false,
"Cmd": [
"/usr/bin/supervisord"
],
"Domainname": "",
"Entrypoint": null,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
],
"ExposedPorts": {
"443/tcp": {},
"80/tcp": {}
},
"Hostname": "8e47bf643eb9",
"Image": "lnmp_nginx:v1",
"Labels": {},
"OnBuild": null,
"OpenStdin": false,
"StdinOnce": false,
"Tty": false,
"User": "",
"Volumes": {
"/tmp/lnmp/nginx-sites/logs/": {}
},
...
}'
'''
import os
import re
import shlex
import traceback
from distutils.version import LooseVersion
from ansible.module_utils.common.text.formatters import human_to_bytes
from ansible.module_utils.docker.common import (
AnsibleDockerClient,
DifferenceTracker,
DockerBaseClass,
compare_generic,
is_image_name_id,
sanitize_result,
parse_healthcheck,
DOCKER_COMMON_ARGS,
)
from ansible.module_utils.six import string_types
try:
from docker import utils
from ansible.module_utils.docker.common import docker_version
if LooseVersion(docker_version) >= LooseVersion('1.10.0'):
from docker.types import Ulimit, LogConfig
else:
from docker.utils.types import Ulimit, LogConfig
from docker.errors import DockerException, APIError, NotFound
except Exception:
# missing Docker SDK for Python handled in ansible.module_utils.docker.common
pass
REQUIRES_CONVERSION_TO_BYTES = [
'kernel_memory',
'memory',
'memory_reservation',
'memory_swap',
'shm_size'
]
def is_volume_permissions(input):
for part in input.split(','):
if part not in ('rw', 'ro', 'z', 'Z', 'consistent', 'delegated', 'cached', 'rprivate', 'private', 'rshared', 'shared', 'rslave', 'slave'):
return False
return True
def parse_port_range(range_or_port, client):
'''
Parses a string containing either a single port or a range of ports.
Returns a list of integers for each port in the list.
'''
if '-' in range_or_port:
start, end = [int(port) for port in range_or_port.split('-')]
if end < start:
client.fail('Invalid port range: {0}'.format(range_or_port))
return list(range(start, end + 1))
else:
return [int(range_or_port)]
def split_colon_ipv6(input, client):
'''
Split string by ':', while keeping IPv6 addresses in square brackets in one component.
'''
if '[' not in input:
return input.split(':')
start = 0
result = []
while start < len(input):
i = input.find('[', start)
if i < 0:
result.extend(input[start:].split(':'))
break
j = input.find(']', i)
if j < 0:
client.fail('Cannot find closing "]" in input "{0}" for opening "[" at index {1}!'.format(input, i + 1))
result.extend(input[start:i].split(':'))
k = input.find(':', j)
if k < 0:
result[-1] += input[i:]
start = len(input)
else:
result[-1] += input[i:k]
if k == len(input):
result.append('')
break
start = k + 1
return result
class TaskParameters(DockerBaseClass):
'''
Access and parse module parameters
'''
def __init__(self, client):
super(TaskParameters, self).__init__()
self.client = client
self.auto_remove = None
self.blkio_weight = None
self.capabilities = None
self.cap_drop = None
self.cleanup = None
self.command = None
self.cpu_period = None
self.cpu_quota = None
self.cpuset_cpus = None
self.cpuset_mems = None
self.cpu_shares = None
self.detach = None
self.debug = None
self.devices = None
self.device_read_bps = None
self.device_write_bps = None
self.device_read_iops = None
self.device_write_iops = None
self.dns_servers = None
self.dns_opts = None
self.dns_search_domains = None
self.domainname = None
self.env = None
self.env_file = None
self.entrypoint = None
self.etc_hosts = None
self.exposed_ports = None
self.force_kill = None
self.groups = None
self.healthcheck = None
self.hostname = None
self.ignore_image = None
self.image = None
self.init = None
self.interactive = None
self.ipc_mode = None
self.keep_volumes = None
self.kernel_memory = None
self.kill_signal = None
self.labels = None
self.links = None
self.log_driver = None
self.output_logs = None
self.log_options = None
self.mac_address = None
self.memory = None
self.memory_reservation = None
self.memory_swap = None
self.memory_swappiness = None
self.name = None
self.network_mode = None
self.userns_mode = None
self.networks = None
self.networks_cli_compatible = None
self.oom_killer = None
self.oom_score_adj = None
self.paused = None
self.pid_mode = None
self.pids_limit = None
self.privileged = None
self.purge_networks = None
self.pull = None
self.read_only = None
self.recreate = None
self.restart = None
self.restart_retries = None
self.restart_policy = None
self.runtime = None
self.shm_size = None
self.security_opts = None
self.state = None
self.stop_signal = None
self.stop_timeout = None
self.tmpfs = None
self.trust_image_content = None
self.tty = None
self.user = None
self.uts = None
self.volumes = None
self.volume_binds = dict()
self.volumes_from = None
self.volume_driver = None
self.working_dir = None
for key, value in client.module.params.items():
setattr(self, key, value)
self.comparisons = client.comparisons
# If state is 'absent', parameters do not have to be parsed or interpreted.
# Only the container's name is needed.
if self.state == 'absent':
return
if self.groups:
# In case integers are passed as groups, we need to convert them to
# strings as docker internally treats them as strings.
self.groups = [str(g) for g in self.groups]
for param_name in REQUIRES_CONVERSION_TO_BYTES:
if client.module.params.get(param_name):
try:
setattr(self, param_name, human_to_bytes(client.module.params.get(param_name)))
except ValueError as exc:
self.fail("Failed to convert %s to bytes: %s" % (param_name, exc))
self.publish_all_ports = False
self.published_ports = self._parse_publish_ports()
if self.published_ports in ('all', 'ALL'):
self.publish_all_ports = True
self.published_ports = None
self.ports = self._parse_exposed_ports(self.published_ports)
self.log("expose ports:")
self.log(self.ports, pretty_print=True)
self.links = self._parse_links(self.links)
if self.volumes:
self.volumes = self._expand_host_paths()
self.tmpfs = self._parse_tmpfs()
self.env = self._get_environment()
self.ulimits = self._parse_ulimits()
self.sysctls = self._parse_sysctls()
self.log_config = self._parse_log_config()
try:
self.healthcheck, self.disable_healthcheck = parse_healthcheck(self.healthcheck)
except ValueError as e:
self.fail(str(e))
self.exp_links = None
self.volume_binds = self._get_volume_binds(self.volumes)
self.pid_mode = self._replace_container_names(self.pid_mode)
self.ipc_mode = self._replace_container_names(self.ipc_mode)
self.network_mode = self._replace_container_names(self.network_mode)
self.log("volumes:")
self.log(self.volumes, pretty_print=True)
self.log("volume binds:")
self.log(self.volume_binds, pretty_print=True)
if self.networks:
for network in self.networks:
network['id'] = self._get_network_id(network['name'])
if not network['id']:
self.fail("Parameter error: network named %s could not be found. Does it exist?" % network['name'])
if network.get('links'):
network['links'] = self._parse_links(network['links'])
if self.mac_address:
# Ensure the MAC address uses colons instead of hyphens for later comparison
self.mac_address = self.mac_address.replace('-', ':')
if self.entrypoint:
# convert from list to str.
self.entrypoint = ' '.join([str(x) for x in self.entrypoint])
if self.command:
# convert from list to str
if isinstance(self.command, list):
self.command = ' '.join([str(x) for x in self.command])
for param_name in ["device_read_bps", "device_write_bps"]:
if client.module.params.get(param_name):
self._process_rate_bps(option=param_name)
for param_name in ["device_read_iops", "device_write_iops"]:
if client.module.params.get(param_name):
self._process_rate_iops(option=param_name)
def fail(self, msg):
self.client.fail(msg)
@property
def update_parameters(self):
'''
Returns parameters used to update a container
'''
update_parameters = dict(
blkio_weight='blkio_weight',
cpu_period='cpu_period',
cpu_quota='cpu_quota',
cpu_shares='cpu_shares',
cpuset_cpus='cpuset_cpus',
cpuset_mems='cpuset_mems',
mem_limit='memory',
mem_reservation='memory_reservation',
memswap_limit='memory_swap',
kernel_memory='kernel_memory',
)
result = dict()
for key, value in update_parameters.items():
if getattr(self, value, None) is not None:
if self.client.option_minimal_versions[value]['supported']:
result[key] = getattr(self, value)
return result
@property
def create_parameters(self):
'''
Returns parameters used to create a container
'''
create_params = dict(
command='command',
domainname='domainname',
hostname='hostname',
user='user',
detach='detach',
stdin_open='interactive',
tty='tty',
ports='ports',
environment='env',
name='name',
entrypoint='entrypoint',
mac_address='mac_address',
labels='labels',
stop_signal='stop_signal',
working_dir='working_dir',
stop_timeout='stop_timeout',
healthcheck='healthcheck',
)
if self.client.docker_py_version < LooseVersion('3.0'):
# cpu_shares and volume_driver moved to create_host_config in > 3
create_params['cpu_shares'] = 'cpu_shares'
create_params['volume_driver'] = 'volume_driver'
result = dict(
host_config=self._host_config(),
volumes=self._get_mounts(),
)
for key, value in create_params.items():
if getattr(self, value, None) is not None:
if self.client.option_minimal_versions[value]['supported']:
result[key] = getattr(self, value)
if self.networks_cli_compatible and self.networks:
network = self.networks[0]
params = dict()
for para in ('ipv4_address', 'ipv6_address', 'links', 'aliases'):
if network.get(para):
params[para] = network[para]
network_config = dict()
network_config[network['name']] = self.client.create_endpoint_config(**params)
result['networking_config'] = self.client.create_networking_config(network_config)
return result
def _expand_host_paths(self):
new_vols = []
for vol in self.volumes:
if ':' in vol:
if len(vol.split(':')) == 3:
host, container, mode = vol.split(':')
if not is_volume_permissions(mode):
self.fail('Found invalid volumes mode: {0}'.format(mode))
if re.match(r'[.~]', host):
host = os.path.abspath(os.path.expanduser(host))
new_vols.append("%s:%s:%s" % (host, container, mode))
continue
elif len(vol.split(':')) == 2:
parts = vol.split(':')
if not is_volume_permissions(parts[1]) and re.match(r'[.~]', parts[0]):
host = os.path.abspath(os.path.expanduser(parts[0]))
new_vols.append("%s:%s:rw" % (host, parts[1]))
continue
new_vols.append(vol)
return new_vols
def _get_mounts(self):
'''
Return a list of container mounts.
:return:
'''
result = []
if self.volumes:
for vol in self.volumes:
if ':' in vol:
if len(vol.split(':')) == 3:
host, container, dummy = vol.split(':')
result.append(container)
continue
if len(vol.split(':')) == 2:
parts = vol.split(':')
if not is_volume_permissions(parts[1]):
result.append(parts[1])
continue
result.append(vol)
self.log("mounts:")
self.log(result, pretty_print=True)
return result
def _host_config(self):
'''
Returns parameters used to create a HostConfig object
'''
host_config_params = dict(
port_bindings='published_ports',
publish_all_ports='publish_all_ports',
links='links',
privileged='privileged',
dns='dns_servers',
dns_opt='dns_opts',
dns_search='dns_search_domains',
binds='volume_binds',
volumes_from='volumes_from',
network_mode='network_mode',
userns_mode='userns_mode',
cap_add='capabilities',
cap_drop='cap_drop',
extra_hosts='etc_hosts',
read_only='read_only',
ipc_mode='ipc_mode',
security_opt='security_opts',
ulimits='ulimits',
sysctls='sysctls',
log_config='log_config',
mem_limit='memory',
memswap_limit='memory_swap',
mem_swappiness='memory_swappiness',
oom_score_adj='oom_score_adj',
oom_kill_disable='oom_killer',
shm_size='shm_size',
group_add='groups',
devices='devices',
pid_mode='pid_mode',
tmpfs='tmpfs',
init='init',
uts_mode='uts',
runtime='runtime',
auto_remove='auto_remove',
device_read_bps='device_read_bps',
device_write_bps='device_write_bps',
device_read_iops='device_read_iops',
device_write_iops='device_write_iops',
pids_limit='pids_limit',
)
if self.client.docker_py_version >= LooseVersion('1.9') and self.client.docker_api_version >= LooseVersion('1.22'):
# blkio_weight can always be updated, but can only be set on creation
# when Docker SDK for Python and Docker API are new enough
host_config_params['blkio_weight'] = 'blkio_weight'
if self.client.docker_py_version >= LooseVersion('3.0'):
# cpu_shares and volume_driver moved to create_host_config in > 3
host_config_params['cpu_shares'] = 'cpu_shares'
host_config_params['volume_driver'] = 'volume_driver'
params = dict()
for key, value in host_config_params.items():
if getattr(self, value, None) is not None:
if self.client.option_minimal_versions[value]['supported']:
params[key] = getattr(self, value)
if self.restart_policy:
params['restart_policy'] = dict(Name=self.restart_policy,
MaximumRetryCount=self.restart_retries)
return self.client.create_host_config(**params)
@property
def default_host_ip(self):
ip = '0.0.0.0'
if not self.networks:
return ip
for net in self.networks:
if net.get('name'):
try:
network = self.client.inspect_network(net['name'])
if network.get('Driver') == 'bridge' and \
network.get('Options', {}).get('com.docker.network.bridge.host_binding_ipv4'):
ip = network['Options']['com.docker.network.bridge.host_binding_ipv4']
break
except NotFound as e:
self.client.fail(
"Cannot inspect the network '{0}' to determine the default IP.".format(net['name']),
exception=traceback.format_exc()
)
return ip
def _parse_publish_ports(self):
'''
Parse ports from docker CLI syntax
'''
if self.published_ports is None:
return None
if 'all' in self.published_ports:
return 'all'
default_ip = self.default_host_ip
binds = {}
for port in self.published_ports:
parts = split_colon_ipv6(str(port), self.client)
container_port = parts[-1]
protocol = ''
if '/' in container_port:
container_port, protocol = parts[-1].split('/')
container_ports = parse_port_range(container_port, self.client)
p_len = len(parts)
if p_len == 1:
port_binds = len(container_ports) * [(default_ip,)]
elif p_len == 2:
port_binds = [(default_ip, port) for port in parse_port_range(parts[0], self.client)]
elif p_len == 3:
# We only allow IPv4 and IPv6 addresses for the bind address
if not re.match(r'^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$', parts[0]) and not re.match(r'^\[[0-9a-fA-F:]+\]$', parts[0]):
self.fail(('Bind addresses for published ports must be IPv4 or IPv6 addresses, not hostnames. '
'Use the dig lookup to resolve hostnames. (Found hostname: {0})').format(parts[0]))
if parts[1]:
port_binds = [(parts[0], port) for port in parse_port_range(parts[1], self.client)]
else:
port_binds = len(container_ports) * [(parts[0],)]
for bind, container_port in zip(port_binds, container_ports):
idx = '{0}/{1}'.format(container_port, protocol) if protocol else container_port
if idx in binds:
old_bind = binds[idx]
if isinstance(old_bind, list):
old_bind.append(bind)
else:
binds[idx] = [old_bind, bind]
else:
binds[idx] = bind
return binds
def _get_volume_binds(self, volumes):
'''
Extract host bindings, if any, from list of volume mapping strings.
:return: dictionary of bind mappings
'''
result = dict()
if volumes:
for vol in volumes:
host = None
if ':' in vol:
if len(vol.split(':')) == 3:
host, container, mode = vol.split(':')
if not is_volume_permissions(mode):
self.fail('Found invalid volumes mode: {0}'.format(mode))
if len(vol.split(':')) == 2:
parts = vol.split(':')
if not is_volume_permissions(parts[1]):
host, container, mode = (vol.split(':') + ['rw'])
if host is not None:
result[host] = dict(
bind=container,
mode=mode
)
return result
def _parse_exposed_ports(self, published_ports):
'''
Parse exposed ports from docker CLI-style ports syntax.
'''
exposed = []
if self.exposed_ports:
for port in self.exposed_ports:
port = str(port).strip()
protocol = 'tcp'
match = re.search(r'(/.+$)', port)
if match:
protocol = match.group(1).replace('/', '')
port = re.sub(r'/.+$', '', port)
exposed.append((port, protocol))
if published_ports:
# Any published port should also be exposed
for publish_port in published_ports:
match = False
if isinstance(publish_port, string_types) and '/' in publish_port:
port, protocol = publish_port.split('/')
port = int(port)
else:
protocol = 'tcp'
port = int(publish_port)
for exposed_port in exposed:
if exposed_port[1] != protocol:
continue
if isinstance(exposed_port[0], string_types) and '-' in exposed_port[0]:
start_port, end_port = exposed_port[0].split('-')
if int(start_port) <= port <= int(end_port):
match = True
elif exposed_port[0] == port:
match = True
if not match:
exposed.append((port, protocol))
return exposed
@staticmethod
def _parse_links(links):
'''
Turn links into a dictionary
'''
if links is None:
return None
result = []
for link in links:
parsed_link = link.split(':', 1)
if len(parsed_link) == 2:
result.append((parsed_link[0], parsed_link[1]))
else:
result.append((parsed_link[0], parsed_link[0]))
return result
def _parse_ulimits(self):
'''
Turn ulimits into an array of Ulimit objects
'''
if self.ulimits is None:
return None
results = []
for limit in self.ulimits:
limits = dict()
pieces = limit.split(':')
if len(pieces) >= 2:
limits['name'] = pieces[0]
limits['soft'] = int(pieces[1])
limits['hard'] = int(pieces[1])
if len(pieces) == 3:
limits['hard'] = int(pieces[2])
try:
results.append(Ulimit(**limits))
except ValueError as exc:
self.fail("Error parsing ulimits value %s - %s" % (limit, exc))
return results
def _parse_sysctls(self):
'''
Turn sysctls into an hash of Sysctl objects
'''
return self.sysctls
def _parse_log_config(self):
'''
Create a LogConfig object
'''
if self.log_driver is None:
return None
options = dict(
Type=self.log_driver,
Config=dict()
)
if self.log_options is not None:
options['Config'] = dict()
for k, v in self.log_options.items():
if not isinstance(v, string_types):
self.client.module.warn(
"Non-string value found for log_options option '%s'. The value is automatically converted to '%s'. "
"If this is not correct, or you want to avoid such warnings, please quote the value." % (k, str(v))
)
v = str(v)
self.log_options[k] = v
options['Config'][k] = v
try:
return LogConfig(**options)
except ValueError as exc:
self.fail('Error parsing logging options - %s' % (exc))
def _parse_tmpfs(self):
'''
Turn tmpfs into a hash of Tmpfs objects
'''
result = dict()
if self.tmpfs is None:
return result
for tmpfs_spec in self.tmpfs:
split_spec = tmpfs_spec.split(":", 1)
if len(split_spec) > 1:
result[split_spec[0]] = split_spec[1]
else:
result[split_spec[0]] = ""
return result
def _get_environment(self):
"""
If environment file is combined with explicit environment variables, the explicit environment variables
take precedence.
"""
final_env = {}
if self.env_file:
parsed_env_file = utils.parse_env_file(self.env_file)
for name, value in parsed_env_file.items():
final_env[name] = str(value)
if self.env:
for name, value in self.env.items():
if not isinstance(value, string_types):
self.fail("Non-string value found for env option. Ambiguous env options must be "
"wrapped in quotes to avoid them being interpreted. Key: %s" % (name, ))
final_env[name] = str(value)
return final_env
def _get_network_id(self, network_name):
network_id = None
try:
for network in self.client.networks(names=[network_name]):
if network['Name'] == network_name:
network_id = network['Id']
break
except Exception as exc:
self.fail("Error getting network id for %s - %s" % (network_name, str(exc)))
return network_id
def _process_rate_bps(self, option):
"""
Format device_read_bps and device_write_bps option
"""
devices_list = []
for v in getattr(self, option):
device_dict = dict((x.title(), y) for x, y in v.items())
device_dict['Rate'] = human_to_bytes(device_dict['Rate'])
devices_list.append(device_dict)
setattr(self, option, devices_list)
def _process_rate_iops(self, option):
"""
Format device_read_iops and device_write_iops option
"""
devices_list = []
for v in getattr(self, option):
device_dict = dict((x.title(), y) for x, y in v.items())
devices_list.append(device_dict)
setattr(self, option, devices_list)
def _replace_container_names(self, mode):
"""
Parse IPC and PID modes. If they contain a container name, replace
with the container's ID.
"""
if mode is None or not mode.startswith('container:'):
return mode
container_name = mode[len('container:'):]
# Try to inspect container to see whether this is an ID or a
# name (and in the latter case, retrieve it's ID)
container = self.client.get_container(container_name)
if container is None:
# If we can't find the container, issue a warning and continue with
# what the user specified.
self.client.module.warn('Cannot find a container with name or ID "{0}"'.format(container_name))
return mode
return 'container:{0}'.format(container['Id'])
class Container(DockerBaseClass):
def __init__(self, container, parameters):
super(Container, self).__init__()
self.raw = container
self.Id = None
self.container = container
if container:
self.Id = container['Id']
self.Image = container['Image']
self.log(self.container, pretty_print=True)
self.parameters = parameters
self.parameters.expected_links = None
self.parameters.expected_ports = None
self.parameters.expected_exposed = None
self.parameters.expected_volumes = None
self.parameters.expected_ulimits = None
self.parameters.expected_sysctls = None
self.parameters.expected_etc_hosts = None
self.parameters.expected_env = None
self.parameters_map = dict()
self.parameters_map['expected_links'] = 'links'
self.parameters_map['expected_ports'] = 'expected_ports'
self.parameters_map['expected_exposed'] = 'exposed_ports'
self.parameters_map['expected_volumes'] = 'volumes'
self.parameters_map['expected_ulimits'] = 'ulimits'
self.parameters_map['expected_sysctls'] = 'sysctls'
self.parameters_map['expected_etc_hosts'] = 'etc_hosts'
self.parameters_map['expected_env'] = 'env'
self.parameters_map['expected_entrypoint'] = 'entrypoint'
self.parameters_map['expected_binds'] = 'volumes'
self.parameters_map['expected_cmd'] = 'command'
self.parameters_map['expected_devices'] = 'devices'
self.parameters_map['expected_healthcheck'] = 'healthcheck'
def fail(self, msg):
self.parameters.client.fail(msg)
@property
def exists(self):
return True if self.container else False
@property
def running(self):
if self.container and self.container.get('State'):
if self.container['State'].get('Running') and not self.container['State'].get('Ghost', False):
return True
return False
@property
def paused(self):
if self.container and self.container.get('State'):
return self.container['State'].get('Paused', False)
return False
def _compare(self, a, b, compare):
'''
Compare values a and b as described in compare.
'''
return compare_generic(a, b, compare['comparison'], compare['type'])
def has_different_configuration(self, image):
'''
Diff parameters vs existing container config. Returns tuple: (True | False, List of differences)
'''
self.log('Starting has_different_configuration')
self.parameters.expected_entrypoint = self._get_expected_entrypoint()
self.parameters.expected_links = self._get_expected_links()
self.parameters.expected_ports = self._get_expected_ports()
self.parameters.expected_exposed = self._get_expected_exposed(image)
self.parameters.expected_volumes = self._get_expected_volumes(image)
self.parameters.expected_binds = self._get_expected_binds(image)
self.parameters.expected_ulimits = self._get_expected_ulimits(self.parameters.ulimits)
self.parameters.expected_sysctls = self._get_expected_sysctls(self.parameters.sysctls)
self.parameters.expected_etc_hosts = self._convert_simple_dict_to_list('etc_hosts')
self.parameters.expected_env = self._get_expected_env(image)
self.parameters.expected_cmd = self._get_expected_cmd()
self.parameters.expected_devices = self._get_expected_devices()
self.parameters.expected_healthcheck = self._get_expected_healthcheck()
if not self.container.get('HostConfig'):
self.fail("has_config_diff: Error parsing container properties. HostConfig missing.")
if not self.container.get('Config'):
self.fail("has_config_diff: Error parsing container properties. Config missing.")
if not self.container.get('NetworkSettings'):
self.fail("has_config_diff: Error parsing container properties. NetworkSettings missing.")
host_config = self.container['HostConfig']
log_config = host_config.get('LogConfig', dict())
restart_policy = host_config.get('RestartPolicy', dict())
config = self.container['Config']
network = self.container['NetworkSettings']
# The previous version of the docker module ignored the detach state by
# assuming if the container was running, it must have been detached.
detach = not (config.get('AttachStderr') and config.get('AttachStdout'))
# "ExposedPorts": null returns None type & causes AttributeError - PR #5517
if config.get('ExposedPorts') is not None:
expected_exposed = [self._normalize_port(p) for p in config.get('ExposedPorts', dict()).keys()]
else:
expected_exposed = []
# Map parameters to container inspect results
config_mapping = dict(
expected_cmd=config.get('Cmd'),
domainname=config.get('Domainname'),
hostname=config.get('Hostname'),
user=config.get('User'),
detach=detach,
init=host_config.get('Init'),
interactive=config.get('OpenStdin'),
capabilities=host_config.get('CapAdd'),
cap_drop=host_config.get('CapDrop'),
expected_devices=host_config.get('Devices'),
dns_servers=host_config.get('Dns'),
dns_opts=host_config.get('DnsOptions'),
dns_search_domains=host_config.get('DnsSearch'),
expected_env=(config.get('Env') or []),
expected_entrypoint=config.get('Entrypoint'),
expected_etc_hosts=host_config['ExtraHosts'],
expected_exposed=expected_exposed,
groups=host_config.get('GroupAdd'),
ipc_mode=host_config.get("IpcMode"),
labels=config.get('Labels'),
expected_links=host_config.get('Links'),
mac_address=network.get('MacAddress'),
memory_swappiness=host_config.get('MemorySwappiness'),
network_mode=host_config.get('NetworkMode'),
userns_mode=host_config.get('UsernsMode'),
oom_killer=host_config.get('OomKillDisable'),
oom_score_adj=host_config.get('OomScoreAdj'),
pid_mode=host_config.get('PidMode'),
privileged=host_config.get('Privileged'),
expected_ports=host_config.get('PortBindings'),
read_only=host_config.get('ReadonlyRootfs'),
restart_policy=restart_policy.get('Name'),
runtime=host_config.get('Runtime'),
shm_size=host_config.get('ShmSize'),
security_opts=host_config.get("SecurityOpt"),
stop_signal=config.get("StopSignal"),
tmpfs=host_config.get('Tmpfs'),
tty=config.get('Tty'),
expected_ulimits=host_config.get('Ulimits'),
expected_sysctls=host_config.get('Sysctls'),
uts=host_config.get('UTSMode'),
expected_volumes=config.get('Volumes'),
expected_binds=host_config.get('Binds'),
volume_driver=host_config.get('VolumeDriver'),
volumes_from=host_config.get('VolumesFrom'),
working_dir=config.get('WorkingDir'),
publish_all_ports=host_config.get('PublishAllPorts'),
expected_healthcheck=config.get('Healthcheck'),
disable_healthcheck=(not config.get('Healthcheck') or config.get('Healthcheck').get('Test') == ['NONE']),
device_read_bps=host_config.get('BlkioDeviceReadBps'),
device_write_bps=host_config.get('BlkioDeviceWriteBps'),
device_read_iops=host_config.get('BlkioDeviceReadIOps'),
device_write_iops=host_config.get('BlkioDeviceWriteIOps'),
pids_limit=host_config.get('PidsLimit'),
)
# Options which don't make sense without their accompanying option
if self.parameters.restart_policy:
config_mapping['restart_retries'] = restart_policy.get('MaximumRetryCount')
if self.parameters.log_driver:
config_mapping['log_driver'] = log_config.get('Type')
config_mapping['log_options'] = log_config.get('Config')
if self.parameters.client.option_minimal_versions['auto_remove']['supported']:
# auto_remove is only supported in Docker SDK for Python >= 2.0.0; unfortunately
# it has a default value, that's why we have to jump through the hoops here
config_mapping['auto_remove'] = host_config.get('AutoRemove')
if self.parameters.client.option_minimal_versions['stop_timeout']['supported']:
# stop_timeout is only supported in Docker SDK for Python >= 2.1. Note that
# stop_timeout has a hybrid role, in that it used to be something only used
# for stopping containers, and is now also used as a container property.
# That's why it needs special handling here.
config_mapping['stop_timeout'] = config.get('StopTimeout')
if self.parameters.client.docker_api_version < LooseVersion('1.22'):
# For docker API < 1.22, update_container() is not supported. Thus
# we need to handle all limits which are usually handled by
# update_container() as configuration changes which require a container
# restart.
config_mapping.update(dict(
blkio_weight=host_config.get('BlkioWeight'),
cpu_period=host_config.get('CpuPeriod'),
cpu_quota=host_config.get('CpuQuota'),
cpu_shares=host_config.get('CpuShares'),
cpuset_cpus=host_config.get('CpusetCpus'),
cpuset_mems=host_config.get('CpusetMems'),
kernel_memory=host_config.get("KernelMemory"),
memory=host_config.get('Memory'),
memory_reservation=host_config.get('MemoryReservation'),
memory_swap=host_config.get('MemorySwap'),
))
differences = DifferenceTracker()
for key, value in config_mapping.items():
minimal_version = self.parameters.client.option_minimal_versions.get(key, {})
if not minimal_version.get('supported', True):
continue
compare = self.parameters.client.comparisons[self.parameters_map.get(key, key)]
self.log('check differences %s %s vs %s (%s)' % (key, getattr(self.parameters, key), str(value), compare))
if getattr(self.parameters, key, None) is not None:
match = self._compare(getattr(self.parameters, key), value, compare)
if not match:
# no match. record the differences
p = getattr(self.parameters, key)
c = value
if compare['type'] == 'set':
# Since the order does not matter, sort so that the diff output is better.
if p is not None:
p = sorted(p)
if c is not None:
c = sorted(c)
elif compare['type'] == 'set(dict)':
# Since the order does not matter, sort so that the diff output is better.
# We sort the list of dictionaries by using the sorted items of a dict as its key.
if p is not None:
p = sorted(p, key=lambda x: sorted(x.items()))
if c is not None:
c = sorted(c, key=lambda x: sorted(x.items()))
differences.add(key, parameter=p, active=c)
has_differences = not differences.empty
return has_differences, differences
def has_different_resource_limits(self):
'''
Diff parameters and container resource limits
'''
if not self.container.get('HostConfig'):
self.fail("limits_differ_from_container: Error parsing container properties. HostConfig missing.")
if self.parameters.client.docker_api_version < LooseVersion('1.22'):
# update_container() call not supported
return False, []
host_config = self.container['HostConfig']
config_mapping = dict(
blkio_weight=host_config.get('BlkioWeight'),
cpu_period=host_config.get('CpuPeriod'),
cpu_quota=host_config.get('CpuQuota'),
cpu_shares=host_config.get('CpuShares'),
cpuset_cpus=host_config.get('CpusetCpus'),
cpuset_mems=host_config.get('CpusetMems'),
kernel_memory=host_config.get("KernelMemory"),
memory=host_config.get('Memory'),
memory_reservation=host_config.get('MemoryReservation'),
memory_swap=host_config.get('MemorySwap'),
)
differences = DifferenceTracker()
for key, value in config_mapping.items():
if getattr(self.parameters, key, None):
compare = self.parameters.client.comparisons[self.parameters_map.get(key, key)]
match = self._compare(getattr(self.parameters, key), value, compare)
if not match:
# no match. record the differences
differences.add(key, parameter=getattr(self.parameters, key), active=value)
different = not differences.empty
return different, differences
def has_network_differences(self):
'''
Check if the container is connected to requested networks with expected options: links, aliases, ipv4, ipv6
'''
different = False
differences = []
if not self.parameters.networks:
return different, differences
if not self.container.get('NetworkSettings'):
self.fail("has_missing_networks: Error parsing container properties. NetworkSettings missing.")
connected_networks = self.container['NetworkSettings']['Networks']
for network in self.parameters.networks:
if connected_networks.get(network['name'], None) is None:
different = True
differences.append(dict(
parameter=network,
container=None
))
else:
diff = False
if network.get('ipv4_address') and network['ipv4_address'] != connected_networks[network['name']].get('IPAddress'):
diff = True
if network.get('ipv6_address') and network['ipv6_address'] != connected_networks[network['name']].get('GlobalIPv6Address'):
diff = True
if network.get('aliases'):
if not compare_generic(network['aliases'], connected_networks[network['name']].get('Aliases'), 'allow_more_present', 'set'):
diff = True
if network.get('links'):
expected_links = []
for link, alias in network['links']:
expected_links.append("%s:%s" % (link, alias))
if not compare_generic(expected_links, connected_networks[network['name']].get('Links'), 'allow_more_present', 'set'):
diff = True
if diff:
different = True
differences.append(dict(
parameter=network,
container=dict(
name=network['name'],
ipv4_address=connected_networks[network['name']].get('IPAddress'),
ipv6_address=connected_networks[network['name']].get('GlobalIPv6Address'),
aliases=connected_networks[network['name']].get('Aliases'),
links=connected_networks[network['name']].get('Links')
)
))
return different, differences
def has_extra_networks(self):
'''
Check if the container is connected to non-requested networks
'''
extra_networks = []
extra = False
if not self.container.get('NetworkSettings'):
self.fail("has_extra_networks: Error parsing container properties. NetworkSettings missing.")
connected_networks = self.container['NetworkSettings'].get('Networks')
if connected_networks:
for network, network_config in connected_networks.items():
keep = False
if self.parameters.networks:
for expected_network in self.parameters.networks:
if expected_network['name'] == network:
keep = True
if not keep:
extra = True
extra_networks.append(dict(name=network, id=network_config['NetworkID']))
return extra, extra_networks
def _get_expected_devices(self):
if not self.parameters.devices:
return None
expected_devices = []
for device in self.parameters.devices:
parts = device.split(':')
if len(parts) == 1:
expected_devices.append(
dict(
CgroupPermissions='rwm',
PathInContainer=parts[0],
PathOnHost=parts[0]
))
elif len(parts) == 2:
parts = device.split(':')
expected_devices.append(
dict(
CgroupPermissions='rwm',
PathInContainer=parts[1],
PathOnHost=parts[0]
)
)
else:
expected_devices.append(
dict(
CgroupPermissions=parts[2],
PathInContainer=parts[1],
PathOnHost=parts[0]
))
return expected_devices
def _get_expected_entrypoint(self):
if not self.parameters.entrypoint:
return None
return shlex.split(self.parameters.entrypoint)
def _get_expected_ports(self):
if not self.parameters.published_ports:
return None
expected_bound_ports = {}
for container_port, config in self.parameters.published_ports.items():
if isinstance(container_port, int):
container_port = "%s/tcp" % container_port
if len(config) == 1:
if isinstance(config[0], int):
expected_bound_ports[container_port] = [{'HostIp': "0.0.0.0", 'HostPort': config[0]}]
else:
expected_bound_ports[container_port] = [{'HostIp': config[0], 'HostPort': ""}]
elif isinstance(config[0], tuple):
expected_bound_ports[container_port] = []
for host_ip, host_port in config:
expected_bound_ports[container_port].append({'HostIp': host_ip, 'HostPort': str(host_port)})
else:
expected_bound_ports[container_port] = [{'HostIp': config[0], 'HostPort': str(config[1])}]
return expected_bound_ports
def _get_expected_links(self):
if self.parameters.links is None:
return None
self.log('parameter links:')
self.log(self.parameters.links, pretty_print=True)
exp_links = []
for link, alias in self.parameters.links:
exp_links.append("/%s:%s/%s" % (link, ('/' + self.parameters.name), alias))
return exp_links
def _get_expected_binds(self, image):
self.log('_get_expected_binds')
image_vols = []
if image:
image_vols = self._get_image_binds(image[self.parameters.client.image_inspect_source].get('Volumes'))
param_vols = []
if self.parameters.volumes:
for vol in self.parameters.volumes:
host = None
if ':' in vol:
if len(vol.split(':')) == 3:
host, container, mode = vol.split(':')
if not is_volume_permissions(mode):
self.fail('Found invalid volumes mode: {0}'.format(mode))
if len(vol.split(':')) == 2:
parts = vol.split(':')
if not is_volume_permissions(parts[1]):
host, container, mode = vol.split(':') + ['rw']
if host:
param_vols.append("%s:%s:%s" % (host, container, mode))
result = list(set(image_vols + param_vols))
self.log("expected_binds:")
self.log(result, pretty_print=True)
return result
def _get_image_binds(self, volumes):
'''
Convert array of binds to array of strings with format host_path:container_path:mode
:param volumes: array of bind dicts
:return: array of strings
'''
results = []
if isinstance(volumes, dict):
results += self._get_bind_from_dict(volumes)
elif isinstance(volumes, list):
for vol in volumes:
results += self._get_bind_from_dict(vol)
return results
@staticmethod
def _get_bind_from_dict(volume_dict):
results = []
if volume_dict:
for host_path, config in volume_dict.items():
if isinstance(config, dict) and config.get('bind'):
container_path = config.get('bind')
mode = config.get('mode', 'rw')
results.append("%s:%s:%s" % (host_path, container_path, mode))
return results
def _get_expected_volumes(self, image):
self.log('_get_expected_volumes')
expected_vols = dict()
if image and image[self.parameters.client.image_inspect_source].get('Volumes'):
expected_vols.update(image[self.parameters.client.image_inspect_source].get('Volumes'))
if self.parameters.volumes:
for vol in self.parameters.volumes:
container = None
if ':' in vol:
if len(vol.split(':')) == 3:
host, container, mode = vol.split(':')
if not is_volume_permissions(mode):
self.fail('Found invalid volumes mode: {0}'.format(mode))
if len(vol.split(':')) == 2:
parts = vol.split(':')
if not is_volume_permissions(parts[1]):
host, container, mode = vol.split(':') + ['rw']
new_vol = dict()
if container:
new_vol[container] = dict()
else:
new_vol[vol] = dict()
expected_vols.update(new_vol)
if not expected_vols:
expected_vols = None
self.log("expected_volumes:")
self.log(expected_vols, pretty_print=True)
return expected_vols
def _get_expected_env(self, image):
self.log('_get_expected_env')
expected_env = dict()
if image and image[self.parameters.client.image_inspect_source].get('Env'):
for env_var in image[self.parameters.client.image_inspect_source]['Env']:
parts = env_var.split('=', 1)
expected_env[parts[0]] = parts[1]
if self.parameters.env:
expected_env.update(self.parameters.env)
param_env = []
for key, value in expected_env.items():
param_env.append("%s=%s" % (key, value))
return param_env
def _get_expected_exposed(self, image):
self.log('_get_expected_exposed')
image_ports = []
if image:
image_exposed_ports = image[self.parameters.client.image_inspect_source].get('ExposedPorts') or {}
image_ports = [self._normalize_port(p) for p in image_exposed_ports.keys()]
param_ports = []
if self.parameters.ports:
param_ports = [str(p[0]) + '/' + p[1] for p in self.parameters.ports]
result = list(set(image_ports + param_ports))
self.log(result, pretty_print=True)
return result
def _get_expected_ulimits(self, config_ulimits):
self.log('_get_expected_ulimits')
if config_ulimits is None:
return None
results = []
for limit in config_ulimits:
results.append(dict(
Name=limit.name,
Soft=limit.soft,
Hard=limit.hard
))
return results
def _get_expected_sysctls(self, config_sysctls):
self.log('_get_expected_sysctls')
if config_sysctls is None:
return None
result = dict()
for key, value in config_sysctls.items():
result[key] = str(value)
return result
def _get_expected_cmd(self):
self.log('_get_expected_cmd')
if not self.parameters.command:
return None
return shlex.split(self.parameters.command)
def _convert_simple_dict_to_list(self, param_name, join_with=':'):
if getattr(self.parameters, param_name, None) is None:
return None
results = []
for key, value in getattr(self.parameters, param_name).items():
results.append("%s%s%s" % (key, join_with, value))
return results
def _normalize_port(self, port):
if '/' not in port:
return port + '/tcp'
return port
def _get_expected_healthcheck(self):
self.log('_get_expected_healthcheck')
expected_healthcheck = dict()
if self.parameters.healthcheck:
expected_healthcheck.update([(k.title().replace("_", ""), v)
for k, v in self.parameters.healthcheck.items()])
return expected_healthcheck
class ContainerManager(DockerBaseClass):
'''
Perform container management tasks
'''
def __init__(self, client):
super(ContainerManager, self).__init__()
if client.module.params.get('log_options') and not client.module.params.get('log_driver'):
client.module.warn('log_options is ignored when log_driver is not specified')
if client.module.params.get('healthcheck') and not client.module.params.get('healthcheck').get('test'):
client.module.warn('healthcheck is ignored when test is not specified')
if client.module.params.get('restart_retries') is not None and not client.module.params.get('restart_policy'):
client.module.warn('restart_retries is ignored when restart_policy is not specified')
self.client = client
self.parameters = TaskParameters(client)
self.check_mode = self.client.check_mode
self.results = {'changed': False, 'actions': []}
self.diff = {}
self.diff_tracker = DifferenceTracker()
self.facts = {}
state = self.parameters.state
if state in ('stopped', 'started', 'present'):
self.present(state)
elif state == 'absent':
self.absent()
if not self.check_mode and not self.parameters.debug:
self.results.pop('actions')
if self.client.module._diff or self.parameters.debug:
self.diff['before'], self.diff['after'] = self.diff_tracker.get_before_after()
self.results['diff'] = self.diff
if self.facts:
self.results['ansible_facts'] = {'docker_container': self.facts}
self.results['container'] = self.facts
def present(self, state):
container = self._get_container(self.parameters.name)
was_running = container.running
was_paused = container.paused
container_created = False
# If the image parameter was passed then we need to deal with the image
# version comparison. Otherwise we handle this depending on whether
# the container already runs or not; in the former case, in case the
# container needs to be restarted, we use the existing container's
# image ID.
image = self._get_image()
self.log(image, pretty_print=True)
if not container.exists:
# New container
self.log('No container found')
if not self.parameters.image:
self.fail('Cannot create container when image is not specified!')
self.diff_tracker.add('exists', parameter=True, active=False)
new_container = self.container_create(self.parameters.image, self.parameters.create_parameters)
if new_container:
container = new_container
container_created = True
else:
# Existing container
different, differences = container.has_different_configuration(image)
image_different = False
if self.parameters.comparisons['image']['comparison'] == 'strict':
image_different = self._image_is_different(image, container)
if image_different or different or self.parameters.recreate:
self.diff_tracker.merge(differences)
self.diff['differences'] = differences.get_legacy_docker_container_diffs()
if image_different:
self.diff['image_different'] = True
self.log("differences")
self.log(differences.get_legacy_docker_container_diffs(), pretty_print=True)
image_to_use = self.parameters.image
if not image_to_use and container and container.Image:
image_to_use = container.Image
if not image_to_use:
self.fail('Cannot recreate container when image is not specified or cannot be extracted from current container!')
if container.running:
self.container_stop(container.Id)
self.container_remove(container.Id)
new_container = self.container_create(image_to_use, self.parameters.create_parameters)
if new_container:
container = new_container
container_created = True
if container and container.exists:
container = self.update_limits(container)
container = self.update_networks(container, container_created)
if state == 'started' and not container.running:
self.diff_tracker.add('running', parameter=True, active=was_running)
container = self.container_start(container.Id)
elif state == 'started' and self.parameters.restart:
self.diff_tracker.add('running', parameter=True, active=was_running)
self.diff_tracker.add('restarted', parameter=True, active=False)
container = self.container_restart(container.Id)
elif state == 'stopped' and container.running:
self.diff_tracker.add('running', parameter=False, active=was_running)
self.container_stop(container.Id)
container = self._get_container(container.Id)
if state == 'started' and container.paused != self.parameters.paused:
self.diff_tracker.add('paused', parameter=self.parameters.paused, active=was_paused)
if not self.check_mode:
try:
if self.parameters.paused:
self.client.pause(container=container.Id)
else:
self.client.unpause(container=container.Id)
except Exception as exc:
self.fail("Error %s container %s: %s" % (
"pausing" if self.parameters.paused else "unpausing", container.Id, str(exc)
))
container = self._get_container(container.Id)
self.results['changed'] = True
self.results['actions'].append(dict(set_paused=self.parameters.paused))
self.facts = container.raw
def absent(self):
container = self._get_container(self.parameters.name)
if container.exists:
if container.running:
self.diff_tracker.add('running', parameter=False, active=True)
self.container_stop(container.Id)
self.diff_tracker.add('exists', parameter=False, active=True)
self.container_remove(container.Id)
def fail(self, msg, **kwargs):
self.client.fail(msg, **kwargs)
def _output_logs(self, msg):
self.client.module.log(msg=msg)
def _get_container(self, container):
'''
Expects container ID or Name. Returns a container object
'''
return Container(self.client.get_container(container), self.parameters)
def _get_image(self):
if not self.parameters.image:
self.log('No image specified')
return None
if is_image_name_id(self.parameters.image):
image = self.client.find_image_by_id(self.parameters.image)
else:
repository, tag = utils.parse_repository_tag(self.parameters.image)
if not tag:
tag = "latest"
image = self.client.find_image(repository, tag)
if not self.check_mode:
if not image or self.parameters.pull:
self.log("Pull the image.")
image, alreadyToLatest = self.client.pull_image(repository, tag)
if alreadyToLatest:
self.results['changed'] = False
else:
self.results['changed'] = True
self.results['actions'].append(dict(pulled_image="%s:%s" % (repository, tag)))
self.log("image")
self.log(image, pretty_print=True)
return image
def _image_is_different(self, image, container):
if image and image.get('Id'):
if container and container.Image:
if image.get('Id') != container.Image:
self.diff_tracker.add('image', parameter=image.get('Id'), active=container.Image)
return True
return False
def update_limits(self, container):
limits_differ, different_limits = container.has_different_resource_limits()
if limits_differ:
self.log("limit differences:")
self.log(different_limits.get_legacy_docker_container_diffs(), pretty_print=True)
self.diff_tracker.merge(different_limits)
if limits_differ and not self.check_mode:
self.container_update(container.Id, self.parameters.update_parameters)
return self._get_container(container.Id)
return container
def update_networks(self, container, container_created):
updated_container = container
if self.parameters.comparisons['networks']['comparison'] != 'ignore' or container_created:
has_network_differences, network_differences = container.has_network_differences()
if has_network_differences:
if self.diff.get('differences'):
self.diff['differences'].append(dict(network_differences=network_differences))
else:
self.diff['differences'] = [dict(network_differences=network_differences)]
for netdiff in network_differences:
self.diff_tracker.add(
'network.{0}'.format(netdiff['parameter']['name']),
parameter=netdiff['parameter'],
active=netdiff['container']
)
self.results['changed'] = True
updated_container = self._add_networks(container, network_differences)
if (self.parameters.comparisons['networks']['comparison'] == 'strict' and self.parameters.networks is not None) or self.parameters.purge_networks:
has_extra_networks, extra_networks = container.has_extra_networks()
if has_extra_networks:
if self.diff.get('differences'):
self.diff['differences'].append(dict(purge_networks=extra_networks))
else:
self.diff['differences'] = [dict(purge_networks=extra_networks)]
for extra_network in extra_networks:
self.diff_tracker.add(
'network.{0}'.format(extra_network['name']),
active=extra_network
)
self.results['changed'] = True
updated_container = self._purge_networks(container, extra_networks)
return updated_container
def _add_networks(self, container, differences):
for diff in differences:
# remove the container from the network, if connected
if diff.get('container'):
self.results['actions'].append(dict(removed_from_network=diff['parameter']['name']))
if not self.check_mode:
try:
self.client.disconnect_container_from_network(container.Id, diff['parameter']['id'])
except Exception as exc:
self.fail("Error disconnecting container from network %s - %s" % (diff['parameter']['name'],
str(exc)))
# connect to the network
params = dict()
for para in ('ipv4_address', 'ipv6_address', 'links', 'aliases'):
if diff['parameter'].get(para):
params[para] = diff['parameter'][para]
self.results['actions'].append(dict(added_to_network=diff['parameter']['name'], network_parameters=params))
if not self.check_mode:
try:
self.log("Connecting container to network %s" % diff['parameter']['id'])
self.log(params, pretty_print=True)
self.client.connect_container_to_network(container.Id, diff['parameter']['id'], **params)
except Exception as exc:
self.fail("Error connecting container to network %s - %s" % (diff['parameter']['name'], str(exc)))
return self._get_container(container.Id)
def _purge_networks(self, container, networks):
for network in networks:
self.results['actions'].append(dict(removed_from_network=network['name']))
if not self.check_mode:
try:
self.client.disconnect_container_from_network(container.Id, network['name'])
except Exception as exc:
self.fail("Error disconnecting container from network %s - %s" % (network['name'],
str(exc)))
return self._get_container(container.Id)
def container_create(self, image, create_parameters):
self.log("create container")
self.log("image: %s parameters:" % image)
self.log(create_parameters, pretty_print=True)
self.results['actions'].append(dict(created="Created container", create_parameters=create_parameters))
self.results['changed'] = True
new_container = None
if not self.check_mode:
try:
new_container = self.client.create_container(image, **create_parameters)
self.client.report_warnings(new_container)
except Exception as exc:
self.fail("Error creating container: %s" % str(exc))
return self._get_container(new_container['Id'])
return new_container
def container_start(self, container_id):
self.log("start container %s" % (container_id))
self.results['actions'].append(dict(started=container_id))
self.results['changed'] = True
if not self.check_mode:
try:
self.client.start(container=container_id)
except Exception as exc:
self.fail("Error starting container %s: %s" % (container_id, str(exc)))
if not self.parameters.detach:
if self.client.docker_py_version >= LooseVersion('3.0'):
status = self.client.wait(container_id)['StatusCode']
else:
status = self.client.wait(container_id)
if self.parameters.auto_remove:
output = "Cannot retrieve result as auto_remove is enabled"
if self.parameters.output_logs:
self.client.module.warn('Cannot output_logs if auto_remove is enabled!')
else:
config = self.client.inspect_container(container_id)
logging_driver = config['HostConfig']['LogConfig']['Type']
if logging_driver == 'json-file' or logging_driver == 'journald':
output = self.client.logs(container_id, stdout=True, stderr=True, stream=False, timestamps=False)
if self.parameters.output_logs:
self._output_logs(msg=output)
else:
output = "Result logged using `%s` driver" % logging_driver
if status != 0:
self.fail(output, status=status)
if self.parameters.cleanup:
self.container_remove(container_id, force=True)
insp = self._get_container(container_id)
if insp.raw:
insp.raw['Output'] = output
else:
insp.raw = dict(Output=output)
return insp
return self._get_container(container_id)
def container_remove(self, container_id, link=False, force=False):
volume_state = (not self.parameters.keep_volumes)
self.log("remove container container:%s v:%s link:%s force%s" % (container_id, volume_state, link, force))
self.results['actions'].append(dict(removed=container_id, volume_state=volume_state, link=link, force=force))
self.results['changed'] = True
response = None
if not self.check_mode:
count = 0
while True:
try:
response = self.client.remove_container(container_id, v=volume_state, link=link, force=force)
except NotFound as dummy:
pass
except APIError as exc:
if 'Unpause the container before stopping or killing' in exc.explanation:
# New docker daemon versions do not allow containers to be removed
# if they are paused. Make sure we don't end up in an infinite loop.
if count == 3:
self.fail("Error removing container %s (tried to unpause three times): %s" % (container_id, str(exc)))
count += 1
# Unpause
try:
self.client.unpause(container=container_id)
except Exception as exc2:
self.fail("Error unpausing container %s for removal: %s" % (container_id, str(exc2)))
# Now try again
continue
if 'removal of container ' in exc.explanation and ' is already in progress' in exc.explanation:
pass
else:
self.fail("Error removing container %s: %s" % (container_id, str(exc)))
except Exception as exc:
self.fail("Error removing container %s: %s" % (container_id, str(exc)))
# We only loop when explicitly requested by 'continue'
break
return response
def container_update(self, container_id, update_parameters):
if update_parameters:
self.log("update container %s" % (container_id))
self.log(update_parameters, pretty_print=True)
self.results['actions'].append(dict(updated=container_id, update_parameters=update_parameters))
self.results['changed'] = True
if not self.check_mode and callable(getattr(self.client, 'update_container')):
try:
result = self.client.update_container(container_id, **update_parameters)
self.client.report_warnings(result)
except Exception as exc:
self.fail("Error updating container %s: %s" % (container_id, str(exc)))
return self._get_container(container_id)
def container_kill(self, container_id):
self.results['actions'].append(dict(killed=container_id, signal=self.parameters.kill_signal))
self.results['changed'] = True
response = None
if not self.check_mode:
try:
if self.parameters.kill_signal:
response = self.client.kill(container_id, signal=self.parameters.kill_signal)
else:
response = self.client.kill(container_id)
except Exception as exc:
self.fail("Error killing container %s: %s" % (container_id, exc))
return response
def container_restart(self, container_id):
self.results['actions'].append(dict(restarted=container_id, timeout=self.parameters.stop_timeout))
self.results['changed'] = True
if not self.check_mode:
try:
if self.parameters.stop_timeout:
response = self.client.restart(container_id, timeout=self.parameters.stop_timeout)
else:
response = self.client.restart(container_id)
except Exception as exc:
self.fail("Error restarting container %s: %s" % (container_id, str(exc)))
return self._get_container(container_id)
def container_stop(self, container_id):
if self.parameters.force_kill:
self.container_kill(container_id)
return
self.results['actions'].append(dict(stopped=container_id, timeout=self.parameters.stop_timeout))
self.results['changed'] = True
response = None
if not self.check_mode:
count = 0
while True:
try:
if self.parameters.stop_timeout:
response = self.client.stop(container_id, timeout=self.parameters.stop_timeout)
else:
response = self.client.stop(container_id)
except APIError as exc:
if 'Unpause the container before stopping or killing' in exc.explanation:
# New docker daemon versions do not allow containers to be removed
# if they are paused. Make sure we don't end up in an infinite loop.
if count == 3:
self.fail("Error removing container %s (tried to unpause three times): %s" % (container_id, str(exc)))
count += 1
# Unpause
try:
self.client.unpause(container=container_id)
except Exception as exc2:
self.fail("Error unpausing container %s for removal: %s" % (container_id, str(exc2)))
# Now try again
continue
self.fail("Error stopping container %s: %s" % (container_id, str(exc)))
except Exception as exc:
self.fail("Error stopping container %s: %s" % (container_id, str(exc)))
# We only loop when explicitly requested by 'continue'
break
return response
def detect_ipvX_address_usage(client):
'''
Helper function to detect whether any specified network uses ipv4_address or ipv6_address
'''
for network in client.module.params.get("networks") or []:
if network.get('ipv4_address') is not None or network.get('ipv6_address') is not None:
return True
return False
class AnsibleDockerClientContainer(AnsibleDockerClient):
# A list of module options which are not docker container properties
__NON_CONTAINER_PROPERTY_OPTIONS = tuple([
'env_file', 'force_kill', 'keep_volumes', 'ignore_image', 'name', 'pull', 'purge_networks',
'recreate', 'restart', 'state', 'trust_image_content', 'networks', 'cleanup', 'kill_signal',
'output_logs', 'paused'
] + list(DOCKER_COMMON_ARGS.keys()))
def _parse_comparisons(self):
comparisons = {}
comp_aliases = {}
# Put in defaults
explicit_types = dict(
command='list',
devices='set(dict)',
dns_search_domains='list',
dns_servers='list',
env='set',
entrypoint='list',
etc_hosts='set',
networks='set(dict)',
ulimits='set(dict)',
device_read_bps='set(dict)',
device_write_bps='set(dict)',
device_read_iops='set(dict)',
device_write_iops='set(dict)',
)
all_options = set() # this is for improving user feedback when a wrong option was specified for comparison
default_values = dict(
stop_timeout='ignore',
)
for option, data in self.module.argument_spec.items():
all_options.add(option)
for alias in data.get('aliases', []):
all_options.add(alias)
# Ignore options which aren't used as container properties
if option in self.__NON_CONTAINER_PROPERTY_OPTIONS and option != 'networks':
continue
# Determine option type
if option in explicit_types:
type = explicit_types[option]
elif data['type'] == 'list':
type = 'set'
elif data['type'] == 'dict':
type = 'dict'
else:
type = 'value'
# Determine comparison type
if option in default_values:
comparison = default_values[option]
elif type in ('list', 'value'):
comparison = 'strict'
else:
comparison = 'allow_more_present'
comparisons[option] = dict(type=type, comparison=comparison, name=option)
# Keep track of aliases
comp_aliases[option] = option
for alias in data.get('aliases', []):
comp_aliases[alias] = option
# Process legacy ignore options
if self.module.params['ignore_image']:
comparisons['image']['comparison'] = 'ignore'
if self.module.params['purge_networks']:
comparisons['networks']['comparison'] = 'strict'
# Process options
if self.module.params.get('comparisons'):
# If '*' appears in comparisons, process it first
if '*' in self.module.params['comparisons']:
value = self.module.params['comparisons']['*']
if value not in ('strict', 'ignore'):
self.fail("The wildcard can only be used with comparison modes 'strict' and 'ignore'!")
for option, v in comparisons.items():
if option == 'networks':
# `networks` is special: only update if
# some value is actually specified
if self.module.params['networks'] is None:
continue
v['comparison'] = value
# Now process all other comparisons.
comp_aliases_used = {}
for key, value in self.module.params['comparisons'].items():
if key == '*':
continue
# Find main key
key_main = comp_aliases.get(key)
if key_main is None:
if key_main in all_options:
self.fail("The module option '%s' cannot be specified in the comparisons dict, "
"since it does not correspond to container's state!" % key)
self.fail("Unknown module option '%s' in comparisons dict!" % key)
if key_main in comp_aliases_used:
self.fail("Both '%s' and '%s' (aliases of %s) are specified in comparisons dict!" % (key, comp_aliases_used[key_main], key_main))
comp_aliases_used[key_main] = key
# Check value and update accordingly
if value in ('strict', 'ignore'):
comparisons[key_main]['comparison'] = value
elif value == 'allow_more_present':
if comparisons[key_main]['type'] == 'value':
self.fail("Option '%s' is a value and not a set/list/dict, so its comparison cannot be %s" % (key, value))
comparisons[key_main]['comparison'] = value
else:
self.fail("Unknown comparison mode '%s'!" % value)
# Add implicit options
comparisons['publish_all_ports'] = dict(type='value', comparison='strict', name='published_ports')
comparisons['expected_ports'] = dict(type='dict', comparison=comparisons['published_ports']['comparison'], name='expected_ports')
comparisons['disable_healthcheck'] = dict(type='value',
comparison='ignore' if comparisons['healthcheck']['comparison'] == 'ignore' else 'strict',
name='disable_healthcheck')
# Check legacy values
if self.module.params['ignore_image'] and comparisons['image']['comparison'] != 'ignore':
self.module.warn('The ignore_image option has been overridden by the comparisons option!')
if self.module.params['purge_networks'] and comparisons['networks']['comparison'] != 'strict':
self.module.warn('The purge_networks option has been overridden by the comparisons option!')
self.comparisons = comparisons
def _get_additional_minimal_versions(self):
stop_timeout_supported = self.docker_api_version >= LooseVersion('1.25')
stop_timeout_needed_for_update = self.module.params.get("stop_timeout") is not None and self.module.params.get('state') != 'absent'
if stop_timeout_supported:
stop_timeout_supported = self.docker_py_version >= LooseVersion('2.1')
if stop_timeout_needed_for_update and not stop_timeout_supported:
# We warn (instead of fail) since in older versions, stop_timeout was not used
# to update the container's configuration, but only when stopping a container.
self.module.warn("Docker SDK for Python's version is %s. Minimum version required is 2.1 to update "
"the container's stop_timeout configuration. "
"If you use the 'docker-py' module, you have to switch to the 'docker' Python package." % (docker_version,))
else:
if stop_timeout_needed_for_update and not stop_timeout_supported:
# We warn (instead of fail) since in older versions, stop_timeout was not used
# to update the container's configuration, but only when stopping a container.
self.module.warn("Docker API version is %s. Minimum version required is 1.25 to set or "
"update the container's stop_timeout configuration." % (self.docker_api_version_str,))
self.option_minimal_versions['stop_timeout']['supported'] = stop_timeout_supported
def __init__(self, **kwargs):
option_minimal_versions = dict(
# internal options
log_config=dict(),
publish_all_ports=dict(),
ports=dict(),
volume_binds=dict(),
name=dict(),
# normal options
device_read_bps=dict(docker_py_version='1.9.0', docker_api_version='1.22'),
device_read_iops=dict(docker_py_version='1.9.0', docker_api_version='1.22'),
device_write_bps=dict(docker_py_version='1.9.0', docker_api_version='1.22'),
device_write_iops=dict(docker_py_version='1.9.0', docker_api_version='1.22'),
dns_opts=dict(docker_api_version='1.21', docker_py_version='1.10.0'),
ipc_mode=dict(docker_api_version='1.25'),
mac_address=dict(docker_api_version='1.25'),
oom_score_adj=dict(docker_api_version='1.22'),
shm_size=dict(docker_api_version='1.22'),
stop_signal=dict(docker_api_version='1.21'),
tmpfs=dict(docker_api_version='1.22'),
volume_driver=dict(docker_api_version='1.21'),
memory_reservation=dict(docker_api_version='1.21'),
kernel_memory=dict(docker_api_version='1.21'),
auto_remove=dict(docker_py_version='2.1.0', docker_api_version='1.25'),
healthcheck=dict(docker_py_version='2.0.0', docker_api_version='1.24'),
init=dict(docker_py_version='2.2.0', docker_api_version='1.25'),
runtime=dict(docker_py_version='2.4.0', docker_api_version='1.25'),
sysctls=dict(docker_py_version='1.10.0', docker_api_version='1.24'),
userns_mode=dict(docker_py_version='1.10.0', docker_api_version='1.23'),
uts=dict(docker_py_version='3.5.0', docker_api_version='1.25'),
pids_limit=dict(docker_py_version='1.10.0', docker_api_version='1.23'),
# specials
ipvX_address_supported=dict(docker_py_version='1.9.0', detect_usage=detect_ipvX_address_usage,
usage_msg='ipv4_address or ipv6_address in networks'),
stop_timeout=dict(), # see _get_additional_minimal_versions()
)
super(AnsibleDockerClientContainer, self).__init__(
option_minimal_versions=option_minimal_versions,
option_minimal_versions_ignore_params=self.__NON_CONTAINER_PROPERTY_OPTIONS,
**kwargs
)
self.image_inspect_source = 'Config'
if self.docker_api_version < LooseVersion('1.21'):
self.image_inspect_source = 'ContainerConfig'
self._get_additional_minimal_versions()
self._parse_comparisons()
def main():
argument_spec = dict(
auto_remove=dict(type='bool', default=False),
blkio_weight=dict(type='int'),
capabilities=dict(type='list', elements='str'),
cap_drop=dict(type='list', elements='str'),
cleanup=dict(type='bool', default=False),
command=dict(type='raw'),
comparisons=dict(type='dict'),
cpu_period=dict(type='int'),
cpu_quota=dict(type='int'),
cpuset_cpus=dict(type='str'),
cpuset_mems=dict(type='str'),
cpu_shares=dict(type='int'),
detach=dict(type='bool', default=True),
devices=dict(type='list', elements='str'),
device_read_bps=dict(type='list', elements='dict', options=dict(
path=dict(required=True, type='str'),
rate=dict(required=True, type='str'),
)),
device_write_bps=dict(type='list', elements='dict', options=dict(
path=dict(required=True, type='str'),
rate=dict(required=True, type='str'),
)),
device_read_iops=dict(type='list', elements='dict', options=dict(
path=dict(required=True, type='str'),
rate=dict(required=True, type='int'),
)),
device_write_iops=dict(type='list', elements='dict', options=dict(
path=dict(required=True, type='str'),
rate=dict(required=True, type='int'),
)),
dns_servers=dict(type='list', elements='str'),
dns_opts=dict(type='list', elements='str'),
dns_search_domains=dict(type='list', elements='str'),
domainname=dict(type='str'),
entrypoint=dict(type='list', elements='str'),
env=dict(type='dict'),
env_file=dict(type='path'),
etc_hosts=dict(type='dict'),
exposed_ports=dict(type='list', elements='str', aliases=['exposed', 'expose']),
force_kill=dict(type='bool', default=False, aliases=['forcekill']),
groups=dict(type='list', elements='str'),
healthcheck=dict(type='dict', options=dict(
test=dict(type='raw'),
interval=dict(type='str'),
timeout=dict(type='str'),
start_period=dict(type='str'),
retries=dict(type='int'),
)),
hostname=dict(type='str'),
ignore_image=dict(type='bool', default=False),
image=dict(type='str'),
init=dict(type='bool', default=False),
interactive=dict(type='bool', default=False),
ipc_mode=dict(type='str'),
keep_volumes=dict(type='bool', default=True),
kernel_memory=dict(type='str'),
kill_signal=dict(type='str'),
labels=dict(type='dict'),
links=dict(type='list', elements='str'),
log_driver=dict(type='str'),
log_options=dict(type='dict', aliases=['log_opt']),
mac_address=dict(type='str'),
memory=dict(type='str', default='0'),
memory_reservation=dict(type='str'),
memory_swap=dict(type='str'),
memory_swappiness=dict(type='int'),
name=dict(type='str', required=True),
network_mode=dict(type='str'),
networks=dict(type='list', elements='dict', options=dict(
name=dict(type='str', required=True),
ipv4_address=dict(type='str'),
ipv6_address=dict(type='str'),
aliases=dict(type='list', elements='str'),
links=dict(type='list', elements='str'),
)),
networks_cli_compatible=dict(type='bool'),
oom_killer=dict(type='bool'),
oom_score_adj=dict(type='int'),
output_logs=dict(type='bool', default=False),
paused=dict(type='bool', default=False),
pid_mode=dict(type='str'),
pids_limit=dict(type='int'),
privileged=dict(type='bool', default=False),
published_ports=dict(type='list', elements='str', aliases=['ports']),
pull=dict(type='bool', default=False),
purge_networks=dict(type='bool', default=False),
read_only=dict(type='bool', default=False),
recreate=dict(type='bool', default=False),
restart=dict(type='bool', default=False),
restart_policy=dict(type='str', choices=['no', 'on-failure', 'always', 'unless-stopped']),
restart_retries=dict(type='int'),
runtime=dict(type='str'),
security_opts=dict(type='list', elements='str'),
shm_size=dict(type='str'),
state=dict(type='str', default='started', choices=['absent', 'present', 'started', 'stopped']),
stop_signal=dict(type='str'),
stop_timeout=dict(type='int'),
sysctls=dict(type='dict'),
tmpfs=dict(type='list', elements='str'),
trust_image_content=dict(type='bool', default=False),
tty=dict(type='bool', default=False),
ulimits=dict(type='list', elements='str'),
user=dict(type='str'),
userns_mode=dict(type='str'),
uts=dict(type='str'),
volume_driver=dict(type='str'),
volumes=dict(type='list', elements='str'),
volumes_from=dict(type='list', elements='str'),
working_dir=dict(type='str'),
)
required_if = [
('state', 'present', ['image'])
]
client = AnsibleDockerClientContainer(
argument_spec=argument_spec,
required_if=required_if,
supports_check_mode=True,
min_docker_api_version='1.20',
)
if client.module.params['networks_cli_compatible'] is None and client.module.params['networks']:
client.module.deprecate(
'Please note that docker_container handles networks slightly different than docker CLI. '
'If you specify networks, the default network will still be attached as the first network. '
'(You can specify purge_networks to remove all networks not explicitly listed.) '
'This behavior will change in Ansible 2.12. You can change the behavior now by setting '
'the new `networks_cli_compatible` option to `yes`, and remove this warning by setting '
'it to `no`',
version='2.12'
)
try:
cm = ContainerManager(client)
client.module.exit_json(**sanitize_result(cm.results))
except DockerException as e:
client.fail('An unexpected docker error occurred: {0}'.format(e), exception=traceback.format_exc())
if __name__ == '__main__':
main()
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,721 |
VMware: vmware_guest throws vmdk already exists
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
<!--- Explain the problem briefly below -->
vmware_guest throws error that vmdk already exists although it does not. It is created during running the module but somehow fails.
pyvmomi-6.7.1.2018.12
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
vmware_guest
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
2.8.1
```
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```yaml
- name: Create new VM
vmware_guest:
hostname: "{{ vcenter_hostname }}"
esxi_hostname: "{{ esxi_host }}"
username: '{{domain_user}}'
password: "{{ domain_user_password }}"
validate_certs: False
datacenter: TM
name: "{{ vm_hostname }}"
folder: "{{ vm_destination }}"
state: poweredon
disk:
- size_gb: '{{ disk_size }}'
type: thin
autoselect_datastore: True
hardware:
memory_mb: "{{ memory }}"
num_cpus: "{{ cores }}"
num_cpu_cores_per_socket: "{{ cores }}"
networks:
- name: LAN
domain: "{{ domain }}"
dns_servers:
- "{{ dns1 }}"
- "{{ dns2 }}"
type: static
ip: "{{ ip }}"
netmask: 255.255.254.0
gateway: 192.168.1.5
customization:
autologon: True
hostname: "{{ vm_hostname }}"
domain: "{{ domain }}"
password: vagrant
domainadmin: "{{ domain_user }}"
domainadminpassword: "{{ domain_user_password }}"
joindomain: "{{ domain }}"
timezone: 105
runonce:
- powershell.exe -ExecutionPolicy Unrestricted -File C:\StartupScripts\ConfigureRemotingForAnsible.ps1 -ForceNewSSLCert -EnableCredSSP
- powershell.exe -ExecutionPolicy Unrestricted -File C:\StartupScripts\DisableFirewall.ps1
wait_for_customization: yes
template: "{{ vm_template }}"
wait_for_ip_address: yes
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
Should just create the VM.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```paste below
Failed to create a virtual machine : Cannot complete the operation because the file or folder [EL02] ********/********.vmdk already exists"
```
|
https://github.com/ansible/ansible/issues/58721
|
https://github.com/ansible/ansible/pull/58737
|
b6273e91cfbcf3f9c9ab849b6803c6a8a3aa7c3d
|
3a5d13b0d761bb5ac5a83d14daa37848e72ec857
| 2019-07-04T09:16:34Z |
python
| 2019-07-15T04:39:54Z |
lib/ansible/modules/cloud/vmware/vmware_guest.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# This module is also sponsored by E.T.A.I. (www.etai.fr)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: vmware_guest
short_description: Manages virtual machines in vCenter
description: >
This module can be used to create new virtual machines from templates or other virtual machines,
manage power state of virtual machine such as power on, power off, suspend, shutdown, reboot, restart etc.,
modify various virtual machine components like network, disk, customization etc.,
rename a virtual machine and remove a virtual machine with associated components.
version_added: '2.2'
author:
- Loic Blot (@nerzhul) <[email protected]>
- Philippe Dellaert (@pdellaert) <[email protected]>
- Abhijeet Kasurde (@Akasurde) <[email protected]>
requirements:
- python >= 2.6
- PyVmomi
notes:
- Please make sure that the user used for vmware_guest has the correct level of privileges.
- For example, following is the list of minimum privileges required by users to create virtual machines.
- " DataStore > Allocate Space"
- " Virtual Machine > Configuration > Add New Disk"
- " Virtual Machine > Configuration > Add or Remove Device"
- " Virtual Machine > Inventory > Create New"
- " Network > Assign Network"
- " Resource > Assign Virtual Machine to Resource Pool"
- "Module may require additional privileges as well, which may be required for gathering facts - e.g. ESXi configurations."
- Tested on vSphere 5.5, 6.0, 6.5 and 6.7
- Use SCSI disks instead of IDE when you want to expand online disks by specifing a SCSI controller
- "For additional information please visit Ansible VMware community wiki - U(https://github.com/ansible/community/wiki/VMware)."
options:
state:
description:
- Specify the state the virtual machine should be in.
- 'If C(state) is set to C(present) and virtual machine exists, ensure the virtual machine
configurations conforms to task arguments.'
- 'If C(state) is set to C(absent) and virtual machine exists, then the specified virtual machine
is removed with its associated components.'
- 'If C(state) is set to one of the following C(poweredon), C(poweredoff), C(present), C(restarted), C(suspended)
and virtual machine does not exists, then virtual machine is deployed with given parameters.'
- 'If C(state) is set to C(poweredon) and virtual machine exists with powerstate other than powered on,
then the specified virtual machine is powered on.'
- 'If C(state) is set to C(poweredoff) and virtual machine exists with powerstate other than powered off,
then the specified virtual machine is powered off.'
- 'If C(state) is set to C(restarted) and virtual machine exists, then the virtual machine is restarted.'
- 'If C(state) is set to C(suspended) and virtual machine exists, then the virtual machine is set to suspended mode.'
- 'If C(state) is set to C(shutdownguest) and virtual machine exists, then the virtual machine is shutdown.'
- 'If C(state) is set to C(rebootguest) and virtual machine exists, then the virtual machine is rebooted.'
default: present
choices: [ present, absent, poweredon, poweredoff, restarted, suspended, shutdownguest, rebootguest ]
name:
description:
- Name of the virtual machine to work with.
- Virtual machine names in vCenter are not necessarily unique, which may be problematic, see C(name_match).
- 'If multiple virtual machines with same name exists, then C(folder) is required parameter to
identify uniqueness of the virtual machine.'
- This parameter is required, if C(state) is set to C(poweredon), C(poweredoff), C(present), C(restarted), C(suspended)
and virtual machine does not exists.
- This parameter is case sensitive.
required: yes
name_match:
description:
- If multiple virtual machines matching the name, use the first or last found.
default: 'first'
choices: [ first, last ]
uuid:
description:
- UUID of the virtual machine to manage if known, this is VMware's unique identifier.
- This is required if C(name) is not supplied.
- If virtual machine does not exists, then this parameter is ignored.
- Please note that a supplied UUID will be ignored on virtual machine creation, as VMware creates the UUID internally.
use_instance_uuid:
description:
- Whether to use the VMware instance UUID rather than the BIOS UUID.
default: no
type: bool
version_added: '2.8'
template:
description:
- Template or existing virtual machine used to create new virtual machine.
- If this value is not set, virtual machine is created without using a template.
- If the virtual machine already exists, this parameter will be ignored.
- This parameter is case sensitive.
- You can also specify template or VM UUID for identifying source. version_added 2.8. Use C(hw_product_uuid) from M(vmware_guest_facts) as UUID value.
- From version 2.8 onwards, absolute path to virtual machine or template can be used.
aliases: [ 'template_src' ]
is_template:
description:
- Flag the instance as a template.
- This will mark the given virtual machine as template.
default: 'no'
type: bool
version_added: '2.3'
folder:
description:
- Destination folder, absolute path to find an existing guest or create the new guest.
- The folder should include the datacenter. ESX's datacenter is ha-datacenter.
- This parameter is case sensitive.
- This parameter is required, while deploying new virtual machine. version_added 2.5.
- 'If multiple machines are found with same name, this parameter is used to identify
uniqueness of the virtual machine. version_added 2.5'
- 'Examples:'
- ' folder: /ha-datacenter/vm'
- ' folder: ha-datacenter/vm'
- ' folder: /datacenter1/vm'
- ' folder: datacenter1/vm'
- ' folder: /datacenter1/vm/folder1'
- ' folder: datacenter1/vm/folder1'
- ' folder: /folder1/datacenter1/vm'
- ' folder: folder1/datacenter1/vm'
- ' folder: /folder1/datacenter1/vm/folder2'
hardware:
description:
- Manage virtual machine's hardware attributes.
- All parameters case sensitive.
- 'Valid attributes are:'
- ' - C(hotadd_cpu) (boolean): Allow virtual CPUs to be added while the virtual machine is running.'
- ' - C(hotremove_cpu) (boolean): Allow virtual CPUs to be removed while the virtual machine is running.
version_added: 2.5'
- ' - C(hotadd_memory) (boolean): Allow memory to be added while the virtual machine is running.'
- ' - C(memory_mb) (integer): Amount of memory in MB.'
- ' - C(nested_virt) (bool): Enable nested virtualization. version_added: 2.5'
- ' - C(num_cpus) (integer): Number of CPUs.'
- ' - C(num_cpu_cores_per_socket) (integer): Number of Cores Per Socket.'
- " C(num_cpus) must be a multiple of C(num_cpu_cores_per_socket).
For example to create a VM with 2 sockets of 4 cores, specify C(num_cpus): 8 and C(num_cpu_cores_per_socket): 4"
- ' - C(scsi) (string): Valid values are C(buslogic), C(lsilogic), C(lsilogicsas) and C(paravirtual) (default).'
- " - C(memory_reservation_lock) (boolean): If set true, memory resource reservation for the virtual machine
will always be equal to the virtual machine's memory size. version_added: 2.5"
- ' - C(max_connections) (integer): Maximum number of active remote display connections for the virtual machines.
version_added: 2.5.'
- ' - C(mem_limit) (integer): The memory utilization of a virtual machine will not exceed this limit. Unit is MB.
version_added: 2.5'
- ' - C(mem_reservation) (integer): The amount of memory resource that is guaranteed available to the virtual
machine. Unit is MB. C(memory_reservation) is alias to this. version_added: 2.5'
- ' - C(cpu_limit) (integer): The CPU utilization of a virtual machine will not exceed this limit. Unit is MHz.
version_added: 2.5'
- ' - C(cpu_reservation) (integer): The amount of CPU resource that is guaranteed available to the virtual machine.
Unit is MHz. version_added: 2.5'
- ' - C(version) (integer): The Virtual machine hardware versions. Default is 10 (ESXi 5.5 and onwards).
Please check VMware documentation for correct virtual machine hardware version.
Incorrect hardware version may lead to failure in deployment. If hardware version is already equal to the given
version then no action is taken. version_added: 2.6'
- ' - C(boot_firmware) (string): Choose which firmware should be used to boot the virtual machine.
Allowed values are "bios" and "efi". version_added: 2.7'
- ' - C(virt_based_security) (bool): Enable Virtualization Based Security feature for Windows 10.
(Support from Virtual machine hardware version 14, Guest OS Windows 10 64 bit, Windows Server 2016)'
guest_id:
description:
- Set the guest ID.
- This parameter is case sensitive.
- 'Examples:'
- " virtual machine with RHEL7 64 bit, will be 'rhel7_64Guest'"
- " virtual machine with CensOS 64 bit, will be 'centos64Guest'"
- " virtual machine with Ubuntu 64 bit, will be 'ubuntu64Guest'"
- This field is required when creating a virtual machine, not required when creating from the template.
- >
Valid values are referenced here:
U(http://pubs.vmware.com/vsphere-6-5/topic/com.vmware.wssdk.apiref.doc/vim.vm.GuestOsDescriptor.GuestOsIdentifier.html)
version_added: '2.3'
disk:
description:
- A list of disks to add.
- This parameter is case sensitive.
- Shrinking disks is not supported.
- Removing existing disks of the virtual machine is not supported.
- 'Valid attributes are:'
- ' - C(size_[tb,gb,mb,kb]) (integer): Disk storage size in specified unit.'
- ' - C(type) (string): Valid values are:'
- ' - C(thin) thin disk'
- ' - C(eagerzeroedthick) eagerzeroedthick disk, added in version 2.5'
- ' Default: C(None) thick disk, no eagerzero.'
- ' - C(datastore) (string): The name of datastore which will be used for the disk. If C(autoselect_datastore) is set to True,
then will select the less used datastore whose name contains this "disk.datastore" string.'
- ' - C(filename) (string): Existing disk image to be used. Filename must be already exists on the datastore.'
- ' Specify filename string in C([datastore_name] path/to/file.vmdk) format. Added in version 2.8.'
- ' - C(autoselect_datastore) (bool): select the less used datastore. "disk.datastore" and "disk.autoselect_datastore"
will not be used if C(datastore) is specified outside this C(disk) configuration.'
- ' - C(disk_mode) (string): Type of disk mode. Added in version 2.6'
- ' - Available options are :'
- ' - C(persistent): Changes are immediately and permanently written to the virtual disk. This is default.'
- ' - C(independent_persistent): Same as persistent, but not affected by snapshots.'
- ' - C(independent_nonpersistent): Changes to virtual disk are made to a redo log and discarded at power off, but not affected by snapshots.'
cdrom:
description:
- A CD-ROM configuration for the virtual machine.
- 'Valid attributes are:'
- ' - C(type) (string): The type of CD-ROM, valid options are C(none), C(client) or C(iso). With C(none) the CD-ROM will be disconnected but present.'
- ' - C(iso_path) (string): The datastore path to the ISO file to use, in the form of C([datastore1] path/to/file.iso). Required if type is set C(iso).'
version_added: '2.5'
resource_pool:
description:
- Use the given resource pool for virtual machine operation.
- This parameter is case sensitive.
- Resource pool should be child of the selected host parent.
version_added: '2.3'
wait_for_ip_address:
description:
- Wait until vCenter detects an IP address for the virtual machine.
- This requires vmware-tools (vmtoolsd) to properly work after creation.
- "vmware-tools needs to be installed on the given virtual machine in order to work with this parameter."
default: 'no'
type: bool
wait_for_customization:
description:
- Wait until vCenter detects all guest customizations as successfully completed.
- When enabled, the VM will automatically be powered on.
default: 'no'
type: bool
version_added: '2.8'
state_change_timeout:
description:
- If the C(state) is set to C(shutdownguest), by default the module will return immediately after sending the shutdown signal.
- If this argument is set to a positive integer, the module will instead wait for the virtual machine to reach the poweredoff state.
- The value sets a timeout in seconds for the module to wait for the state change.
default: 0
version_added: '2.6'
snapshot_src:
description:
- Name of the existing snapshot to use to create a clone of a virtual machine.
- This parameter is case sensitive.
- While creating linked clone using C(linked_clone) parameter, this parameter is required.
version_added: '2.4'
linked_clone:
description:
- Whether to create a linked clone from the snapshot specified.
- If specified, then C(snapshot_src) is required parameter.
default: 'no'
type: bool
version_added: '2.4'
force:
description:
- Ignore warnings and complete the actions.
- This parameter is useful while removing virtual machine which is powered on state.
- 'This module reflects the VMware vCenter API and UI workflow, as such, in some cases the `force` flag will
be mandatory to perform the action to ensure you are certain the action has to be taken, no matter what the consequence.
This is specifically the case for removing a powered on the virtual machine when C(state) is set to C(absent).'
default: 'no'
type: bool
datacenter:
description:
- Destination datacenter for the deploy operation.
- This parameter is case sensitive.
default: ha-datacenter
cluster:
description:
- The cluster name where the virtual machine will run.
- This is a required parameter, if C(esxi_hostname) is not set.
- C(esxi_hostname) and C(cluster) are mutually exclusive parameters.
- This parameter is case sensitive.
version_added: '2.3'
esxi_hostname:
description:
- The ESXi hostname where the virtual machine will run.
- This is a required parameter, if C(cluster) is not set.
- C(esxi_hostname) and C(cluster) are mutually exclusive parameters.
- This parameter is case sensitive.
annotation:
description:
- A note or annotation to include in the virtual machine.
version_added: '2.3'
customvalues:
description:
- Define a list of custom values to set on virtual machine.
- A custom value object takes two fields C(key) and C(value).
- Incorrect key and values will be ignored.
version_added: '2.3'
networks:
description:
- A list of networks (in the order of the NICs).
- Removing NICs is not allowed, while reconfiguring the virtual machine.
- All parameters and VMware object names are case sensetive.
- 'One of the below parameters is required per entry:'
- ' - C(name) (string): Name of the portgroup or distributed virtual portgroup for this interface.
When specifying distributed virtual portgroup make sure given C(esxi_hostname) or C(cluster) is associated with it.'
- ' - C(vlan) (integer): VLAN number for this interface.'
- 'Optional parameters per entry (used for virtual hardware):'
- ' - C(device_type) (string): Virtual network device (one of C(e1000), C(e1000e), C(pcnet32), C(vmxnet2), C(vmxnet3) (default), C(sriov)).'
- ' - C(mac) (string): Customize MAC address.'
- ' - C(dvswitch_name) (string): Name of the distributed vSwitch.
This value is required if multiple distributed portgroups exists with the same name. version_added 2.7'
- ' - C(start_connected) (bool): Indicates that virtual network adapter starts with associated virtual machine powers on. version_added: 2.5'
- 'Optional parameters per entry (used for OS customization):'
- ' - C(type) (string): Type of IP assignment (either C(dhcp) or C(static)). C(dhcp) is default.'
- ' - C(ip) (string): Static IP address (implies C(type: static)).'
- ' - C(netmask) (string): Static netmask required for C(ip).'
- ' - C(gateway) (string): Static gateway.'
- ' - C(dns_servers) (string): DNS servers for this network interface (Windows).'
- ' - C(domain) (string): Domain name for this network interface (Windows).'
- ' - C(wake_on_lan) (bool): Indicates if wake-on-LAN is enabled on this virtual network adapter. version_added: 2.5'
- ' - C(allow_guest_control) (bool): Enables guest control over whether the connectable device is connected. version_added: 2.5'
version_added: '2.3'
customization:
description:
- Parameters for OS customization when cloning from the template or the virtual machine, or apply to the existing virtual machine directly.
- Not all operating systems are supported for customization with respective vCenter version,
please check VMware documentation for respective OS customization.
- For supported customization operating system matrix, (see U(http://partnerweb.vmware.com/programs/guestOS/guest-os-customization-matrix.pdf))
- All parameters and VMware object names are case sensitive.
- Linux based OSes requires Perl package to be installed for OS customizations.
- 'Common parameters (Linux/Windows):'
- ' - C(existing_vm) (bool): If set to C(True), do OS customization on the specified virtual machine directly.
If set to C(False) or not specified, do OS customization when cloning from the template or the virtual machine. version_added: 2.8'
- ' - C(dns_servers) (list): List of DNS servers to configure.'
- ' - C(dns_suffix) (list): List of domain suffixes, also known as DNS search path (default: C(domain) parameter).'
- ' - C(domain) (string): DNS domain name to use.'
- ' - C(hostname) (string): Computer hostname (default: shorted C(name) parameter). Allowed characters are alphanumeric (uppercase and lowercase)
and minus, rest of the characters are dropped as per RFC 952.'
- 'Parameters related to Linux customization:'
- ' - C(timezone) (string): Timezone (See List of supported time zones for different vSphere versions in Linux/Unix
systems (2145518) U(https://kb.vmware.com/s/article/2145518)). version_added: 2.9'
- ' - C(hwclockUTC) (bool): Specifies whether the hardware clock is in UTC or local time.
True when the hardware clock is in UTC, False when the hardware clock is in local time. version_added: 2.9'
- 'Parameters related to Windows customization:'
- ' - C(autologon) (bool): Auto logon after virtual machine customization (default: False).'
- ' - C(autologoncount) (int): Number of autologon after reboot (default: 1).'
- ' - C(domainadmin) (string): User used to join in AD domain (mandatory with C(joindomain)).'
- ' - C(domainadminpassword) (string): Password used to join in AD domain (mandatory with C(joindomain)).'
- ' - C(fullname) (string): Server owner name (default: Administrator).'
- ' - C(joindomain) (string): AD domain to join (Not compatible with C(joinworkgroup)).'
- ' - C(joinworkgroup) (string): Workgroup to join (Not compatible with C(joindomain), default: WORKGROUP).'
- ' - C(orgname) (string): Organisation name (default: ACME).'
- ' - C(password) (string): Local administrator password.'
- ' - C(productid) (string): Product ID.'
- ' - C(runonce) (list): List of commands to run at first user logon.'
- ' - C(timezone) (int): Timezone (See U(https://msdn.microsoft.com/en-us/library/ms912391.aspx)).'
version_added: '2.3'
vapp_properties:
description:
- A list of vApp properties
- 'For full list of attributes and types refer to: U(https://github.com/vmware/pyvmomi/blob/master/docs/vim/vApp/PropertyInfo.rst)'
- 'Basic attributes are:'
- ' - C(id) (string): Property id - required.'
- ' - C(value) (string): Property value.'
- ' - C(type) (string): Value type, string type by default.'
- ' - C(operation): C(remove): This attribute is required only when removing properties.'
version_added: '2.6'
customization_spec:
description:
- Unique name identifying the requested customization specification.
- This parameter is case sensitive.
- If set, then overrides C(customization) parameter values.
version_added: '2.6'
datastore:
description:
- Specify datastore or datastore cluster to provision virtual machine.
- 'This parameter takes precedence over "disk.datastore" parameter.'
- 'This parameter can be used to override datastore or datastore cluster setting of the virtual machine when deployed
from the template.'
- Please see example for more usage.
version_added: '2.7'
convert:
description:
- Specify convert disk type while cloning template or virtual machine.
choices: [ thin, thick, eagerzeroedthick ]
version_added: '2.8'
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Create a virtual machine on given ESXi hostname
vmware_guest:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: no
folder: /DC1/vm/
name: test_vm_0001
state: poweredon
guest_id: centos64Guest
# This is hostname of particular ESXi server on which user wants VM to be deployed
esxi_hostname: "{{ esxi_hostname }}"
disk:
- size_gb: 10
type: thin
datastore: datastore1
hardware:
memory_mb: 512
num_cpus: 4
scsi: paravirtual
networks:
- name: VM Network
mac: aa:bb:dd:aa:00:14
ip: 10.10.10.100
netmask: 255.255.255.0
device_type: vmxnet3
wait_for_ip_address: yes
delegate_to: localhost
register: deploy_vm
- name: Create a virtual machine from a template
vmware_guest:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: no
folder: /testvms
name: testvm_2
state: poweredon
template: template_el7
disk:
- size_gb: 10
type: thin
datastore: g73_datastore
hardware:
memory_mb: 512
num_cpus: 6
num_cpu_cores_per_socket: 3
scsi: paravirtual
memory_reservation_lock: True
mem_limit: 8096
mem_reservation: 4096
cpu_limit: 8096
cpu_reservation: 4096
max_connections: 5
hotadd_cpu: True
hotremove_cpu: True
hotadd_memory: False
version: 12 # Hardware version of virtual machine
boot_firmware: "efi"
cdrom:
type: iso
iso_path: "[datastore1] livecd.iso"
networks:
- name: VM Network
mac: aa:bb:dd:aa:00:14
wait_for_ip_address: yes
delegate_to: localhost
register: deploy
- name: Clone a virtual machine from Windows template and customize
vmware_guest:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: no
datacenter: datacenter1
cluster: cluster
name: testvm-2
template: template_windows
networks:
- name: VM Network
ip: 192.168.1.100
netmask: 255.255.255.0
gateway: 192.168.1.1
mac: aa:bb:dd:aa:00:14
domain: my_domain
dns_servers:
- 192.168.1.1
- 192.168.1.2
- vlan: 1234
type: dhcp
customization:
autologon: yes
dns_servers:
- 192.168.1.1
- 192.168.1.2
domain: my_domain
password: new_vm_password
runonce:
- powershell.exe -ExecutionPolicy Unrestricted -File C:\Windows\Temp\ConfigureRemotingForAnsible.ps1 -ForceNewSSLCert -EnableCredSSP
delegate_to: localhost
- name: Clone a virtual machine from Linux template and customize
vmware_guest:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: no
datacenter: "{{ datacenter }}"
state: present
folder: /DC1/vm
template: "{{ template }}"
name: "{{ vm_name }}"
cluster: DC1_C1
networks:
- name: VM Network
ip: 192.168.10.11
netmask: 255.255.255.0
wait_for_ip_address: True
customization:
domain: "{{ guest_domain }}"
dns_servers:
- 8.9.9.9
- 7.8.8.9
dns_suffix:
- example.com
- example2.com
delegate_to: localhost
- name: Rename a virtual machine (requires the virtual machine's uuid)
vmware_guest:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: no
uuid: "{{ vm_uuid }}"
name: new_name
state: present
delegate_to: localhost
- name: Remove a virtual machine by uuid
vmware_guest:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: no
uuid: "{{ vm_uuid }}"
state: absent
delegate_to: localhost
- name: Manipulate vApp properties
vmware_guest:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: no
name: vm_name
state: present
vapp_properties:
- id: remoteIP
category: Backup
label: Backup server IP
type: str
value: 10.10.10.1
- id: old_property
operation: remove
delegate_to: localhost
- name: Set powerstate of a virtual machine to poweroff by using UUID
vmware_guest:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: no
uuid: "{{ vm_uuid }}"
state: poweredoff
delegate_to: localhost
- name: Deploy a virtual machine in a datastore different from the datastore of the template
vmware_guest:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
name: "{{ vm_name }}"
state: present
template: "{{ template_name }}"
# Here datastore can be different which holds template
datastore: "{{ virtual_machine_datastore }}"
hardware:
memory_mb: 512
num_cpus: 2
scsi: paravirtual
delegate_to: localhost
'''
RETURN = r'''
instance:
description: metadata about the new virtual machine
returned: always
type: dict
sample: None
'''
import re
import time
import string
HAS_PYVMOMI = False
try:
from pyVmomi import vim, vmodl, VmomiSupport
HAS_PYVMOMI = True
except ImportError:
pass
from random import randint
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.network import is_mac
from ansible.module_utils._text import to_text, to_native
from ansible.module_utils.vmware import (find_obj, gather_vm_facts, get_all_objs,
compile_folder_path_for_object, serialize_spec,
vmware_argument_spec, set_vm_power_state, PyVmomi,
find_dvs_by_name, find_dvspg_by_name, wait_for_vm_ip,
wait_for_task, TaskError)
class PyVmomiDeviceHelper(object):
""" This class is a helper to create easily VMware Objects for PyVmomiHelper """
def __init__(self, module):
self.module = module
self.next_disk_unit_number = 0
self.scsi_device_type = {
'lsilogic': vim.vm.device.VirtualLsiLogicController,
'paravirtual': vim.vm.device.ParaVirtualSCSIController,
'buslogic': vim.vm.device.VirtualBusLogicController,
'lsilogicsas': vim.vm.device.VirtualLsiLogicSASController,
}
def create_scsi_controller(self, scsi_type):
scsi_ctl = vim.vm.device.VirtualDeviceSpec()
scsi_ctl.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
scsi_device = self.scsi_device_type.get(scsi_type, vim.vm.device.ParaVirtualSCSIController)
scsi_ctl.device = scsi_device()
scsi_ctl.device.busNumber = 0
# While creating a new SCSI controller, temporary key value
# should be unique negative integers
scsi_ctl.device.key = -randint(1000, 9999)
scsi_ctl.device.hotAddRemove = True
scsi_ctl.device.sharedBus = 'noSharing'
scsi_ctl.device.scsiCtlrUnitNumber = 7
return scsi_ctl
def is_scsi_controller(self, device):
return isinstance(device, tuple(self.scsi_device_type.values()))
@staticmethod
def create_ide_controller():
ide_ctl = vim.vm.device.VirtualDeviceSpec()
ide_ctl.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
ide_ctl.device = vim.vm.device.VirtualIDEController()
ide_ctl.device.deviceInfo = vim.Description()
# While creating a new IDE controller, temporary key value
# should be unique negative integers
ide_ctl.device.key = -randint(200, 299)
ide_ctl.device.busNumber = 0
return ide_ctl
@staticmethod
def create_cdrom(ide_ctl, cdrom_type, iso_path=None):
cdrom_spec = vim.vm.device.VirtualDeviceSpec()
cdrom_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
cdrom_spec.device = vim.vm.device.VirtualCdrom()
cdrom_spec.device.controllerKey = ide_ctl.device.key
cdrom_spec.device.key = -1
cdrom_spec.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
cdrom_spec.device.connectable.allowGuestControl = True
cdrom_spec.device.connectable.startConnected = (cdrom_type != "none")
if cdrom_type in ["none", "client"]:
cdrom_spec.device.backing = vim.vm.device.VirtualCdrom.RemotePassthroughBackingInfo()
elif cdrom_type == "iso":
cdrom_spec.device.backing = vim.vm.device.VirtualCdrom.IsoBackingInfo(fileName=iso_path)
return cdrom_spec
@staticmethod
def is_equal_cdrom(vm_obj, cdrom_device, cdrom_type, iso_path):
if cdrom_type == "none":
return (isinstance(cdrom_device.backing, vim.vm.device.VirtualCdrom.RemotePassthroughBackingInfo) and
cdrom_device.connectable.allowGuestControl and
not cdrom_device.connectable.startConnected and
(vm_obj.runtime.powerState != vim.VirtualMachinePowerState.poweredOn or not cdrom_device.connectable.connected))
elif cdrom_type == "client":
return (isinstance(cdrom_device.backing, vim.vm.device.VirtualCdrom.RemotePassthroughBackingInfo) and
cdrom_device.connectable.allowGuestControl and
cdrom_device.connectable.startConnected and
(vm_obj.runtime.powerState != vim.VirtualMachinePowerState.poweredOn or cdrom_device.connectable.connected))
elif cdrom_type == "iso":
return (isinstance(cdrom_device.backing, vim.vm.device.VirtualCdrom.IsoBackingInfo) and
cdrom_device.backing.fileName == iso_path and
cdrom_device.connectable.allowGuestControl and
cdrom_device.connectable.startConnected and
(vm_obj.runtime.powerState != vim.VirtualMachinePowerState.poweredOn or cdrom_device.connectable.connected))
def create_scsi_disk(self, scsi_ctl, disk_index=None):
diskspec = vim.vm.device.VirtualDeviceSpec()
diskspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
diskspec.device = vim.vm.device.VirtualDisk()
diskspec.device.backing = vim.vm.device.VirtualDisk.FlatVer2BackingInfo()
diskspec.device.controllerKey = scsi_ctl.device.key
if self.next_disk_unit_number == 7:
raise AssertionError()
if disk_index == 7:
raise AssertionError()
"""
Configure disk unit number.
"""
if disk_index is not None:
diskspec.device.unitNumber = disk_index
self.next_disk_unit_number = disk_index + 1
else:
diskspec.device.unitNumber = self.next_disk_unit_number
self.next_disk_unit_number += 1
# unit number 7 is reserved to SCSI controller, increase next index
if self.next_disk_unit_number == 7:
self.next_disk_unit_number += 1
return diskspec
def get_device(self, device_type, name):
nic_dict = dict(pcnet32=vim.vm.device.VirtualPCNet32(),
vmxnet2=vim.vm.device.VirtualVmxnet2(),
vmxnet3=vim.vm.device.VirtualVmxnet3(),
e1000=vim.vm.device.VirtualE1000(),
e1000e=vim.vm.device.VirtualE1000e(),
sriov=vim.vm.device.VirtualSriovEthernetCard(),
)
if device_type in nic_dict:
return nic_dict[device_type]
else:
self.module.fail_json(msg='Invalid device_type "%s"'
' for network "%s"' % (device_type, name))
def create_nic(self, device_type, device_label, device_infos):
nic = vim.vm.device.VirtualDeviceSpec()
nic.device = self.get_device(device_type, device_infos['name'])
nic.device.wakeOnLanEnabled = bool(device_infos.get('wake_on_lan', True))
nic.device.deviceInfo = vim.Description()
nic.device.deviceInfo.label = device_label
nic.device.deviceInfo.summary = device_infos['name']
nic.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
nic.device.connectable.startConnected = bool(device_infos.get('start_connected', True))
nic.device.connectable.allowGuestControl = bool(device_infos.get('allow_guest_control', True))
nic.device.connectable.connected = True
if 'mac' in device_infos and is_mac(device_infos['mac']):
nic.device.addressType = 'manual'
nic.device.macAddress = device_infos['mac']
else:
nic.device.addressType = 'generated'
return nic
def integer_value(self, input_value, name):
"""
Function to return int value for given input, else return error
Args:
input_value: Input value to retrive int value from
name: Name of the Input value (used to build error message)
Returns: (int) if integer value can be obtained, otherwise will send a error message.
"""
if isinstance(input_value, int):
return input_value
elif isinstance(input_value, str) and input_value.isdigit():
return int(input_value)
else:
self.module.fail_json(msg='"%s" attribute should be an'
' integer value.' % name)
class PyVmomiCache(object):
""" This class caches references to objects which are requested multiples times but not modified """
def __init__(self, content, dc_name=None):
self.content = content
self.dc_name = dc_name
self.networks = {}
self.clusters = {}
self.esx_hosts = {}
self.parent_datacenters = {}
def find_obj(self, content, types, name, confine_to_datacenter=True):
""" Wrapper around find_obj to set datacenter context """
result = find_obj(content, types, name)
if result and confine_to_datacenter:
if to_text(self.get_parent_datacenter(result).name) != to_text(self.dc_name):
result = None
objects = self.get_all_objs(content, types, confine_to_datacenter=True)
for obj in objects:
if name is None or to_text(obj.name) == to_text(name):
return obj
return result
def get_all_objs(self, content, types, confine_to_datacenter=True):
""" Wrapper around get_all_objs to set datacenter context """
objects = get_all_objs(content, types)
if confine_to_datacenter:
if hasattr(objects, 'items'):
# resource pools come back as a dictionary
# make a copy
tmpobjs = objects.copy()
for k, v in objects.items():
parent_dc = self.get_parent_datacenter(k)
if parent_dc.name != self.dc_name:
tmpobjs.pop(k, None)
objects = tmpobjs
else:
# everything else should be a list
objects = [x for x in objects if self.get_parent_datacenter(x).name == self.dc_name]
return objects
def get_network(self, network):
if network not in self.networks:
self.networks[network] = self.find_obj(self.content, [vim.Network], network)
return self.networks[network]
def get_cluster(self, cluster):
if cluster not in self.clusters:
self.clusters[cluster] = self.find_obj(self.content, [vim.ClusterComputeResource], cluster)
return self.clusters[cluster]
def get_esx_host(self, host):
if host not in self.esx_hosts:
self.esx_hosts[host] = self.find_obj(self.content, [vim.HostSystem], host)
return self.esx_hosts[host]
def get_parent_datacenter(self, obj):
""" Walk the parent tree to find the objects datacenter """
if isinstance(obj, vim.Datacenter):
return obj
if obj in self.parent_datacenters:
return self.parent_datacenters[obj]
datacenter = None
while True:
if not hasattr(obj, 'parent'):
break
obj = obj.parent
if isinstance(obj, vim.Datacenter):
datacenter = obj
break
self.parent_datacenters[obj] = datacenter
return datacenter
class PyVmomiHelper(PyVmomi):
def __init__(self, module):
super(PyVmomiHelper, self).__init__(module)
self.device_helper = PyVmomiDeviceHelper(self.module)
self.configspec = None
self.relospec = None
self.change_detected = False # a change was detected and needs to be applied through reconfiguration
self.change_applied = False # a change was applied meaning at least one task succeeded
self.customspec = None
self.cache = PyVmomiCache(self.content, dc_name=self.params['datacenter'])
def gather_facts(self, vm):
return gather_vm_facts(self.content, vm)
def remove_vm(self, vm):
# https://www.vmware.com/support/developer/converter-sdk/conv60_apireference/vim.ManagedEntity.html#destroy
if vm.summary.runtime.powerState.lower() == 'poweredon':
self.module.fail_json(msg="Virtual machine %s found in 'powered on' state, "
"please use 'force' parameter to remove or poweroff VM "
"and try removing VM again." % vm.name)
task = vm.Destroy()
self.wait_for_task(task)
if task.info.state == 'error':
return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'destroy'}
else:
return {'changed': self.change_applied, 'failed': False}
def configure_guestid(self, vm_obj, vm_creation=False):
# guest_id is not required when using templates
if self.params['template']:
return
# guest_id is only mandatory on VM creation
if vm_creation and self.params['guest_id'] is None:
self.module.fail_json(msg="guest_id attribute is mandatory for VM creation")
if self.params['guest_id'] and \
(vm_obj is None or self.params['guest_id'].lower() != vm_obj.summary.config.guestId.lower()):
self.change_detected = True
self.configspec.guestId = self.params['guest_id']
def configure_resource_alloc_info(self, vm_obj):
"""
Function to configure resource allocation information about virtual machine
:param vm_obj: VM object in case of reconfigure, None in case of deploy
:return: None
"""
rai_change_detected = False
memory_allocation = vim.ResourceAllocationInfo()
cpu_allocation = vim.ResourceAllocationInfo()
if 'hardware' in self.params:
if 'mem_limit' in self.params['hardware']:
mem_limit = None
try:
mem_limit = int(self.params['hardware'].get('mem_limit'))
except ValueError:
self.module.fail_json(msg="hardware.mem_limit attribute should be an integer value.")
memory_allocation.limit = mem_limit
if vm_obj is None or memory_allocation.limit != vm_obj.config.memoryAllocation.limit:
rai_change_detected = True
if 'mem_reservation' in self.params['hardware'] or 'memory_reservation' in self.params['hardware']:
mem_reservation = self.params['hardware'].get('mem_reservation') or self.params['hardware'].get('memory_reservation') or None
try:
mem_reservation = int(mem_reservation)
except ValueError:
self.module.fail_json(msg="hardware.mem_reservation or hardware.memory_reservation should be an integer value.")
memory_allocation.reservation = mem_reservation
if vm_obj is None or \
memory_allocation.reservation != vm_obj.config.memoryAllocation.reservation:
rai_change_detected = True
if 'cpu_limit' in self.params['hardware']:
cpu_limit = None
try:
cpu_limit = int(self.params['hardware'].get('cpu_limit'))
except ValueError:
self.module.fail_json(msg="hardware.cpu_limit attribute should be an integer value.")
cpu_allocation.limit = cpu_limit
if vm_obj is None or cpu_allocation.limit != vm_obj.config.cpuAllocation.limit:
rai_change_detected = True
if 'cpu_reservation' in self.params['hardware']:
cpu_reservation = None
try:
cpu_reservation = int(self.params['hardware'].get('cpu_reservation'))
except ValueError:
self.module.fail_json(msg="hardware.cpu_reservation should be an integer value.")
cpu_allocation.reservation = cpu_reservation
if vm_obj is None or \
cpu_allocation.reservation != vm_obj.config.cpuAllocation.reservation:
rai_change_detected = True
if rai_change_detected:
self.configspec.memoryAllocation = memory_allocation
self.configspec.cpuAllocation = cpu_allocation
self.change_detected = True
def configure_cpu_and_memory(self, vm_obj, vm_creation=False):
# set cpu/memory/etc
if 'hardware' in self.params:
if 'num_cpus' in self.params['hardware']:
try:
num_cpus = int(self.params['hardware']['num_cpus'])
except ValueError:
self.module.fail_json(msg="hardware.num_cpus attribute should be an integer value.")
# check VM power state and cpu hot-add/hot-remove state before re-config VM
if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn:
if not vm_obj.config.cpuHotRemoveEnabled and num_cpus < vm_obj.config.hardware.numCPU:
self.module.fail_json(msg="Configured cpu number is less than the cpu number of the VM, "
"cpuHotRemove is not enabled")
if not vm_obj.config.cpuHotAddEnabled and num_cpus > vm_obj.config.hardware.numCPU:
self.module.fail_json(msg="Configured cpu number is more than the cpu number of the VM, "
"cpuHotAdd is not enabled")
if 'num_cpu_cores_per_socket' in self.params['hardware']:
try:
num_cpu_cores_per_socket = int(self.params['hardware']['num_cpu_cores_per_socket'])
except ValueError:
self.module.fail_json(msg="hardware.num_cpu_cores_per_socket attribute "
"should be an integer value.")
if num_cpus % num_cpu_cores_per_socket != 0:
self.module.fail_json(msg="hardware.num_cpus attribute should be a multiple "
"of hardware.num_cpu_cores_per_socket")
self.configspec.numCoresPerSocket = num_cpu_cores_per_socket
if vm_obj is None or self.configspec.numCoresPerSocket != vm_obj.config.hardware.numCoresPerSocket:
self.change_detected = True
self.configspec.numCPUs = num_cpus
if vm_obj is None or self.configspec.numCPUs != vm_obj.config.hardware.numCPU:
self.change_detected = True
# num_cpu is mandatory for VM creation
elif vm_creation and not self.params['template']:
self.module.fail_json(msg="hardware.num_cpus attribute is mandatory for VM creation")
if 'memory_mb' in self.params['hardware']:
try:
memory_mb = int(self.params['hardware']['memory_mb'])
except ValueError:
self.module.fail_json(msg="Failed to parse hardware.memory_mb value."
" Please refer the documentation and provide"
" correct value.")
# check VM power state and memory hotadd state before re-config VM
if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn:
if vm_obj.config.memoryHotAddEnabled and memory_mb < vm_obj.config.hardware.memoryMB:
self.module.fail_json(msg="Configured memory is less than memory size of the VM, "
"operation is not supported")
elif not vm_obj.config.memoryHotAddEnabled and memory_mb != vm_obj.config.hardware.memoryMB:
self.module.fail_json(msg="memoryHotAdd is not enabled")
self.configspec.memoryMB = memory_mb
if vm_obj is None or self.configspec.memoryMB != vm_obj.config.hardware.memoryMB:
self.change_detected = True
# memory_mb is mandatory for VM creation
elif vm_creation and not self.params['template']:
self.module.fail_json(msg="hardware.memory_mb attribute is mandatory for VM creation")
if 'hotadd_memory' in self.params['hardware']:
if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn and \
vm_obj.config.memoryHotAddEnabled != bool(self.params['hardware']['hotadd_memory']):
self.module.fail_json(msg="Configure hotadd memory operation is not supported when VM is power on")
self.configspec.memoryHotAddEnabled = bool(self.params['hardware']['hotadd_memory'])
if vm_obj is None or self.configspec.memoryHotAddEnabled != vm_obj.config.memoryHotAddEnabled:
self.change_detected = True
if 'hotadd_cpu' in self.params['hardware']:
if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn and \
vm_obj.config.cpuHotAddEnabled != bool(self.params['hardware']['hotadd_cpu']):
self.module.fail_json(msg="Configure hotadd cpu operation is not supported when VM is power on")
self.configspec.cpuHotAddEnabled = bool(self.params['hardware']['hotadd_cpu'])
if vm_obj is None or self.configspec.cpuHotAddEnabled != vm_obj.config.cpuHotAddEnabled:
self.change_detected = True
if 'hotremove_cpu' in self.params['hardware']:
if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn and \
vm_obj.config.cpuHotRemoveEnabled != bool(self.params['hardware']['hotremove_cpu']):
self.module.fail_json(msg="Configure hotremove cpu operation is not supported when VM is power on")
self.configspec.cpuHotRemoveEnabled = bool(self.params['hardware']['hotremove_cpu'])
if vm_obj is None or self.configspec.cpuHotRemoveEnabled != vm_obj.config.cpuHotRemoveEnabled:
self.change_detected = True
if 'memory_reservation_lock' in self.params['hardware']:
self.configspec.memoryReservationLockedToMax = bool(self.params['hardware']['memory_reservation_lock'])
if vm_obj is None or self.configspec.memoryReservationLockedToMax != vm_obj.config.memoryReservationLockedToMax:
self.change_detected = True
if 'boot_firmware' in self.params['hardware']:
# boot firmware re-config can cause boot issue
if vm_obj is not None:
return
boot_firmware = self.params['hardware']['boot_firmware'].lower()
if boot_firmware not in ('bios', 'efi'):
self.module.fail_json(msg="hardware.boot_firmware value is invalid [%s]."
" Need one of ['bios', 'efi']." % boot_firmware)
self.configspec.firmware = boot_firmware
self.change_detected = True
def configure_cdrom(self, vm_obj):
# Configure the VM CD-ROM
if "cdrom" in self.params and self.params["cdrom"]:
if "type" not in self.params["cdrom"] or self.params["cdrom"]["type"] not in ["none", "client", "iso"]:
self.module.fail_json(msg="cdrom.type is mandatory")
if self.params["cdrom"]["type"] == "iso" and ("iso_path" not in self.params["cdrom"] or not self.params["cdrom"]["iso_path"]):
self.module.fail_json(msg="cdrom.iso_path is mandatory in case cdrom.type is iso")
if vm_obj and vm_obj.config.template:
# Changing CD-ROM settings on a template is not supported
return
cdrom_spec = None
cdrom_device = self.get_vm_cdrom_device(vm=vm_obj)
iso_path = self.params["cdrom"]["iso_path"] if "iso_path" in self.params["cdrom"] else None
if cdrom_device is None:
# Creating new CD-ROM
ide_device = self.get_vm_ide_device(vm=vm_obj)
if ide_device is None:
# Creating new IDE device
ide_device = self.device_helper.create_ide_controller()
self.change_detected = True
self.configspec.deviceChange.append(ide_device)
elif len(ide_device.device) > 3:
self.module.fail_json(msg="hardware.cdrom specified for a VM or template which already has 4 IDE devices of which none are a cdrom")
cdrom_spec = self.device_helper.create_cdrom(ide_ctl=ide_device, cdrom_type=self.params["cdrom"]["type"], iso_path=iso_path)
if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn:
cdrom_spec.device.connectable.connected = (self.params["cdrom"]["type"] != "none")
elif not self.device_helper.is_equal_cdrom(vm_obj=vm_obj, cdrom_device=cdrom_device, cdrom_type=self.params["cdrom"]["type"], iso_path=iso_path):
# Updating an existing CD-ROM
if self.params["cdrom"]["type"] in ["client", "none"]:
cdrom_device.backing = vim.vm.device.VirtualCdrom.RemotePassthroughBackingInfo()
elif self.params["cdrom"]["type"] == "iso":
cdrom_device.backing = vim.vm.device.VirtualCdrom.IsoBackingInfo(fileName=iso_path)
cdrom_device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
cdrom_device.connectable.allowGuestControl = True
cdrom_device.connectable.startConnected = (self.params["cdrom"]["type"] != "none")
if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn:
cdrom_device.connectable.connected = (self.params["cdrom"]["type"] != "none")
cdrom_spec = vim.vm.device.VirtualDeviceSpec()
cdrom_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
cdrom_spec.device = cdrom_device
if cdrom_spec:
self.change_detected = True
self.configspec.deviceChange.append(cdrom_spec)
def configure_hardware_params(self, vm_obj):
"""
Function to configure hardware related configuration of virtual machine
Args:
vm_obj: virtual machine object
"""
if 'hardware' in self.params:
if 'max_connections' in self.params['hardware']:
# maxMksConnections == max_connections
self.configspec.maxMksConnections = int(self.params['hardware']['max_connections'])
if vm_obj is None or self.configspec.maxMksConnections != vm_obj.config.maxMksConnections:
self.change_detected = True
if 'nested_virt' in self.params['hardware']:
self.configspec.nestedHVEnabled = bool(self.params['hardware']['nested_virt'])
if vm_obj is None or self.configspec.nestedHVEnabled != bool(vm_obj.config.nestedHVEnabled):
self.change_detected = True
if 'version' in self.params['hardware']:
hw_version_check_failed = False
temp_version = self.params['hardware'].get('version', 10)
try:
temp_version = int(temp_version)
except ValueError:
hw_version_check_failed = True
if temp_version not in range(3, 15):
hw_version_check_failed = True
if hw_version_check_failed:
self.module.fail_json(msg="Failed to set hardware.version '%s' value as valid"
" values range from 3 (ESX 2.x) to 14 (ESXi 6.5 and greater)." % temp_version)
# Hardware version is denoted as "vmx-10"
version = "vmx-%02d" % temp_version
self.configspec.version = version
if vm_obj is None or self.configspec.version != vm_obj.config.version:
self.change_detected = True
if vm_obj is not None:
# VM exists and we need to update the hardware version
current_version = vm_obj.config.version
# current_version = "vmx-10"
version_digit = int(current_version.split("-", 1)[-1])
if temp_version < version_digit:
self.module.fail_json(msg="Current hardware version '%d' which is greater than the specified"
" version '%d'. Downgrading hardware version is"
" not supported. Please specify version greater"
" than the current version." % (version_digit,
temp_version))
new_version = "vmx-%02d" % temp_version
try:
task = vm_obj.UpgradeVM_Task(new_version)
self.wait_for_task(task)
if task.info.state == 'error':
return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'upgrade'}
except vim.fault.AlreadyUpgraded:
# Don't fail if VM is already upgraded.
pass
if 'virt_based_security' in self.params['hardware']:
host_version = self.select_host().summary.config.product.version
if int(host_version.split('.')[0]) < 6 or (int(host_version.split('.')[0]) == 6 and int(host_version.split('.')[1]) < 7):
self.module.fail_json(msg="ESXi version %s not support VBS." % host_version)
guest_ids = ['windows9_64Guest', 'windows9Server64Guest']
if vm_obj is None:
guestid = self.configspec.guestId
else:
guestid = vm_obj.summary.config.guestId
if guestid not in guest_ids:
self.module.fail_json(msg="Guest '%s' not support VBS." % guestid)
if (vm_obj is None and int(self.configspec.version.split('-')[1]) >= 14) or \
(vm_obj and int(vm_obj.config.version.split('-')[1]) >= 14 and (vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOff)):
self.configspec.flags = vim.vm.FlagInfo()
self.configspec.flags.vbsEnabled = bool(self.params['hardware']['virt_based_security'])
if bool(self.params['hardware']['virt_based_security']):
self.configspec.flags.vvtdEnabled = True
self.configspec.nestedHVEnabled = True
if (vm_obj is None and self.configspec.firmware == 'efi') or \
(vm_obj and vm_obj.config.firmware == 'efi'):
self.configspec.bootOptions = vim.vm.BootOptions()
self.configspec.bootOptions.efiSecureBootEnabled = True
else:
self.module.fail_json(msg="Not support VBS when firmware is BIOS.")
if vm_obj is None or self.configspec.flags.vbsEnabled != vm_obj.config.flags.vbsEnabled:
self.change_detected = True
def get_device_by_type(self, vm=None, type=None):
if vm is None or type is None:
return None
for device in vm.config.hardware.device:
if isinstance(device, type):
return device
return None
def get_vm_cdrom_device(self, vm=None):
return self.get_device_by_type(vm=vm, type=vim.vm.device.VirtualCdrom)
def get_vm_ide_device(self, vm=None):
return self.get_device_by_type(vm=vm, type=vim.vm.device.VirtualIDEController)
def get_vm_network_interfaces(self, vm=None):
device_list = []
if vm is None:
return device_list
nw_device_types = (vim.vm.device.VirtualPCNet32, vim.vm.device.VirtualVmxnet2,
vim.vm.device.VirtualVmxnet3, vim.vm.device.VirtualE1000,
vim.vm.device.VirtualE1000e, vim.vm.device.VirtualSriovEthernetCard)
for device in vm.config.hardware.device:
if isinstance(device, nw_device_types):
device_list.append(device)
return device_list
def sanitize_network_params(self):
"""
Sanitize user provided network provided params
Returns: A sanitized list of network params, else fails
"""
network_devices = list()
# Clean up user data here
for network in self.params['networks']:
if 'name' not in network and 'vlan' not in network:
self.module.fail_json(msg="Please specify at least a network name or"
" a VLAN name under VM network list.")
if 'name' in network and self.cache.get_network(network['name']) is None:
self.module.fail_json(msg="Network '%(name)s' does not exist." % network)
elif 'vlan' in network:
dvps = self.cache.get_all_objs(self.content, [vim.dvs.DistributedVirtualPortgroup])
for dvp in dvps:
if hasattr(dvp.config.defaultPortConfig, 'vlan') and \
isinstance(dvp.config.defaultPortConfig.vlan.vlanId, int) and \
str(dvp.config.defaultPortConfig.vlan.vlanId) == str(network['vlan']):
network['name'] = dvp.config.name
break
if 'dvswitch_name' in network and \
dvp.config.distributedVirtualSwitch.name == network['dvswitch_name'] and \
dvp.config.name == network['vlan']:
network['name'] = dvp.config.name
break
if dvp.config.name == network['vlan']:
network['name'] = dvp.config.name
break
else:
self.module.fail_json(msg="VLAN '%(vlan)s' does not exist." % network)
if 'type' in network:
if network['type'] not in ['dhcp', 'static']:
self.module.fail_json(msg="Network type '%(type)s' is not a valid parameter."
" Valid parameters are ['dhcp', 'static']." % network)
if network['type'] != 'static' and ('ip' in network or 'netmask' in network):
self.module.fail_json(msg='Static IP information provided for network "%(name)s",'
' but "type" is set to "%(type)s".' % network)
else:
# Type is optional parameter, if user provided IP or Subnet assume
# network type as 'static'
if 'ip' in network or 'netmask' in network:
network['type'] = 'static'
else:
# User wants network type as 'dhcp'
network['type'] = 'dhcp'
if network.get('type') == 'static':
if 'ip' in network and 'netmask' not in network:
self.module.fail_json(msg="'netmask' is required if 'ip' is"
" specified under VM network list.")
if 'ip' not in network and 'netmask' in network:
self.module.fail_json(msg="'ip' is required if 'netmask' is"
" specified under VM network list.")
validate_device_types = ['pcnet32', 'vmxnet2', 'vmxnet3', 'e1000', 'e1000e', 'sriov']
if 'device_type' in network and network['device_type'] not in validate_device_types:
self.module.fail_json(msg="Device type specified '%s' is not valid."
" Please specify correct device"
" type from ['%s']." % (network['device_type'],
"', '".join(validate_device_types)))
if 'mac' in network and not is_mac(network['mac']):
self.module.fail_json(msg="Device MAC address '%s' is invalid."
" Please provide correct MAC address." % network['mac'])
network_devices.append(network)
return network_devices
def configure_network(self, vm_obj):
# Ignore empty networks, this permits to keep networks when deploying a template/cloning a VM
if len(self.params['networks']) == 0:
return
network_devices = self.sanitize_network_params()
# List current device for Clone or Idempotency
current_net_devices = self.get_vm_network_interfaces(vm=vm_obj)
if len(network_devices) < len(current_net_devices):
self.module.fail_json(msg="Given network device list is lesser than current VM device list (%d < %d). "
"Removing interfaces is not allowed"
% (len(network_devices), len(current_net_devices)))
for key in range(0, len(network_devices)):
nic_change_detected = False
network_name = network_devices[key]['name']
if key < len(current_net_devices) and (vm_obj or self.params['template']):
# We are editing existing network devices, this is either when
# are cloning from VM or Template
nic = vim.vm.device.VirtualDeviceSpec()
nic.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
nic.device = current_net_devices[key]
if ('wake_on_lan' in network_devices[key] and
nic.device.wakeOnLanEnabled != network_devices[key].get('wake_on_lan')):
nic.device.wakeOnLanEnabled = network_devices[key].get('wake_on_lan')
nic_change_detected = True
if ('start_connected' in network_devices[key] and
nic.device.connectable.startConnected != network_devices[key].get('start_connected')):
nic.device.connectable.startConnected = network_devices[key].get('start_connected')
nic_change_detected = True
if ('allow_guest_control' in network_devices[key] and
nic.device.connectable.allowGuestControl != network_devices[key].get('allow_guest_control')):
nic.device.connectable.allowGuestControl = network_devices[key].get('allow_guest_control')
nic_change_detected = True
if nic.device.deviceInfo.summary != network_name:
nic.device.deviceInfo.summary = network_name
nic_change_detected = True
if 'device_type' in network_devices[key]:
device = self.device_helper.get_device(network_devices[key]['device_type'], network_name)
device_class = type(device)
if not isinstance(nic.device, device_class):
self.module.fail_json(msg="Changing the device type is not possible when interface is already present. "
"The failing device type is %s" % network_devices[key]['device_type'])
# Changing mac address has no effect when editing interface
if 'mac' in network_devices[key] and nic.device.macAddress != current_net_devices[key].macAddress:
self.module.fail_json(msg="Changing MAC address has not effect when interface is already present. "
"The failing new MAC address is %s" % nic.device.macAddress)
else:
# Default device type is vmxnet3, VMware best practice
device_type = network_devices[key].get('device_type', 'vmxnet3')
nic = self.device_helper.create_nic(device_type,
'Network Adapter %s' % (key + 1),
network_devices[key])
nic.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
nic_change_detected = True
if hasattr(self.cache.get_network(network_name), 'portKeys'):
# VDS switch
pg_obj = None
if 'dvswitch_name' in network_devices[key]:
dvs_name = network_devices[key]['dvswitch_name']
dvs_obj = find_dvs_by_name(self.content, dvs_name)
if dvs_obj is None:
self.module.fail_json(msg="Unable to find distributed virtual switch %s" % dvs_name)
pg_obj = find_dvspg_by_name(dvs_obj, network_name)
if pg_obj is None:
self.module.fail_json(msg="Unable to find distributed port group %s" % network_name)
else:
pg_obj = self.cache.find_obj(self.content, [vim.dvs.DistributedVirtualPortgroup], network_name)
if (nic.device.backing and
(not hasattr(nic.device.backing, 'port') or
(nic.device.backing.port.portgroupKey != pg_obj.key or
nic.device.backing.port.switchUuid != pg_obj.config.distributedVirtualSwitch.uuid))):
nic_change_detected = True
dvs_port_connection = vim.dvs.PortConnection()
dvs_port_connection.portgroupKey = pg_obj.key
# If user specifies distributed port group without associating to the hostsystem on which
# virtual machine is going to be deployed then we get error. We can infer that there is no
# association between given distributed port group and host system.
host_system = self.params.get('esxi_hostname')
if host_system and host_system not in [host.config.host.name for host in pg_obj.config.distributedVirtualSwitch.config.host]:
self.module.fail_json(msg="It seems that host system '%s' is not associated with distributed"
" virtual portgroup '%s'. Please make sure host system is associated"
" with given distributed virtual portgroup" % (host_system, pg_obj.name))
# TODO: (akasurde) There is no way to find association between resource pool and distributed virtual portgroup
# For now, check if we are able to find distributed virtual switch
if not pg_obj.config.distributedVirtualSwitch:
self.module.fail_json(msg="Failed to find distributed virtual switch which is associated with"
" distributed virtual portgroup '%s'. Make sure hostsystem is associated with"
" the given distributed virtual portgroup." % pg_obj.name)
dvs_port_connection.switchUuid = pg_obj.config.distributedVirtualSwitch.uuid
nic.device.backing = vim.vm.device.VirtualEthernetCard.DistributedVirtualPortBackingInfo()
nic.device.backing.port = dvs_port_connection
elif isinstance(self.cache.get_network(network_name), vim.OpaqueNetwork):
# NSX-T Logical Switch
nic.device.backing = vim.vm.device.VirtualEthernetCard.OpaqueNetworkBackingInfo()
network_id = self.cache.get_network(network_name).summary.opaqueNetworkId
nic.device.backing.opaqueNetworkType = 'nsx.LogicalSwitch'
nic.device.backing.opaqueNetworkId = network_id
nic.device.deviceInfo.summary = 'nsx.LogicalSwitch: %s' % network_id
nic_change_detected = True
else:
# vSwitch
if not isinstance(nic.device.backing, vim.vm.device.VirtualEthernetCard.NetworkBackingInfo):
nic.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
nic_change_detected = True
net_obj = self.cache.get_network(network_name)
if nic.device.backing.network != net_obj:
nic.device.backing.network = net_obj
nic_change_detected = True
if nic.device.backing.deviceName != network_name:
nic.device.backing.deviceName = network_name
nic_change_detected = True
if nic_change_detected:
# Change to fix the issue found while configuring opaque network
# VMs cloned from a template with opaque network will get disconnected
# Replacing deprecated config parameter with relocation Spec
if isinstance(self.cache.get_network(network_name), vim.OpaqueNetwork):
self.relospec.deviceChange.append(nic)
else:
self.configspec.deviceChange.append(nic)
self.change_detected = True
def configure_vapp_properties(self, vm_obj):
if len(self.params['vapp_properties']) == 0:
return
for x in self.params['vapp_properties']:
if not x.get('id'):
self.module.fail_json(msg="id is required to set vApp property")
new_vmconfig_spec = vim.vApp.VmConfigSpec()
if vm_obj:
# VM exists
# This is primarily for vcsim/integration tests, unset vAppConfig was not seen on my deployments
orig_spec = vm_obj.config.vAppConfig if vm_obj.config.vAppConfig else new_vmconfig_spec
vapp_properties_current = dict((x.id, x) for x in orig_spec.property)
vapp_properties_to_change = dict((x['id'], x) for x in self.params['vapp_properties'])
# each property must have a unique key
# init key counter with max value + 1
all_keys = [x.key for x in orig_spec.property]
new_property_index = max(all_keys) + 1 if all_keys else 0
for property_id, property_spec in vapp_properties_to_change.items():
is_property_changed = False
new_vapp_property_spec = vim.vApp.PropertySpec()
if property_id in vapp_properties_current:
if property_spec.get('operation') == 'remove':
new_vapp_property_spec.operation = 'remove'
new_vapp_property_spec.removeKey = vapp_properties_current[property_id].key
is_property_changed = True
else:
# this is 'edit' branch
new_vapp_property_spec.operation = 'edit'
new_vapp_property_spec.info = vapp_properties_current[property_id]
try:
for property_name, property_value in property_spec.items():
if property_name == 'operation':
# operation is not an info object property
# if set to anything other than 'remove' we don't fail
continue
# Updating attributes only if needed
if getattr(new_vapp_property_spec.info, property_name) != property_value:
setattr(new_vapp_property_spec.info, property_name, property_value)
is_property_changed = True
except Exception as e:
msg = "Failed to set vApp property field='%s' and value='%s'. Error: %s" % (property_name, property_value, to_text(e))
self.module.fail_json(msg=msg)
else:
if property_spec.get('operation') == 'remove':
# attempt to delete non-existent property
continue
# this is add new property branch
new_vapp_property_spec.operation = 'add'
property_info = vim.vApp.PropertyInfo()
property_info.classId = property_spec.get('classId')
property_info.instanceId = property_spec.get('instanceId')
property_info.id = property_spec.get('id')
property_info.category = property_spec.get('category')
property_info.label = property_spec.get('label')
property_info.type = property_spec.get('type', 'string')
property_info.userConfigurable = property_spec.get('userConfigurable', True)
property_info.defaultValue = property_spec.get('defaultValue')
property_info.value = property_spec.get('value', '')
property_info.description = property_spec.get('description')
new_vapp_property_spec.info = property_info
new_vapp_property_spec.info.key = new_property_index
new_property_index += 1
is_property_changed = True
if is_property_changed:
new_vmconfig_spec.property.append(new_vapp_property_spec)
else:
# New VM
all_keys = [x.key for x in new_vmconfig_spec.property]
new_property_index = max(all_keys) + 1 if all_keys else 0
vapp_properties_to_change = dict((x['id'], x) for x in self.params['vapp_properties'])
is_property_changed = False
for property_id, property_spec in vapp_properties_to_change.items():
new_vapp_property_spec = vim.vApp.PropertySpec()
# this is add new property branch
new_vapp_property_spec.operation = 'add'
property_info = vim.vApp.PropertyInfo()
property_info.classId = property_spec.get('classId')
property_info.instanceId = property_spec.get('instanceId')
property_info.id = property_spec.get('id')
property_info.category = property_spec.get('category')
property_info.label = property_spec.get('label')
property_info.type = property_spec.get('type', 'string')
property_info.userConfigurable = property_spec.get('userConfigurable', True)
property_info.defaultValue = property_spec.get('defaultValue')
property_info.value = property_spec.get('value', '')
property_info.description = property_spec.get('description')
new_vapp_property_spec.info = property_info
new_vapp_property_spec.info.key = new_property_index
new_property_index += 1
is_property_changed = True
if is_property_changed:
new_vmconfig_spec.property.append(new_vapp_property_spec)
if new_vmconfig_spec.property:
self.configspec.vAppConfig = new_vmconfig_spec
self.change_detected = True
def customize_customvalues(self, vm_obj, config_spec):
if len(self.params['customvalues']) == 0:
return
vm_custom_spec = config_spec
vm_custom_spec.extraConfig = []
changed = False
facts = self.gather_facts(vm_obj)
for kv in self.params['customvalues']:
if 'key' not in kv or 'value' not in kv:
self.module.exit_json(msg="customvalues items required both 'key' and 'value fields.")
# If kv is not kv fetched from facts, change it
if kv['key'] not in facts['customvalues'] or facts['customvalues'][kv['key']] != kv['value']:
option = vim.option.OptionValue()
option.key = kv['key']
option.value = kv['value']
vm_custom_spec.extraConfig.append(option)
changed = True
if changed:
self.change_detected = True
def customize_vm(self, vm_obj):
# User specified customization specification
custom_spec_name = self.params.get('customization_spec')
if custom_spec_name:
cc_mgr = self.content.customizationSpecManager
if cc_mgr.DoesCustomizationSpecExist(name=custom_spec_name):
temp_spec = cc_mgr.GetCustomizationSpec(name=custom_spec_name)
self.customspec = temp_spec.spec
return
else:
self.module.fail_json(msg="Unable to find customization specification"
" '%s' in given configuration." % custom_spec_name)
# Network settings
adaptermaps = []
for network in self.params['networks']:
guest_map = vim.vm.customization.AdapterMapping()
guest_map.adapter = vim.vm.customization.IPSettings()
if 'ip' in network and 'netmask' in network:
guest_map.adapter.ip = vim.vm.customization.FixedIp()
guest_map.adapter.ip.ipAddress = str(network['ip'])
guest_map.adapter.subnetMask = str(network['netmask'])
elif 'type' in network and network['type'] == 'dhcp':
guest_map.adapter.ip = vim.vm.customization.DhcpIpGenerator()
if 'gateway' in network:
guest_map.adapter.gateway = network['gateway']
# On Windows, DNS domain and DNS servers can be set by network interface
# https://pubs.vmware.com/vi3/sdk/ReferenceGuide/vim.vm.customization.IPSettings.html
if 'domain' in network:
guest_map.adapter.dnsDomain = network['domain']
elif 'domain' in self.params['customization']:
guest_map.adapter.dnsDomain = self.params['customization']['domain']
if 'dns_servers' in network:
guest_map.adapter.dnsServerList = network['dns_servers']
elif 'dns_servers' in self.params['customization']:
guest_map.adapter.dnsServerList = self.params['customization']['dns_servers']
adaptermaps.append(guest_map)
# Global DNS settings
globalip = vim.vm.customization.GlobalIPSettings()
if 'dns_servers' in self.params['customization']:
globalip.dnsServerList = self.params['customization']['dns_servers']
# TODO: Maybe list the different domains from the interfaces here by default ?
if 'dns_suffix' in self.params['customization']:
dns_suffix = self.params['customization']['dns_suffix']
if isinstance(dns_suffix, list):
globalip.dnsSuffixList = " ".join(dns_suffix)
else:
globalip.dnsSuffixList = dns_suffix
elif 'domain' in self.params['customization']:
globalip.dnsSuffixList = self.params['customization']['domain']
if self.params['guest_id']:
guest_id = self.params['guest_id']
else:
guest_id = vm_obj.summary.config.guestId
# For windows guest OS, use SysPrep
# https://pubs.vmware.com/vi3/sdk/ReferenceGuide/vim.vm.customization.Sysprep.html#field_detail
if 'win' in guest_id:
ident = vim.vm.customization.Sysprep()
ident.userData = vim.vm.customization.UserData()
# Setting hostName, orgName and fullName is mandatory, so we set some default when missing
ident.userData.computerName = vim.vm.customization.FixedName()
# computer name will be truncated to 15 characters if using VM name
default_name = self.params['name'].replace(' ', '')
default_name = ''.join([c for c in default_name if c not in string.punctuation])
ident.userData.computerName.name = str(self.params['customization'].get('hostname', default_name[0:15]))
ident.userData.fullName = str(self.params['customization'].get('fullname', 'Administrator'))
ident.userData.orgName = str(self.params['customization'].get('orgname', 'ACME'))
if 'productid' in self.params['customization']:
ident.userData.productId = str(self.params['customization']['productid'])
ident.guiUnattended = vim.vm.customization.GuiUnattended()
if 'autologon' in self.params['customization']:
ident.guiUnattended.autoLogon = self.params['customization']['autologon']
ident.guiUnattended.autoLogonCount = self.params['customization'].get('autologoncount', 1)
if 'timezone' in self.params['customization']:
# Check if timezone value is a int before proceeding.
ident.guiUnattended.timeZone = self.device_helper.integer_value(
self.params['customization']['timezone'],
'customization.timezone')
ident.identification = vim.vm.customization.Identification()
if self.params['customization'].get('password', '') != '':
ident.guiUnattended.password = vim.vm.customization.Password()
ident.guiUnattended.password.value = str(self.params['customization']['password'])
ident.guiUnattended.password.plainText = True
if 'joindomain' in self.params['customization']:
if 'domainadmin' not in self.params['customization'] or 'domainadminpassword' not in self.params['customization']:
self.module.fail_json(msg="'domainadmin' and 'domainadminpassword' entries are mandatory in 'customization' section to use "
"joindomain feature")
ident.identification.domainAdmin = str(self.params['customization']['domainadmin'])
ident.identification.joinDomain = str(self.params['customization']['joindomain'])
ident.identification.domainAdminPassword = vim.vm.customization.Password()
ident.identification.domainAdminPassword.value = str(self.params['customization']['domainadminpassword'])
ident.identification.domainAdminPassword.plainText = True
elif 'joinworkgroup' in self.params['customization']:
ident.identification.joinWorkgroup = str(self.params['customization']['joinworkgroup'])
if 'runonce' in self.params['customization']:
ident.guiRunOnce = vim.vm.customization.GuiRunOnce()
ident.guiRunOnce.commandList = self.params['customization']['runonce']
else:
# FIXME: We have no clue whether this non-Windows OS is actually Linux, hence it might fail!
# For Linux guest OS, use LinuxPrep
# https://pubs.vmware.com/vi3/sdk/ReferenceGuide/vim.vm.customization.LinuxPrep.html
ident = vim.vm.customization.LinuxPrep()
# TODO: Maybe add domain from interface if missing ?
if 'domain' in self.params['customization']:
ident.domain = str(self.params['customization']['domain'])
ident.hostName = vim.vm.customization.FixedName()
hostname = str(self.params['customization'].get('hostname', self.params['name'].split('.')[0]))
# Remove all characters except alphanumeric and minus which is allowed by RFC 952
valid_hostname = re.sub(r"[^a-zA-Z0-9\-]", "", hostname)
ident.hostName.name = valid_hostname
# List of supported time zones for different vSphere versions in Linux/Unix systems
# https://kb.vmware.com/s/article/2145518
if 'timezone' in self.params['customization']:
ident.timeZone = str(self.params['customization']['timezone'])
if 'hwclockUTC' in self.params['customization']:
ident.hwClockUTC = self.params['customization']['hwclockUTC']
self.customspec = vim.vm.customization.Specification()
self.customspec.nicSettingMap = adaptermaps
self.customspec.globalIPSettings = globalip
self.customspec.identity = ident
def get_vm_scsi_controller(self, vm_obj):
# If vm_obj doesn't exist there is no SCSI controller to find
if vm_obj is None:
return None
for device in vm_obj.config.hardware.device:
if self.device_helper.is_scsi_controller(device):
scsi_ctl = vim.vm.device.VirtualDeviceSpec()
scsi_ctl.device = device
return scsi_ctl
return None
def get_configured_disk_size(self, expected_disk_spec):
# what size is it?
if [x for x in expected_disk_spec.keys() if x.startswith('size_') or x == 'size']:
# size, size_tb, size_gb, size_mb, size_kb
if 'size' in expected_disk_spec:
size_regex = re.compile(r'(\d+(?:\.\d+)?)([tgmkTGMK][bB])')
disk_size_m = size_regex.match(expected_disk_spec['size'])
try:
if disk_size_m:
expected = disk_size_m.group(1)
unit = disk_size_m.group(2)
else:
raise ValueError
if re.match(r'\d+\.\d+', expected):
# We found float value in string, let's typecast it
expected = float(expected)
else:
# We found int value in string, let's typecast it
expected = int(expected)
if not expected or not unit:
raise ValueError
except (TypeError, ValueError, NameError):
# Common failure
self.module.fail_json(msg="Failed to parse disk size please review value"
" provided using documentation.")
else:
param = [x for x in expected_disk_spec.keys() if x.startswith('size_')][0]
unit = param.split('_')[-1].lower()
expected = [x[1] for x in expected_disk_spec.items() if x[0].startswith('size_')][0]
expected = int(expected)
disk_units = dict(tb=3, gb=2, mb=1, kb=0)
if unit in disk_units:
unit = unit.lower()
return expected * (1024 ** disk_units[unit])
else:
self.module.fail_json(msg="%s is not a supported unit for disk size."
" Supported units are ['%s']." % (unit,
"', '".join(disk_units.keys())))
# No size found but disk, fail
self.module.fail_json(
msg="No size, size_kb, size_mb, size_gb or size_tb attribute found into disk configuration")
def find_vmdk(self, vmdk_path):
"""
Takes a vsphere datastore path in the format
[datastore_name] path/to/file.vmdk
Returns vsphere file object or raises RuntimeError
"""
datastore_name, vmdk_fullpath, vmdk_filename, vmdk_folder = self.vmdk_disk_path_split(vmdk_path)
datastore = self.cache.find_obj(self.content, [vim.Datastore], datastore_name)
if datastore is None:
self.module.fail_json(msg="Failed to find the datastore %s" % datastore_name)
return self.find_vmdk_file(datastore, vmdk_fullpath, vmdk_filename, vmdk_folder)
def add_existing_vmdk(self, vm_obj, expected_disk_spec, diskspec, scsi_ctl):
"""
Adds vmdk file described by expected_disk_spec['filename'], retrieves the file
information and adds the correct spec to self.configspec.deviceChange.
"""
filename = expected_disk_spec['filename']
# if this is a new disk, or the disk file names are different
if (vm_obj and diskspec.device.backing.fileName != filename) or vm_obj is None:
vmdk_file = self.find_vmdk(expected_disk_spec['filename'])
diskspec.device.backing.fileName = expected_disk_spec['filename']
diskspec.device.capacityInKB = VmomiSupport.vmodlTypes['long'](vmdk_file.fileSize / 1024)
diskspec.device.key = -1
self.change_detected = True
self.configspec.deviceChange.append(diskspec)
def configure_disks(self, vm_obj):
# Ignore empty disk list, this permits to keep disks when deploying a template/cloning a VM
if len(self.params['disk']) == 0:
return
scsi_ctl = self.get_vm_scsi_controller(vm_obj)
# Create scsi controller only if we are deploying a new VM, not a template or reconfiguring
if vm_obj is None or scsi_ctl is None:
scsi_ctl = self.device_helper.create_scsi_controller(self.get_scsi_type())
self.change_detected = True
self.configspec.deviceChange.append(scsi_ctl)
disks = [x for x in vm_obj.config.hardware.device if isinstance(x, vim.vm.device.VirtualDisk)] \
if vm_obj is not None else None
if disks is not None and self.params.get('disk') and len(self.params.get('disk')) < len(disks):
self.module.fail_json(msg="Provided disks configuration has less disks than "
"the target object (%d vs %d)" % (len(self.params.get('disk')), len(disks)))
disk_index = 0
for expected_disk_spec in self.params.get('disk'):
disk_modified = False
# If we are manipulating and existing objects which has disks and disk_index is in disks
if vm_obj is not None and disks is not None and disk_index < len(disks):
diskspec = vim.vm.device.VirtualDeviceSpec()
# set the operation to edit so that it knows to keep other settings
diskspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
diskspec.device = disks[disk_index]
else:
diskspec = self.device_helper.create_scsi_disk(scsi_ctl, disk_index)
disk_modified = True
# increment index for next disk search
disk_index += 1
# index 7 is reserved to SCSI controller
if disk_index == 7:
disk_index += 1
if 'disk_mode' in expected_disk_spec:
disk_mode = expected_disk_spec.get('disk_mode', 'persistent').lower()
valid_disk_mode = ['persistent', 'independent_persistent', 'independent_nonpersistent']
if disk_mode not in valid_disk_mode:
self.module.fail_json(msg="disk_mode specified is not valid."
" Should be one of ['%s']" % "', '".join(valid_disk_mode))
if (vm_obj and diskspec.device.backing.diskMode != disk_mode) or (vm_obj is None):
diskspec.device.backing.diskMode = disk_mode
disk_modified = True
else:
diskspec.device.backing.diskMode = "persistent"
# is it thin?
if 'type' in expected_disk_spec:
disk_type = expected_disk_spec.get('type', '').lower()
if disk_type == 'thin':
diskspec.device.backing.thinProvisioned = True
elif disk_type == 'eagerzeroedthick':
diskspec.device.backing.eagerlyScrub = True
if 'filename' in expected_disk_spec and expected_disk_spec['filename'] is not None:
self.add_existing_vmdk(vm_obj, expected_disk_spec, diskspec, scsi_ctl)
continue
elif vm_obj is None or self.params['template']:
# We are creating new VM or from Template
diskspec.fileOperation = vim.vm.device.VirtualDeviceSpec.FileOperation.create
# which datastore?
if expected_disk_spec.get('datastore'):
# TODO: This is already handled by the relocation spec,
# but it needs to eventually be handled for all the
# other disks defined
pass
kb = self.get_configured_disk_size(expected_disk_spec)
# VMware doesn't allow to reduce disk sizes
if kb < diskspec.device.capacityInKB:
self.module.fail_json(
msg="Given disk size is smaller than found (%d < %d). Reducing disks is not allowed." %
(kb, diskspec.device.capacityInKB))
if kb != diskspec.device.capacityInKB or disk_modified:
diskspec.device.capacityInKB = kb
self.configspec.deviceChange.append(diskspec)
self.change_detected = True
def select_host(self):
hostsystem = self.cache.get_esx_host(self.params['esxi_hostname'])
if not hostsystem:
self.module.fail_json(msg='Failed to find ESX host "%(esxi_hostname)s"' % self.params)
if hostsystem.runtime.connectionState != 'connected' or hostsystem.runtime.inMaintenanceMode:
self.module.fail_json(msg='ESXi "%(esxi_hostname)s" is in invalid state or in maintenance mode.' % self.params)
return hostsystem
def autoselect_datastore(self):
datastore = None
datastores = self.cache.get_all_objs(self.content, [vim.Datastore])
if datastores is None or len(datastores) == 0:
self.module.fail_json(msg="Unable to find a datastore list when autoselecting")
datastore_freespace = 0
for ds in datastores:
if ds.summary.freeSpace > datastore_freespace:
datastore = ds
datastore_freespace = ds.summary.freeSpace
return datastore
def get_recommended_datastore(self, datastore_cluster_obj=None):
"""
Function to return Storage DRS recommended datastore from datastore cluster
Args:
datastore_cluster_obj: datastore cluster managed object
Returns: Name of recommended datastore from the given datastore cluster
"""
if datastore_cluster_obj is None:
return None
# Check if Datastore Cluster provided by user is SDRS ready
sdrs_status = datastore_cluster_obj.podStorageDrsEntry.storageDrsConfig.podConfig.enabled
if sdrs_status:
# We can get storage recommendation only if SDRS is enabled on given datastorage cluster
pod_sel_spec = vim.storageDrs.PodSelectionSpec()
pod_sel_spec.storagePod = datastore_cluster_obj
storage_spec = vim.storageDrs.StoragePlacementSpec()
storage_spec.podSelectionSpec = pod_sel_spec
storage_spec.type = 'create'
try:
rec = self.content.storageResourceManager.RecommendDatastores(storageSpec=storage_spec)
rec_action = rec.recommendations[0].action[0]
return rec_action.destination.name
except Exception:
# There is some error so we fall back to general workflow
pass
datastore = None
datastore_freespace = 0
for ds in datastore_cluster_obj.childEntity:
if isinstance(ds, vim.Datastore) and ds.summary.freeSpace > datastore_freespace:
# If datastore field is provided, filter destination datastores
datastore = ds
datastore_freespace = ds.summary.freeSpace
if datastore:
return datastore.name
return None
def select_datastore(self, vm_obj=None):
datastore = None
datastore_name = None
if len(self.params['disk']) != 0:
# TODO: really use the datastore for newly created disks
if 'autoselect_datastore' in self.params['disk'][0] and self.params['disk'][0]['autoselect_datastore']:
datastores = self.cache.get_all_objs(self.content, [vim.Datastore])
datastores = [x for x in datastores if self.cache.get_parent_datacenter(x).name == self.params['datacenter']]
if datastores is None or len(datastores) == 0:
self.module.fail_json(msg="Unable to find a datastore list when autoselecting")
datastore_freespace = 0
for ds in datastores:
if (ds.summary.freeSpace > datastore_freespace) or (ds.summary.freeSpace == datastore_freespace and not datastore):
# If datastore field is provided, filter destination datastores
if 'datastore' in self.params['disk'][0] and \
isinstance(self.params['disk'][0]['datastore'], str) and \
ds.name.find(self.params['disk'][0]['datastore']) < 0:
continue
datastore = ds
datastore_name = datastore.name
datastore_freespace = ds.summary.freeSpace
elif 'datastore' in self.params['disk'][0]:
datastore_name = self.params['disk'][0]['datastore']
# Check if user has provided datastore cluster first
datastore_cluster = self.cache.find_obj(self.content, [vim.StoragePod], datastore_name)
if datastore_cluster:
# If user specified datastore cluster so get recommended datastore
datastore_name = self.get_recommended_datastore(datastore_cluster_obj=datastore_cluster)
# Check if get_recommended_datastore or user specified datastore exists or not
datastore = self.cache.find_obj(self.content, [vim.Datastore], datastore_name)
else:
self.module.fail_json(msg="Either datastore or autoselect_datastore should be provided to select datastore")
if not datastore and self.params['template']:
# use the template's existing DS
disks = [x for x in vm_obj.config.hardware.device if isinstance(x, vim.vm.device.VirtualDisk)]
if disks:
datastore = disks[0].backing.datastore
datastore_name = datastore.name
# validation
if datastore:
dc = self.cache.get_parent_datacenter(datastore)
if dc.name != self.params['datacenter']:
datastore = self.autoselect_datastore()
datastore_name = datastore.name
if not datastore:
if len(self.params['disk']) != 0 or self.params['template'] is None:
self.module.fail_json(msg="Unable to find the datastore with given parameters."
" This could mean, %s is a non-existent virtual machine and module tried to"
" deploy it as new virtual machine with no disk. Please specify disks parameter"
" or specify template to clone from." % self.params['name'])
self.module.fail_json(msg="Failed to find a matching datastore")
return datastore, datastore_name
def obj_has_parent(self, obj, parent):
if obj is None and parent is None:
raise AssertionError()
current_parent = obj
while True:
if current_parent.name == parent.name:
return True
# Check if we have reached till root folder
moid = current_parent._moId
if moid in ['group-d1', 'ha-folder-root']:
return False
current_parent = current_parent.parent
if current_parent is None:
return False
def get_scsi_type(self):
disk_controller_type = "paravirtual"
# set cpu/memory/etc
if 'hardware' in self.params:
if 'scsi' in self.params['hardware']:
if self.params['hardware']['scsi'] in ['buslogic', 'paravirtual', 'lsilogic', 'lsilogicsas']:
disk_controller_type = self.params['hardware']['scsi']
else:
self.module.fail_json(msg="hardware.scsi attribute should be 'paravirtual' or 'lsilogic'")
return disk_controller_type
def find_folder(self, searchpath):
""" Walk inventory objects one position of the searchpath at a time """
# split the searchpath so we can iterate through it
paths = [x.replace('/', '') for x in searchpath.split('/')]
paths_total = len(paths) - 1
position = 0
# recursive walk while looking for next element in searchpath
root = self.content.rootFolder
while root and position <= paths_total:
change = False
if hasattr(root, 'childEntity'):
for child in root.childEntity:
if child.name == paths[position]:
root = child
position += 1
change = True
break
elif isinstance(root, vim.Datacenter):
if hasattr(root, 'vmFolder'):
if root.vmFolder.name == paths[position]:
root = root.vmFolder
position += 1
change = True
else:
root = None
if not change:
root = None
return root
def get_resource_pool(self, cluster=None, host=None, resource_pool=None):
""" Get a resource pool, filter on cluster, esxi_hostname or resource_pool if given """
cluster_name = cluster or self.params.get('cluster', None)
host_name = host or self.params.get('esxi_hostname', None)
resource_pool_name = resource_pool or self.params.get('resource_pool', None)
# get the datacenter object
datacenter = find_obj(self.content, [vim.Datacenter], self.params['datacenter'])
if not datacenter:
self.module.fail_json(msg='Unable to find datacenter "%s"' % self.params['datacenter'])
# if cluster is given, get the cluster object
if cluster_name:
cluster = find_obj(self.content, [vim.ComputeResource], cluster_name, folder=datacenter)
if not cluster:
self.module.fail_json(msg='Unable to find cluster "%s"' % cluster_name)
# if host is given, get the cluster object using the host
elif host_name:
host = find_obj(self.content, [vim.HostSystem], host_name, folder=datacenter)
if not host:
self.module.fail_json(msg='Unable to find host "%s"' % host_name)
cluster = host.parent
else:
cluster = None
# get resource pools limiting search to cluster or datacenter
resource_pool = find_obj(self.content, [vim.ResourcePool], resource_pool_name, folder=cluster or datacenter)
if not resource_pool:
if resource_pool_name:
self.module.fail_json(msg='Unable to find resource_pool "%s"' % resource_pool_name)
else:
self.module.fail_json(msg='Unable to find resource pool, need esxi_hostname, resource_pool, or cluster')
return resource_pool
def deploy_vm(self):
# https://github.com/vmware/pyvmomi-community-samples/blob/master/samples/clone_vm.py
# https://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.vm.CloneSpec.html
# https://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.vm.ConfigSpec.html
# https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.vm.RelocateSpec.html
# FIXME:
# - static IPs
self.folder = self.params.get('folder', None)
if self.folder is None:
self.module.fail_json(msg="Folder is required parameter while deploying new virtual machine")
# Prepend / if it was missing from the folder path, also strip trailing slashes
if not self.folder.startswith('/'):
self.folder = '/%(folder)s' % self.params
self.folder = self.folder.rstrip('/')
datacenter = self.cache.find_obj(self.content, [vim.Datacenter], self.params['datacenter'])
if datacenter is None:
self.module.fail_json(msg='No datacenter named %(datacenter)s was found' % self.params)
dcpath = compile_folder_path_for_object(datacenter)
# Nested folder does not have trailing /
if not dcpath.endswith('/'):
dcpath += '/'
# Check for full path first in case it was already supplied
if (self.folder.startswith(dcpath + self.params['datacenter'] + '/vm') or
self.folder.startswith(dcpath + '/' + self.params['datacenter'] + '/vm')):
fullpath = self.folder
elif self.folder.startswith('/vm/') or self.folder == '/vm':
fullpath = "%s%s%s" % (dcpath, self.params['datacenter'], self.folder)
elif self.folder.startswith('/'):
fullpath = "%s%s/vm%s" % (dcpath, self.params['datacenter'], self.folder)
else:
fullpath = "%s%s/vm/%s" % (dcpath, self.params['datacenter'], self.folder)
f_obj = self.content.searchIndex.FindByInventoryPath(fullpath)
# abort if no strategy was successful
if f_obj is None:
# Add some debugging values in failure.
details = {
'datacenter': datacenter.name,
'datacenter_path': dcpath,
'folder': self.folder,
'full_search_path': fullpath,
}
self.module.fail_json(msg='No folder %s matched in the search path : %s' % (self.folder, fullpath),
details=details)
destfolder = f_obj
if self.params['template']:
vm_obj = self.get_vm_or_template(template_name=self.params['template'])
if vm_obj is None:
self.module.fail_json(msg="Could not find a template named %(template)s" % self.params)
else:
vm_obj = None
# always get a resource_pool
resource_pool = self.get_resource_pool()
# set the destination datastore for VM & disks
if self.params['datastore']:
# Give precedence to datastore value provided by user
# User may want to deploy VM to specific datastore.
datastore_name = self.params['datastore']
# Check if user has provided datastore cluster first
datastore_cluster = self.cache.find_obj(self.content, [vim.StoragePod], datastore_name)
if datastore_cluster:
# If user specified datastore cluster so get recommended datastore
datastore_name = self.get_recommended_datastore(datastore_cluster_obj=datastore_cluster)
# Check if get_recommended_datastore or user specified datastore exists or not
datastore = self.cache.find_obj(self.content, [vim.Datastore], datastore_name)
else:
(datastore, datastore_name) = self.select_datastore(vm_obj)
self.configspec = vim.vm.ConfigSpec()
self.configspec.deviceChange = []
# create the relocation spec
self.relospec = vim.vm.RelocateSpec()
self.relospec.deviceChange = []
self.configure_guestid(vm_obj=vm_obj, vm_creation=True)
self.configure_cpu_and_memory(vm_obj=vm_obj, vm_creation=True)
self.configure_hardware_params(vm_obj=vm_obj)
self.configure_resource_alloc_info(vm_obj=vm_obj)
self.configure_vapp_properties(vm_obj=vm_obj)
self.configure_disks(vm_obj=vm_obj)
self.configure_network(vm_obj=vm_obj)
self.configure_cdrom(vm_obj=vm_obj)
# Find if we need network customizations (find keys in dictionary that requires customizations)
network_changes = False
for nw in self.params['networks']:
for key in nw:
# We don't need customizations for these keys
if key not in ('device_type', 'mac', 'name', 'vlan', 'type', 'start_connected'):
network_changes = True
break
if len(self.params['customization']) > 0 or network_changes or self.params.get('customization_spec') is not None:
self.customize_vm(vm_obj=vm_obj)
clonespec = None
clone_method = None
try:
if self.params['template']:
# Only select specific host when ESXi hostname is provided
if self.params['esxi_hostname']:
self.relospec.host = self.select_host()
self.relospec.datastore = datastore
# Convert disk present in template if is set
if self.params['convert']:
for device in vm_obj.config.hardware.device:
if hasattr(device.backing, 'fileName'):
disk_locator = vim.vm.RelocateSpec.DiskLocator()
disk_locator.diskBackingInfo = vim.vm.device.VirtualDisk.FlatVer2BackingInfo()
if self.params['convert'] in ['thin']:
disk_locator.diskBackingInfo.thinProvisioned = True
if self.params['convert'] in ['eagerzeroedthick']:
disk_locator.diskBackingInfo.eagerlyScrub = True
if self.params['convert'] in ['thick']:
disk_locator.diskBackingInfo.diskMode = "persistent"
disk_locator.diskId = device.key
disk_locator.datastore = datastore
self.relospec.disk.append(disk_locator)
# https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.vm.RelocateSpec.html
# > pool: For a clone operation from a template to a virtual machine, this argument is required.
self.relospec.pool = resource_pool
linked_clone = self.params.get('linked_clone')
snapshot_src = self.params.get('snapshot_src', None)
if linked_clone:
if snapshot_src is not None:
self.relospec.diskMoveType = vim.vm.RelocateSpec.DiskMoveOptions.createNewChildDiskBacking
else:
self.module.fail_json(msg="Parameter 'linked_src' and 'snapshot_src' are"
" required together for linked clone operation.")
clonespec = vim.vm.CloneSpec(template=self.params['is_template'], location=self.relospec)
if self.customspec:
clonespec.customization = self.customspec
if snapshot_src is not None:
if vm_obj.snapshot is None:
self.module.fail_json(msg="No snapshots present for virtual machine or template [%(template)s]" % self.params)
snapshot = self.get_snapshots_by_name_recursively(snapshots=vm_obj.snapshot.rootSnapshotList,
snapname=snapshot_src)
if len(snapshot) != 1:
self.module.fail_json(msg='virtual machine "%(template)s" does not contain'
' snapshot named "%(snapshot_src)s"' % self.params)
clonespec.snapshot = snapshot[0].snapshot
clonespec.config = self.configspec
clone_method = 'Clone'
try:
task = vm_obj.Clone(folder=destfolder, name=self.params['name'], spec=clonespec)
except vim.fault.NoPermission as e:
self.module.fail_json(msg="Failed to clone virtual machine %s to folder %s "
"due to permission issue: %s" % (self.params['name'],
destfolder,
to_native(e.msg)))
self.change_detected = True
else:
# ConfigSpec require name for VM creation
self.configspec.name = self.params['name']
self.configspec.files = vim.vm.FileInfo(logDirectory=None,
snapshotDirectory=None,
suspendDirectory=None,
vmPathName="[" + datastore_name + "]")
clone_method = 'CreateVM_Task'
try:
task = destfolder.CreateVM_Task(config=self.configspec, pool=resource_pool)
except vmodl.fault.InvalidRequest as e:
self.module.fail_json(msg="Failed to create virtual machine due to invalid configuration "
"parameter %s" % to_native(e.msg))
except vim.fault.RestrictedVersion as e:
self.module.fail_json(msg="Failed to create virtual machine due to "
"product versioning restrictions: %s" % to_native(e.msg))
self.change_detected = True
self.wait_for_task(task)
except TypeError as e:
self.module.fail_json(msg="TypeError was returned, please ensure to give correct inputs. %s" % to_text(e))
if task.info.state == 'error':
# https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2021361
# https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2173
# provide these to the user for debugging
clonespec_json = serialize_spec(clonespec)
configspec_json = serialize_spec(self.configspec)
kwargs = {
'changed': self.change_applied,
'failed': True,
'msg': task.info.error.msg,
'clonespec': clonespec_json,
'configspec': configspec_json,
'clone_method': clone_method
}
return kwargs
else:
# set annotation
vm = task.info.result
if self.params['annotation']:
annotation_spec = vim.vm.ConfigSpec()
annotation_spec.annotation = str(self.params['annotation'])
task = vm.ReconfigVM_Task(annotation_spec)
self.wait_for_task(task)
if task.info.state == 'error':
return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'annotation'}
if self.params['customvalues']:
vm_custom_spec = vim.vm.ConfigSpec()
self.customize_customvalues(vm_obj=vm, config_spec=vm_custom_spec)
task = vm.ReconfigVM_Task(vm_custom_spec)
self.wait_for_task(task)
if task.info.state == 'error':
return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'customvalues'}
if self.params['wait_for_ip_address'] or self.params['wait_for_customization'] or self.params['state'] in ['poweredon', 'restarted']:
set_vm_power_state(self.content, vm, 'poweredon', force=False)
if self.params['wait_for_ip_address']:
self.wait_for_vm_ip(vm)
if self.params['wait_for_customization']:
is_customization_ok = self.wait_for_customization(vm)
if not is_customization_ok:
vm_facts = self.gather_facts(vm)
return {'changed': self.change_applied, 'failed': True, 'instance': vm_facts, 'op': 'customization'}
vm_facts = self.gather_facts(vm)
return {'changed': self.change_applied, 'failed': False, 'instance': vm_facts}
def get_snapshots_by_name_recursively(self, snapshots, snapname):
snap_obj = []
for snapshot in snapshots:
if snapshot.name == snapname:
snap_obj.append(snapshot)
else:
snap_obj = snap_obj + self.get_snapshots_by_name_recursively(snapshot.childSnapshotList, snapname)
return snap_obj
def reconfigure_vm(self):
self.configspec = vim.vm.ConfigSpec()
self.configspec.deviceChange = []
# create the relocation spec
self.relospec = vim.vm.RelocateSpec()
self.relospec.deviceChange = []
self.configure_guestid(vm_obj=self.current_vm_obj)
self.configure_cpu_and_memory(vm_obj=self.current_vm_obj)
self.configure_hardware_params(vm_obj=self.current_vm_obj)
self.configure_disks(vm_obj=self.current_vm_obj)
self.configure_network(vm_obj=self.current_vm_obj)
self.configure_cdrom(vm_obj=self.current_vm_obj)
self.customize_customvalues(vm_obj=self.current_vm_obj, config_spec=self.configspec)
self.configure_resource_alloc_info(vm_obj=self.current_vm_obj)
self.configure_vapp_properties(vm_obj=self.current_vm_obj)
if self.params['annotation'] and self.current_vm_obj.config.annotation != self.params['annotation']:
self.configspec.annotation = str(self.params['annotation'])
self.change_detected = True
if self.params['resource_pool']:
self.relospec.pool = self.get_resource_pool()
if self.relospec.pool != self.current_vm_obj.resourcePool:
task = self.current_vm_obj.RelocateVM_Task(spec=self.relospec)
self.wait_for_task(task)
if task.info.state == 'error':
return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'relocate'}
# Only send VMware task if we see a modification
if self.change_detected:
task = None
try:
task = self.current_vm_obj.ReconfigVM_Task(spec=self.configspec)
except vim.fault.RestrictedVersion as e:
self.module.fail_json(msg="Failed to reconfigure virtual machine due to"
" product versioning restrictions: %s" % to_native(e.msg))
self.wait_for_task(task)
if task.info.state == 'error':
return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'reconfig'}
# Rename VM
if self.params['uuid'] and self.params['name'] and self.params['name'] != self.current_vm_obj.config.name:
task = self.current_vm_obj.Rename_Task(self.params['name'])
self.wait_for_task(task)
if task.info.state == 'error':
return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'rename'}
# Mark VM as Template
if self.params['is_template'] and not self.current_vm_obj.config.template:
try:
self.current_vm_obj.MarkAsTemplate()
self.change_applied = True
except vmodl.fault.NotSupported as e:
self.module.fail_json(msg="Failed to mark virtual machine [%s] "
"as template: %s" % (self.params['name'], e.msg))
# Mark Template as VM
elif not self.params['is_template'] and self.current_vm_obj.config.template:
resource_pool = self.get_resource_pool()
kwargs = dict(pool=resource_pool)
if self.params.get('esxi_hostname', None):
host_system_obj = self.select_host()
kwargs.update(host=host_system_obj)
try:
self.current_vm_obj.MarkAsVirtualMachine(**kwargs)
self.change_applied = True
except vim.fault.InvalidState as invalid_state:
self.module.fail_json(msg="Virtual machine is not marked"
" as template : %s" % to_native(invalid_state.msg))
except vim.fault.InvalidDatastore as invalid_ds:
self.module.fail_json(msg="Converting template to virtual machine"
" operation cannot be performed on the"
" target datastores: %s" % to_native(invalid_ds.msg))
except vim.fault.CannotAccessVmComponent as cannot_access:
self.module.fail_json(msg="Failed to convert template to virtual machine"
" as operation unable access virtual machine"
" component: %s" % to_native(cannot_access.msg))
except vmodl.fault.InvalidArgument as invalid_argument:
self.module.fail_json(msg="Failed to convert template to virtual machine"
" due to : %s" % to_native(invalid_argument.msg))
except Exception as generic_exc:
self.module.fail_json(msg="Failed to convert template to virtual machine"
" due to generic error : %s" % to_native(generic_exc))
# Automatically update VMware UUID when converting template to VM.
# This avoids an interactive prompt during VM startup.
uuid_action = [x for x in self.current_vm_obj.config.extraConfig if x.key == "uuid.action"]
if not uuid_action:
uuid_action_opt = vim.option.OptionValue()
uuid_action_opt.key = "uuid.action"
uuid_action_opt.value = "create"
self.configspec.extraConfig.append(uuid_action_opt)
self.change_detected = True
# add customize existing VM after VM re-configure
if 'existing_vm' in self.params['customization'] and self.params['customization']['existing_vm']:
if self.current_vm_obj.config.template:
self.module.fail_json(msg="VM is template, not support guest OS customization.")
if self.current_vm_obj.runtime.powerState != vim.VirtualMachinePowerState.poweredOff:
self.module.fail_json(msg="VM is not in poweroff state, can not do guest OS customization.")
cus_result = self.customize_exist_vm()
if cus_result['failed']:
return cus_result
vm_facts = self.gather_facts(self.current_vm_obj)
return {'changed': self.change_applied, 'failed': False, 'instance': vm_facts}
def customize_exist_vm(self):
task = None
# Find if we need network customizations (find keys in dictionary that requires customizations)
network_changes = False
for nw in self.params['networks']:
for key in nw:
# We don't need customizations for these keys
if key not in ('device_type', 'mac', 'name', 'vlan', 'type', 'start_connected'):
network_changes = True
break
if len(self.params['customization']) > 1 or network_changes or self.params.get('customization_spec'):
self.customize_vm(vm_obj=self.current_vm_obj)
try:
task = self.current_vm_obj.CustomizeVM_Task(self.customspec)
except vim.fault.CustomizationFault as e:
self.module.fail_json(msg="Failed to customization virtual machine due to CustomizationFault: %s" % to_native(e.msg))
except vim.fault.RuntimeFault as e:
self.module.fail_json(msg="failed to customization virtual machine due to RuntimeFault: %s" % to_native(e.msg))
except Exception as e:
self.module.fail_json(msg="failed to customization virtual machine due to fault: %s" % to_native(e.msg))
self.wait_for_task(task)
if task.info.state == 'error':
return {'changed': self.change_applied, 'failed': True, 'msg': task.info.error.msg, 'op': 'customize_exist'}
if self.params['wait_for_customization']:
set_vm_power_state(self.content, self.current_vm_obj, 'poweredon', force=False)
is_customization_ok = self.wait_for_customization(self.current_vm_obj)
if not is_customization_ok:
return {'changed': self.change_applied, 'failed': True, 'op': 'wait_for_customize_exist'}
return {'changed': self.change_applied, 'failed': False}
def wait_for_task(self, task, poll_interval=1):
"""
Wait for a VMware task to complete. Terminal states are 'error' and 'success'.
Inputs:
- task: the task to wait for
- poll_interval: polling interval to check the task, in seconds
Modifies:
- self.change_applied
"""
# https://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.Task.html
# https://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.TaskInfo.html
# https://github.com/virtdevninja/pyvmomi-community-samples/blob/master/samples/tools/tasks.py
while task.info.state not in ['error', 'success']:
time.sleep(poll_interval)
self.change_applied = self.change_applied or task.info.state == 'success'
def wait_for_vm_ip(self, vm, poll=100, sleep=5):
ips = None
facts = {}
thispoll = 0
while not ips and thispoll <= poll:
newvm = self.get_vm()
facts = self.gather_facts(newvm)
if facts['ipv4'] or facts['ipv6']:
ips = True
else:
time.sleep(sleep)
thispoll += 1
return facts
def get_vm_events(self, vm, eventTypeIdList):
byEntity = vim.event.EventFilterSpec.ByEntity(entity=vm, recursion="self")
filterSpec = vim.event.EventFilterSpec(entity=byEntity, eventTypeId=eventTypeIdList)
eventManager = self.content.eventManager
return eventManager.QueryEvent(filterSpec)
def wait_for_customization(self, vm, poll=10000, sleep=10):
thispoll = 0
while thispoll <= poll:
eventStarted = self.get_vm_events(vm, ['CustomizationStartedEvent'])
if len(eventStarted):
thispoll = 0
while thispoll <= poll:
eventsFinishedResult = self.get_vm_events(vm, ['CustomizationSucceeded', 'CustomizationFailed'])
if len(eventsFinishedResult):
if not isinstance(eventsFinishedResult[0], vim.event.CustomizationSucceeded):
self.module.fail_json(msg='Customization failed with error {0}:\n{1}'.format(
eventsFinishedResult[0]._wsdlName, eventsFinishedResult[0].fullFormattedMessage))
return False
break
else:
time.sleep(sleep)
thispoll += 1
return True
else:
time.sleep(sleep)
thispoll += 1
self.module.fail_json('waiting for customizations timed out.')
return False
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(
state=dict(type='str', default='present',
choices=['absent', 'poweredoff', 'poweredon', 'present', 'rebootguest', 'restarted', 'shutdownguest', 'suspended']),
template=dict(type='str', aliases=['template_src']),
is_template=dict(type='bool', default=False),
annotation=dict(type='str', aliases=['notes']),
customvalues=dict(type='list', default=[]),
name=dict(type='str'),
name_match=dict(type='str', choices=['first', 'last'], default='first'),
uuid=dict(type='str'),
use_instance_uuid=dict(type='bool', default=False),
folder=dict(type='str'),
guest_id=dict(type='str'),
disk=dict(type='list', default=[]),
cdrom=dict(type='dict', default={}),
hardware=dict(type='dict', default={}),
force=dict(type='bool', default=False),
datacenter=dict(type='str', default='ha-datacenter'),
esxi_hostname=dict(type='str'),
cluster=dict(type='str'),
wait_for_ip_address=dict(type='bool', default=False),
state_change_timeout=dict(type='int', default=0),
snapshot_src=dict(type='str'),
linked_clone=dict(type='bool', default=False),
networks=dict(type='list', default=[]),
resource_pool=dict(type='str'),
customization=dict(type='dict', default={}, no_log=True),
customization_spec=dict(type='str', default=None),
wait_for_customization=dict(type='bool', default=False),
vapp_properties=dict(type='list', default=[]),
datastore=dict(type='str'),
convert=dict(type='str', choices=['thin', 'thick', 'eagerzeroedthick']),
)
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=True,
mutually_exclusive=[
['cluster', 'esxi_hostname'],
],
required_one_of=[
['name', 'uuid'],
],
)
result = {'failed': False, 'changed': False}
pyv = PyVmomiHelper(module)
# Check if the VM exists before continuing
vm = pyv.get_vm()
# VM already exists
if vm:
if module.params['state'] == 'absent':
# destroy it
if module.check_mode:
result.update(
vm_name=vm.name,
changed=True,
current_powerstate=vm.summary.runtime.powerState.lower(),
desired_operation='remove_vm',
)
module.exit_json(**result)
if module.params['force']:
# has to be poweredoff first
set_vm_power_state(pyv.content, vm, 'poweredoff', module.params['force'])
result = pyv.remove_vm(vm)
elif module.params['state'] == 'present':
if module.check_mode:
result.update(
vm_name=vm.name,
changed=True,
desired_operation='reconfigure_vm',
)
module.exit_json(**result)
result = pyv.reconfigure_vm()
elif module.params['state'] in ['poweredon', 'poweredoff', 'restarted', 'suspended', 'shutdownguest', 'rebootguest']:
if module.check_mode:
result.update(
vm_name=vm.name,
changed=True,
current_powerstate=vm.summary.runtime.powerState.lower(),
desired_operation='set_vm_power_state',
)
module.exit_json(**result)
# set powerstate
tmp_result = set_vm_power_state(pyv.content, vm, module.params['state'], module.params['force'], module.params['state_change_timeout'])
if tmp_result['changed']:
result["changed"] = True
if module.params['state'] in ['poweredon', 'restarted', 'rebootguest'] and module.params['wait_for_ip_address']:
wait_result = wait_for_vm_ip(pyv.content, vm)
if not wait_result:
module.fail_json(msg='Waiting for IP address timed out')
tmp_result['instance'] = wait_result
if not tmp_result["failed"]:
result["failed"] = False
result['instance'] = tmp_result['instance']
if tmp_result["failed"]:
result["failed"] = True
result["msg"] = tmp_result["msg"]
else:
# This should not happen
raise AssertionError()
# VM doesn't exist
else:
if module.params['state'] in ['poweredon', 'poweredoff', 'present', 'restarted', 'suspended']:
if module.check_mode:
result.update(
changed=True,
desired_operation='deploy_vm',
)
module.exit_json(**result)
result = pyv.deploy_vm()
if result['failed']:
module.fail_json(msg='Failed to create a virtual machine : %s' % result['msg'])
if result['failed']:
module.fail_json(**result)
else:
module.exit_json(**result)
if __name__ == '__main__':
main()
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,721 |
VMware: vmware_guest throws vmdk already exists
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
<!--- Explain the problem briefly below -->
vmware_guest throws error that vmdk already exists although it does not. It is created during running the module but somehow fails.
pyvmomi-6.7.1.2018.12
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
vmware_guest
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
2.8.1
```
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```yaml
- name: Create new VM
vmware_guest:
hostname: "{{ vcenter_hostname }}"
esxi_hostname: "{{ esxi_host }}"
username: '{{domain_user}}'
password: "{{ domain_user_password }}"
validate_certs: False
datacenter: TM
name: "{{ vm_hostname }}"
folder: "{{ vm_destination }}"
state: poweredon
disk:
- size_gb: '{{ disk_size }}'
type: thin
autoselect_datastore: True
hardware:
memory_mb: "{{ memory }}"
num_cpus: "{{ cores }}"
num_cpu_cores_per_socket: "{{ cores }}"
networks:
- name: LAN
domain: "{{ domain }}"
dns_servers:
- "{{ dns1 }}"
- "{{ dns2 }}"
type: static
ip: "{{ ip }}"
netmask: 255.255.254.0
gateway: 192.168.1.5
customization:
autologon: True
hostname: "{{ vm_hostname }}"
domain: "{{ domain }}"
password: vagrant
domainadmin: "{{ domain_user }}"
domainadminpassword: "{{ domain_user_password }}"
joindomain: "{{ domain }}"
timezone: 105
runonce:
- powershell.exe -ExecutionPolicy Unrestricted -File C:\StartupScripts\ConfigureRemotingForAnsible.ps1 -ForceNewSSLCert -EnableCredSSP
- powershell.exe -ExecutionPolicy Unrestricted -File C:\StartupScripts\DisableFirewall.ps1
wait_for_customization: yes
template: "{{ vm_template }}"
wait_for_ip_address: yes
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
Should just create the VM.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```paste below
Failed to create a virtual machine : Cannot complete the operation because the file or folder [EL02] ********/********.vmdk already exists"
```
|
https://github.com/ansible/ansible/issues/58721
|
https://github.com/ansible/ansible/pull/58737
|
b6273e91cfbcf3f9c9ab849b6803c6a8a3aa7c3d
|
3a5d13b0d761bb5ac5a83d14daa37848e72ec857
| 2019-07-04T09:16:34Z |
python
| 2019-07-15T04:39:54Z |
test/integration/targets/vmware_guest/tasks/clone_resize_disks.yml
| |
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,721 |
VMware: vmware_guest throws vmdk already exists
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
<!--- Explain the problem briefly below -->
vmware_guest throws error that vmdk already exists although it does not. It is created during running the module but somehow fails.
pyvmomi-6.7.1.2018.12
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
vmware_guest
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
2.8.1
```
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```yaml
- name: Create new VM
vmware_guest:
hostname: "{{ vcenter_hostname }}"
esxi_hostname: "{{ esxi_host }}"
username: '{{domain_user}}'
password: "{{ domain_user_password }}"
validate_certs: False
datacenter: TM
name: "{{ vm_hostname }}"
folder: "{{ vm_destination }}"
state: poweredon
disk:
- size_gb: '{{ disk_size }}'
type: thin
autoselect_datastore: True
hardware:
memory_mb: "{{ memory }}"
num_cpus: "{{ cores }}"
num_cpu_cores_per_socket: "{{ cores }}"
networks:
- name: LAN
domain: "{{ domain }}"
dns_servers:
- "{{ dns1 }}"
- "{{ dns2 }}"
type: static
ip: "{{ ip }}"
netmask: 255.255.254.0
gateway: 192.168.1.5
customization:
autologon: True
hostname: "{{ vm_hostname }}"
domain: "{{ domain }}"
password: vagrant
domainadmin: "{{ domain_user }}"
domainadminpassword: "{{ domain_user_password }}"
joindomain: "{{ domain }}"
timezone: 105
runonce:
- powershell.exe -ExecutionPolicy Unrestricted -File C:\StartupScripts\ConfigureRemotingForAnsible.ps1 -ForceNewSSLCert -EnableCredSSP
- powershell.exe -ExecutionPolicy Unrestricted -File C:\StartupScripts\DisableFirewall.ps1
wait_for_customization: yes
template: "{{ vm_template }}"
wait_for_ip_address: yes
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
Should just create the VM.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```paste below
Failed to create a virtual machine : Cannot complete the operation because the file or folder [EL02] ********/********.vmdk already exists"
```
|
https://github.com/ansible/ansible/issues/58721
|
https://github.com/ansible/ansible/pull/58737
|
b6273e91cfbcf3f9c9ab849b6803c6a8a3aa7c3d
|
3a5d13b0d761bb5ac5a83d14daa37848e72ec857
| 2019-07-04T09:16:34Z |
python
| 2019-07-15T04:39:54Z |
test/integration/targets/vmware_guest/tasks/main.yml
|
# Test code for the vmware_guest module.
# Copyright: (c) 2017, James Tanner <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
- import_role:
name: prepare_vmware_tests
vars:
setup_datacenter: true
setup_attach_host: true
setup_datastore: true
setup_virtualmachines: true
setup_resource_pool: true
- block:
- include: poweroff_d1_c1_f0.yml
- include: poweroff_d1_c1_f1.yml
- include: check_mode.yml
- include: clone_d1_c1_f0.yml
- include: create_d1_c1_f0.yml
- include: cdrom_d1_c1_f0.yml
- include: create_rp_d1_c1_f0.yml
- include: create_guest_invalid_d1_c1_f0.yml
- include: mac_address_d1_c1_f0.yml
- include: disk_type_d1_c1_f0.yml
- include: create_nw_d1_c1_f0.yml
- include: delete_vm.yml
- include: non_existent_vm_ops.yml
always:
- name: Remove VM
vmware_guest:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: no
cluster: "{{ ccr1 }}"
name: '{{ item }}'
force: yes
state: absent
with_items:
- CDROM-Test
- CDROM-Test-38679
- newvm_2
- newvm_3
- newvmnw_4
- DC0_H0_VM12
- import_role:
name: prepare_vmware_tests
vars:
setup_attach_host: true
setup_datastore: true
setup_virtualmachines: true
- block:
- include: network_negative_test.yml
# VCSIM does not return list of portgroups for dvswitch so commenting following TC
#- include: network_with_portgroup.yml
# Currently, VCSIM doesn't support DVPG (as portkeys are not available) so commenting this test
# - include: network_with_dvpg.yml
#- include: template_d1_c1_f0.yml
- include: vapp_d1_c1_f0.yml
- include: disk_size_d1_c1_f0.yml
- include: network_with_device.yml
- include: disk_mode_d1_c1_f0.yml
- include: linked_clone_d1_c1_f0.yml
always:
- name: Remove VM
vmware_guest:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: no
cluster: "{{ ccr1 }}"
name: '{{ item }}'
force: yes
state: absent
with_items:
- disk_mode_d1_c1_f0
- network_with_device
- new_vm_no_nw_type
- vApp-Test
- import_role:
name: prepare_vmware_tests
vars:
setup_attach_host: true
setup_datastore: true
setup_virtualmachines: true
- block:
- include: boot_firmware_d1_c1_f0.yml
# Failing, see: https://github.com/ansible/ansible/issues/57653
# - include: clone_with_convert.yml
# - include: clone_customize_guest_test.yml
- include: max_connections.yml
always:
- name: Remove VM
vmware_guest:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: no
cluster: "{{ ccr1 }}"
name: '{{ item }}'
force: yes
state: absent
with_items:
- newvm_DC0_H0_VM0
- newvm_DC0_H0_VM1
- newvm_efi_DC0_H0_VM0
- newvm_efi_DC0_H0_VM1
- newvm_mk_conn_DC0_H0_VM0
- newvm_mk_conn_DC0_H0_VM1
- thin_DC0_H0_VM0
- thin_DC0_H0_VM1
- thick_DC0_H0_VM0
- thick_DC0_H0_VM1
- eagerzeroedthick_DC0_H0_VM0
- eagerzeroedthick_DC0_H0_VM1
- net_customize_DC0_H0_VM0
- net_customize_DC0_H0_VM1
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 59,101 |
gcp_compute incorrectly prints data to screen, breaking JSON output for ansible-inventory
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
<!--- Explain the problem briefly below -->
`ansible-inventory` is supposed to return JSON...
but it does not when installing anisble@devel, and running a GCE inventory update with this `gcp_compute.yml` to use the gcp inventory plugin:
```
auth_kind: serviceaccount
filters: null
plugin: gcp_compute
projects:
- myproject
service_account_file: creds.json
```
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
gcp inventory plugin
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible-inventory --version
ansible-inventory 2.9.0.dev0
config file = /etc/ansible/ansible.cfg
configured module search path = ['/home/elijah/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /home/elijah/venvs/py36towerqa/lib64/python3.6/site-packages/ansible
executable location = /home/elijah/venvs/py36towerqa/bin/ansible-inventory
python version = 3.6.8 (default, Feb 19 2019, 21:10:40) [GCC 9.0.1 20190209 (Red Hat 9.0.1-0.4)]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
#no output
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
1) Create gcp_comput.yml and creds.json to access your gcp account
2) Create python36 venv
3) install [email protected]
4) run `ansible-inventory -i gcp_compute.yml --list > ouput.28`
5) Inspect the output, see that it is valid JSON.
6) install ansible@devel
4) run `ansible-inventory -i gcp_compute.yml --list > ouput.devel`
7) Inspect output, see that before the part that starts the JSON that looks like:
```
{
"_meta": {
"hostvars": {
```
there is a bug chunk of key/value pairs in a list:
```
[{'key': 'blahkey', 'value': 'blahvalue}, {'key': 'ssh-keys', 'value': 'somebody's key'} {'key': 'more keys', 'value': 'more values' ...... ]
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
JSON
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
List of key/value pairs then regular json ouput
<!--- Paste verbatim command output between quotes -->
```paste below
```
This is a tower blocker for the next release of ansible.
(private repo) https://github.com/ansible/tower/issues/3605
|
https://github.com/ansible/ansible/issues/59101
|
https://github.com/ansible/ansible/pull/59104
|
4898b0a4a298448677c2aee2a03157ba5b662759
|
a6d32eda84623305755ff46503c37d345a8d2feb
| 2019-07-15T14:26:18Z |
python
| 2019-07-15T17:26:19Z |
lib/ansible/plugins/inventory/gcp_compute.py
|
# Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
name: gcp_compute
plugin_type: inventory
short_description: Google Cloud Compute Engine inventory source
requirements:
- requests >= 2.18.4
- google-auth >= 1.3.0
extends_documentation_fragment:
- constructed
- inventory_cache
description:
- Get inventory hosts from Google Cloud Platform GCE.
- Uses a YAML configuration file that ends with gcp_compute.(yml|yaml) or gcp.(yml|yaml).
options:
plugin:
description: token that ensures this is a source file for the 'gcp_compute' plugin.
required: True
choices: ['gcp_compute']
zones:
description: A list of regions in which to describe GCE instances.
If none provided, it defaults to all zones available to a given project.
type: list
projects:
description: A list of projects in which to describe GCE instances.
type: list
required: True
filters:
description: >
A list of filter value pairs. Available filters are listed here
U(https://cloud.google.com/compute/docs/reference/rest/v1/instances/aggregatedList).
Each additional filter in the list will act be added as an AND condition
(filter1 and filter2)
type: list
hostnames:
description: A list of options that describe the ordering for which
hostnames should be assigned. Currently supported hostnames are
'public_ip', 'private_ip', or 'name'.
default: ['public_ip', 'private_ip', 'name']
type: list
auth_kind:
description:
- The type of credential used.
required: True
choices: ['application', 'serviceaccount', 'machineaccount']
env:
- name: GCP_AUTH_KIND
version_added: "2.8.2"
scopes:
description: list of authentication scopes
type: list
default: ['https://www.googleapis.com/auth/compute']
env:
- name: GCP_SCOPES
version_added: "2.8.2"
service_account_file:
description:
- The path of a Service Account JSON file if serviceaccount is selected as type.
type: path
env:
- name: GCP_SERVICE_ACCOUNT_FILE
version_added: "2.8.2"
- name: GCE_CREDENTIALS_FILE_PATH
version_added: "2.8"
service_account_contents:
description:
- A string representing the contents of a Service Account JSON file. This should not be passed in as a dictionary,
but a string that has the exact contents of a service account json file (valid JSON).
type: string
env:
- name: GCP_SERVICE_ACCOUNT_CONTENTS
version_added: "2.8.2"
service_account_email:
description:
- An optional service account email address if machineaccount is selected
and the user does not wish to use the default email.
env:
- name: GCP_SERVICE_ACCOUNT_EMAIL
version_added: "2.8.2"
vars_prefix:
description: prefix to apply to host variables, does not include facts nor params
default: ''
use_contrib_script_compatible_sanitization:
description:
- By default this plugin is using a general group name sanitization to create safe and usable group names for use in Ansible.
This option allows you to override that, in efforts to allow migration from the old inventory script.
- For this to work you should also turn off the TRANSFORM_INVALID_GROUP_CHARS setting,
otherwise the core engine will just use the standard sanitization on top.
- This is not the default as such names break certain functionality as not all characters are valid Python identifiers
which group names end up being used as.
type: bool
default: False
version_added: '2.8'
retrieve_image_info:
description:
- Populate the C(image) host fact for the instances returned with the GCP image name
- By default this plugin does not attempt to resolve the boot image of an instance to the image name cataloged in GCP
because of the performance overhead of the task.
- Unless this option is enabled, the C(image) host variable will be C(null)
type: bool
default: False
version_added: '2.8'
'''
EXAMPLES = '''
plugin: gcp_compute
zones: # populate inventory with instances in these regions
- us-east1-a
projects:
- gcp-prod-gke-100
- gcp-cicd-101
filters:
- machineType = n1-standard-1
- scheduling.automaticRestart = true AND machineType = n1-standard-1
service_account_file: /tmp/service_account.json
auth_kind: serviceaccount
scopes:
- 'https://www.googleapis.com/auth/cloud-platform'
- 'https://www.googleapis.com/auth/compute.readonly'
keyed_groups:
# Create groups from GCE labels
- prefix: gcp
key: labels
hostnames:
# List host by name instead of the default public ip
- name
compose:
# Set an inventory parameter to use the Public IP address to connect to the host
# For Private ip use "networkInterfaces[0].networkIP"
ansible_host: networkInterfaces[0].accessConfigs[0].natIP
'''
import json
from ansible.errors import AnsibleError, AnsibleParserError
from ansible.module_utils._text import to_text
from ansible.module_utils.basic import missing_required_lib
from ansible.module_utils.gcp_utils import GcpSession, navigate_hash, GcpRequestException, HAS_GOOGLE_LIBRARIES
from ansible.plugins.inventory import BaseInventoryPlugin, Constructable, Cacheable
# Mocking a module to reuse module_utils
class GcpMockModule(object):
def __init__(self, params):
self.params = params
def fail_json(self, *args, **kwargs):
raise AnsibleError(kwargs['msg'])
class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
NAME = 'gcp_compute'
_instances = r"https://www.googleapis.com/compute/v1/projects/%s/aggregated/instances"
def __init__(self):
super(InventoryModule, self).__init__()
self.group_prefix = 'gcp_'
def _populate_host(self, item):
'''
:param item: A GCP instance
'''
hostname = self._get_hostname(item)
self.inventory.add_host(hostname)
for key in item:
try:
self.inventory.set_variable(hostname, self.get_option('vars_prefix') + key, item[key])
except (ValueError, TypeError) as e:
self.display.warning("Could not set host info hostvar for %s, skipping %s: %s" % (hostname, key, to_text(e)))
self.inventory.add_child('all', hostname)
def verify_file(self, path):
'''
:param path: the path to the inventory config file
:return the contents of the config file
'''
if super(InventoryModule, self).verify_file(path):
if path.endswith(('gcp.yml', 'gcp.yaml')):
return True
elif path.endswith(('gcp_compute.yml', 'gcp_compute.yaml')):
return True
return False
def fetch_list(self, params, link, query):
'''
:param params: a dict containing all of the fields relevant to build URL
:param link: a formatted URL
:param query: a formatted query string
:return the JSON response containing a list of instances.
'''
response = self.auth_session.get(link, params={'filter': query})
return self._return_if_object(self.fake_module, response)
def _get_query_options(self, filters):
'''
:param config_data: contents of the inventory config file
:return A fully built query string
'''
if not filters:
return ''
if len(filters) == 1:
return filters[0]
else:
queries = []
for f in filters:
# For multiple queries, all queries should have ()
if f[0] != '(' and f[-1] != ')':
queries.append("(%s)" % ''.join(f))
else:
queries.append(f)
return ' '.join(queries)
def _return_if_object(self, module, response):
'''
:param module: A GcpModule
:param response: A Requests response object
:return JSON response
'''
# If not found, return nothing.
if response.status_code == 404:
return None
# If no content, return nothing.
if response.status_code == 204:
return None
try:
response.raise_for_status
result = response.json()
except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst:
module.fail_json(msg="Invalid JSON response with error: %s" % inst)
except GcpRequestException as inst:
module.fail_json(msg="Network error: %s" % inst)
if navigate_hash(result, ['error', 'errors']):
module.fail_json(msg=navigate_hash(result, ['error', 'errors']))
return result
def _format_items(self, items, project_disks):
'''
:param items: A list of hosts
'''
for host in items:
if 'zone' in host:
host['zone_selflink'] = host['zone']
host['zone'] = host['zone'].split('/')[-1]
if 'machineType' in host:
host['machineType_selflink'] = host['machineType']
host['machineType'] = host['machineType'].split('/')[-1]
if 'networkInterfaces' in host:
for network in host['networkInterfaces']:
if 'network' in network:
network['network'] = self._format_network_info(network['network'])
if 'subnetwork' in network:
network['subnetwork'] = self._format_network_info(network['subnetwork'])
if 'metadata' in host:
# If no metadata, 'items' will be blank.
# We want the metadata hash overriden anyways for consistency.
host['metadata'] = self._format_metadata(host['metadata'].get('items', {}))
host['project'] = host['selfLink'].split('/')[6]
host['image'] = self._get_image(host, project_disks)
return items
def _add_hosts(self, items, config_data, format_items=True, project_disks=None):
'''
:param items: A list of hosts
:param config_data: configuration data
:param format_items: format items or not
'''
if not items:
return
if format_items:
items = self._format_items(items, project_disks)
for host in items:
self._populate_host(host)
hostname = self._get_hostname(host)
self._set_composite_vars(self.get_option('compose'), host, hostname)
self._add_host_to_composed_groups(self.get_option('groups'), host, hostname)
self._add_host_to_keyed_groups(self.get_option('keyed_groups'), host, hostname)
def _format_network_info(self, address):
'''
:param address: A GCP network address
:return a dict with network shortname and region
'''
split = address.split('/')
region = ''
if 'global' in split:
region = 'global'
else:
region = split[8]
return {
'region': region,
'name': split[-1],
'selfLink': address
}
def _format_metadata(self, metadata):
'''
:param metadata: A list of dicts where each dict has keys "key" and "value"
:return a dict with key/value pairs for each in list.
'''
new_metadata = {}
print(metadata)
for pair in metadata:
new_metadata[pair["key"]] = pair["value"]
return new_metadata
def _get_hostname(self, item):
'''
:param item: A host response from GCP
:return the hostname of this instance
'''
hostname_ordering = ['public_ip', 'private_ip', 'name']
if self.get_option('hostnames'):
hostname_ordering = self.get_option('hostnames')
for order in hostname_ordering:
name = None
if order == 'public_ip':
name = self._get_publicip(item)
elif order == 'private_ip':
name = self._get_privateip(item)
elif order == 'name':
name = item[u'name']
else:
raise AnsibleParserError("%s is not a valid hostname precedent" % order)
if name:
return name
raise AnsibleParserError("No valid name found for host")
def _get_publicip(self, item):
'''
:param item: A host response from GCP
:return the publicIP of this instance or None
'''
# Get public IP if exists
for interface in item['networkInterfaces']:
if 'accessConfigs' in interface:
for accessConfig in interface['accessConfigs']:
if 'natIP' in accessConfig:
return accessConfig[u'natIP']
return None
def _get_image(self, instance, project_disks):
'''
:param instance: A instance response from GCP
:return the image of this instance or None
'''
image = None
if project_disks and 'disks' in instance:
for disk in instance['disks']:
if disk.get('boot'):
image = project_disks[disk["source"]]
return image
def _get_project_disks(self, config_data, query):
'''
project space disk images
'''
try:
self._project_disks
except AttributeError:
self._project_disks = {}
request_params = {'maxResults': 500, 'filter': query}
for project in config_data['projects']:
session_responses = []
page_token = True
while page_token:
response = self.auth_session.get(
'https://www.googleapis.com/compute/v1/projects/{0}/aggregated/disks'.format(project),
params=request_params
)
response_json = response.json()
if 'nextPageToken' in response_json:
request_params['pageToken'] = response_json['nextPageToken']
elif 'pageToken' in request_params:
del request_params['pageToken']
if 'items' in response_json:
session_responses.append(response_json)
page_token = 'pageToken' in request_params
for response in session_responses:
if 'items' in response:
# example k would be a zone or region name
# example v would be { "disks" : [], "otherkey" : "..." }
for zone_or_region, aggregate in response['items'].items():
if 'zones' in zone_or_region:
if 'disks' in aggregate:
zone = zone_or_region.replace('zones/', '')
for disk in aggregate['disks']:
if 'zones' in config_data and zone in config_data['zones']:
# If zones specified, only store those zones' data
if 'sourceImage' in disk:
self._project_disks[disk['selfLink']] = disk['sourceImage'].split('/')[-1]
else:
self._project_disks[disk['selfLink']] = disk['selfLink'].split('/')[-1]
else:
if 'sourceImage' in disk:
self._project_disks[disk['selfLink']] = disk['sourceImage'].split('/')[-1]
else:
self._project_disks[disk['selfLink']] = disk['selfLink'].split('/')[-1]
return self._project_disks
def _get_privateip(self, item):
'''
:param item: A host response from GCP
:return the privateIP of this instance or None
'''
# Fallback: Get private IP
for interface in item[u'networkInterfaces']:
if 'networkIP' in interface:
return interface[u'networkIP']
def parse(self, inventory, loader, path, cache=True):
if not HAS_GOOGLE_LIBRARIES:
raise AnsibleParserError('gce inventory plugin cannot start: %s' % missing_required_lib('google-auth'))
super(InventoryModule, self).parse(inventory, loader, path)
config_data = {}
config_data = self._read_config_data(path)
if self.get_option('use_contrib_script_compatible_sanitization'):
self._sanitize_group_name = self._legacy_script_compatible_group_sanitization
# setup parameters as expected by 'fake module class' to reuse module_utils w/o changing the API
params = {
'filters': self.get_option('filters'),
'projects': self.get_option('projects'),
'scopes': self.get_option('scopes'),
'zones': self.get_option('zones'),
'auth_kind': self.get_option('auth_kind'),
'service_account_file': self.get_option('service_account_file'),
'service_account_contents': self.get_option('service_account_contents'),
'service_account_email': self.get_option('service_account_email'),
}
self.fake_module = GcpMockModule(params)
self.auth_session = GcpSession(self.fake_module, 'compute')
query = self._get_query_options(params['filters'])
if self.get_option('retrieve_image_info'):
project_disks = self._get_project_disks(config_data, query)
else:
project_disks = None
# Cache logic
if cache:
cache = self.get_option('cache')
cache_key = self.get_cache_key(path)
else:
cache_key = None
cache_needs_update = False
if cache:
try:
results = self._cache[cache_key]
for project in results:
for zone in results[project]:
self._add_hosts(results[project][zone], config_data, False, project_disks=project_disks)
except KeyError:
cache_needs_update = True
if not cache or cache_needs_update:
cached_data = {}
for project in params['projects']:
cached_data[project] = {}
params['project'] = project
zones = params['zones']
# Fetch all instances
link = self._instances % project
resp = self.fetch_list(params, link, query)
for key, value in resp.get('items').items():
if 'instances' in value:
# Key is in format: "zones/europe-west1-b"
zone = key[6:]
if not zones or zone in zones:
self._add_hosts(value['instances'], config_data, project_disks=project_disks)
cached_data[project][zone] = value['instances']
if cache_needs_update:
self._cache[cache_key] = cached_data
@staticmethod
def _legacy_script_compatible_group_sanitization(name):
return name
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,808 |
mail module should send email with "Date" header
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
mail module does not send email with Date header. It should send email with "Date" header automatically without any manual email header manipulation.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
mail
##### ANSIBLE VERSION
```
ansible 2.8.1
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/yclee/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.15+ (default, Nov 27 2018, 23:36:35) [GCC 7.3.0]
```
##### CONFIGURATION
(None)
##### OS / ENVIRONMENT
Ubuntu 18.04
##### STEPS TO REPRODUCE
N/A
##### EXPECTED RESULTS
email should have Date headers
##### ACTUAL RESULTS
email did not have Date headers and I have to manually insert it
|
https://github.com/ansible/ansible/issues/58808
|
https://github.com/ansible/ansible/pull/59080
|
de66abe52182bc124ffbd0ef0559375d471c79fe
|
f0eaf1fb397e0123852e2c87bca9f3809b1ed167
| 2019-07-08T03:59:31Z |
python
| 2019-07-16T14:55:59Z |
changelogs/fragments/58808-mail-add-date-header.yaml
| |
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,808 |
mail module should send email with "Date" header
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
mail module does not send email with Date header. It should send email with "Date" header automatically without any manual email header manipulation.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
mail
##### ANSIBLE VERSION
```
ansible 2.8.1
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/yclee/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.15+ (default, Nov 27 2018, 23:36:35) [GCC 7.3.0]
```
##### CONFIGURATION
(None)
##### OS / ENVIRONMENT
Ubuntu 18.04
##### STEPS TO REPRODUCE
N/A
##### EXPECTED RESULTS
email should have Date headers
##### ACTUAL RESULTS
email did not have Date headers and I have to manually insert it
|
https://github.com/ansible/ansible/issues/58808
|
https://github.com/ansible/ansible/pull/59080
|
de66abe52182bc124ffbd0ef0559375d471c79fe
|
f0eaf1fb397e0123852e2c87bca9f3809b1ed167
| 2019-07-08T03:59:31Z |
python
| 2019-07-16T14:55:59Z |
lib/ansible/modules/notification/mail.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2012, Dag Wieers (@dagwieers) <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
author:
- Dag Wieers (@dagwieers)
module: mail
short_description: Send an email
description:
- This module is useful for sending emails from playbooks.
- One may wonder why automate sending emails? In complex environments
there are from time to time processes that cannot be automated, either
because you lack the authority to make it so, or because not everyone
agrees to a common approach.
- If you cannot automate a specific step, but the step is non-blocking,
sending out an email to the responsible party to make them perform their
part of the bargain is an elegant way to put the responsibility in
someone else's lap.
- Of course sending out a mail can be equally useful as a way to notify
one or more people in a team that a specific action has been
(successfully) taken.
version_added: '0.8'
options:
from:
description:
- The email-address the mail is sent from. May contain address and phrase.
type: str
default: root
to:
description:
- The email-address(es) the mail is being sent to.
- This is a list, which may contain address and phrase portions.
type: list
default: root
aliases: [ recipients ]
cc:
description:
- The email-address(es) the mail is being copied to.
- This is a list, which may contain address and phrase portions.
type: list
bcc:
description:
- The email-address(es) the mail is being 'blind' copied to.
- This is a list, which may contain address and phrase portions.
type: list
subject:
description:
- The subject of the email being sent.
required: yes
type: str
body:
description:
- The body of the email being sent.
type: str
default: $subject
username:
description:
- If SMTP requires username.
type: str
version_added: '1.9'
password:
description:
- If SMTP requires password.
type: str
version_added: '1.9'
host:
description:
- The mail server.
type: str
default: localhost
port:
description:
- The mail server port.
- This must be a valid integer between 1 and 65534
type: int
default: 25
version_added: '1.0'
attach:
description:
- A list of pathnames of files to attach to the message.
- Attached files will have their content-type set to C(application/octet-stream).
type: list
default: []
version_added: '1.0'
headers:
description:
- A list of headers which should be added to the message.
- Each individual header is specified as C(header=value) (see example below).
type: list
default: []
version_added: '1.0'
charset:
description:
- The character set of email being sent.
type: str
default: utf-8
subtype:
description:
- The minor mime type, can be either C(plain) or C(html).
- The major type is always C(text).
type: str
choices: [ html, plain ]
default: plain
version_added: '2.0'
secure:
description:
- If C(always), the connection will only send email if the connection is Encrypted.
If the server doesn't accept the encrypted connection it will fail.
- If C(try), the connection will attempt to setup a secure SSL/TLS session, before trying to send.
- If C(never), the connection will not attempt to setup a secure SSL/TLS session, before sending
- If C(starttls), the connection will try to upgrade to a secure SSL/TLS connection, before sending.
If it is unable to do so it will fail.
type: str
choices: [ always, never, starttls, try ]
default: try
version_added: '2.3'
timeout:
description:
- Sets the timeout in seconds for connection attempts.
type: int
default: 20
version_added: '2.3'
'''
EXAMPLES = r'''
- name: Example playbook sending mail to root
mail:
subject: System {{ ansible_hostname }} has been successfully provisioned.
delegate_to: localhost
- name: Sending an e-mail using Gmail SMTP servers
mail:
host: smtp.gmail.com
port: 587
username: [email protected]
password: mysecret
to: John Smith <[email protected]>
subject: Ansible-report
body: System {{ ansible_hostname }} has been successfully provisioned.
delegate_to: localhost
- name: Send e-mail to a bunch of users, attaching files
mail:
host: 127.0.0.1
port: 2025
subject: Ansible-report
body: Hello, this is an e-mail. I hope you like it ;-)
from: [email protected] (Jane Jolie)
to:
- John Doe <[email protected]>
- Suzie Something <[email protected]>
cc: Charlie Root <root@localhost>
attach:
- /etc/group
- /tmp/avatar2.png
headers:
- [email protected]
- X-Special="Something or other"
charset: us-ascii
delegate_to: localhost
- name: Sending an e-mail using the remote machine, not the Ansible controller node
mail:
host: localhost
port: 25
to: John Smith <[email protected]>
subject: Ansible-report
body: System {{ ansible_hostname }} has been successfully provisioned.
- name: Sending an e-mail using Legacy SSL to the remote machine
mail:
host: localhost
port: 25
to: John Smith <[email protected]>
subject: Ansible-report
body: System {{ ansible_hostname }} has been successfully provisioned.
secure: always
- name: Sending an e-mail using StartTLS to the remote machine
mail:
host: localhost
port: 25
to: John Smith <[email protected]>
subject: Ansible-report
body: System {{ ansible_hostname }} has been successfully provisioned.
secure: starttls
'''
import os
import smtplib
import ssl
import traceback
from email import encoders
from email.utils import parseaddr, formataddr
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six import PY3
from ansible.module_utils._text import to_native
def main():
module = AnsibleModule(
argument_spec=dict(
username=dict(type='str'),
password=dict(type='str', no_log=True),
host=dict(type='str', default='localhost'),
port=dict(type='int', default=25),
sender=dict(type='str', default='root', aliases=['from']),
to=dict(type='list', default=['root'], aliases=['recipients']),
cc=dict(type='list', default=[]),
bcc=dict(type='list', default=[]),
subject=dict(type='str', required=True, aliases=['msg']),
body=dict(type='str'),
attach=dict(type='list', default=[]),
headers=dict(type='list', default=[]),
charset=dict(type='str', default='utf-8'),
subtype=dict(type='str', default='plain', choices=['html', 'plain']),
secure=dict(type='str', default='try', choices=['always', 'never', 'starttls', 'try']),
timeout=dict(type='int', default=20),
),
required_together=[['password', 'username']],
)
username = module.params.get('username')
password = module.params.get('password')
host = module.params.get('host')
port = module.params.get('port')
sender = module.params.get('sender')
recipients = module.params.get('to')
copies = module.params.get('cc')
blindcopies = module.params.get('bcc')
subject = module.params.get('subject')
body = module.params.get('body')
attach_files = module.params.get('attach')
headers = module.params.get('headers')
charset = module.params.get('charset')
subtype = module.params.get('subtype')
secure = module.params.get('secure')
timeout = module.params.get('timeout')
code = 0
secure_state = False
sender_phrase, sender_addr = parseaddr(sender)
if not body:
body = subject
try:
if secure != 'never':
try:
if PY3:
smtp = smtplib.SMTP_SSL(host=host, port=port, timeout=timeout)
else:
smtp = smtplib.SMTP_SSL(timeout=timeout)
code, smtpmessage = smtp.connect(host, port)
secure_state = True
except ssl.SSLError as e:
if secure == 'always':
module.fail_json(rc=1, msg='Unable to start an encrypted session to %s:%s: %s' %
(host, port, to_native(e)), exception=traceback.format_exc())
except Exception:
pass
if not secure_state:
if PY3:
smtp = smtplib.SMTP(host=host, port=port, timeout=timeout)
else:
smtp = smtplib.SMTP(timeout=timeout)
code, smtpmessage = smtp.connect(host, port)
except smtplib.SMTPException as e:
module.fail_json(rc=1, msg='Unable to Connect %s:%s: %s' % (host, port, to_native(e)), exception=traceback.format_exc())
try:
smtp.ehlo()
except smtplib.SMTPException as e:
module.fail_json(rc=1, msg='Helo failed for host %s:%s: %s' % (host, port, to_native(e)), exception=traceback.format_exc())
if int(code) > 0:
if not secure_state and secure in ('starttls', 'try'):
if smtp.has_extn('STARTTLS'):
try:
smtp.starttls()
secure_state = True
except smtplib.SMTPException as e:
module.fail_json(rc=1, msg='Unable to start an encrypted session to %s:%s: %s' %
(host, port, to_native(e)), exception=traceback.format_exc())
try:
smtp.ehlo()
except smtplib.SMTPException as e:
module.fail_json(rc=1, msg='Helo failed for host %s:%s: %s' % (host, port, to_native(e)), exception=traceback.format_exc())
else:
if secure == 'starttls':
module.fail_json(rc=1, msg='StartTLS is not offered on server %s:%s' % (host, port))
if username and password:
if smtp.has_extn('AUTH'):
try:
smtp.login(username, password)
except smtplib.SMTPAuthenticationError:
module.fail_json(rc=1, msg='Authentication to %s:%s failed, please check your username and/or password' % (host, port))
except smtplib.SMTPException:
module.fail_json(rc=1, msg='No Suitable authentication method was found on %s:%s' % (host, port))
else:
module.fail_json(rc=1, msg="No Authentication on the server at %s:%s" % (host, port))
if not secure_state and (username and password):
module.warn('Username and Password was sent without encryption')
msg = MIMEMultipart(_charset=charset)
msg['From'] = formataddr((sender_phrase, sender_addr))
msg['Subject'] = Header(subject, charset)
msg.preamble = "Multipart message"
for header in headers:
# NOTE: Backward compatible with old syntax using '|' as delimiter
for hdr in [x.strip() for x in header.split('|')]:
try:
h_key, h_val = hdr.split('=')
h_val = to_native(Header(h_val, charset))
msg.add_header(h_key, h_val)
except Exception:
module.warn("Skipping header '%s', unable to parse" % hdr)
if 'X-Mailer' not in msg:
msg.add_header('X-Mailer', 'Ansible mail module')
addr_list = []
for addr in [x.strip() for x in blindcopies]:
addr_list.append(parseaddr(addr)[1]) # address only, w/o phrase
to_list = []
for addr in [x.strip() for x in recipients]:
to_list.append(formataddr(parseaddr(addr)))
addr_list.append(parseaddr(addr)[1]) # address only, w/o phrase
msg['To'] = ", ".join(to_list)
cc_list = []
for addr in [x.strip() for x in copies]:
cc_list.append(formataddr(parseaddr(addr)))
addr_list.append(parseaddr(addr)[1]) # address only, w/o phrase
msg['Cc'] = ", ".join(cc_list)
part = MIMEText(body + "\n\n", _subtype=subtype, _charset=charset)
msg.attach(part)
# NOTE: Backware compatibility with old syntax using space as delimiter is not retained
# This breaks files with spaces in it :-(
for filename in attach_files:
try:
part = MIMEBase('application', 'octet-stream')
with open(filename, 'rb') as fp:
part.set_payload(fp.read())
encoders.encode_base64(part)
part.add_header('Content-disposition', 'attachment', filename=os.path.basename(filename))
msg.attach(part)
except Exception as e:
module.fail_json(rc=1, msg="Failed to send mail: can't attach file %s: %s" %
(filename, to_native(e)), exception=traceback.format_exc())
composed = msg.as_string()
try:
result = smtp.sendmail(sender_addr, set(addr_list), composed)
except Exception as e:
module.fail_json(rc=1, msg="Failed to send mail to '%s': %s" %
(", ".join(set(addr_list)), to_native(e)), exception=traceback.format_exc())
smtp.quit()
if result:
for key in result:
module.warn("Failed to send mail to '%s': %s %s" % (key, result[key][0], result[key][1]))
module.exit_json(msg='Failed to send mail to at least one recipient', result=result)
module.exit_json(msg='Mail sent successfully', result=result)
if __name__ == '__main__':
main()
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 59,063 |
chroot connection plugin crashes with AttributeError: 'Connection' object has no attribute '_load_name'
|
##### SUMMARY
The chroot connection plugin crashes with an exception: `AttributeError: 'Connection' object has no attribute '_load_name'`
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
chroot connection plugin
##### ANSIBLE VERSION
```
ansible 2.8.2
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/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.13 (default, Sep 26 2018, 18:42:22) [GCC 6.3.0 20170516]
```
##### OS / ENVIRONMENT
Debian 9 with ansible 2.8.2-1ppa~trusty from the ppa:ansible/ansible
##### STEPS TO REPRODUCE
```
# ansible -m setup -c chroot -i /target, all -vvv
```
##### EXPECTED RESULTS
Ansible should run in a `chroot /target` environment and report the discovered facts.
##### ACTUAL RESULTS
```
ansible 2.8.2
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/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.13 (default, Sep 26 2018, 18:42:22) [GCC 6.3.0 20170516]
Using /etc/ansible/ansible.cfg as config file
Unable to parse address from hostname, leaving unchanged: Not a valid network hostname: /target
Parsed /target, inventory source with host_list plugin
META: ran handlers
The full traceback is:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/ansible/executor/task_executor.py", line 144, in run
res = self._execute()
File "/usr/lib/python2.7/dist-packages/ansible/executor/task_executor.py", line 590, in _execute
self._connection = self._get_connection(variables=variables, templar=templar)
File "/usr/lib/python2.7/dist-packages/ansible/executor/task_executor.py", line 892, in _get_connection
ansible_playbook_pid=to_text(os.getppid())
File "/usr/lib/python2.7/dist-packages/ansible/plugins/loader.py", line 579, in get
obj = obj(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/ansible/plugins/connection/chroot.py", line 99, in __init__
if os.path.isabs(self.get_option('chroot_exe')):
File "/usr/lib/python2.7/dist-packages/ansible/plugins/__init__.py", line 58, in get_option
option_value = C.config.get_config_value(option, plugin_type=get_plugin_class(self), plugin_name=self._load_name, variables=hostvars)
AttributeError: 'Connection' object has no attribute '_load_name'
/target | FAILED! => {
"msg": "Unexpected failure during module execution.",
"stdout": ""
}
```
|
https://github.com/ansible/ansible/issues/59063
|
https://github.com/ansible/ansible/pull/59065
|
88c4cf28eac874d7a0b62559b2f931ca1b9572e0
|
b16c264dcada92fbd5a539c85ad1c2bbff0551f4
| 2019-07-13T21:12:43Z |
python
| 2019-07-16T15:31:06Z |
lib/ansible/plugins/connection/chroot.py
|
# Based on local.py (c) 2012, Michael DeHaan <[email protected]>
#
# (c) 2013, Maykel Moya <[email protected]>
# (c) 2015, Toshio Kuratomi <[email protected]>
# Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
author: Maykel Moya <[email protected]>
connection: chroot
short_description: Interact with local chroot
description:
- Run commands or put/fetch files to an existing chroot on the Ansible controller.
version_added: "1.1"
options:
remote_addr:
description:
- The path of the chroot you want to access.
default: inventory_hostname
vars:
- name: ansible_host
executable:
description:
- User specified executable shell
ini:
- section: defaults
key: executable
env:
- name: ANSIBLE_EXECUTABLE
vars:
- name: ansible_executable
default: /bin/sh
chroot_exe:
version_added: '2.8'
description:
- User specified chroot binary
ini:
- section: chroot_connection
key: exe
env:
- name: ANSIBLE_CHROOT_EXE
vars:
- name: ansible_chroot_exe
default: chroot
"""
import os
import os.path
import subprocess
import traceback
from ansible.errors import AnsibleError
from ansible.module_utils.basic import is_executable
from ansible.module_utils.common.process import get_bin_path
from ansible.module_utils.six.moves import shlex_quote
from ansible.module_utils._text import to_bytes, to_native
from ansible.plugins.connection import ConnectionBase, BUFSIZE
from ansible.utils.display import Display
display = Display()
class Connection(ConnectionBase):
''' Local chroot based connections '''
transport = 'chroot'
has_pipelining = True
# su currently has an undiagnosed issue with calculating the file
# checksums (so copy, for instance, doesn't work right)
# Have to look into that before re-enabling this
has_tty = False
default_user = 'root'
def __init__(self, play_context, new_stdin, *args, **kwargs):
super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs)
self.chroot = self._play_context.remote_addr
if os.geteuid() != 0:
raise AnsibleError("chroot connection requires running as root")
# we're running as root on the local system so do some
# trivial checks for ensuring 'host' is actually a chroot'able dir
if not os.path.isdir(self.chroot):
raise AnsibleError("%s is not a directory" % self.chroot)
chrootsh = os.path.join(self.chroot, 'bin/sh')
# Want to check for a usable bourne shell inside the chroot.
# is_executable() == True is sufficient. For symlinks it
# gets really complicated really fast. So we punt on finding that
# out. As long as it's a symlink we assume that it will work
if not (is_executable(chrootsh) or (os.path.lexists(chrootsh) and os.path.islink(chrootsh))):
raise AnsibleError("%s does not look like a chrootable dir (/bin/sh missing)" % self.chroot)
if os.path.isabs(self.get_option('chroot_exe')):
self.chroot_cmd = self.get_option('chroot_exe')
else:
self.chroot_cmd = get_bin_path(self.get_option('chroot_exe'))
if not self.chroot_cmd:
raise AnsibleError("chroot command (%s) not found in PATH" % to_native(self.get_option('chroot_exe')))
def _connect(self):
''' connect to the chroot; nothing to do here '''
super(Connection, self)._connect()
if not self._connected:
display.vvv("THIS IS A LOCAL CHROOT DIR", host=self.chroot)
self._connected = True
def _buffered_exec_command(self, cmd, stdin=subprocess.PIPE):
''' run a command on the chroot. This is only needed for implementing
put_file() get_file() so that we don't have to read the whole file
into memory.
compared to exec_command() it looses some niceties like being able to
return the process's exit code immediately.
'''
executable = self.get_option('executable')
local_cmd = [self.chroot_cmd, self.chroot, executable, '-c', cmd]
display.vvv("EXEC %s" % (local_cmd), host=self.chroot)
local_cmd = [to_bytes(i, errors='surrogate_or_strict') for i in local_cmd]
p = subprocess.Popen(local_cmd, shell=False, stdin=stdin,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return p
def exec_command(self, cmd, in_data=None, sudoable=False):
''' run a command on the chroot '''
super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)
p = self._buffered_exec_command(cmd)
stdout, stderr = p.communicate(in_data)
return (p.returncode, stdout, stderr)
def _prefix_login_path(self, remote_path):
''' Make sure that we put files into a standard path
If a path is relative, then we need to choose where to put it.
ssh chooses $HOME but we aren't guaranteed that a home dir will
exist in any given chroot. So for now we're choosing "/" instead.
This also happens to be the former default.
Can revisit using $HOME instead if it's a problem
'''
if not remote_path.startswith(os.path.sep):
remote_path = os.path.join(os.path.sep, remote_path)
return os.path.normpath(remote_path)
def put_file(self, in_path, out_path):
''' transfer a file from local to chroot '''
super(Connection, self).put_file(in_path, out_path)
display.vvv("PUT %s TO %s" % (in_path, out_path), host=self.chroot)
out_path = shlex_quote(self._prefix_login_path(out_path))
try:
with open(to_bytes(in_path, errors='surrogate_or_strict'), 'rb') as in_file:
if not os.fstat(in_file.fileno()).st_size:
count = ' count=0'
else:
count = ''
try:
p = self._buffered_exec_command('dd of=%s bs=%s%s' % (out_path, BUFSIZE, count), stdin=in_file)
except OSError:
raise AnsibleError("chroot connection requires dd command in the chroot")
try:
stdout, stderr = p.communicate()
except Exception:
traceback.print_exc()
raise AnsibleError("failed to transfer file %s to %s" % (in_path, out_path))
if p.returncode != 0:
raise AnsibleError("failed to transfer file %s to %s:\n%s\n%s" % (in_path, out_path, stdout, stderr))
except IOError:
raise AnsibleError("file or module does not exist at: %s" % in_path)
def fetch_file(self, in_path, out_path):
''' fetch a file from chroot to local '''
super(Connection, self).fetch_file(in_path, out_path)
display.vvv("FETCH %s TO %s" % (in_path, out_path), host=self.chroot)
in_path = shlex_quote(self._prefix_login_path(in_path))
try:
p = self._buffered_exec_command('dd if=%s bs=%s' % (in_path, BUFSIZE))
except OSError:
raise AnsibleError("chroot connection requires dd command in the chroot")
with open(to_bytes(out_path, errors='surrogate_or_strict'), 'wb+') as out_file:
try:
chunk = p.stdout.read(BUFSIZE)
while chunk:
out_file.write(chunk)
chunk = p.stdout.read(BUFSIZE)
except Exception:
traceback.print_exc()
raise AnsibleError("failed to transfer file %s to %s" % (in_path, out_path))
stdout, stderr = p.communicate()
if p.returncode != 0:
raise AnsibleError("failed to transfer file %s to %s:\n%s\n%s" % (in_path, out_path, stdout, stderr))
def close(self):
''' terminate the connection; nothing to do here '''
super(Connection, self).close()
self._connected = False
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,940 |
win_domain_group_membership add fails with domain credentials
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
win_domain_group_membership module gives error when you add members to the group when domain_username/domain_password specified. I am trying to run the module from a windows instance joined to the AD domain controller.
I can run the same from powershell and it works.
Once added the usernames to the group, win_domain_group_membership (pure option) can delete the user. Pure option is deleting the user properly but cannot add any user. I think somewhere in add part passing credentials are not working properly.
It works when run directly on domain controllers (no need for domain_username/password args).
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
win_domain_group_membership
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
2.8.1
2.8.2
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
OS is windows 2019 AWS base AMI
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```yaml
- name: Add UserName to GroupName
win_domain_group_membership:
domain_username: '{{ domain_username }}'
domain_password: '{{ domain_password }}'
name: groupName
members:
- "userName"
state: pure
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
```
ok: [3.00.00.00] => (item={'key': 'groupName, 'value': {'description': 'desc', 'path': 'OU=ra,OU=role,OU=Groups,OU=random'}}) => {
"added": [],
"ansible_loop_var": "item",
"changed": false,
"item": {
"key": "groupName",
"value": {
"description": "desc",
"path": "OU=ra,OU=role,OU=Groups,OU=random"
}
},
"members": [userName],
"removed": []
}
```
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```
The full traceback is:
The server has rejected the client credentials.
At line:55 char:21
+ ... up_member = Get-ADObject -Filter "SamAccountName -eq '$member' -and $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : SecurityError: (:) [Get-ADObject], AuthenticationException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.Security.Authentication.AuthenticationException,Microsoft.ActiveDirectory.Management.Commands.GetADObject
ScriptStackTrace:
at <ScriptBlock>, <No file>: line 55
System.Security.Authentication.AuthenticationException: The server has rejected the client credentials. ---> System.ServiceModel.Security.SecurityNegotiationException: The server has rejected the client credentials. ---> System.Security.Authentication.InvalidCredentialException: The server has rejected the client credentials. ---> System.ComponentModel.Win32Exception: The logon attempt failed
--- End of inner exception stack trace ---
at System.Net.Security.NegoState.ProcessReceivedBlob(Byte[] message, LazyAsyncResult lazyResult)
at System.Net.Security.NegoState.StartSendBlob(Byte[] message, LazyAsyncResult lazyResult)
at System.Net.Security.NegoState.StartSendBlob(Byte[] message, LazyAsyncResult lazyResult)
at System.Net.Security.NegoState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.Security.NegotiateStream.AuthenticateAsClient(NetworkCredential credential, String targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel)
at System.ServiceModel.Channels.WindowsStreamSecurityUpgradeProvider.WindowsStreamSecurityUpgradeInitiator.OnInitiateUpgrade(Stream stream, SecurityMessageProperty& remoteSecurity)
--- End of inner exception stack trace ---
Server stack trace:
at System.ServiceModel.Channels.WindowsStreamSecurityUpgradeProvider.WindowsStreamSecurityUpgradeInitiator.OnInitiateUpgrade(Stream stream, SecurityMessageProperty& remoteSecurity)
at System.ServiceModel.Channels.StreamSecurityUpgradeInitiatorBase.InitiateUpgrade(Stream stream)
at System.ServiceModel.Channels.ConnectionUpgradeHelper.InitiateUpgrade(StreamUpgradeInitiator upgradeInitiator, IConnection& connection, ClientFramingDecoder decoder, IDefaultCommunicationTimeouts defaultTimeouts, TimeoutHelper& timeoutHelper)
at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.SendPreamble(IConnection connection, ArraySegment`1 preamble, TimeoutHelper& timeoutHelper)
at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.DuplexConnectionPoolHelper.AcceptPooledConnection(IConnection connection, TimeoutHelper& timeoutHelper)
at System.ServiceModel.Channels.ConnectionPoolHelper.EstablishConnection(TimeSpan timeout)
at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel channel, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
at System.ServiceModel.Channels.ServiceChannel.EnsureOpened(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Microsoft.ActiveDirectory.WebServices.Proxy.Resource.Get(Message request)
at Microsoft.ActiveDirectory.Management.AdwsConnection.SearchAnObject(ADSearchRequest request)
--- End of inner exception stack trace ---
at Microsoft.ActiveDirectory.Management.AdwsConnection.ThrowAuthenticationRelatedExceptionIfAny(CommunicationException exception)
at Microsoft.ActiveDirectory.Management.AdwsConnection.SearchAnObject(ADSearchRequest request)
at Microsoft.ActiveDirectory.Management.AdwsConnection.Search(ADSearchRequest request)
at Microsoft.ActiveDirectory.Management.ADWebServiceStoreAccess.Microsoft.ActiveDirectory.Management.IADSyncOperations.Search(ADSessionHandle handle, ADSearchRequest request)
at Microsoft.ActiveDirectory.Management.ADObjectSearcher.GetRootDSE()
at Microsoft.ActiveDirectory.Management.Commands.ADCmdletBase`1.GetRootDSE()
at Microsoft.ActiveDirectory.Management.Commands.ADCmdletBase`1.GetConnectedStore()
at Microsoft.ActiveDirectory.Management.Commands.ADCmdletBase`1.GetCmdletSessionInfo()
at Microsoft.ActiveDirectory.Management.Commands.ADGetCmdletBase`3.ADGetCmdletBaseBeginCSRoutine()
at Microsoft.ActiveDirectory.Management.CmdletSubroutinePipeline.Invoke()
at Microsoft.ActiveDirectory.Management.Commands.ADCmdletBase`1.BeginProcessing()
fatal: [3.00.00.00]: FAILED! => {
"changed": false,
"msg": "Unhandled exception while executing module: The server has rejected the client credentials."
}
PLAY RECAP ********************************************************************************************************************************************************************************************************************************************************************************
3.00.00.00 : ok=5 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
```
|
https://github.com/ansible/ansible/issues/58940
|
https://github.com/ansible/ansible/pull/58943
|
e5e3486be647f317c5ad242196fe588bdfbbc12c
|
681ab6515abb589174f04c884a4d1e21f2c6f356
| 2019-07-10T19:34:20Z |
python
| 2019-07-16T19:38:42Z |
lib/ansible/modules/windows/win_domain_group_membership.ps1
|
#!powershell
# Copyright: (c) 2019, Marius Rieder <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#Requires -Module Ansible.ModuleUtils.Legacy
try {
Import-Module ActiveDirectory
}
catch {
Fail-Json -obj @{} -message "win_domain_group_membership requires the ActiveDirectory PS module to be installed"
}
$params = Parse-Args $args -supports_check_mode $true
$check_mode = Get-AnsibleParam -obj $params -name "_ansible_check_mode" -type "bool" -default $false
$diff_mode = Get-AnsibleParam -obj $params -name "_ansible_diff" -type "bool" -default $false
# Module control parameters
$state = Get-AnsibleParam -obj $params -name "state" -type "str" -default "present" -validateset "present","absent","pure"
$domain_username = Get-AnsibleParam -obj $params -name "domain_username" -type "str"
$domain_password = Get-AnsibleParam -obj $params -name "domain_password" -type "str" -failifempty ($null -ne $domain_username)
$domain_server = Get-AnsibleParam -obj $params -name "domain_server" -type "str"
# Group Membership parameters
$name = Get-AnsibleParam -obj $params -name "name" -type "str" -failifempty $true
$members = Get-AnsibleParam -obj $params -name "members" -type "list" -failifempty $true
# Filter ADObjects by ObjectClass
$ad_object_class_filter = "(ObjectClass -eq 'user' -or ObjectClass -eq 'group' -or ObjectClass -eq 'computer' -or ObjectClass -eq 'msDS-ManagedServiceAccount')"
$extra_args = @{}
if ($null -ne $domain_username) {
$domain_password = ConvertTo-SecureString $domain_password -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $domain_username, $domain_password
$extra_args.Credential = $credential
}
if ($nul -ne $domain_server) {
$extra_args.Server = $domain_server
}
$result = @{
changed = $false
added = [System.Collections.Generic.List`1[String]]@()
removed = [System.Collections.Generic.List`1[String]]@()
}
if ($diff_mode) {
$result.diff = @{}
}
$members_before = Get-AdGroupMember -Identity $name @extra_args
$pure_members = [System.Collections.Generic.List`1[String]]@()
foreach ($member in $members) {
$group_member = Get-ADObject -Filter "SamAccountName -eq '$member' -and $ad_object_class_filter" -Properties objectSid, sAMAccountName @extra_vars
if (!$group_member) {
Fail-Json -obj $result "Could not find domain user, group, service account or computer named $member"
}
if ($state -eq "pure") {
$pure_members.Add($group_member.objectSid)
}
$user_in_group = $false
foreach ($current_member in $members_before) {
if ($current_member.sid -eq $group_member.objectSid) {
$user_in_group = $true
break
}
}
if ($state -in @("present", "pure") -and !$user_in_group) {
Add-ADGroupMember -Identity $name -Members $group_member -WhatIf:$check_mode @extra_args
$result.added.Add($group_member.SamAccountName)
$result.changed = $true
} elseif ($state -eq "absent" -and $user_in_group) {
Remove-ADGroupMember -Identity $name -Members $group_member -WhatIf:$check_mode @extra_args -Confirm:$False
$result.removed.Add($group_member.SamAccountName)
$result.changed = $true
}
}
if ($state -eq "pure") {
# Perform removals for existing group members not defined in $members
$current_members = Get-AdGroupMember -Identity $name @extra_args
foreach ($current_member in $current_members) {
$user_to_remove = $true
foreach ($pure_member in $pure_members) {
if ($pure_member -eq $current_member.sid) {
$user_to_remove = $false
break
}
}
if ($user_to_remove) {
Remove-ADGroupMember -Identity $name -Members $current_member -WhatIf:$check_mode @extra_args -Confirm:$False
$result.removed.Add($current_member.SamAccountName)
$result.changed = $true
}
}
}
$final_members = Get-AdGroupMember -Identity $name @extra_args
if ($final_members) {
$result.members = [Array]$final_members.SamAccountName
} else {
$result.members = @()
}
if ($diff_mode -and $result.changed) {
$result.diff.before = $members_before.SamAccountName | Out-String
if (!$check_mode) {
$result.diff.after = [Array]$final_members.SamAccountName | Out-String
} else {
$after = [System.Collections.Generic.List`1[String]]$result.members
$result.removed | ForEach-Object { $after.Remove($_) > $null }
$after.AddRange($result.added)
$result.diff.after = $after | Out-String
}
}
Exit-Json -obj $result
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,775 |
npm module gives completely cryptic, useless error when you list multiple packages under name:
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
npm doesn't allow "name" arg to be list, gives completely useless, cryptic error when it is
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
npm
##### ANSIBLE VERSION
```paste below
ansible 2.8.1
config file = /home/jik/src/family-orchestration/ansible.cfg
configured module search path = [u'/home/jik/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.16 (default, Apr 6 2019, 01:42:57) [GCC 8.3.0]
```
##### CONFIGURATION
```paste below
ANSIBLE_PIPELINING(/home/jik/src/family-orchestration/ansible.cfg) = True
DEFAULT_HOST_LIST(/home/jik/src/family-orchestration/ansible.cfg) = [u'/home/jik
DEFAULT_REMOTE_USER(/home/jik/src/family-orchestration/ansible.cfg) = root
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
Both console and remote ansible host are Ubuntu 19.04 amd64.
##### STEPS TO REPRODUCE
<!--- Paste example playbooks or commands between quotes below -->
```yaml
----
- hosts: localhost
tasks:
- npm:
name:
- eslint
- eslint-scope
```
##### EXPECTED RESULTS
The listed npm packages are installed in a two npm invocations (one to determine which are installed, one to install the missing ones).
##### ACTUAL RESULTS
Completely incomprehensible "ValueError: No JSON object could be decoded" error that doesn't tell you anything about what you're doing wrong or how to fix it.
|
https://github.com/ansible/ansible/issues/58775
|
https://github.com/ansible/ansible/pull/58965
|
fbb4eaaba90890c2b58972a5eae210a4df49b89f
|
6f94995b52ec93477b398e28a36ab2b2b99205ae
| 2019-07-05T17:41:29Z |
python
| 2019-07-17T04:04:58Z |
changelogs/fragments/58965-npm-validate-option-types.yml
| |
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,775 |
npm module gives completely cryptic, useless error when you list multiple packages under name:
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
npm doesn't allow "name" arg to be list, gives completely useless, cryptic error when it is
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
npm
##### ANSIBLE VERSION
```paste below
ansible 2.8.1
config file = /home/jik/src/family-orchestration/ansible.cfg
configured module search path = [u'/home/jik/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.16 (default, Apr 6 2019, 01:42:57) [GCC 8.3.0]
```
##### CONFIGURATION
```paste below
ANSIBLE_PIPELINING(/home/jik/src/family-orchestration/ansible.cfg) = True
DEFAULT_HOST_LIST(/home/jik/src/family-orchestration/ansible.cfg) = [u'/home/jik
DEFAULT_REMOTE_USER(/home/jik/src/family-orchestration/ansible.cfg) = root
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
Both console and remote ansible host are Ubuntu 19.04 amd64.
##### STEPS TO REPRODUCE
<!--- Paste example playbooks or commands between quotes below -->
```yaml
----
- hosts: localhost
tasks:
- npm:
name:
- eslint
- eslint-scope
```
##### EXPECTED RESULTS
The listed npm packages are installed in a two npm invocations (one to determine which are installed, one to install the missing ones).
##### ACTUAL RESULTS
Completely incomprehensible "ValueError: No JSON object could be decoded" error that doesn't tell you anything about what you're doing wrong or how to fix it.
|
https://github.com/ansible/ansible/issues/58775
|
https://github.com/ansible/ansible/pull/58965
|
fbb4eaaba90890c2b58972a5eae210a4df49b89f
|
6f94995b52ec93477b398e28a36ab2b2b99205ae
| 2019-07-05T17:41:29Z |
python
| 2019-07-17T04:04:58Z |
lib/ansible/modules/packaging/language/npm.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Chris Hoffman <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: npm
short_description: Manage node.js packages with npm
description:
- Manage node.js packages with Node Package Manager (npm)
version_added: 1.2
author: "Chris Hoffman (@chrishoffman)"
options:
name:
description:
- The name of a node.js library to install
required: false
path:
description:
- The base path where to install the node.js libraries
required: false
version:
description:
- The version to be installed
required: false
global:
description:
- Install the node.js library globally
required: false
default: no
type: bool
executable:
description:
- The executable location for npm.
- This is useful if you are using a version manager, such as nvm
required: false
ignore_scripts:
description:
- Use the C(--ignore-scripts) flag when installing.
required: false
type: bool
default: no
version_added: "1.8"
unsafe_perm:
description:
- Use the C(--unsafe-perm) flag when installing.
type: bool
default: no
version_added: "2.8"
ci:
description:
- Install packages based on package-lock file, same as running npm ci
type: bool
default: no
version_added: "2.8"
production:
description:
- Install dependencies in production mode, excluding devDependencies
required: false
type: bool
default: no
registry:
description:
- The registry to install modules from.
required: false
version_added: "1.6"
state:
description:
- The state of the node.js library
required: false
default: present
choices: [ "present", "absent", "latest" ]
requirements:
- npm installed in bin path (recommended /usr/local/bin)
'''
EXAMPLES = '''
- name: Install "coffee-script" node.js package.
npm:
name: coffee-script
path: /app/location
- name: Install "coffee-script" node.js package on version 1.6.1.
npm:
name: coffee-script
version: '1.6.1'
path: /app/location
- name: Install "coffee-script" node.js package globally.
npm:
name: coffee-script
global: yes
- name: Remove the globally package "coffee-script".
npm:
name: coffee-script
global: yes
state: absent
- name: Install "coffee-script" node.js package from custom registry.
npm:
name: coffee-script
registry: 'http://registry.mysite.com'
- name: Install packages based on package.json.
npm:
path: /app/location
- name: Update packages based on package.json to their latest version.
npm:
path: /app/location
state: latest
- name: Install packages based on package.json using the npm installed with nvm v0.10.1.
npm:
path: /app/location
executable: /opt/nvm/v0.10.1/bin/npm
state: present
'''
import os
import re
from ansible.module_utils.basic import AnsibleModule
import json
class Npm(object):
def __init__(self, module, **kwargs):
self.module = module
self.glbl = kwargs['glbl']
self.name = kwargs['name']
self.version = kwargs['version']
self.path = kwargs['path']
self.registry = kwargs['registry']
self.production = kwargs['production']
self.ignore_scripts = kwargs['ignore_scripts']
self.unsafe_perm = kwargs['unsafe_perm']
self.state = kwargs['state']
if kwargs['executable']:
self.executable = kwargs['executable'].split(' ')
else:
self.executable = [module.get_bin_path('npm', True)]
if kwargs['version'] and self.state != 'absent':
self.name_version = self.name + '@' + str(self.version)
else:
self.name_version = self.name
def _exec(self, args, run_in_check_mode=False, check_rc=True):
if not self.module.check_mode or (self.module.check_mode and run_in_check_mode):
cmd = self.executable + args
if self.glbl:
cmd.append('--global')
if self.production and ('install' in cmd or 'update' in cmd):
cmd.append('--production')
if self.ignore_scripts:
cmd.append('--ignore-scripts')
if self.unsafe_perm:
cmd.append('--unsafe-perm')
if self.name:
cmd.append(self.name_version)
if self.registry:
cmd.append('--registry')
cmd.append(self.registry)
# If path is specified, cd into that path and run the command.
cwd = None
if self.path:
if not os.path.exists(self.path):
os.makedirs(self.path)
if not os.path.isdir(self.path):
self.module.fail_json(msg="path %s is not a directory" % self.path)
cwd = self.path
rc, out, err = self.module.run_command(cmd, check_rc=check_rc, cwd=cwd)
return out
return ''
def list(self):
cmd = ['list', '--json', '--long']
installed = list()
missing = list()
data = json.loads(self._exec(cmd, True, False))
if 'dependencies' in data:
for dep in data['dependencies']:
if 'missing' in data['dependencies'][dep] and data['dependencies'][dep]['missing']:
missing.append(dep)
elif 'invalid' in data['dependencies'][dep] and data['dependencies'][dep]['invalid']:
missing.append(dep)
else:
installed.append(dep)
if self.name and self.name not in installed:
missing.append(self.name)
# Named dependency not installed
else:
missing.append(self.name)
return installed, missing
def install(self):
return self._exec(['install'])
def ci_install(self):
return self._exec(['ci'])
def update(self):
return self._exec(['update'])
def uninstall(self):
return self._exec(['uninstall'])
def list_outdated(self):
outdated = list()
data = self._exec(['outdated'], True, False)
for dep in data.splitlines():
if dep:
# node.js v0.10.22 changed the `npm outdated` module separator
# from "@" to " ". Split on both for backwards compatibility.
pkg, other = re.split(r'\s|@', dep, 1)
outdated.append(pkg)
return outdated
def main():
arg_spec = dict(
name=dict(default=None),
path=dict(default=None, type='path'),
version=dict(default=None),
production=dict(default='no', type='bool'),
executable=dict(default=None, type='path'),
registry=dict(default=None),
state=dict(default='present', choices=['present', 'absent', 'latest']),
ignore_scripts=dict(default=False, type='bool'),
unsafe_perm=dict(default=False, type='bool'),
ci=dict(default=False, type='bool'),
)
arg_spec['global'] = dict(default='no', type='bool')
module = AnsibleModule(
argument_spec=arg_spec,
supports_check_mode=True
)
name = module.params['name']
path = module.params['path']
version = module.params['version']
glbl = module.params['global']
production = module.params['production']
executable = module.params['executable']
registry = module.params['registry']
state = module.params['state']
ignore_scripts = module.params['ignore_scripts']
unsafe_perm = module.params['unsafe_perm']
ci = module.params['ci']
if not path and not glbl:
module.fail_json(msg='path must be specified when not using global')
if state == 'absent' and not name:
module.fail_json(msg='uninstalling a package is only available for named packages')
npm = Npm(module, name=name, path=path, version=version, glbl=glbl, production=production,
executable=executable, registry=registry, ignore_scripts=ignore_scripts,
unsafe_perm=unsafe_perm, state=state)
changed = False
if ci:
npm.ci_install()
changed = True
elif state == 'present':
installed, missing = npm.list()
if missing:
changed = True
npm.install()
elif state == 'latest':
installed, missing = npm.list()
outdated = npm.list_outdated()
if missing:
changed = True
npm.install()
if outdated:
changed = True
npm.update()
else: # absent
installed, missing = npm.list()
if name in installed:
changed = True
npm.uninstall()
module.exit_json(changed=changed)
if __name__ == '__main__':
main()
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,775 |
npm module gives completely cryptic, useless error when you list multiple packages under name:
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
npm doesn't allow "name" arg to be list, gives completely useless, cryptic error when it is
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
npm
##### ANSIBLE VERSION
```paste below
ansible 2.8.1
config file = /home/jik/src/family-orchestration/ansible.cfg
configured module search path = [u'/home/jik/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.16 (default, Apr 6 2019, 01:42:57) [GCC 8.3.0]
```
##### CONFIGURATION
```paste below
ANSIBLE_PIPELINING(/home/jik/src/family-orchestration/ansible.cfg) = True
DEFAULT_HOST_LIST(/home/jik/src/family-orchestration/ansible.cfg) = [u'/home/jik
DEFAULT_REMOTE_USER(/home/jik/src/family-orchestration/ansible.cfg) = root
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
Both console and remote ansible host are Ubuntu 19.04 amd64.
##### STEPS TO REPRODUCE
<!--- Paste example playbooks or commands between quotes below -->
```yaml
----
- hosts: localhost
tasks:
- npm:
name:
- eslint
- eslint-scope
```
##### EXPECTED RESULTS
The listed npm packages are installed in a two npm invocations (one to determine which are installed, one to install the missing ones).
##### ACTUAL RESULTS
Completely incomprehensible "ValueError: No JSON object could be decoded" error that doesn't tell you anything about what you're doing wrong or how to fix it.
|
https://github.com/ansible/ansible/issues/58775
|
https://github.com/ansible/ansible/pull/58965
|
fbb4eaaba90890c2b58972a5eae210a4df49b89f
|
6f94995b52ec93477b398e28a36ab2b2b99205ae
| 2019-07-05T17:41:29Z |
python
| 2019-07-17T04:04:58Z |
test/sanity/validate-modules/ignore.txt
|
lib/ansible/modules/cloud/alicloud/ali_instance_info.py E337
lib/ansible/modules/cloud/alicloud/ali_instance_info.py E338
lib/ansible/modules/cloud/alicloud/ali_instance.py E337
lib/ansible/modules/cloud/alicloud/ali_instance.py E338
lib/ansible/modules/cloud/amazon/aws_acm_info.py E337
lib/ansible/modules/cloud/amazon/aws_acm_info.py E338
lib/ansible/modules/cloud/amazon/aws_api_gateway.py E322
lib/ansible/modules/cloud/amazon/aws_api_gateway.py E337
lib/ansible/modules/cloud/amazon/aws_application_scaling_policy.py E322
lib/ansible/modules/cloud/amazon/aws_application_scaling_policy.py E326
lib/ansible/modules/cloud/amazon/aws_application_scaling_policy.py E337
lib/ansible/modules/cloud/amazon/aws_az_info.py E337
lib/ansible/modules/cloud/amazon/aws_batch_compute_environment.py E337
lib/ansible/modules/cloud/amazon/aws_batch_compute_environment.py E338
lib/ansible/modules/cloud/amazon/aws_batch_job_definition.py E337
lib/ansible/modules/cloud/amazon/aws_batch_job_definition.py E338
lib/ansible/modules/cloud/amazon/aws_batch_job_queue.py E337
lib/ansible/modules/cloud/amazon/aws_batch_job_queue.py E338
lib/ansible/modules/cloud/amazon/aws_codebuild.py E337
lib/ansible/modules/cloud/amazon/aws_codebuild.py E338
lib/ansible/modules/cloud/amazon/aws_codecommit.py E338
lib/ansible/modules/cloud/amazon/aws_codepipeline.py E337
lib/ansible/modules/cloud/amazon/aws_codepipeline.py E338
lib/ansible/modules/cloud/amazon/aws_config_aggregation_authorization.py E337
lib/ansible/modules/cloud/amazon/aws_config_aggregator.py E337
lib/ansible/modules/cloud/amazon/aws_config_delivery_channel.py E337
lib/ansible/modules/cloud/amazon/aws_config_recorder.py E337
lib/ansible/modules/cloud/amazon/aws_config_rule.py E337
lib/ansible/modules/cloud/amazon/aws_direct_connect_connection.py E338
lib/ansible/modules/cloud/amazon/aws_direct_connect_gateway.py E322
lib/ansible/modules/cloud/amazon/aws_direct_connect_gateway.py E324
lib/ansible/modules/cloud/amazon/aws_direct_connect_gateway.py E337
lib/ansible/modules/cloud/amazon/aws_direct_connect_gateway.py E338
lib/ansible/modules/cloud/amazon/aws_direct_connect_link_aggregation_group.py E337
lib/ansible/modules/cloud/amazon/aws_direct_connect_link_aggregation_group.py E338
lib/ansible/modules/cloud/amazon/aws_direct_connect_virtual_interface.py E337
lib/ansible/modules/cloud/amazon/aws_direct_connect_virtual_interface.py E338
lib/ansible/modules/cloud/amazon/aws_eks_cluster.py E337
lib/ansible/modules/cloud/amazon/aws_eks_cluster.py E338
lib/ansible/modules/cloud/amazon/aws_elasticbeanstalk_app.py E337
lib/ansible/modules/cloud/amazon/aws_elasticbeanstalk_app.py E338
lib/ansible/modules/cloud/amazon/aws_glue_connection.py E337
lib/ansible/modules/cloud/amazon/aws_glue_job.py E337
lib/ansible/modules/cloud/amazon/aws_inspector_target.py E337
lib/ansible/modules/cloud/amazon/aws_inspector_target.py E338
lib/ansible/modules/cloud/amazon/aws_kms_info.py E337
lib/ansible/modules/cloud/amazon/aws_kms.py E337
lib/ansible/modules/cloud/amazon/aws_kms.py E338
lib/ansible/modules/cloud/amazon/aws_region_info.py E337
lib/ansible/modules/cloud/amazon/aws_s3_cors.py E337
lib/ansible/modules/cloud/amazon/aws_s3.py E322
lib/ansible/modules/cloud/amazon/aws_s3.py E324
lib/ansible/modules/cloud/amazon/aws_s3.py E337
lib/ansible/modules/cloud/amazon/aws_s3.py E338
lib/ansible/modules/cloud/amazon/aws_secret.py E337
lib/ansible/modules/cloud/amazon/aws_secret.py E338
lib/ansible/modules/cloud/amazon/aws_ses_identity_policy.py E337
lib/ansible/modules/cloud/amazon/aws_ses_identity_policy.py E338
lib/ansible/modules/cloud/amazon/aws_ses_identity.py E337
lib/ansible/modules/cloud/amazon/aws_ses_identity.py E338
lib/ansible/modules/cloud/amazon/aws_ses_rule_set.py E337
lib/ansible/modules/cloud/amazon/aws_ssm_parameter_store.py E324
lib/ansible/modules/cloud/amazon/aws_ssm_parameter_store.py E338
lib/ansible/modules/cloud/amazon/aws_waf_condition.py E337
lib/ansible/modules/cloud/amazon/aws_waf_condition.py E338
lib/ansible/modules/cloud/amazon/aws_waf_info.py E338
lib/ansible/modules/cloud/amazon/aws_waf_rule.py E337
lib/ansible/modules/cloud/amazon/aws_waf_rule.py E338
lib/ansible/modules/cloud/amazon/aws_waf_web_acl.py E337
lib/ansible/modules/cloud/amazon/aws_waf_web_acl.py E338
lib/ansible/modules/cloud/amazon/cloudformation_facts.py E338
lib/ansible/modules/cloud/amazon/cloudformation.py E324
lib/ansible/modules/cloud/amazon/cloudformation.py E337
lib/ansible/modules/cloud/amazon/cloudformation.py E338
lib/ansible/modules/cloud/amazon/cloudformation_stack_set.py E337
lib/ansible/modules/cloud/amazon/cloudformation_stack_set.py E338
lib/ansible/modules/cloud/amazon/cloudfront_distribution.py E324
lib/ansible/modules/cloud/amazon/cloudfront_distribution.py E326
lib/ansible/modules/cloud/amazon/cloudfront_distribution.py E337
lib/ansible/modules/cloud/amazon/cloudfront_distribution.py E338
lib/ansible/modules/cloud/amazon/cloudfront_facts.py E323
lib/ansible/modules/cloud/amazon/cloudfront_facts.py E337
lib/ansible/modules/cloud/amazon/cloudfront_invalidation.py E324
lib/ansible/modules/cloud/amazon/cloudfront_invalidation.py E337
lib/ansible/modules/cloud/amazon/cloudfront_invalidation.py E338
lib/ansible/modules/cloud/amazon/cloudfront_origin_access_identity.py E324
lib/ansible/modules/cloud/amazon/cloudfront_origin_access_identity.py E338
lib/ansible/modules/cloud/amazon/cloudtrail.py E324
lib/ansible/modules/cloud/amazon/cloudtrail.py E337
lib/ansible/modules/cloud/amazon/cloudtrail.py E338
lib/ansible/modules/cloud/amazon/cloudwatchevent_rule.py E337
lib/ansible/modules/cloud/amazon/cloudwatchevent_rule.py E338
lib/ansible/modules/cloud/amazon/cloudwatchlogs_log_group_info.py E338
lib/ansible/modules/cloud/amazon/cloudwatchlogs_log_group.py E337
lib/ansible/modules/cloud/amazon/cloudwatchlogs_log_group.py E338
lib/ansible/modules/cloud/amazon/data_pipeline.py E322
lib/ansible/modules/cloud/amazon/data_pipeline.py E337
lib/ansible/modules/cloud/amazon/data_pipeline.py E338
lib/ansible/modules/cloud/amazon/dms_endpoint.py E337
lib/ansible/modules/cloud/amazon/dms_endpoint.py E338
lib/ansible/modules/cloud/amazon/dynamodb_table.py E337
lib/ansible/modules/cloud/amazon/dynamodb_table.py E338
lib/ansible/modules/cloud/amazon/dynamodb_ttl.py E324
lib/ansible/modules/cloud/amazon/dynamodb_ttl.py E338
lib/ansible/modules/cloud/amazon/ec2_ami_copy.py E337
lib/ansible/modules/cloud/amazon/ec2_ami_copy.py E338
lib/ansible/modules/cloud/amazon/ec2_ami_info.py E337
lib/ansible/modules/cloud/amazon/ec2_ami.py E324
lib/ansible/modules/cloud/amazon/ec2_ami.py E337
lib/ansible/modules/cloud/amazon/ec2_ami.py E338
lib/ansible/modules/cloud/amazon/ec2_asg_info.py E337
lib/ansible/modules/cloud/amazon/ec2_asg_lifecycle_hook.py E327
lib/ansible/modules/cloud/amazon/ec2_asg_lifecycle_hook.py E337
lib/ansible/modules/cloud/amazon/ec2_asg_lifecycle_hook.py E338
lib/ansible/modules/cloud/amazon/ec2_asg.py E324
lib/ansible/modules/cloud/amazon/ec2_asg.py E326
lib/ansible/modules/cloud/amazon/ec2_asg.py E327
lib/ansible/modules/cloud/amazon/ec2_asg.py E337
lib/ansible/modules/cloud/amazon/ec2_asg.py E338
lib/ansible/modules/cloud/amazon/ec2_customer_gateway_info.py E337
lib/ansible/modules/cloud/amazon/ec2_customer_gateway.py E337
lib/ansible/modules/cloud/amazon/ec2_customer_gateway.py E338
lib/ansible/modules/cloud/amazon/ec2_eip_info.py E337
lib/ansible/modules/cloud/amazon/ec2_eip.py E322
lib/ansible/modules/cloud/amazon/ec2_eip.py E324
lib/ansible/modules/cloud/amazon/ec2_eip.py E337
lib/ansible/modules/cloud/amazon/ec2_eip.py E338
lib/ansible/modules/cloud/amazon/ec2_elb_info.py E323
lib/ansible/modules/cloud/amazon/ec2_elb_info.py E337
lib/ansible/modules/cloud/amazon/ec2_elb.py E326
lib/ansible/modules/cloud/amazon/ec2_elb.py E337
lib/ansible/modules/cloud/amazon/ec2_elb.py E338
lib/ansible/modules/cloud/amazon/ec2_eni_info.py E337
lib/ansible/modules/cloud/amazon/ec2_eni.py E337
lib/ansible/modules/cloud/amazon/ec2_eni.py E338
lib/ansible/modules/cloud/amazon/ec2_group_info.py E337
lib/ansible/modules/cloud/amazon/ec2_group.py E322
lib/ansible/modules/cloud/amazon/ec2_group.py E337
lib/ansible/modules/cloud/amazon/ec2_group.py E338
lib/ansible/modules/cloud/amazon/ec2_instance_info.py E337
lib/ansible/modules/cloud/amazon/ec2_instance.py E324
lib/ansible/modules/cloud/amazon/ec2_instance.py E337
lib/ansible/modules/cloud/amazon/ec2_instance.py E338
lib/ansible/modules/cloud/amazon/ec2_key.py E337
lib/ansible/modules/cloud/amazon/ec2_key.py E338
lib/ansible/modules/cloud/amazon/ec2_launch_template.py E337
lib/ansible/modules/cloud/amazon/ec2_launch_template.py E338
lib/ansible/modules/cloud/amazon/ec2_lc_find.py E337
lib/ansible/modules/cloud/amazon/ec2_lc_find.py E338
lib/ansible/modules/cloud/amazon/ec2_lc_info.py E337
lib/ansible/modules/cloud/amazon/ec2_lc_info.py E338
lib/ansible/modules/cloud/amazon/ec2_lc.py E322
lib/ansible/modules/cloud/amazon/ec2_lc.py E324
lib/ansible/modules/cloud/amazon/ec2_lc.py E326
lib/ansible/modules/cloud/amazon/ec2_lc.py E337
lib/ansible/modules/cloud/amazon/ec2_lc.py E338
lib/ansible/modules/cloud/amazon/ec2_metric_alarm.py E324
lib/ansible/modules/cloud/amazon/ec2_metric_alarm.py E337
lib/ansible/modules/cloud/amazon/ec2_metric_alarm.py E338
lib/ansible/modules/cloud/amazon/ec2_placement_group_info.py E337
lib/ansible/modules/cloud/amazon/ec2_placement_group.py E337
lib/ansible/modules/cloud/amazon/ec2_placement_group.py E338
lib/ansible/modules/cloud/amazon/ec2.py E322
lib/ansible/modules/cloud/amazon/ec2.py E337
lib/ansible/modules/cloud/amazon/ec2_scaling_policy.py E324
lib/ansible/modules/cloud/amazon/ec2_scaling_policy.py E337
lib/ansible/modules/cloud/amazon/ec2_scaling_policy.py E338
lib/ansible/modules/cloud/amazon/ec2_snapshot_copy.py E337
lib/ansible/modules/cloud/amazon/ec2_snapshot_copy.py E338
lib/ansible/modules/cloud/amazon/ec2_snapshot_info.py E337
lib/ansible/modules/cloud/amazon/ec2_snapshot.py E337
lib/ansible/modules/cloud/amazon/ec2_snapshot.py E338
lib/ansible/modules/cloud/amazon/ec2_tag.py E337
lib/ansible/modules/cloud/amazon/ec2_tag.py E338
lib/ansible/modules/cloud/amazon/ec2_transit_gateway.py E337
lib/ansible/modules/cloud/amazon/ec2_transit_gateway.py E338
lib/ansible/modules/cloud/amazon/ec2_vol_info.py E337
lib/ansible/modules/cloud/amazon/ec2_vol.py E322
lib/ansible/modules/cloud/amazon/ec2_vol.py E324
lib/ansible/modules/cloud/amazon/ec2_vol.py E326
lib/ansible/modules/cloud/amazon/ec2_vol.py E337
lib/ansible/modules/cloud/amazon/ec2_vol.py E338
lib/ansible/modules/cloud/amazon/ec2_vpc_dhcp_option_info.py E322
lib/ansible/modules/cloud/amazon/ec2_vpc_dhcp_option_info.py E337
lib/ansible/modules/cloud/amazon/ec2_vpc_dhcp_option.py E337
lib/ansible/modules/cloud/amazon/ec2_vpc_egress_igw.py E338
lib/ansible/modules/cloud/amazon/ec2_vpc_endpoint_info.py E337
lib/ansible/modules/cloud/amazon/ec2_vpc_endpoint_info.py E338
lib/ansible/modules/cloud/amazon/ec2_vpc_endpoint.py E337
lib/ansible/modules/cloud/amazon/ec2_vpc_endpoint.py E338
lib/ansible/modules/cloud/amazon/ec2_vpc_igw_info.py E337
lib/ansible/modules/cloud/amazon/ec2_vpc_igw.py E337
lib/ansible/modules/cloud/amazon/ec2_vpc_igw.py E338
lib/ansible/modules/cloud/amazon/ec2_vpc_nacl_info.py E337
lib/ansible/modules/cloud/amazon/ec2_vpc_nacl.py E337
lib/ansible/modules/cloud/amazon/ec2_vpc_nacl.py E338
lib/ansible/modules/cloud/amazon/ec2_vpc_nat_gateway_info.py E337
lib/ansible/modules/cloud/amazon/ec2_vpc_nat_gateway.py E324
lib/ansible/modules/cloud/amazon/ec2_vpc_nat_gateway.py E337
lib/ansible/modules/cloud/amazon/ec2_vpc_nat_gateway.py E338
lib/ansible/modules/cloud/amazon/ec2_vpc_net_info.py E337
lib/ansible/modules/cloud/amazon/ec2_vpc_net.py E337
lib/ansible/modules/cloud/amazon/ec2_vpc_net.py E338
lib/ansible/modules/cloud/amazon/ec2_vpc_peering_info.py E337
lib/ansible/modules/cloud/amazon/ec2_vpc_peer.py E337
lib/ansible/modules/cloud/amazon/ec2_vpc_peer.py E338
lib/ansible/modules/cloud/amazon/ec2_vpc_route_table_info.py E337
lib/ansible/modules/cloud/amazon/ec2_vpc_route_table.py E337
lib/ansible/modules/cloud/amazon/ec2_vpc_route_table.py E338
lib/ansible/modules/cloud/amazon/ec2_vpc_subnet_info.py E337
lib/ansible/modules/cloud/amazon/ec2_vpc_subnet.py E317
lib/ansible/modules/cloud/amazon/ec2_vpc_subnet.py E337
lib/ansible/modules/cloud/amazon/ec2_vpc_subnet.py E338
lib/ansible/modules/cloud/amazon/ec2_vpc_vgw_info.py E337
lib/ansible/modules/cloud/amazon/ec2_vpc_vgw.py E323
lib/ansible/modules/cloud/amazon/ec2_vpc_vgw.py E324
lib/ansible/modules/cloud/amazon/ec2_vpc_vgw.py E337
lib/ansible/modules/cloud/amazon/ec2_vpc_vgw.py E338
lib/ansible/modules/cloud/amazon/ec2_vpc_vpn_info.py E337
lib/ansible/modules/cloud/amazon/ec2_vpc_vpn.py E326
lib/ansible/modules/cloud/amazon/ec2_vpc_vpn.py E337
lib/ansible/modules/cloud/amazon/ec2_win_password.py E337
lib/ansible/modules/cloud/amazon/ec2_win_password.py E338
lib/ansible/modules/cloud/amazon/ecs_attribute.py E337
lib/ansible/modules/cloud/amazon/ecs_attribute.py E338
lib/ansible/modules/cloud/amazon/ecs_cluster.py E324
lib/ansible/modules/cloud/amazon/ecs_cluster.py E337
lib/ansible/modules/cloud/amazon/ecs_cluster.py E338
lib/ansible/modules/cloud/amazon/ecs_ecr.py E337
lib/ansible/modules/cloud/amazon/ecs_ecr.py E338
lib/ansible/modules/cloud/amazon/ecs_service_facts.py E324
lib/ansible/modules/cloud/amazon/ecs_service_facts.py E337
lib/ansible/modules/cloud/amazon/ecs_service_facts.py E338
lib/ansible/modules/cloud/amazon/ecs_service.py E337
lib/ansible/modules/cloud/amazon/ecs_service.py E338
lib/ansible/modules/cloud/amazon/ecs_taskdefinition_facts.py E337
lib/ansible/modules/cloud/amazon/ecs_taskdefinition.py E337
lib/ansible/modules/cloud/amazon/ecs_taskdefinition.py E338
lib/ansible/modules/cloud/amazon/ecs_task.py E337
lib/ansible/modules/cloud/amazon/ecs_task.py E338
lib/ansible/modules/cloud/amazon/efs_facts.py E337
lib/ansible/modules/cloud/amazon/efs_facts.py E338
lib/ansible/modules/cloud/amazon/efs.py E337
lib/ansible/modules/cloud/amazon/elasticache_info.py E338
lib/ansible/modules/cloud/amazon/elasticache_parameter_group.py E326
lib/ansible/modules/cloud/amazon/elasticache_parameter_group.py E337
lib/ansible/modules/cloud/amazon/elasticache_parameter_group.py E338
lib/ansible/modules/cloud/amazon/elasticache.py E324
lib/ansible/modules/cloud/amazon/elasticache.py E326
lib/ansible/modules/cloud/amazon/elasticache.py E337
lib/ansible/modules/cloud/amazon/elasticache.py E338
lib/ansible/modules/cloud/amazon/elasticache_snapshot.py E337
lib/ansible/modules/cloud/amazon/elasticache_subnet_group.py E324
lib/ansible/modules/cloud/amazon/elasticache_subnet_group.py E337
lib/ansible/modules/cloud/amazon/elasticache_subnet_group.py E338
lib/ansible/modules/cloud/amazon/elb_application_lb_info.py E337
lib/ansible/modules/cloud/amazon/elb_application_lb.py E324
lib/ansible/modules/cloud/amazon/elb_application_lb.py E337
lib/ansible/modules/cloud/amazon/elb_application_lb.py E338
lib/ansible/modules/cloud/amazon/elb_classic_lb_info.py E323
lib/ansible/modules/cloud/amazon/elb_classic_lb_info.py E337
lib/ansible/modules/cloud/amazon/elb_classic_lb.py E337
lib/ansible/modules/cloud/amazon/elb_classic_lb.py E338
lib/ansible/modules/cloud/amazon/elb_instance.py E326
lib/ansible/modules/cloud/amazon/elb_instance.py E337
lib/ansible/modules/cloud/amazon/elb_instance.py E338
lib/ansible/modules/cloud/amazon/elb_network_lb.py E337
lib/ansible/modules/cloud/amazon/elb_network_lb.py E338
lib/ansible/modules/cloud/amazon/elb_target_group_info.py E337
lib/ansible/modules/cloud/amazon/elb_target_group.py E324
lib/ansible/modules/cloud/amazon/elb_target_group.py E326
lib/ansible/modules/cloud/amazon/elb_target_group.py E337
lib/ansible/modules/cloud/amazon/elb_target_group.py E338
lib/ansible/modules/cloud/amazon/elb_target.py E327
lib/ansible/modules/cloud/amazon/elb_target.py E337
lib/ansible/modules/cloud/amazon/execute_lambda.py E324
lib/ansible/modules/cloud/amazon/execute_lambda.py E337
lib/ansible/modules/cloud/amazon/execute_lambda.py E338
lib/ansible/modules/cloud/amazon/iam_cert.py E338
lib/ansible/modules/cloud/amazon/iam_group.py E337
lib/ansible/modules/cloud/amazon/iam_group.py E338
lib/ansible/modules/cloud/amazon/iam_managed_policy.py E322
lib/ansible/modules/cloud/amazon/iam_managed_policy.py E324
lib/ansible/modules/cloud/amazon/iam_managed_policy.py E337
lib/ansible/modules/cloud/amazon/iam_managed_policy.py E338
lib/ansible/modules/cloud/amazon/iam_mfa_device_info.py E338
lib/ansible/modules/cloud/amazon/iam_password_policy.py E337
lib/ansible/modules/cloud/amazon/iam_password_policy.py E338
lib/ansible/modules/cloud/amazon/iam_policy.py E317
lib/ansible/modules/cloud/amazon/iam_policy.py E327
lib/ansible/modules/cloud/amazon/iam_policy.py E337
lib/ansible/modules/cloud/amazon/iam_policy.py E338
lib/ansible/modules/cloud/amazon/iam.py E317
lib/ansible/modules/cloud/amazon/iam.py E326
lib/ansible/modules/cloud/amazon/iam.py E337
lib/ansible/modules/cloud/amazon/iam.py E338
lib/ansible/modules/cloud/amazon/iam_role_info.py E338
lib/ansible/modules/cloud/amazon/iam_role.py E337
lib/ansible/modules/cloud/amazon/iam_server_certificate_info.py E337
lib/ansible/modules/cloud/amazon/iam_user.py E337
lib/ansible/modules/cloud/amazon/iam_user.py E338
lib/ansible/modules/cloud/amazon/kinesis_stream.py E317
lib/ansible/modules/cloud/amazon/kinesis_stream.py E324
lib/ansible/modules/cloud/amazon/kinesis_stream.py E326
lib/ansible/modules/cloud/amazon/kinesis_stream.py E337
lib/ansible/modules/cloud/amazon/kinesis_stream.py E338
lib/ansible/modules/cloud/amazon/lambda_alias.py E317
lib/ansible/modules/cloud/amazon/lambda_alias.py E337
lib/ansible/modules/cloud/amazon/lambda_alias.py E338
lib/ansible/modules/cloud/amazon/lambda_event.py E317
lib/ansible/modules/cloud/amazon/lambda_event.py E337
lib/ansible/modules/cloud/amazon/lambda_event.py E338
lib/ansible/modules/cloud/amazon/lambda_facts.py E338
lib/ansible/modules/cloud/amazon/lambda_policy.py E337
lib/ansible/modules/cloud/amazon/lambda_policy.py E338
lib/ansible/modules/cloud/amazon/lambda.py E323
lib/ansible/modules/cloud/amazon/lambda.py E337
lib/ansible/modules/cloud/amazon/lambda.py E338
lib/ansible/modules/cloud/amazon/lightsail.py E337
lib/ansible/modules/cloud/amazon/rds_instance_info.py E337
lib/ansible/modules/cloud/amazon/rds_instance_info.py E338
lib/ansible/modules/cloud/amazon/rds_param_group.py E324
lib/ansible/modules/cloud/amazon/rds_param_group.py E337
lib/ansible/modules/cloud/amazon/rds_param_group.py E338
lib/ansible/modules/cloud/amazon/rds.py E322
lib/ansible/modules/cloud/amazon/rds.py E327
lib/ansible/modules/cloud/amazon/rds.py E337
lib/ansible/modules/cloud/amazon/rds.py E338
lib/ansible/modules/cloud/amazon/rds_snapshot_info.py E338
lib/ansible/modules/cloud/amazon/rds_subnet_group.py E324
lib/ansible/modules/cloud/amazon/rds_subnet_group.py E337
lib/ansible/modules/cloud/amazon/rds_subnet_group.py E338
lib/ansible/modules/cloud/amazon/redshift_cross_region_snapshots.py E337
lib/ansible/modules/cloud/amazon/redshift_info.py E337
lib/ansible/modules/cloud/amazon/redshift.py E322
lib/ansible/modules/cloud/amazon/redshift.py E326
lib/ansible/modules/cloud/amazon/redshift.py E337
lib/ansible/modules/cloud/amazon/redshift.py E338
lib/ansible/modules/cloud/amazon/redshift_subnet_group.py E324
lib/ansible/modules/cloud/amazon/redshift_subnet_group.py E337
lib/ansible/modules/cloud/amazon/redshift_subnet_group.py E338
lib/ansible/modules/cloud/amazon/route53_health_check.py E324
lib/ansible/modules/cloud/amazon/route53_health_check.py E337
lib/ansible/modules/cloud/amazon/route53_health_check.py E338
lib/ansible/modules/cloud/amazon/route53_info.py E337
lib/ansible/modules/cloud/amazon/route53_info.py E338
lib/ansible/modules/cloud/amazon/route53.py E326
lib/ansible/modules/cloud/amazon/route53.py E327
lib/ansible/modules/cloud/amazon/route53.py E337
lib/ansible/modules/cloud/amazon/route53_zone.py E338
lib/ansible/modules/cloud/amazon/s3_bucket.py E337
lib/ansible/modules/cloud/amazon/s3_bucket.py E338
lib/ansible/modules/cloud/amazon/s3_lifecycle.py E322
lib/ansible/modules/cloud/amazon/s3_lifecycle.py E337
lib/ansible/modules/cloud/amazon/s3_lifecycle.py E338
lib/ansible/modules/cloud/amazon/s3_logging.py E338
lib/ansible/modules/cloud/amazon/s3_sync.py E322
lib/ansible/modules/cloud/amazon/s3_sync.py E326
lib/ansible/modules/cloud/amazon/s3_sync.py E337
lib/ansible/modules/cloud/amazon/s3_sync.py E338
lib/ansible/modules/cloud/amazon/s3_website.py E324
lib/ansible/modules/cloud/amazon/s3_website.py E337
lib/ansible/modules/cloud/amazon/sns.py E337
lib/ansible/modules/cloud/amazon/sns.py E338
lib/ansible/modules/cloud/amazon/sns_topic.py E337
lib/ansible/modules/cloud/amazon/sns_topic.py E338
lib/ansible/modules/cloud/amazon/sqs_queue.py E337
lib/ansible/modules/cloud/amazon/sqs_queue.py E338
lib/ansible/modules/cloud/amazon/sts_assume_role.py E317
lib/ansible/modules/cloud/amazon/sts_assume_role.py E337
lib/ansible/modules/cloud/amazon/sts_assume_role.py E338
lib/ansible/modules/cloud/amazon/sts_session_token.py E337
lib/ansible/modules/cloud/amazon/sts_session_token.py E338
lib/ansible/modules/cloud/atomic/atomic_container.py E317
lib/ansible/modules/cloud/atomic/atomic_container.py E337
lib/ansible/modules/cloud/atomic/atomic_container.py E338
lib/ansible/modules/cloud/atomic/atomic_host.py E337
lib/ansible/modules/cloud/atomic/atomic_image.py E337
lib/ansible/modules/cloud/azure/azure_rm_acs.py E337
lib/ansible/modules/cloud/azure/azure_rm_aks_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_aks.py E337
lib/ansible/modules/cloud/azure/azure_rm_aksversion_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_appgateway.py E337
lib/ansible/modules/cloud/azure/azure_rm_applicationsecuritygroup_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_applicationsecuritygroup.py E337
lib/ansible/modules/cloud/azure/azure_rm_appserviceplan_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_appserviceplan.py E337
lib/ansible/modules/cloud/azure/azure_rm_autoscale_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_autoscale.py E337
lib/ansible/modules/cloud/azure/azure_rm_availabilityset_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_availabilityset.py E337
lib/ansible/modules/cloud/azure/azure_rm_azurefirewall.py E337
lib/ansible/modules/cloud/azure/azure_rm_batchaccount.py E337
lib/ansible/modules/cloud/azure/azure_rm_cdnendpoint_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_cdnendpoint.py E337
lib/ansible/modules/cloud/azure/azure_rm_cdnprofile_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_cdnprofile.py E337
lib/ansible/modules/cloud/azure/azure_rm_containerinstance_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_containerinstance.py E337
lib/ansible/modules/cloud/azure/azure_rm_containerregistry_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_containerregistry.py E337
lib/ansible/modules/cloud/azure/azure_rm_cosmosdbaccount_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_cosmosdbaccount.py E337
lib/ansible/modules/cloud/azure/azure_rm_deployment_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_deployment.py E337
lib/ansible/modules/cloud/azure/azure_rm_devtestlabarmtemplate_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_devtestlabartifact_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_devtestlabartifactsource_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_devtestlabartifactsource.py E337
lib/ansible/modules/cloud/azure/azure_rm_devtestlabcustomimage_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_devtestlabcustomimage.py E337
lib/ansible/modules/cloud/azure/azure_rm_devtestlabenvironment_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_devtestlabenvironment.py E337
lib/ansible/modules/cloud/azure/azure_rm_devtestlab_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_devtestlabpolicy_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_devtestlabpolicy.py E337
lib/ansible/modules/cloud/azure/azure_rm_devtestlab.py E337
lib/ansible/modules/cloud/azure/azure_rm_devtestlabschedule_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_devtestlabschedule.py E337
lib/ansible/modules/cloud/azure/azure_rm_devtestlabvirtualmachine_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_devtestlabvirtualmachine.py E337
lib/ansible/modules/cloud/azure/azure_rm_devtestlabvirtualnetwork_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_devtestlabvirtualnetwork.py E337
lib/ansible/modules/cloud/azure/azure_rm_dnsrecordset_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_dnsrecordset.py E337
lib/ansible/modules/cloud/azure/azure_rm_dnsrecordset.py E338
lib/ansible/modules/cloud/azure/azure_rm_dnszone_facts.py E325
lib/ansible/modules/cloud/azure/azure_rm_dnszone_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_dnszone.py E337
lib/ansible/modules/cloud/azure/azure_rm_functionapp_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_functionapp.py E337
lib/ansible/modules/cloud/azure/azure_rm_hdinsightcluster_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_hdinsightcluster.py E337
lib/ansible/modules/cloud/azure/azure_rm_image_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_image.py E337
lib/ansible/modules/cloud/azure/azure_rm_keyvault_info.py E337
lib/ansible/modules/cloud/azure/azure_rm_keyvaultkey.py E337
lib/ansible/modules/cloud/azure/azure_rm_keyvault.py E337
lib/ansible/modules/cloud/azure/azure_rm_keyvaultsecret.py E337
lib/ansible/modules/cloud/azure/azure_rm_loadbalancer_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_loadbalancer.py E337
lib/ansible/modules/cloud/azure/azure_rm_loganalyticsworkspace_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_loganalyticsworkspace.py E337
lib/ansible/modules/cloud/azure/azure_rm_manageddisk_facts.py E325
lib/ansible/modules/cloud/azure/azure_rm_manageddisk.py E337
lib/ansible/modules/cloud/azure/azure_rm_mariadbconfiguration_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_mariadbconfiguration.py E337
lib/ansible/modules/cloud/azure/azure_rm_mariadbdatabase_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_mariadbdatabase.py E337
lib/ansible/modules/cloud/azure/azure_rm_mariadbfirewallrule_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_mariadbfirewallrule.py E337
lib/ansible/modules/cloud/azure/azure_rm_mariadbserver_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_mariadbserver.py E337
lib/ansible/modules/cloud/azure/azure_rm_mysqlconfiguration_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_mysqlconfiguration.py E337
lib/ansible/modules/cloud/azure/azure_rm_mysqldatabase_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_mysqldatabase.py E337
lib/ansible/modules/cloud/azure/azure_rm_mysqlfirewallrule_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_mysqlfirewallrule.py E337
lib/ansible/modules/cloud/azure/azure_rm_mysqlserver_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_mysqlserver.py E337
lib/ansible/modules/cloud/azure/azure_rm_networkinterface_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_networkinterface.py E337
lib/ansible/modules/cloud/azure/azure_rm_networkinterface.py E338
lib/ansible/modules/cloud/azure/azure_rm_postgresqlconfiguration_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_postgresqlconfiguration.py E337
lib/ansible/modules/cloud/azure/azure_rm_postgresqldatabase_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_postgresqldatabase.py E337
lib/ansible/modules/cloud/azure/azure_rm_postgresqlfirewallrule_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_postgresqlfirewallrule.py E337
lib/ansible/modules/cloud/azure/azure_rm_postgresqlserver_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_postgresqlserver.py E337
lib/ansible/modules/cloud/azure/azure_rm_publicipaddress_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_publicipaddress.py E337
lib/ansible/modules/cloud/azure/azure_rm_rediscache_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_rediscachefirewallrule.py E337
lib/ansible/modules/cloud/azure/azure_rm_rediscache.py E337
lib/ansible/modules/cloud/azure/azure_rm_resource_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_resourcegroup_info.py E337
lib/ansible/modules/cloud/azure/azure_rm_resourcegroup.py E337
lib/ansible/modules/cloud/azure/azure_rm_resource.py E337
lib/ansible/modules/cloud/azure/azure_rm_roleassignment_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_roleassignment.py E337
lib/ansible/modules/cloud/azure/azure_rm_roledefinition_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_roledefinition.py E337
lib/ansible/modules/cloud/azure/azure_rm_route.py E337
lib/ansible/modules/cloud/azure/azure_rm_routetable_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_routetable.py E337
lib/ansible/modules/cloud/azure/azure_rm_securitygroup_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_securitygroup.py E337
lib/ansible/modules/cloud/azure/azure_rm_servicebus_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_servicebus.py E337
lib/ansible/modules/cloud/azure/azure_rm_servicebusqueue.py E337
lib/ansible/modules/cloud/azure/azure_rm_servicebussaspolicy.py E337
lib/ansible/modules/cloud/azure/azure_rm_servicebustopic.py E337
lib/ansible/modules/cloud/azure/azure_rm_servicebustopicsubscription.py E337
lib/ansible/modules/cloud/azure/azure_rm_sqldatabase_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_sqldatabase.py E337
lib/ansible/modules/cloud/azure/azure_rm_sqlfirewallrule_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_sqlfirewallrule.py E337
lib/ansible/modules/cloud/azure/azure_rm_sqlserver_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_sqlserver.py E337
lib/ansible/modules/cloud/azure/azure_rm_storageaccount_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_storageaccount.py E337
lib/ansible/modules/cloud/azure/azure_rm_storageaccount.py E338
lib/ansible/modules/cloud/azure/azure_rm_storageblob.py E337
lib/ansible/modules/cloud/azure/azure_rm_subnet_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_subnet.py E337
lib/ansible/modules/cloud/azure/azure_rm_trafficmanagerendpoint_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_trafficmanagerendpoint.py E337
lib/ansible/modules/cloud/azure/azure_rm_trafficmanagerprofile_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_trafficmanagerprofile.py E337
lib/ansible/modules/cloud/azure/azure_rm_virtualmachineextension_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_virtualmachineextension.py E337
lib/ansible/modules/cloud/azure/azure_rm_virtualmachine_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_virtualmachineimage_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_virtualmachine.py E337
lib/ansible/modules/cloud/azure/azure_rm_virtualmachinescalesetextension_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_virtualmachinescalesetextension.py E337
lib/ansible/modules/cloud/azure/azure_rm_virtualmachinescaleset_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_virtualmachinescalesetinstance_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_virtualmachinescalesetinstance.py E337
lib/ansible/modules/cloud/azure/azure_rm_virtualmachinescaleset.py E337
lib/ansible/modules/cloud/azure/azure_rm_virtualnetwork_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_virtualnetworkgateway.py E337
lib/ansible/modules/cloud/azure/azure_rm_virtualnetworkgateway.py E338
lib/ansible/modules/cloud/azure/azure_rm_virtualnetworkpeering_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_virtualnetworkpeering.py E337
lib/ansible/modules/cloud/azure/azure_rm_virtualnetwork.py E337
lib/ansible/modules/cloud/azure/azure_rm_webapp_facts.py E337
lib/ansible/modules/cloud/azure/azure_rm_webapp.py E337
lib/ansible/modules/cloud/azure/azure_rm_webappslot.py E337
lib/ansible/modules/cloud/centurylink/clc_aa_policy.py E335
lib/ansible/modules/cloud/centurylink/clc_aa_policy.py E338
lib/ansible/modules/cloud/centurylink/clc_alert_policy.py E317
lib/ansible/modules/cloud/centurylink/clc_alert_policy.py E337
lib/ansible/modules/cloud/centurylink/clc_alert_policy.py E338
lib/ansible/modules/cloud/centurylink/clc_blueprint_package.py E335
lib/ansible/modules/cloud/centurylink/clc_blueprint_package.py E337
lib/ansible/modules/cloud/centurylink/clc_blueprint_package.py E338
lib/ansible/modules/cloud/centurylink/clc_firewall_policy.py E317
lib/ansible/modules/cloud/centurylink/clc_firewall_policy.py E324
lib/ansible/modules/cloud/centurylink/clc_firewall_policy.py E326
lib/ansible/modules/cloud/centurylink/clc_firewall_policy.py E335
lib/ansible/modules/cloud/centurylink/clc_firewall_policy.py E337
lib/ansible/modules/cloud/centurylink/clc_firewall_policy.py E338
lib/ansible/modules/cloud/centurylink/clc_group.py E338
lib/ansible/modules/cloud/centurylink/clc_loadbalancer.py E337
lib/ansible/modules/cloud/centurylink/clc_loadbalancer.py E338
lib/ansible/modules/cloud/centurylink/clc_modify_server.py E337
lib/ansible/modules/cloud/centurylink/clc_modify_server.py E338
lib/ansible/modules/cloud/centurylink/clc_publicip.py E337
lib/ansible/modules/cloud/centurylink/clc_publicip.py E338
lib/ansible/modules/cloud/centurylink/clc_server.py E337
lib/ansible/modules/cloud/centurylink/clc_server.py E338
lib/ansible/modules/cloud/centurylink/clc_server_snapshot.py E335
lib/ansible/modules/cloud/centurylink/clc_server_snapshot.py E337
lib/ansible/modules/cloud/centurylink/clc_server_snapshot.py E338
lib/ansible/modules/cloud/cloudscale/cloudscale_floating_ip.py E337
lib/ansible/modules/cloud/cloudscale/cloudscale_floating_ip.py E338
lib/ansible/modules/cloud/cloudscale/cloudscale_server_group.py E337
lib/ansible/modules/cloud/cloudscale/cloudscale_server_group.py E338
lib/ansible/modules/cloud/cloudscale/cloudscale_server.py E337
lib/ansible/modules/cloud/cloudscale/cloudscale_server.py E338
lib/ansible/modules/cloud/cloudscale/cloudscale_volume.py E337
lib/ansible/modules/cloud/cloudscale/cloudscale_volume.py E338
lib/ansible/modules/cloud/cloudstack/cs_affinitygroup.py E338
lib/ansible/modules/cloud/cloudstack/cs_network.py E338
lib/ansible/modules/cloud/cloudstack/cs_role.py E338
lib/ansible/modules/cloud/cloudstack/cs_zone_facts.py E338
lib/ansible/modules/cloud/digital_ocean/digital_ocean_block_storage.py E337
lib/ansible/modules/cloud/digital_ocean/digital_ocean_block_storage.py E338
lib/ansible/modules/cloud/digital_ocean/digital_ocean_certificate_info.py E337
lib/ansible/modules/cloud/digital_ocean/digital_ocean_certificate.py E337
lib/ansible/modules/cloud/digital_ocean/digital_ocean_certificate.py E338
lib/ansible/modules/cloud/digital_ocean/digital_ocean_domain_info.py E337
lib/ansible/modules/cloud/digital_ocean/digital_ocean_domain.py E337
lib/ansible/modules/cloud/digital_ocean/digital_ocean_domain.py E338
lib/ansible/modules/cloud/digital_ocean/digital_ocean_droplet.py E337
lib/ansible/modules/cloud/digital_ocean/digital_ocean_droplet.py E338
lib/ansible/modules/cloud/digital_ocean/digital_ocean_firewall_info.py E337
lib/ansible/modules/cloud/digital_ocean/digital_ocean_floating_ip.py E322
lib/ansible/modules/cloud/digital_ocean/digital_ocean_floating_ip.py E324
lib/ansible/modules/cloud/digital_ocean/digital_ocean_floating_ip.py E337
lib/ansible/modules/cloud/digital_ocean/digital_ocean_floating_ip.py E338
lib/ansible/modules/cloud/digital_ocean/digital_ocean_image_info.py E337
lib/ansible/modules/cloud/digital_ocean/digital_ocean_load_balancer_info.py E337
lib/ansible/modules/cloud/digital_ocean/_digital_ocean.py E322
lib/ansible/modules/cloud/digital_ocean/_digital_ocean.py E337
lib/ansible/modules/cloud/digital_ocean/_digital_ocean.py E338
lib/ansible/modules/cloud/digital_ocean/digital_ocean_snapshot_info.py E337
lib/ansible/modules/cloud/digital_ocean/digital_ocean_sshkey.py E322
lib/ansible/modules/cloud/digital_ocean/digital_ocean_sshkey.py E324
lib/ansible/modules/cloud/digital_ocean/digital_ocean_sshkey.py E337
lib/ansible/modules/cloud/digital_ocean/digital_ocean_sshkey.py E338
lib/ansible/modules/cloud/digital_ocean/digital_ocean_tag_info.py E337
lib/ansible/modules/cloud/digital_ocean/digital_ocean_tag.py E337
lib/ansible/modules/cloud/digital_ocean/digital_ocean_tag.py E338
lib/ansible/modules/cloud/digital_ocean/digital_ocean_volume_info.py E337
lib/ansible/modules/cloud/dimensiondata/dimensiondata_network.py E326
lib/ansible/modules/cloud/dimensiondata/dimensiondata_network.py E337
lib/ansible/modules/cloud/dimensiondata/dimensiondata_network.py E338
lib/ansible/modules/cloud/dimensiondata/dimensiondata_vlan.py E326
lib/ansible/modules/cloud/dimensiondata/dimensiondata_vlan.py E337
lib/ansible/modules/cloud/dimensiondata/dimensiondata_vlan.py E338
lib/ansible/modules/cloud/google/_gcdns_record.py E337
lib/ansible/modules/cloud/google/_gcdns_zone.py E337
lib/ansible/modules/cloud/google/gce_eip.py E322
lib/ansible/modules/cloud/google/gce_eip.py E337
lib/ansible/modules/cloud/google/gce_eip.py E338
lib/ansible/modules/cloud/google/gce_img.py E337
lib/ansible/modules/cloud/google/gce_img.py E338
lib/ansible/modules/cloud/google/gce_instance_template.py E322
lib/ansible/modules/cloud/google/gce_instance_template.py E324
lib/ansible/modules/cloud/google/gce_instance_template.py E326
lib/ansible/modules/cloud/google/gce_instance_template.py E337
lib/ansible/modules/cloud/google/gce_instance_template.py E338
lib/ansible/modules/cloud/google/gce_labels.py E322
lib/ansible/modules/cloud/google/gce_labels.py E324
lib/ansible/modules/cloud/google/gce_labels.py E326
lib/ansible/modules/cloud/google/gce_labels.py E337
lib/ansible/modules/cloud/google/gce_labels.py E338
lib/ansible/modules/cloud/google/gce_lb.py E323
lib/ansible/modules/cloud/google/gce_lb.py E326
lib/ansible/modules/cloud/google/gce_lb.py E337
lib/ansible/modules/cloud/google/gce_lb.py E338
lib/ansible/modules/cloud/google/gce_mig.py E322
lib/ansible/modules/cloud/google/gce_mig.py E337
lib/ansible/modules/cloud/google/gce_mig.py E338
lib/ansible/modules/cloud/google/gce_net.py E323
lib/ansible/modules/cloud/google/gce_net.py E326
lib/ansible/modules/cloud/google/gce_net.py E337
lib/ansible/modules/cloud/google/gce_net.py E338
lib/ansible/modules/cloud/google/gce_pd.py E322
lib/ansible/modules/cloud/google/gce_pd.py E326
lib/ansible/modules/cloud/google/gce_pd.py E337
lib/ansible/modules/cloud/google/gce_pd.py E338
lib/ansible/modules/cloud/google/_gce.py E326
lib/ansible/modules/cloud/google/_gce.py E337
lib/ansible/modules/cloud/google/_gce.py E338
lib/ansible/modules/cloud/google/gce_snapshot.py E324
lib/ansible/modules/cloud/google/gce_snapshot.py E337
lib/ansible/modules/cloud/google/gce_snapshot.py E338
lib/ansible/modules/cloud/google/gce_tag.py E337
lib/ansible/modules/cloud/google/_gcp_backend_service.py E322
lib/ansible/modules/cloud/google/_gcp_backend_service.py E324
lib/ansible/modules/cloud/google/_gcp_backend_service.py E326
lib/ansible/modules/cloud/google/_gcp_backend_service.py E337
lib/ansible/modules/cloud/google/_gcp_backend_service.py E338
lib/ansible/modules/cloud/google/gcp_bigquery_dataset.py E337
lib/ansible/modules/cloud/google/gcp_bigquery_table_facts.py E337
lib/ansible/modules/cloud/google/gcp_bigquery_table.py E337
lib/ansible/modules/cloud/google/gcp_cloudbuild_trigger.py E337
lib/ansible/modules/cloud/google/gcp_cloudscheduler_job_facts.py E337
lib/ansible/modules/cloud/google/gcp_cloudscheduler_job.py E337
lib/ansible/modules/cloud/google/gcp_compute_address_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_address.py E337
lib/ansible/modules/cloud/google/gcp_compute_backend_bucket_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_backend_bucket.py E337
lib/ansible/modules/cloud/google/gcp_compute_backend_service_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_backend_service.py E337
lib/ansible/modules/cloud/google/gcp_compute_disk_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_disk.py E337
lib/ansible/modules/cloud/google/gcp_compute_firewall_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_firewall.py E337
lib/ansible/modules/cloud/google/gcp_compute_forwarding_rule_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_forwarding_rule.py E337
lib/ansible/modules/cloud/google/gcp_compute_global_address_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_global_address.py E337
lib/ansible/modules/cloud/google/gcp_compute_global_forwarding_rule_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_global_forwarding_rule.py E337
lib/ansible/modules/cloud/google/gcp_compute_health_check_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_health_check.py E337
lib/ansible/modules/cloud/google/gcp_compute_http_health_check_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_http_health_check.py E337
lib/ansible/modules/cloud/google/gcp_compute_https_health_check_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_https_health_check.py E337
lib/ansible/modules/cloud/google/gcp_compute_image_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_image.py E337
lib/ansible/modules/cloud/google/gcp_compute_instance_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_instance_group_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_instance_group_manager_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_instance_group_manager.py E337
lib/ansible/modules/cloud/google/gcp_compute_instance_group.py E337
lib/ansible/modules/cloud/google/gcp_compute_instance.py E337
lib/ansible/modules/cloud/google/gcp_compute_instance_template_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_instance_template.py E337
lib/ansible/modules/cloud/google/gcp_compute_interconnect_attachment_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_interconnect_attachment.py E337
lib/ansible/modules/cloud/google/gcp_compute_network_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_network.py E337
lib/ansible/modules/cloud/google/gcp_compute_region_disk_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_region_disk.py E337
lib/ansible/modules/cloud/google/gcp_compute_route_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_route.py E337
lib/ansible/modules/cloud/google/gcp_compute_router_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_router.py E337
lib/ansible/modules/cloud/google/gcp_compute_ssl_certificate_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_ssl_certificate.py E337
lib/ansible/modules/cloud/google/gcp_compute_ssl_policy_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_ssl_policy.py E337
lib/ansible/modules/cloud/google/gcp_compute_subnetwork_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_subnetwork.py E337
lib/ansible/modules/cloud/google/gcp_compute_target_http_proxy_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_target_http_proxy.py E337
lib/ansible/modules/cloud/google/gcp_compute_target_https_proxy_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_target_https_proxy.py E337
lib/ansible/modules/cloud/google/gcp_compute_target_pool_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_target_pool.py E337
lib/ansible/modules/cloud/google/gcp_compute_target_ssl_proxy_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_target_ssl_proxy.py E337
lib/ansible/modules/cloud/google/gcp_compute_target_tcp_proxy_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_target_tcp_proxy.py E337
lib/ansible/modules/cloud/google/gcp_compute_target_vpn_gateway_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_target_vpn_gateway.py E337
lib/ansible/modules/cloud/google/gcp_compute_url_map_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_url_map.py E337
lib/ansible/modules/cloud/google/gcp_compute_vpn_tunnel_facts.py E337
lib/ansible/modules/cloud/google/gcp_compute_vpn_tunnel.py E337
lib/ansible/modules/cloud/google/gcp_container_cluster_facts.py E337
lib/ansible/modules/cloud/google/gcp_container_cluster.py E337
lib/ansible/modules/cloud/google/gcp_container_node_pool_facts.py E337
lib/ansible/modules/cloud/google/gcp_container_node_pool.py E337
lib/ansible/modules/cloud/google/gcp_dns_managed_zone_facts.py E337
lib/ansible/modules/cloud/google/gcp_dns_managed_zone.py E337
lib/ansible/modules/cloud/google/gcp_dns_resource_record_set_facts.py E337
lib/ansible/modules/cloud/google/gcp_dns_resource_record_set.py E337
lib/ansible/modules/cloud/google/_gcp_forwarding_rule.py E322
lib/ansible/modules/cloud/google/_gcp_forwarding_rule.py E324
lib/ansible/modules/cloud/google/_gcp_forwarding_rule.py E326
lib/ansible/modules/cloud/google/_gcp_forwarding_rule.py E337
lib/ansible/modules/cloud/google/_gcp_forwarding_rule.py E338
lib/ansible/modules/cloud/google/_gcp_healthcheck.py E324
lib/ansible/modules/cloud/google/_gcp_healthcheck.py E326
lib/ansible/modules/cloud/google/_gcp_healthcheck.py E337
lib/ansible/modules/cloud/google/_gcp_healthcheck.py E338
lib/ansible/modules/cloud/google/gcp_iam_role.py E337
lib/ansible/modules/cloud/google/gcp_iam_service_account_key.py E337
lib/ansible/modules/cloud/google/gcp_iam_service_account.py E337
lib/ansible/modules/cloud/google/gcp_pubsub_subscription.py E337
lib/ansible/modules/cloud/google/gcp_pubsub_topic.py E337
lib/ansible/modules/cloud/google/gcp_redis_instance_facts.py E337
lib/ansible/modules/cloud/google/gcp_redis_instance.py E337
lib/ansible/modules/cloud/google/gcp_resourcemanager_project.py E337
lib/ansible/modules/cloud/google/gcp_sourcerepo_repository.py E337
lib/ansible/modules/cloud/google/gcp_spanner_database_facts.py E337
lib/ansible/modules/cloud/google/gcp_spanner_database.py E337
lib/ansible/modules/cloud/google/gcp_spanner_instance.py E337
lib/ansible/modules/cloud/google/gcp_sql_database_facts.py E337
lib/ansible/modules/cloud/google/gcp_sql_database.py E337
lib/ansible/modules/cloud/google/gcp_sql_instance.py E337
lib/ansible/modules/cloud/google/gcp_sql_user_facts.py E337
lib/ansible/modules/cloud/google/gcp_sql_user.py E337
lib/ansible/modules/cloud/google/gcp_storage_bucket_access_control.py E337
lib/ansible/modules/cloud/google/gcp_storage_bucket.py E337
lib/ansible/modules/cloud/google/gcp_storage_object.py E337
lib/ansible/modules/cloud/google/_gcp_target_proxy.py E322
lib/ansible/modules/cloud/google/_gcp_target_proxy.py E326
lib/ansible/modules/cloud/google/_gcp_target_proxy.py E337
lib/ansible/modules/cloud/google/_gcp_target_proxy.py E338
lib/ansible/modules/cloud/google/gcp_tpu_node_facts.py E337
lib/ansible/modules/cloud/google/gcp_tpu_node.py E337
lib/ansible/modules/cloud/google/gcpubsub_facts.py E322
lib/ansible/modules/cloud/google/gcpubsub_facts.py E324
lib/ansible/modules/cloud/google/gcpubsub_facts.py E326
lib/ansible/modules/cloud/google/gcpubsub_facts.py E338
lib/ansible/modules/cloud/google/gcpubsub.py E322
lib/ansible/modules/cloud/google/gcpubsub.py E323
lib/ansible/modules/cloud/google/gcpubsub.py E337
lib/ansible/modules/cloud/google/_gcp_url_map.py E322
lib/ansible/modules/cloud/google/_gcp_url_map.py E324
lib/ansible/modules/cloud/google/_gcp_url_map.py E326
lib/ansible/modules/cloud/google/_gcp_url_map.py E337
lib/ansible/modules/cloud/google/_gcp_url_map.py E338
lib/ansible/modules/cloud/google/_gcspanner.py E322
lib/ansible/modules/cloud/google/_gcspanner.py E337
lib/ansible/modules/cloud/google/gc_storage.py E322
lib/ansible/modules/cloud/google/gc_storage.py E324
lib/ansible/modules/cloud/google/gc_storage.py E326
lib/ansible/modules/cloud/google/gc_storage.py E337
lib/ansible/modules/cloud/google/gc_storage.py E338
lib/ansible/modules/cloud/hcloud/hcloud_image_facts.py E338
lib/ansible/modules/cloud/heroku/heroku_collaborator.py E337
lib/ansible/modules/cloud/kubevirt/kubevirt_cdi_upload.py E338
lib/ansible/modules/cloud/kubevirt/kubevirt_preset.py E337
lib/ansible/modules/cloud/kubevirt/kubevirt_preset.py E338
lib/ansible/modules/cloud/kubevirt/kubevirt_pvc.py E337
lib/ansible/modules/cloud/kubevirt/kubevirt_pvc.py E338
lib/ansible/modules/cloud/kubevirt/kubevirt_rs.py E337
lib/ansible/modules/cloud/kubevirt/kubevirt_rs.py E338
lib/ansible/modules/cloud/kubevirt/kubevirt_template.py E338
lib/ansible/modules/cloud/kubevirt/kubevirt_vm.py E337
lib/ansible/modules/cloud/kubevirt/kubevirt_vm.py E338
lib/ansible/modules/cloud/linode/linode.py E322
lib/ansible/modules/cloud/linode/linode.py E324
lib/ansible/modules/cloud/linode/linode.py E337
lib/ansible/modules/cloud/linode/linode_v4.py E337
lib/ansible/modules/cloud/lxc/lxc_container.py E210
lib/ansible/modules/cloud/lxc/lxc_container.py E324
lib/ansible/modules/cloud/lxc/lxc_container.py E326
lib/ansible/modules/cloud/lxc/lxc_container.py E337
lib/ansible/modules/cloud/lxc/lxc_container.py E338
lib/ansible/modules/cloud/lxd/lxd_container.py E322
lib/ansible/modules/cloud/lxd/lxd_container.py E324
lib/ansible/modules/cloud/lxd/lxd_container.py E337
lib/ansible/modules/cloud/lxd/lxd_container.py E338
lib/ansible/modules/cloud/lxd/lxd_profile.py E324
lib/ansible/modules/cloud/lxd/lxd_profile.py E337
lib/ansible/modules/cloud/lxd/lxd_profile.py E338
lib/ansible/modules/cloud/memset/memset_dns_reload.py E337
lib/ansible/modules/cloud/memset/memset_memstore_info.py E337
lib/ansible/modules/cloud/memset/memset_server_info.py E337
lib/ansible/modules/cloud/memset/memset_zone_domain.py E337
lib/ansible/modules/cloud/memset/memset_zone.py E337
lib/ansible/modules/cloud/memset/memset_zone_record.py E337
lib/ansible/modules/cloud/misc/cloud_init_data_facts.py E338
lib/ansible/modules/cloud/misc/helm.py E337
lib/ansible/modules/cloud/misc/helm.py E338
lib/ansible/modules/cloud/misc/ovirt.py E322
lib/ansible/modules/cloud/misc/ovirt.py E326
lib/ansible/modules/cloud/misc/ovirt.py E337
lib/ansible/modules/cloud/misc/proxmox_kvm.py E322
lib/ansible/modules/cloud/misc/proxmox_kvm.py E324
lib/ansible/modules/cloud/misc/proxmox_kvm.py E337
lib/ansible/modules/cloud/misc/proxmox_kvm.py E338
lib/ansible/modules/cloud/misc/proxmox.py E337
lib/ansible/modules/cloud/misc/proxmox.py E338
lib/ansible/modules/cloud/misc/proxmox_template.py E323
lib/ansible/modules/cloud/misc/proxmox_template.py E337
lib/ansible/modules/cloud/misc/proxmox_template.py E338
lib/ansible/modules/cloud/misc/terraform.py E324
lib/ansible/modules/cloud/misc/terraform.py E337
lib/ansible/modules/cloud/misc/terraform.py E338
lib/ansible/modules/cloud/misc/virt_net.py E338
lib/ansible/modules/cloud/misc/virt_pool.py E326
lib/ansible/modules/cloud/misc/virt_pool.py E338
lib/ansible/modules/cloud/misc/virt.py E322
lib/ansible/modules/cloud/misc/virt.py E326
lib/ansible/modules/cloud/misc/virt.py E337
lib/ansible/modules/cloud/oneandone/oneandone_firewall_policy.py E337
lib/ansible/modules/cloud/oneandone/oneandone_load_balancer.py E324
lib/ansible/modules/cloud/oneandone/oneandone_load_balancer.py E337
lib/ansible/modules/cloud/oneandone/oneandone_load_balancer.py E338
lib/ansible/modules/cloud/oneandone/oneandone_monitoring_policy.py E337
lib/ansible/modules/cloud/oneandone/oneandone_private_network.py E326
lib/ansible/modules/cloud/oneandone/oneandone_private_network.py E337
lib/ansible/modules/cloud/oneandone/oneandone_private_network.py E338
lib/ansible/modules/cloud/oneandone/oneandone_public_ip.py E324
lib/ansible/modules/cloud/oneandone/oneandone_public_ip.py E326
lib/ansible/modules/cloud/oneandone/oneandone_public_ip.py E337
lib/ansible/modules/cloud/oneandone/oneandone_public_ip.py E338
lib/ansible/modules/cloud/oneandone/oneandone_server.py E326
lib/ansible/modules/cloud/oneandone/oneandone_server.py E337
lib/ansible/modules/cloud/oneandone/oneandone_server.py E338
lib/ansible/modules/cloud/opennebula/one_host.py E337
lib/ansible/modules/cloud/opennebula/one_host.py E338
lib/ansible/modules/cloud/opennebula/one_image_info.py E337
lib/ansible/modules/cloud/opennebula/one_image.py E337
lib/ansible/modules/cloud/opennebula/one_service.py E337
lib/ansible/modules/cloud/opennebula/one_vm.py E337
lib/ansible/modules/cloud/openstack/os_auth.py E338
lib/ansible/modules/cloud/openstack/os_client_config.py E337
lib/ansible/modules/cloud/openstack/os_coe_cluster.py E337
lib/ansible/modules/cloud/openstack/os_coe_cluster.py E338
lib/ansible/modules/cloud/openstack/os_coe_cluster_template.py E337
lib/ansible/modules/cloud/openstack/os_coe_cluster_template.py E338
lib/ansible/modules/cloud/openstack/os_flavor_facts.py E324
lib/ansible/modules/cloud/openstack/os_flavor_facts.py E335
lib/ansible/modules/cloud/openstack/os_flavor_facts.py E337
lib/ansible/modules/cloud/openstack/os_flavor_facts.py E338
lib/ansible/modules/cloud/openstack/os_floating_ip.py E338
lib/ansible/modules/cloud/openstack/os_group.py E338
lib/ansible/modules/cloud/openstack/os_image_facts.py E338
lib/ansible/modules/cloud/openstack/os_image.py E324
lib/ansible/modules/cloud/openstack/os_image.py E326
lib/ansible/modules/cloud/openstack/os_image.py E337
lib/ansible/modules/cloud/openstack/os_image.py E338
lib/ansible/modules/cloud/openstack/os_ironic_inspect.py E338
lib/ansible/modules/cloud/openstack/os_ironic_node.py E322
lib/ansible/modules/cloud/openstack/os_ironic_node.py E324
lib/ansible/modules/cloud/openstack/os_ironic_node.py E326
lib/ansible/modules/cloud/openstack/os_ironic_node.py E335
lib/ansible/modules/cloud/openstack/os_ironic_node.py E337
lib/ansible/modules/cloud/openstack/os_ironic_node.py E338
lib/ansible/modules/cloud/openstack/os_ironic.py E322
lib/ansible/modules/cloud/openstack/os_ironic.py E323
lib/ansible/modules/cloud/openstack/os_ironic.py E326
lib/ansible/modules/cloud/openstack/os_ironic.py E337
lib/ansible/modules/cloud/openstack/os_ironic.py E338
lib/ansible/modules/cloud/openstack/os_keypair.py E338
lib/ansible/modules/cloud/openstack/os_keystone_domain_facts.py E337
lib/ansible/modules/cloud/openstack/os_keystone_domain_facts.py E338
lib/ansible/modules/cloud/openstack/os_keystone_domain.py E338
lib/ansible/modules/cloud/openstack/os_keystone_endpoint.py E322
lib/ansible/modules/cloud/openstack/os_keystone_endpoint.py E326
lib/ansible/modules/cloud/openstack/os_keystone_endpoint.py E337
lib/ansible/modules/cloud/openstack/os_keystone_endpoint.py E338
lib/ansible/modules/cloud/openstack/os_keystone_role.py E338
lib/ansible/modules/cloud/openstack/os_keystone_service.py E338
lib/ansible/modules/cloud/openstack/os_listener.py E337
lib/ansible/modules/cloud/openstack/os_listener.py E338
lib/ansible/modules/cloud/openstack/os_loadbalancer.py E337
lib/ansible/modules/cloud/openstack/os_loadbalancer.py E338
lib/ansible/modules/cloud/openstack/os_member.py E337
lib/ansible/modules/cloud/openstack/os_member.py E338
lib/ansible/modules/cloud/openstack/os_network.py E337
lib/ansible/modules/cloud/openstack/os_network.py E338
lib/ansible/modules/cloud/openstack/os_networks_facts.py E337
lib/ansible/modules/cloud/openstack/os_networks_facts.py E338
lib/ansible/modules/cloud/openstack/os_nova_flavor.py E337
lib/ansible/modules/cloud/openstack/os_nova_flavor.py E338
lib/ansible/modules/cloud/openstack/os_nova_host_aggregate.py E337
lib/ansible/modules/cloud/openstack/os_nova_host_aggregate.py E338
lib/ansible/modules/cloud/openstack/os_object.py E338
lib/ansible/modules/cloud/openstack/os_pool.py E338
lib/ansible/modules/cloud/openstack/os_port_facts.py E337
lib/ansible/modules/cloud/openstack/os_port_facts.py E338
lib/ansible/modules/cloud/openstack/os_port.py E337
lib/ansible/modules/cloud/openstack/os_port.py E338
lib/ansible/modules/cloud/openstack/os_project_access.py E337
lib/ansible/modules/cloud/openstack/os_project_access.py E338
lib/ansible/modules/cloud/openstack/os_project_facts.py E337
lib/ansible/modules/cloud/openstack/os_project_facts.py E338
lib/ansible/modules/cloud/openstack/os_project.py E338
lib/ansible/modules/cloud/openstack/os_quota.py E322
lib/ansible/modules/cloud/openstack/os_quota.py E323
lib/ansible/modules/cloud/openstack/os_quota.py E326
lib/ansible/modules/cloud/openstack/os_quota.py E337
lib/ansible/modules/cloud/openstack/os_quota.py E338
lib/ansible/modules/cloud/openstack/os_recordset.py E337
lib/ansible/modules/cloud/openstack/os_recordset.py E338
lib/ansible/modules/cloud/openstack/os_router.py E337
lib/ansible/modules/cloud/openstack/os_router.py E338
lib/ansible/modules/cloud/openstack/os_security_group.py E338
lib/ansible/modules/cloud/openstack/os_security_group_rule.py E337
lib/ansible/modules/cloud/openstack/os_security_group_rule.py E338
lib/ansible/modules/cloud/openstack/os_server_action.py E324
lib/ansible/modules/cloud/openstack/os_server_action.py E338
lib/ansible/modules/cloud/openstack/os_server_facts.py E337
lib/ansible/modules/cloud/openstack/os_server_facts.py E338
lib/ansible/modules/cloud/openstack/os_server_group.py E337
lib/ansible/modules/cloud/openstack/os_server_group.py E338
lib/ansible/modules/cloud/openstack/os_server_metadata.py E337
lib/ansible/modules/cloud/openstack/os_server_metadata.py E338
lib/ansible/modules/cloud/openstack/os_server.py E322
lib/ansible/modules/cloud/openstack/os_server.py E324
lib/ansible/modules/cloud/openstack/os_server.py E337
lib/ansible/modules/cloud/openstack/os_server.py E338
lib/ansible/modules/cloud/openstack/os_server_volume.py E338
lib/ansible/modules/cloud/openstack/os_stack.py E324
lib/ansible/modules/cloud/openstack/os_stack.py E337
lib/ansible/modules/cloud/openstack/os_stack.py E338
lib/ansible/modules/cloud/openstack/os_subnet.py E326
lib/ansible/modules/cloud/openstack/os_subnet.py E337
lib/ansible/modules/cloud/openstack/os_subnet.py E338
lib/ansible/modules/cloud/openstack/os_subnets_facts.py E337
lib/ansible/modules/cloud/openstack/os_subnets_facts.py E338
lib/ansible/modules/cloud/openstack/os_user_facts.py E337
lib/ansible/modules/cloud/openstack/os_user_facts.py E338
lib/ansible/modules/cloud/openstack/os_user_group.py E338
lib/ansible/modules/cloud/openstack/os_user.py E337
lib/ansible/modules/cloud/openstack/os_user.py E338
lib/ansible/modules/cloud/openstack/os_user_role.py E338
lib/ansible/modules/cloud/openstack/os_volume.py E322
lib/ansible/modules/cloud/openstack/os_volume.py E337
lib/ansible/modules/cloud/openstack/os_volume.py E338
lib/ansible/modules/cloud/openstack/os_volume_snapshot.py E338
lib/ansible/modules/cloud/openstack/os_zone.py E326
lib/ansible/modules/cloud/openstack/os_zone.py E337
lib/ansible/modules/cloud/openstack/os_zone.py E338
lib/ansible/modules/cloud/oracle/oci_vcn.py E337
lib/ansible/modules/cloud/ovh/ovh_ip_failover.py E337
lib/ansible/modules/cloud/ovh/ovh_ip_failover.py E338
lib/ansible/modules/cloud/ovh/ovh_ip_loadbalancing_backend.py E337
lib/ansible/modules/cloud/ovh/ovh_ip_loadbalancing_backend.py E338
lib/ansible/modules/cloud/ovirt/ovirt_affinity_group.py E337
lib/ansible/modules/cloud/ovirt/ovirt_affinity_label_facts.py E338
lib/ansible/modules/cloud/ovirt/ovirt_affinity_label.py E317
lib/ansible/modules/cloud/ovirt/ovirt_affinity_label.py E337
lib/ansible/modules/cloud/ovirt/ovirt_affinity_label.py E338
lib/ansible/modules/cloud/ovirt/ovirt_auth.py E322
lib/ansible/modules/cloud/ovirt/ovirt_auth.py E324
lib/ansible/modules/cloud/ovirt/ovirt_auth.py E337
lib/ansible/modules/cloud/ovirt/ovirt_auth.py E338
lib/ansible/modules/cloud/ovirt/ovirt_cluster_facts.py E338
lib/ansible/modules/cloud/ovirt/ovirt_cluster.py E317
lib/ansible/modules/cloud/ovirt/ovirt_cluster.py E322
lib/ansible/modules/cloud/ovirt/ovirt_cluster.py E326
lib/ansible/modules/cloud/ovirt/ovirt_cluster.py E337
lib/ansible/modules/cloud/ovirt/ovirt_cluster.py E338
lib/ansible/modules/cloud/ovirt/ovirt_datacenter_facts.py E338
lib/ansible/modules/cloud/ovirt/ovirt_datacenter.py E317
lib/ansible/modules/cloud/ovirt/ovirt_datacenter.py E338
lib/ansible/modules/cloud/ovirt/ovirt_disk_facts.py E338
lib/ansible/modules/cloud/ovirt/ovirt_disk.py E322
lib/ansible/modules/cloud/ovirt/ovirt_disk.py E324
lib/ansible/modules/cloud/ovirt/ovirt_disk.py E326
lib/ansible/modules/cloud/ovirt/ovirt_disk.py E337
lib/ansible/modules/cloud/ovirt/ovirt_disk.py E338
lib/ansible/modules/cloud/ovirt/ovirt_external_provider_facts.py E317
lib/ansible/modules/cloud/ovirt/ovirt_external_provider_facts.py E322
lib/ansible/modules/cloud/ovirt/ovirt_external_provider_facts.py E338
lib/ansible/modules/cloud/ovirt/ovirt_external_provider.py E317
lib/ansible/modules/cloud/ovirt/ovirt_external_provider.py E322
lib/ansible/modules/cloud/ovirt/ovirt_external_provider.py E324
lib/ansible/modules/cloud/ovirt/ovirt_external_provider.py E337
lib/ansible/modules/cloud/ovirt/ovirt_external_provider.py E338
lib/ansible/modules/cloud/ovirt/ovirt_group_facts.py E338
lib/ansible/modules/cloud/ovirt/ovirt_group.py E338
lib/ansible/modules/cloud/ovirt/ovirt_host_facts.py E338
lib/ansible/modules/cloud/ovirt/ovirt_host_network.py E337
lib/ansible/modules/cloud/ovirt/ovirt_host_network.py E338
lib/ansible/modules/cloud/ovirt/ovirt_host_pm.py E317
lib/ansible/modules/cloud/ovirt/ovirt_host_pm.py E337
lib/ansible/modules/cloud/ovirt/ovirt_host_pm.py E338
lib/ansible/modules/cloud/ovirt/ovirt_host.py E335
lib/ansible/modules/cloud/ovirt/ovirt_host.py E337
lib/ansible/modules/cloud/ovirt/ovirt_host.py E338
lib/ansible/modules/cloud/ovirt/ovirt_host_storage_facts.py E337
lib/ansible/modules/cloud/ovirt/ovirt_host_storage_facts.py E338
lib/ansible/modules/cloud/ovirt/ovirt_instance_type.py E337
lib/ansible/modules/cloud/ovirt/ovirt_job.py E338
lib/ansible/modules/cloud/ovirt/ovirt_mac_pool.py E337
lib/ansible/modules/cloud/ovirt/ovirt_mac_pool.py E338
lib/ansible/modules/cloud/ovirt/ovirt_network_facts.py E338
lib/ansible/modules/cloud/ovirt/ovirt_network.py E337
lib/ansible/modules/cloud/ovirt/ovirt_network.py E338
lib/ansible/modules/cloud/ovirt/ovirt_nic_facts.py E338
lib/ansible/modules/cloud/ovirt/ovirt_nic.py E337
lib/ansible/modules/cloud/ovirt/ovirt_nic.py E338
lib/ansible/modules/cloud/ovirt/ovirt_permission_facts.py E338
lib/ansible/modules/cloud/ovirt/ovirt_permission.py E337
lib/ansible/modules/cloud/ovirt/ovirt_quota_facts.py E338
lib/ansible/modules/cloud/ovirt/ovirt_quota.py E337
lib/ansible/modules/cloud/ovirt/ovirt_quota.py E338
lib/ansible/modules/cloud/ovirt/ovirt_role.py E337
lib/ansible/modules/cloud/ovirt/ovirt_role.py E338
lib/ansible/modules/cloud/ovirt/ovirt_scheduling_policy_facts.py E338
lib/ansible/modules/cloud/ovirt/ovirt_snapshot_facts.py E338
lib/ansible/modules/cloud/ovirt/ovirt_snapshot.py E337
lib/ansible/modules/cloud/ovirt/ovirt_snapshot.py E338
lib/ansible/modules/cloud/ovirt/ovirt_storage_connection.py E337
lib/ansible/modules/cloud/ovirt/ovirt_storage_connection.py E338
lib/ansible/modules/cloud/ovirt/ovirt_storage_domain_facts.py E338
lib/ansible/modules/cloud/ovirt/ovirt_storage_domain.py E337
lib/ansible/modules/cloud/ovirt/ovirt_storage_domain.py E338
lib/ansible/modules/cloud/ovirt/ovirt_storage_template_facts.py E337
lib/ansible/modules/cloud/ovirt/ovirt_storage_template_facts.py E338
lib/ansible/modules/cloud/ovirt/ovirt_storage_vm_facts.py E337
lib/ansible/modules/cloud/ovirt/ovirt_storage_vm_facts.py E338
lib/ansible/modules/cloud/ovirt/ovirt_tag_facts.py E338
lib/ansible/modules/cloud/ovirt/ovirt_tag.py E337
lib/ansible/modules/cloud/ovirt/ovirt_tag.py E338
lib/ansible/modules/cloud/ovirt/ovirt_template_facts.py E338
lib/ansible/modules/cloud/ovirt/ovirt_template.py E337
lib/ansible/modules/cloud/ovirt/ovirt_template.py E338
lib/ansible/modules/cloud/ovirt/ovirt_user_facts.py E338
lib/ansible/modules/cloud/ovirt/ovirt_user.py E338
lib/ansible/modules/cloud/ovirt/ovirt_vm_facts.py E337
lib/ansible/modules/cloud/ovirt/ovirt_vm_facts.py E338
lib/ansible/modules/cloud/ovirt/ovirt_vmpool_facts.py E338
lib/ansible/modules/cloud/ovirt/ovirt_vmpool.py E337
lib/ansible/modules/cloud/ovirt/ovirt_vmpool.py E338
lib/ansible/modules/cloud/ovirt/ovirt_vm.py E337
lib/ansible/modules/cloud/ovirt/ovirt_vm.py E338
lib/ansible/modules/cloud/ovirt/ovirt_vnic_profile.py E337
lib/ansible/modules/cloud/packet/packet_device.py E337
lib/ansible/modules/cloud/packet/packet_device.py E338
lib/ansible/modules/cloud/packet/packet_sshkey.py E322
lib/ansible/modules/cloud/packet/packet_sshkey.py E337
lib/ansible/modules/cloud/packet/packet_sshkey.py E338
lib/ansible/modules/cloud/podman/podman_image_info.py E337
lib/ansible/modules/cloud/podman/podman_image.py E337
lib/ansible/modules/cloud/profitbricks/profitbricks_datacenter.py E326
lib/ansible/modules/cloud/profitbricks/profitbricks_datacenter.py E337
lib/ansible/modules/cloud/profitbricks/profitbricks_datacenter.py E338
lib/ansible/modules/cloud/profitbricks/profitbricks_nic.py E324
lib/ansible/modules/cloud/profitbricks/profitbricks_nic.py E326
lib/ansible/modules/cloud/profitbricks/profitbricks_nic.py E337
lib/ansible/modules/cloud/profitbricks/profitbricks_nic.py E338
lib/ansible/modules/cloud/profitbricks/profitbricks.py E322
lib/ansible/modules/cloud/profitbricks/profitbricks.py E324
lib/ansible/modules/cloud/profitbricks/profitbricks.py E326
lib/ansible/modules/cloud/profitbricks/profitbricks.py E337
lib/ansible/modules/cloud/profitbricks/profitbricks.py E338
lib/ansible/modules/cloud/profitbricks/profitbricks_volume_attachments.py E326
lib/ansible/modules/cloud/profitbricks/profitbricks_volume_attachments.py E337
lib/ansible/modules/cloud/profitbricks/profitbricks_volume_attachments.py E338
lib/ansible/modules/cloud/profitbricks/profitbricks_volume.py E322
lib/ansible/modules/cloud/profitbricks/profitbricks_volume.py E326
lib/ansible/modules/cloud/profitbricks/profitbricks_volume.py E337
lib/ansible/modules/cloud/profitbricks/profitbricks_volume.py E338
lib/ansible/modules/cloud/pubnub/pubnub_blocks.py E324
lib/ansible/modules/cloud/pubnub/pubnub_blocks.py E337
lib/ansible/modules/cloud/rackspace/rax_cbs_attachments.py E324
lib/ansible/modules/cloud/rackspace/rax_cbs_attachments.py E337
lib/ansible/modules/cloud/rackspace/rax_cbs_attachments.py E338
lib/ansible/modules/cloud/rackspace/rax_cbs.py E324
lib/ansible/modules/cloud/rackspace/rax_cbs.py E337
lib/ansible/modules/cloud/rackspace/rax_cbs.py E338
lib/ansible/modules/cloud/rackspace/rax_cdb_database.py E324
lib/ansible/modules/cloud/rackspace/rax_cdb_database.py E337
lib/ansible/modules/cloud/rackspace/rax_cdb_database.py E338
lib/ansible/modules/cloud/rackspace/rax_cdb.py E324
lib/ansible/modules/cloud/rackspace/rax_cdb.py E326
lib/ansible/modules/cloud/rackspace/rax_cdb.py E337
lib/ansible/modules/cloud/rackspace/rax_cdb.py E338
lib/ansible/modules/cloud/rackspace/rax_cdb_user.py E324
lib/ansible/modules/cloud/rackspace/rax_cdb_user.py E337
lib/ansible/modules/cloud/rackspace/rax_cdb_user.py E338
lib/ansible/modules/cloud/rackspace/rax_clb_nodes.py E322
lib/ansible/modules/cloud/rackspace/rax_clb_nodes.py E324
lib/ansible/modules/cloud/rackspace/rax_clb_nodes.py E337
lib/ansible/modules/cloud/rackspace/rax_clb_nodes.py E338
lib/ansible/modules/cloud/rackspace/rax_clb.py E324
lib/ansible/modules/cloud/rackspace/rax_clb.py E337
lib/ansible/modules/cloud/rackspace/rax_clb.py E338
lib/ansible/modules/cloud/rackspace/rax_clb_ssl.py E324
lib/ansible/modules/cloud/rackspace/rax_clb_ssl.py E337
lib/ansible/modules/cloud/rackspace/rax_clb_ssl.py E338
lib/ansible/modules/cloud/rackspace/rax_dns.py E324
lib/ansible/modules/cloud/rackspace/rax_dns.py E337
lib/ansible/modules/cloud/rackspace/rax_dns.py E338
lib/ansible/modules/cloud/rackspace/rax_dns_record.py E324
lib/ansible/modules/cloud/rackspace/rax_dns_record.py E337
lib/ansible/modules/cloud/rackspace/rax_dns_record.py E338
lib/ansible/modules/cloud/rackspace/rax_facts.py E324
lib/ansible/modules/cloud/rackspace/rax_facts.py E337
lib/ansible/modules/cloud/rackspace/rax_facts.py E338
lib/ansible/modules/cloud/rackspace/rax_files_objects.py E323
lib/ansible/modules/cloud/rackspace/rax_files_objects.py E324
lib/ansible/modules/cloud/rackspace/rax_files_objects.py E337
lib/ansible/modules/cloud/rackspace/rax_files_objects.py E338
lib/ansible/modules/cloud/rackspace/rax_files.py E324
lib/ansible/modules/cloud/rackspace/rax_files.py E326
lib/ansible/modules/cloud/rackspace/rax_files.py E337
lib/ansible/modules/cloud/rackspace/rax_files.py E338
lib/ansible/modules/cloud/rackspace/rax_identity.py E324
lib/ansible/modules/cloud/rackspace/rax_identity.py E326
lib/ansible/modules/cloud/rackspace/rax_identity.py E337
lib/ansible/modules/cloud/rackspace/rax_identity.py E338
lib/ansible/modules/cloud/rackspace/rax_keypair.py E324
lib/ansible/modules/cloud/rackspace/rax_keypair.py E337
lib/ansible/modules/cloud/rackspace/rax_keypair.py E338
lib/ansible/modules/cloud/rackspace/rax_meta.py E324
lib/ansible/modules/cloud/rackspace/rax_meta.py E337
lib/ansible/modules/cloud/rackspace/rax_meta.py E338
lib/ansible/modules/cloud/rackspace/rax_mon_alarm.py E324
lib/ansible/modules/cloud/rackspace/rax_mon_alarm.py E337
lib/ansible/modules/cloud/rackspace/rax_mon_alarm.py E338
lib/ansible/modules/cloud/rackspace/rax_mon_check.py E324
lib/ansible/modules/cloud/rackspace/rax_mon_check.py E326
lib/ansible/modules/cloud/rackspace/rax_mon_check.py E337
lib/ansible/modules/cloud/rackspace/rax_mon_check.py E338
lib/ansible/modules/cloud/rackspace/rax_mon_entity.py E324
lib/ansible/modules/cloud/rackspace/rax_mon_entity.py E337
lib/ansible/modules/cloud/rackspace/rax_mon_entity.py E338
lib/ansible/modules/cloud/rackspace/rax_mon_notification_plan.py E324
lib/ansible/modules/cloud/rackspace/rax_mon_notification_plan.py E337
lib/ansible/modules/cloud/rackspace/rax_mon_notification_plan.py E338
lib/ansible/modules/cloud/rackspace/rax_mon_notification.py E324
lib/ansible/modules/cloud/rackspace/rax_mon_notification.py E337
lib/ansible/modules/cloud/rackspace/rax_mon_notification.py E338
lib/ansible/modules/cloud/rackspace/rax_network.py E324
lib/ansible/modules/cloud/rackspace/rax_network.py E337
lib/ansible/modules/cloud/rackspace/rax_network.py E338
lib/ansible/modules/cloud/rackspace/rax.py E322
lib/ansible/modules/cloud/rackspace/rax.py E324
lib/ansible/modules/cloud/rackspace/rax.py E337
lib/ansible/modules/cloud/rackspace/rax.py E338
lib/ansible/modules/cloud/rackspace/rax_queue.py E324
lib/ansible/modules/cloud/rackspace/rax_queue.py E337
lib/ansible/modules/cloud/rackspace/rax_queue.py E338
lib/ansible/modules/cloud/rackspace/rax_scaling_group.py E324
lib/ansible/modules/cloud/rackspace/rax_scaling_group.py E337
lib/ansible/modules/cloud/rackspace/rax_scaling_group.py E338
lib/ansible/modules/cloud/rackspace/rax_scaling_policy.py E324
lib/ansible/modules/cloud/rackspace/rax_scaling_policy.py E337
lib/ansible/modules/cloud/rackspace/rax_scaling_policy.py E338
lib/ansible/modules/cloud/scaleway/scaleway_compute.py E337
lib/ansible/modules/cloud/scaleway/scaleway_compute.py E338
lib/ansible/modules/cloud/scaleway/scaleway_image_facts.py E338
lib/ansible/modules/cloud/scaleway/scaleway_ip_facts.py E338
lib/ansible/modules/cloud/scaleway/scaleway_ip.py E338
lib/ansible/modules/cloud/scaleway/scaleway_lb.py E337
lib/ansible/modules/cloud/scaleway/scaleway_lb.py E338
lib/ansible/modules/cloud/scaleway/scaleway_security_group_facts.py E338
lib/ansible/modules/cloud/scaleway/scaleway_security_group_rule.py E337
lib/ansible/modules/cloud/scaleway/scaleway_server_facts.py E338
lib/ansible/modules/cloud/scaleway/scaleway_snapshot_facts.py E338
lib/ansible/modules/cloud/scaleway/scaleway_sshkey.py E338
lib/ansible/modules/cloud/scaleway/scaleway_user_data.py E337
lib/ansible/modules/cloud/scaleway/scaleway_user_data.py E338
lib/ansible/modules/cloud/scaleway/scaleway_volume_facts.py E338
lib/ansible/modules/cloud/scaleway/scaleway_volume.py E337
lib/ansible/modules/cloud/scaleway/scaleway_volume.py E338
lib/ansible/modules/cloud/smartos/imgadm.py E317
lib/ansible/modules/cloud/smartos/imgadm.py E338
lib/ansible/modules/cloud/smartos/smartos_image_facts.py E338
lib/ansible/modules/cloud/smartos/vmadm.py E322
lib/ansible/modules/cloud/smartos/vmadm.py E324
lib/ansible/modules/cloud/smartos/vmadm.py E326
lib/ansible/modules/cloud/smartos/vmadm.py E337
lib/ansible/modules/cloud/softlayer/sl_vm.py E324
lib/ansible/modules/cloud/softlayer/sl_vm.py E326
lib/ansible/modules/cloud/softlayer/sl_vm.py E337
lib/ansible/modules/cloud/spotinst/spotinst_aws_elastigroup.py E322
lib/ansible/modules/cloud/spotinst/spotinst_aws_elastigroup.py E323
lib/ansible/modules/cloud/spotinst/spotinst_aws_elastigroup.py E324
lib/ansible/modules/cloud/spotinst/spotinst_aws_elastigroup.py E326
lib/ansible/modules/cloud/spotinst/spotinst_aws_elastigroup.py E337
lib/ansible/modules/cloud/spotinst/spotinst_aws_elastigroup.py E338
lib/ansible/modules/cloud/univention/udm_dns_record.py E326
lib/ansible/modules/cloud/univention/udm_dns_record.py E337
lib/ansible/modules/cloud/univention/udm_dns_zone.py E322
lib/ansible/modules/cloud/univention/udm_dns_zone.py E326
lib/ansible/modules/cloud/univention/udm_dns_zone.py E337
lib/ansible/modules/cloud/univention/udm_group.py E324
lib/ansible/modules/cloud/univention/udm_group.py E337
lib/ansible/modules/cloud/univention/udm_share.py E322
lib/ansible/modules/cloud/univention/udm_share.py E323
lib/ansible/modules/cloud/univention/udm_share.py E324
lib/ansible/modules/cloud/univention/udm_share.py E326
lib/ansible/modules/cloud/univention/udm_share.py E337
lib/ansible/modules/cloud/univention/udm_user.py E324
lib/ansible/modules/cloud/univention/udm_user.py E326
lib/ansible/modules/cloud/univention/udm_user.py E337
lib/ansible/modules/cloud/vmware/vca_fw.py E322
lib/ansible/modules/cloud/vmware/vca_fw.py E324
lib/ansible/modules/cloud/vmware/vca_fw.py E337
lib/ansible/modules/cloud/vmware/vca_fw.py E338
lib/ansible/modules/cloud/vmware/vca_nat.py E322
lib/ansible/modules/cloud/vmware/vca_nat.py E324
lib/ansible/modules/cloud/vmware/vca_nat.py E337
lib/ansible/modules/cloud/vmware/vca_nat.py E338
lib/ansible/modules/cloud/vmware/vca_vapp.py E322
lib/ansible/modules/cloud/vmware/vca_vapp.py E324
lib/ansible/modules/cloud/vmware/vca_vapp.py E338
lib/ansible/modules/cloud/vmware/vcenter_extension.py E337
lib/ansible/modules/cloud/vmware/vcenter_folder.py E337
lib/ansible/modules/cloud/vmware/vcenter_license.py E337
lib/ansible/modules/cloud/vmware/vmware_category.py E337
lib/ansible/modules/cloud/vmware/vmware_cfg_backup.py E337
lib/ansible/modules/cloud/vmware/vmware_cluster_facts.py E337
lib/ansible/modules/cloud/vmware/vmware_cluster.py E337
lib/ansible/modules/cloud/vmware/vmware_datacenter.py E337
lib/ansible/modules/cloud/vmware/vmware_datastore_cluster.py E337
lib/ansible/modules/cloud/vmware/vmware_datastore_facts.py E337
lib/ansible/modules/cloud/vmware/vmware_datastore_maintenancemode.py E337
lib/ansible/modules/cloud/vmware/vmware_deploy_ovf.py E337
lib/ansible/modules/cloud/vmware/vmware_dns_config.py E337
lib/ansible/modules/cloud/vmware/vmware_drs_group_facts.py E337
lib/ansible/modules/cloud/vmware/vmware_drs_group.py E337
lib/ansible/modules/cloud/vmware/vmware_drs_rule_facts.py E337
lib/ansible/modules/cloud/vmware/vmware_dvs_host.py E337
lib/ansible/modules/cloud/vmware/vmware_dvs_portgroup.py E337
lib/ansible/modules/cloud/vmware/vmware_dvswitch_lacp.py E338
lib/ansible/modules/cloud/vmware/vmware_dvswitch_uplink_pg.py E337
lib/ansible/modules/cloud/vmware/vmware_export_ovf.py E337
lib/ansible/modules/cloud/vmware/vmware_guest_boot_facts.py E337
lib/ansible/modules/cloud/vmware/vmware_guest_boot_facts.py E338
lib/ansible/modules/cloud/vmware/vmware_guest_boot_manager.py E337
lib/ansible/modules/cloud/vmware/vmware_guest_boot_manager.py E338
lib/ansible/modules/cloud/vmware/vmware_guest_custom_attribute_defs.py E337
lib/ansible/modules/cloud/vmware/vmware_guest_custom_attributes.py E337
lib/ansible/modules/cloud/vmware/vmware_guest_customization_facts.py E337
lib/ansible/modules/cloud/vmware/vmware_guest_disk_facts.py E337
lib/ansible/modules/cloud/vmware/vmware_guest_disk.py E337
lib/ansible/modules/cloud/vmware/vmware_guest_facts.py E337
lib/ansible/modules/cloud/vmware/vmware_guest_file_operation.py E337
lib/ansible/modules/cloud/vmware/vmware_guest_find.py E337
lib/ansible/modules/cloud/vmware/vmware_guest_move.py E337
lib/ansible/modules/cloud/vmware/vmware_guest_powerstate.py E337
lib/ansible/modules/cloud/vmware/vmware_guest.py E322
lib/ansible/modules/cloud/vmware/vmware_guest.py E337
lib/ansible/modules/cloud/vmware/vmware_guest_snapshot_facts.py E337
lib/ansible/modules/cloud/vmware/vmware_guest_snapshot.py E337
lib/ansible/modules/cloud/vmware/vmware_guest_snapshot.py E338
lib/ansible/modules/cloud/vmware/vmware_guest_tools_upgrade.py E337
lib/ansible/modules/cloud/vmware/vmware_guest_tools_wait.py E337
lib/ansible/modules/cloud/vmware/vmware_guest_video.py E337
lib/ansible/modules/cloud/vmware/vmware_guest_vnc.py E337
lib/ansible/modules/cloud/vmware/vmware_host_acceptance.py E337
lib/ansible/modules/cloud/vmware/vmware_host_capability_facts.py E337
lib/ansible/modules/cloud/vmware/vmware_host_config_facts.py E337
lib/ansible/modules/cloud/vmware/vmware_host_config_manager.py E337
lib/ansible/modules/cloud/vmware/vmware_host_datastore.py E337
lib/ansible/modules/cloud/vmware/vmware_host_dns_facts.py E337
lib/ansible/modules/cloud/vmware/vmware_host_facts.py E337
lib/ansible/modules/cloud/vmware/vmware_host_feature_facts.py E337
lib/ansible/modules/cloud/vmware/vmware_host_firewall_facts.py E337
lib/ansible/modules/cloud/vmware/vmware_host_firewall_manager.py E337
lib/ansible/modules/cloud/vmware/vmware_host_lockdown.py E337
lib/ansible/modules/cloud/vmware/vmware_host_lockdown.py E338
lib/ansible/modules/cloud/vmware/vmware_host_ntp_facts.py E337
lib/ansible/modules/cloud/vmware/vmware_host_package_facts.py E337
lib/ansible/modules/cloud/vmware/vmware_host_powermgmt_policy.py E337
lib/ansible/modules/cloud/vmware/vmware_host_powerstate.py E337
lib/ansible/modules/cloud/vmware/vmware_host_scanhba.py E337
lib/ansible/modules/cloud/vmware/vmware_host_service_facts.py E337
lib/ansible/modules/cloud/vmware/vmware_host_service_manager.py E337
lib/ansible/modules/cloud/vmware/vmware_host_snmp.py E337
lib/ansible/modules/cloud/vmware/vmware_host_ssl_facts.py E337
lib/ansible/modules/cloud/vmware/vmware_local_role_manager.py E337
lib/ansible/modules/cloud/vmware/vmware_local_user_manager.py E337
lib/ansible/modules/cloud/vmware/vmware_maintenancemode.py E337
lib/ansible/modules/cloud/vmware/vmware_maintenancemode.py E338
lib/ansible/modules/cloud/vmware/vmware_migrate_vmk.py E337
lib/ansible/modules/cloud/vmware/vmware_object_role_permission.py E337
lib/ansible/modules/cloud/vmware/vmware_portgroup_facts.py E337
lib/ansible/modules/cloud/vmware/vmware_portgroup.py E337
lib/ansible/modules/cloud/vmware/vmware_resource_pool.py E337
lib/ansible/modules/cloud/vmware/vmware_tag_manager.py E337
lib/ansible/modules/cloud/vmware/vmware_tag.py E337
lib/ansible/modules/cloud/vmware/vmware_target_canonical_facts.py E337
lib/ansible/modules/cloud/vmware/vmware_vm_host_drs_rule.py E337
lib/ansible/modules/cloud/vmware/vmware_vmkernel_facts.py E337
lib/ansible/modules/cloud/vmware/vmware_vmkernel_ip_config.py E337
lib/ansible/modules/cloud/vmware/vmware_vmkernel.py E337
lib/ansible/modules/cloud/vmware/vmware_vmotion.py E338
lib/ansible/modules/cloud/vmware/vmware_vm_shell.py E337
lib/ansible/modules/cloud/vmware/vmware_vm_vm_drs_rule.py E337
lib/ansible/modules/cloud/vmware/vmware_vm_vss_dvs_migrate.py E337
lib/ansible/modules/cloud/vmware/vmware_vsan_cluster.py E337
lib/ansible/modules/cloud/vmware/vmware_vspan_session.py E337
lib/ansible/modules/cloud/vmware/vmware_vswitch_facts.py E337
lib/ansible/modules/cloud/vmware/vmware_vswitch.py E337
lib/ansible/modules/cloud/vmware/vsphere_copy.py E322
lib/ansible/modules/cloud/vmware/vsphere_copy.py E338
lib/ansible/modules/cloud/vultr/vultr_block_storage.py E337
lib/ansible/modules/cloud/vultr/vultr_block_storage.py E338
lib/ansible/modules/cloud/vultr/vultr_dns_domain.py E338
lib/ansible/modules/cloud/vultr/vultr_dns_record.py E337
lib/ansible/modules/cloud/vultr/vultr_dns_record.py E338
lib/ansible/modules/cloud/vultr/vultr_firewall_group.py E338
lib/ansible/modules/cloud/vultr/vultr_firewall_rule.py E337
lib/ansible/modules/cloud/vultr/vultr_firewall_rule.py E338
lib/ansible/modules/cloud/vultr/vultr_network.py E338
lib/ansible/modules/cloud/webfaction/webfaction_app.py E338
lib/ansible/modules/cloud/webfaction/webfaction_db.py E338
lib/ansible/modules/cloud/webfaction/webfaction_domain.py E337
lib/ansible/modules/cloud/webfaction/webfaction_domain.py E338
lib/ansible/modules/cloud/webfaction/webfaction_mailbox.py E338
lib/ansible/modules/cloud/webfaction/webfaction_site.py E337
lib/ansible/modules/cloud/webfaction/webfaction_site.py E338
lib/ansible/modules/clustering/consul_acl.py E338
lib/ansible/modules/clustering/consul_kv.py E337
lib/ansible/modules/clustering/consul.py E322
lib/ansible/modules/clustering/consul.py E338
lib/ansible/modules/clustering/etcd3.py E326
lib/ansible/modules/clustering/etcd3.py E337
lib/ansible/modules/clustering/k8s/k8s_auth.py E337
lib/ansible/modules/clustering/k8s/k8s_auth.py E338
lib/ansible/modules/clustering/k8s/k8s_info.py E337
lib/ansible/modules/clustering/k8s/k8s_info.py E338
lib/ansible/modules/clustering/k8s/k8s.py E337
lib/ansible/modules/clustering/k8s/k8s.py E338
lib/ansible/modules/clustering/k8s/k8s_scale.py E337
lib/ansible/modules/clustering/k8s/k8s_scale.py E338
lib/ansible/modules/clustering/k8s/k8s_service.py E337
lib/ansible/modules/clustering/k8s/k8s_service.py E338
lib/ansible/modules/clustering/pacemaker_cluster.py E337
lib/ansible/modules/clustering/znode.py E326
lib/ansible/modules/clustering/znode.py E337
lib/ansible/modules/clustering/znode.py E338
lib/ansible/modules/commands/command.py E322
lib/ansible/modules/commands/command.py E323
lib/ansible/modules/commands/command.py E338
lib/ansible/modules/commands/expect.py E338
lib/ansible/modules/database/influxdb/influxdb_database.py E324
lib/ansible/modules/database/influxdb/influxdb_database.py E337
lib/ansible/modules/database/influxdb/influxdb_query.py E324
lib/ansible/modules/database/influxdb/influxdb_query.py E337
lib/ansible/modules/database/influxdb/influxdb_retention_policy.py E324
lib/ansible/modules/database/influxdb/influxdb_retention_policy.py E337
lib/ansible/modules/database/influxdb/influxdb_user.py E324
lib/ansible/modules/database/influxdb/influxdb_user.py E337
lib/ansible/modules/database/influxdb/influxdb_write.py E324
lib/ansible/modules/database/influxdb/influxdb_write.py E337
lib/ansible/modules/database/misc/elasticsearch_plugin.py E337
lib/ansible/modules/database/misc/elasticsearch_plugin.py E338
lib/ansible/modules/database/misc/kibana_plugin.py E337
lib/ansible/modules/database/misc/kibana_plugin.py E338
lib/ansible/modules/database/misc/redis.py E337
lib/ansible/modules/database/misc/riak.py E324
lib/ansible/modules/database/misc/riak.py E337
lib/ansible/modules/database/misc/riak.py E338
lib/ansible/modules/database/mongodb/mongodb_parameter.py E317
lib/ansible/modules/database/mongodb/mongodb_parameter.py E323
lib/ansible/modules/database/mongodb/mongodb_parameter.py E326
lib/ansible/modules/database/mongodb/mongodb_parameter.py E337
lib/ansible/modules/database/mongodb/mongodb_parameter.py E338
lib/ansible/modules/database/mongodb/mongodb_shard.py E337
lib/ansible/modules/database/mongodb/mongodb_shard.py E338
lib/ansible/modules/database/mongodb/mongodb_user.py E322
lib/ansible/modules/database/mongodb/mongodb_user.py E337
lib/ansible/modules/database/mongodb/mongodb_user.py E338
lib/ansible/modules/database/mssql/mssql_db.py E338
lib/ansible/modules/database/mysql/mysql_db.py E210
lib/ansible/modules/database/mysql/mysql_db.py E337
lib/ansible/modules/database/mysql/mysql_user.py E322
lib/ansible/modules/database/mysql/mysql_user.py E337
lib/ansible/modules/database/postgresql/postgresql_db.py E210
lib/ansible/modules/database/postgresql/postgresql_db.py E337
lib/ansible/modules/database/postgresql/postgresql_ext.py E337
lib/ansible/modules/database/postgresql/postgresql_pg_hba.py E337
lib/ansible/modules/database/postgresql/postgresql_schema.py E337
lib/ansible/modules/database/postgresql/postgresql_tablespace.py E337
lib/ansible/modules/database/postgresql/postgresql_user.py E326
lib/ansible/modules/database/postgresql/postgresql_user.py E337
lib/ansible/modules/database/proxysql/proxysql_backend_servers.py E322
lib/ansible/modules/database/proxysql/proxysql_backend_servers.py E337
lib/ansible/modules/database/proxysql/proxysql_backend_servers.py E338
lib/ansible/modules/database/proxysql/proxysql_global_variables.py E322
lib/ansible/modules/database/proxysql/proxysql_global_variables.py E337
lib/ansible/modules/database/proxysql/proxysql_global_variables.py E338
lib/ansible/modules/database/proxysql/proxysql_manage_config.py E322
lib/ansible/modules/database/proxysql/proxysql_manage_config.py E338
lib/ansible/modules/database/proxysql/proxysql_mysql_users.py E322
lib/ansible/modules/database/proxysql/proxysql_mysql_users.py E337
lib/ansible/modules/database/proxysql/proxysql_mysql_users.py E338
lib/ansible/modules/database/proxysql/proxysql_query_rules.py E322
lib/ansible/modules/database/proxysql/proxysql_query_rules.py E337
lib/ansible/modules/database/proxysql/proxysql_query_rules.py E338
lib/ansible/modules/database/proxysql/proxysql_replication_hostgroups.py E322
lib/ansible/modules/database/proxysql/proxysql_replication_hostgroups.py E337
lib/ansible/modules/database/proxysql/proxysql_replication_hostgroups.py E338
lib/ansible/modules/database/proxysql/proxysql_scheduler.py E322
lib/ansible/modules/database/proxysql/proxysql_scheduler.py E337
lib/ansible/modules/database/proxysql/proxysql_scheduler.py E338
lib/ansible/modules/database/vertica/vertica_configuration.py E338
lib/ansible/modules/database/vertica/vertica_facts.py E338
lib/ansible/modules/database/vertica/vertica_role.py E322
lib/ansible/modules/database/vertica/vertica_role.py E338
lib/ansible/modules/database/vertica/vertica_schema.py E322
lib/ansible/modules/database/vertica/vertica_schema.py E338
lib/ansible/modules/database/vertica/vertica_user.py E322
lib/ansible/modules/database/vertica/vertica_user.py E338
lib/ansible/modules/files/acl.py E337
lib/ansible/modules/files/assemble.py E323
lib/ansible/modules/files/blockinfile.py E324
lib/ansible/modules/files/blockinfile.py E326
lib/ansible/modules/files/copy.py E322
lib/ansible/modules/files/copy.py E323
lib/ansible/modules/files/copy.py E324
lib/ansible/modules/files/file.py E322
lib/ansible/modules/files/file.py E324
lib/ansible/modules/files/find.py E337
lib/ansible/modules/files/ini_file.py E323
lib/ansible/modules/files/iso_extract.py E324
lib/ansible/modules/files/lineinfile.py E323
lib/ansible/modules/files/lineinfile.py E324
lib/ansible/modules/files/lineinfile.py E326
lib/ansible/modules/files/replace.py E323
lib/ansible/modules/files/stat.py E322
lib/ansible/modules/files/stat.py E336
lib/ansible/modules/files/stat.py E337
lib/ansible/modules/files/synchronize.py E322
lib/ansible/modules/files/synchronize.py E323
lib/ansible/modules/files/synchronize.py E324
lib/ansible/modules/files/synchronize.py E337
lib/ansible/modules/files/unarchive.py E323
lib/ansible/modules/identity/cyberark/cyberark_authentication.py E337
lib/ansible/modules/identity/ipa/ipa_config.py E337
lib/ansible/modules/identity/ipa/ipa_dnsrecord.py E337
lib/ansible/modules/identity/ipa/ipa_dnszone.py E337
lib/ansible/modules/identity/ipa/ipa_group.py E337
lib/ansible/modules/identity/ipa/ipa_hbacrule.py E337
lib/ansible/modules/identity/ipa/ipa_hostgroup.py E337
lib/ansible/modules/identity/ipa/ipa_host.py E337
lib/ansible/modules/identity/ipa/ipa_role.py E337
lib/ansible/modules/identity/ipa/ipa_service.py E337
lib/ansible/modules/identity/ipa/ipa_subca.py E337
lib/ansible/modules/identity/ipa/ipa_sudocmdgroup.py E337
lib/ansible/modules/identity/ipa/ipa_sudocmd.py E337
lib/ansible/modules/identity/ipa/ipa_sudorule.py E337
lib/ansible/modules/identity/ipa/ipa_user.py E337
lib/ansible/modules/identity/ipa/ipa_vault.py E337
lib/ansible/modules/identity/keycloak/keycloak_client.py E324
lib/ansible/modules/identity/keycloak/keycloak_client.py E337
lib/ansible/modules/identity/keycloak/keycloak_client.py E338
lib/ansible/modules/identity/keycloak/keycloak_clienttemplate.py E324
lib/ansible/modules/identity/keycloak/keycloak_clienttemplate.py E337
lib/ansible/modules/identity/keycloak/keycloak_clienttemplate.py E338
lib/ansible/modules/identity/onepassword_facts.py E337
lib/ansible/modules/identity/opendj/opendj_backendprop.py E337
lib/ansible/modules/identity/opendj/opendj_backendprop.py E338
lib/ansible/modules/messaging/rabbitmq/rabbitmq_binding.py E324
lib/ansible/modules/messaging/rabbitmq/rabbitmq_binding.py E337
lib/ansible/modules/messaging/rabbitmq/rabbitmq_exchange.py E324
lib/ansible/modules/messaging/rabbitmq/rabbitmq_exchange.py E326
lib/ansible/modules/messaging/rabbitmq/rabbitmq_exchange.py E337
lib/ansible/modules/messaging/rabbitmq/rabbitmq_global_parameter.py E337
lib/ansible/modules/messaging/rabbitmq/rabbitmq_global_parameter.py E338
lib/ansible/modules/messaging/rabbitmq/rabbitmq_parameter.py E338
lib/ansible/modules/messaging/rabbitmq/rabbitmq_plugin.py E338
lib/ansible/modules/messaging/rabbitmq/rabbitmq_policy.py E324
lib/ansible/modules/messaging/rabbitmq/rabbitmq_policy.py E337
lib/ansible/modules/messaging/rabbitmq/rabbitmq_policy.py E338
lib/ansible/modules/messaging/rabbitmq/rabbitmq_queue.py E324
lib/ansible/modules/messaging/rabbitmq/rabbitmq_queue.py E327
lib/ansible/modules/messaging/rabbitmq/rabbitmq_queue.py E337
lib/ansible/modules/messaging/rabbitmq/rabbitmq_user.py E337
lib/ansible/modules/messaging/rabbitmq/rabbitmq_user.py E338
lib/ansible/modules/messaging/rabbitmq/rabbitmq_vhost_limits.py E337
lib/ansible/modules/messaging/rabbitmq/rabbitmq_vhost.py E338
lib/ansible/modules/monitoring/airbrake_deployment.py E324
lib/ansible/modules/monitoring/airbrake_deployment.py E338
lib/ansible/modules/monitoring/bigpanda.py E322
lib/ansible/modules/monitoring/bigpanda.py E324
lib/ansible/modules/monitoring/bigpanda.py E338
lib/ansible/modules/monitoring/circonus_annotation.py E327
lib/ansible/modules/monitoring/circonus_annotation.py E337
lib/ansible/modules/monitoring/circonus_annotation.py E338
lib/ansible/modules/monitoring/datadog_event.py E324
lib/ansible/modules/monitoring/datadog_event.py E327
lib/ansible/modules/monitoring/datadog_event.py E337
lib/ansible/modules/monitoring/datadog_event.py E338
lib/ansible/modules/monitoring/datadog_monitor.py E324
lib/ansible/modules/monitoring/datadog_monitor.py E337
lib/ansible/modules/monitoring/grafana_dashboard.py E337
lib/ansible/modules/monitoring/grafana_dashboard.py E338
lib/ansible/modules/monitoring/grafana_datasource.py E324
lib/ansible/modules/monitoring/grafana_datasource.py E337
lib/ansible/modules/monitoring/grafana_datasource.py E338
lib/ansible/modules/monitoring/grafana_plugin.py E337
lib/ansible/modules/monitoring/grafana_plugin.py E338
lib/ansible/modules/monitoring/honeybadger_deployment.py E338
lib/ansible/modules/monitoring/icinga2_feature.py E337
lib/ansible/modules/monitoring/icinga2_host.py E322
lib/ansible/modules/monitoring/icinga2_host.py E324
lib/ansible/modules/monitoring/icinga2_host.py E337
lib/ansible/modules/monitoring/icinga2_host.py E338
lib/ansible/modules/monitoring/librato_annotation.py E337
lib/ansible/modules/monitoring/librato_annotation.py E338
lib/ansible/modules/monitoring/logentries.py E322
lib/ansible/modules/monitoring/logentries.py E326
lib/ansible/modules/monitoring/logentries.py E337
lib/ansible/modules/monitoring/logentries.py E338
lib/ansible/modules/monitoring/logicmonitor_facts.py E317
lib/ansible/modules/monitoring/logicmonitor_facts.py E324
lib/ansible/modules/monitoring/logicmonitor_facts.py E338
lib/ansible/modules/monitoring/logicmonitor.py E317
lib/ansible/modules/monitoring/logicmonitor.py E324
lib/ansible/modules/monitoring/logicmonitor.py E326
lib/ansible/modules/monitoring/logicmonitor.py E337
lib/ansible/modules/monitoring/logicmonitor.py E338
lib/ansible/modules/monitoring/logstash_plugin.py E337
lib/ansible/modules/monitoring/logstash_plugin.py E338
lib/ansible/modules/monitoring/monit.py E337
lib/ansible/modules/monitoring/monit.py E338
lib/ansible/modules/monitoring/nagios.py E317
lib/ansible/modules/monitoring/nagios.py E324
lib/ansible/modules/monitoring/nagios.py E337
lib/ansible/modules/monitoring/nagios.py E338
lib/ansible/modules/monitoring/newrelic_deployment.py E338
lib/ansible/modules/monitoring/pagerduty_alert.py E338
lib/ansible/modules/monitoring/pagerduty.py E324
lib/ansible/modules/monitoring/pagerduty.py E337
lib/ansible/modules/monitoring/pagerduty.py E338
lib/ansible/modules/monitoring/pingdom.py E326
lib/ansible/modules/monitoring/pingdom.py E338
lib/ansible/modules/monitoring/rollbar_deployment.py E338
lib/ansible/modules/monitoring/sensu_check.py E324
lib/ansible/modules/monitoring/sensu_check.py E337
lib/ansible/modules/monitoring/sensu_client.py E324
lib/ansible/modules/monitoring/sensu_client.py E337
lib/ansible/modules/monitoring/sensu_handler.py E326
lib/ansible/modules/monitoring/sensu_handler.py E337
lib/ansible/modules/monitoring/sensu_silence.py E337
lib/ansible/modules/monitoring/sensu_silence.py E338
lib/ansible/modules/monitoring/sensu_subscription.py E337
lib/ansible/modules/monitoring/spectrum_device.py E337
lib/ansible/modules/monitoring/spectrum_device.py E338
lib/ansible/modules/monitoring/stackdriver.py E338
lib/ansible/modules/monitoring/statusio_maintenance.py E337
lib/ansible/modules/monitoring/statusio_maintenance.py E338
lib/ansible/modules/monitoring/uptimerobot.py E338
lib/ansible/modules/monitoring/zabbix/zabbix_action.py E337
lib/ansible/modules/monitoring/zabbix/zabbix_group_info.py E337
lib/ansible/modules/monitoring/zabbix/zabbix_group.py E337
lib/ansible/modules/monitoring/zabbix/zabbix_group.py E338
lib/ansible/modules/monitoring/zabbix/zabbix_host_info.py E337
lib/ansible/modules/monitoring/zabbix/zabbix_hostmacro.py E337
lib/ansible/modules/monitoring/zabbix/zabbix_hostmacro.py E338
lib/ansible/modules/monitoring/zabbix/zabbix_host.py E337
lib/ansible/modules/monitoring/zabbix/zabbix_host.py E338
lib/ansible/modules/monitoring/zabbix/zabbix_maintenance.py E317
lib/ansible/modules/monitoring/zabbix/zabbix_maintenance.py E337
lib/ansible/modules/monitoring/zabbix/zabbix_maintenance.py E338
lib/ansible/modules/monitoring/zabbix/zabbix_map.py E337
lib/ansible/modules/monitoring/zabbix/zabbix_map.py E338
lib/ansible/modules/monitoring/zabbix/zabbix_proxy.py E337
lib/ansible/modules/monitoring/zabbix/zabbix_proxy.py E338
lib/ansible/modules/monitoring/zabbix/zabbix_template.py E337
lib/ansible/modules/monitoring/zabbix/zabbix_template.py E338
lib/ansible/modules/net_tools/basics/get_url.py E337
lib/ansible/modules/net_tools/basics/uri.py E337
lib/ansible/modules/net_tools/cloudflare_dns.py E337
lib/ansible/modules/net_tools/dnsmadeeasy.py E337
lib/ansible/modules/net_tools/dnsmadeeasy.py E338
lib/ansible/modules/net_tools/ipinfoio_facts.py E337
lib/ansible/modules/net_tools/ipinfoio_facts.py E338
lib/ansible/modules/net_tools/ip_netns.py E338
lib/ansible/modules/net_tools/ldap/ldap_attr.py E337
lib/ansible/modules/net_tools/ldap/ldap_entry.py E337
lib/ansible/modules/net_tools/ldap/ldap_entry.py E338
lib/ansible/modules/net_tools/ldap/ldap_passwd.py E338
lib/ansible/modules/net_tools/netbox/netbox_device.py E337
lib/ansible/modules/net_tools/netbox/netbox_device.py E338
lib/ansible/modules/net_tools/netbox/netbox_interface.py E337
lib/ansible/modules/net_tools/netbox/netbox_ip_address.py E337
lib/ansible/modules/net_tools/netbox/netbox_ip_address.py E338
lib/ansible/modules/net_tools/netbox/netbox_prefix.py E337
lib/ansible/modules/net_tools/netbox/netbox_prefix.py E338
lib/ansible/modules/net_tools/netbox/netbox_site.py E337
lib/ansible/modules/net_tools/netcup_dns.py E337
lib/ansible/modules/net_tools/netcup_dns.py E338
lib/ansible/modules/net_tools/nios/nios_aaaa_record.py E337
lib/ansible/modules/net_tools/nios/nios_aaaa_record.py E338
lib/ansible/modules/net_tools/nios/nios_a_record.py E337
lib/ansible/modules/net_tools/nios/nios_a_record.py E338
lib/ansible/modules/net_tools/nios/nios_cname_record.py E337
lib/ansible/modules/net_tools/nios/nios_cname_record.py E338
lib/ansible/modules/net_tools/nios/nios_dns_view.py E337
lib/ansible/modules/net_tools/nios/nios_dns_view.py E338
lib/ansible/modules/net_tools/nios/nios_fixed_address.py E337
lib/ansible/modules/net_tools/nios/nios_fixed_address.py E338
lib/ansible/modules/net_tools/nios/nios_host_record.py E337
lib/ansible/modules/net_tools/nios/nios_host_record.py E338
lib/ansible/modules/net_tools/nios/nios_member.py E337
lib/ansible/modules/net_tools/nios/nios_member.py E338
lib/ansible/modules/net_tools/nios/nios_mx_record.py E337
lib/ansible/modules/net_tools/nios/nios_mx_record.py E338
lib/ansible/modules/net_tools/nios/nios_naptr_record.py E337
lib/ansible/modules/net_tools/nios/nios_naptr_record.py E338
lib/ansible/modules/net_tools/nios/nios_network.py E337
lib/ansible/modules/net_tools/nios/nios_network.py E338
lib/ansible/modules/net_tools/nios/nios_network_view.py E337
lib/ansible/modules/net_tools/nios/nios_network_view.py E338
lib/ansible/modules/net_tools/nios/nios_nsgroup.py E337
lib/ansible/modules/net_tools/nios/nios_nsgroup.py E338
lib/ansible/modules/net_tools/nios/nios_ptr_record.py E337
lib/ansible/modules/net_tools/nios/nios_ptr_record.py E338
lib/ansible/modules/net_tools/nios/nios_srv_record.py E337
lib/ansible/modules/net_tools/nios/nios_srv_record.py E338
lib/ansible/modules/net_tools/nios/nios_txt_record.py E337
lib/ansible/modules/net_tools/nios/nios_txt_record.py E338
lib/ansible/modules/net_tools/nios/nios_zone.py E337
lib/ansible/modules/net_tools/nios/nios_zone.py E338
lib/ansible/modules/net_tools/nmcli.py E337
lib/ansible/modules/net_tools/nsupdate.py E337
lib/ansible/modules/network/a10/a10_server_axapi3.py E326
lib/ansible/modules/network/a10/a10_server_axapi3.py E337
lib/ansible/modules/network/a10/a10_server.py E337
lib/ansible/modules/network/a10/a10_service_group.py E337
lib/ansible/modules/network/a10/a10_virtual_server.py E324
lib/ansible/modules/network/a10/a10_virtual_server.py E337
lib/ansible/modules/network/aci/aci_access_port_block_to_access_port.py E337
lib/ansible/modules/network/aci/aci_access_sub_port_block_to_access_port.py E337
lib/ansible/modules/network/aci/aci_bd.py E337
lib/ansible/modules/network/aci/aci_contract_subject.py E337
lib/ansible/modules/network/aci/aci_fabric_scheduler.py E337
lib/ansible/modules/network/aci/aci_firmware_group_node.py E337
lib/ansible/modules/network/aci/aci_firmware_group.py E337
lib/ansible/modules/network/aci/aci_firmware_policy.py E337
lib/ansible/modules/network/aci/aci_maintenance_group_node.py E337
lib/ansible/modules/network/aci/aci_maintenance_group.py E337
lib/ansible/modules/network/aci/aci_maintenance_policy.py E337
lib/ansible/modules/network/aci/mso_site.py E337
lib/ansible/modules/network/aireos/aireos_command.py E337
lib/ansible/modules/network/aireos/aireos_command.py E338
lib/ansible/modules/network/aireos/aireos_config.py E337
lib/ansible/modules/network/aireos/aireos_config.py E338
lib/ansible/modules/network/aruba/aruba_command.py E337
lib/ansible/modules/network/aruba/aruba_command.py E338
lib/ansible/modules/network/aruba/aruba_config.py E337
lib/ansible/modules/network/aruba/aruba_config.py E338
lib/ansible/modules/network/asa/asa_acl.py E337
lib/ansible/modules/network/asa/asa_acl.py E338
lib/ansible/modules/network/asa/asa_command.py E337
lib/ansible/modules/network/asa/asa_command.py E338
lib/ansible/modules/network/asa/asa_config.py E324
lib/ansible/modules/network/asa/asa_config.py E335
lib/ansible/modules/network/asa/asa_config.py E337
lib/ansible/modules/network/asa/asa_config.py E338
lib/ansible/modules/network/asa/asa_og.py E337
lib/ansible/modules/network/asa/asa_og.py E338
lib/ansible/modules/network/avi/avi_actiongroupconfig.py E337
lib/ansible/modules/network/avi/avi_actiongroupconfig.py E338
lib/ansible/modules/network/avi/avi_alertconfig.py E337
lib/ansible/modules/network/avi/avi_alertconfig.py E338
lib/ansible/modules/network/avi/avi_alertemailconfig.py E337
lib/ansible/modules/network/avi/avi_alertemailconfig.py E338
lib/ansible/modules/network/avi/avi_alertscriptconfig.py E337
lib/ansible/modules/network/avi/avi_alertscriptconfig.py E338
lib/ansible/modules/network/avi/avi_alertsyslogconfig.py E337
lib/ansible/modules/network/avi/avi_alertsyslogconfig.py E338
lib/ansible/modules/network/avi/avi_analyticsprofile.py E337
lib/ansible/modules/network/avi/avi_analyticsprofile.py E338
lib/ansible/modules/network/avi/avi_api_session.py E337
lib/ansible/modules/network/avi/avi_api_session.py E338
lib/ansible/modules/network/avi/avi_applicationpersistenceprofile.py E337
lib/ansible/modules/network/avi/avi_applicationpersistenceprofile.py E338
lib/ansible/modules/network/avi/avi_applicationprofile.py E337
lib/ansible/modules/network/avi/avi_applicationprofile.py E338
lib/ansible/modules/network/avi/avi_authprofile.py E337
lib/ansible/modules/network/avi/avi_authprofile.py E338
lib/ansible/modules/network/avi/avi_autoscalelaunchconfig.py E337
lib/ansible/modules/network/avi/avi_autoscalelaunchconfig.py E338
lib/ansible/modules/network/avi/avi_backupconfiguration.py E337
lib/ansible/modules/network/avi/avi_backupconfiguration.py E338
lib/ansible/modules/network/avi/avi_backup.py E337
lib/ansible/modules/network/avi/avi_backup.py E338
lib/ansible/modules/network/avi/avi_certificatemanagementprofile.py E337
lib/ansible/modules/network/avi/avi_certificatemanagementprofile.py E338
lib/ansible/modules/network/avi/avi_cloudconnectoruser.py E337
lib/ansible/modules/network/avi/avi_cloudconnectoruser.py E338
lib/ansible/modules/network/avi/avi_cloudproperties.py E337
lib/ansible/modules/network/avi/avi_cloudproperties.py E338
lib/ansible/modules/network/avi/avi_cloud.py E337
lib/ansible/modules/network/avi/avi_cloud.py E338
lib/ansible/modules/network/avi/avi_clusterclouddetails.py E337
lib/ansible/modules/network/avi/avi_clusterclouddetails.py E338
lib/ansible/modules/network/avi/avi_cluster.py E337
lib/ansible/modules/network/avi/avi_cluster.py E338
lib/ansible/modules/network/avi/avi_controllerproperties.py E337
lib/ansible/modules/network/avi/avi_controllerproperties.py E338
lib/ansible/modules/network/avi/avi_customipamdnsprofile.py E337
lib/ansible/modules/network/avi/avi_customipamdnsprofile.py E338
lib/ansible/modules/network/avi/avi_dnspolicy.py E337
lib/ansible/modules/network/avi/avi_dnspolicy.py E338
lib/ansible/modules/network/avi/avi_errorpagebody.py E337
lib/ansible/modules/network/avi/avi_errorpagebody.py E338
lib/ansible/modules/network/avi/avi_errorpageprofile.py E337
lib/ansible/modules/network/avi/avi_errorpageprofile.py E338
lib/ansible/modules/network/avi/avi_gslbgeodbprofile.py E337
lib/ansible/modules/network/avi/avi_gslbgeodbprofile.py E338
lib/ansible/modules/network/avi/avi_gslb.py E337
lib/ansible/modules/network/avi/avi_gslb.py E338
lib/ansible/modules/network/avi/avi_gslbservice_patch_member.py E337
lib/ansible/modules/network/avi/avi_gslbservice_patch_member.py E338
lib/ansible/modules/network/avi/avi_gslbservice.py E337
lib/ansible/modules/network/avi/avi_gslbservice.py E338
lib/ansible/modules/network/avi/avi_hardwaresecuritymodulegroup.py E337
lib/ansible/modules/network/avi/avi_hardwaresecuritymodulegroup.py E338
lib/ansible/modules/network/avi/avi_healthmonitor.py E337
lib/ansible/modules/network/avi/avi_healthmonitor.py E338
lib/ansible/modules/network/avi/avi_httppolicyset.py E337
lib/ansible/modules/network/avi/avi_httppolicyset.py E338
lib/ansible/modules/network/avi/avi_ipaddrgroup.py E337
lib/ansible/modules/network/avi/avi_ipaddrgroup.py E338
lib/ansible/modules/network/avi/avi_ipamdnsproviderprofile.py E337
lib/ansible/modules/network/avi/avi_ipamdnsproviderprofile.py E338
lib/ansible/modules/network/avi/avi_l4policyset.py E337
lib/ansible/modules/network/avi/avi_l4policyset.py E338
lib/ansible/modules/network/avi/avi_microservicegroup.py E337
lib/ansible/modules/network/avi/avi_microservicegroup.py E338
lib/ansible/modules/network/avi/avi_networkprofile.py E337
lib/ansible/modules/network/avi/avi_networkprofile.py E338
lib/ansible/modules/network/avi/avi_network.py E337
lib/ansible/modules/network/avi/avi_network.py E338
lib/ansible/modules/network/avi/avi_networksecuritypolicy.py E337
lib/ansible/modules/network/avi/avi_networksecuritypolicy.py E338
lib/ansible/modules/network/avi/avi_pkiprofile.py E337
lib/ansible/modules/network/avi/avi_pkiprofile.py E338
lib/ansible/modules/network/avi/avi_poolgroupdeploymentpolicy.py E337
lib/ansible/modules/network/avi/avi_poolgroupdeploymentpolicy.py E338
lib/ansible/modules/network/avi/avi_poolgroup.py E337
lib/ansible/modules/network/avi/avi_poolgroup.py E338
lib/ansible/modules/network/avi/avi_pool.py E337
lib/ansible/modules/network/avi/avi_pool.py E338
lib/ansible/modules/network/avi/avi_prioritylabels.py E337
lib/ansible/modules/network/avi/avi_prioritylabels.py E338
lib/ansible/modules/network/avi/avi_role.py E337
lib/ansible/modules/network/avi/avi_role.py E338
lib/ansible/modules/network/avi/avi_scheduler.py E337
lib/ansible/modules/network/avi/avi_scheduler.py E338
lib/ansible/modules/network/avi/avi_seproperties.py E337
lib/ansible/modules/network/avi/avi_seproperties.py E338
lib/ansible/modules/network/avi/avi_serverautoscalepolicy.py E337
lib/ansible/modules/network/avi/avi_serverautoscalepolicy.py E338
lib/ansible/modules/network/avi/avi_serviceenginegroup.py E337
lib/ansible/modules/network/avi/avi_serviceenginegroup.py E338
lib/ansible/modules/network/avi/avi_serviceengine.py E337
lib/ansible/modules/network/avi/avi_serviceengine.py E338
lib/ansible/modules/network/avi/avi_snmptrapprofile.py E337
lib/ansible/modules/network/avi/avi_snmptrapprofile.py E338
lib/ansible/modules/network/avi/avi_sslkeyandcertificate.py E337
lib/ansible/modules/network/avi/avi_sslkeyandcertificate.py E338
lib/ansible/modules/network/avi/avi_sslprofile.py E337
lib/ansible/modules/network/avi/avi_sslprofile.py E338
lib/ansible/modules/network/avi/avi_stringgroup.py E337
lib/ansible/modules/network/avi/avi_stringgroup.py E338
lib/ansible/modules/network/avi/avi_systemconfiguration.py E337
lib/ansible/modules/network/avi/avi_systemconfiguration.py E338
lib/ansible/modules/network/avi/avi_tenant.py E337
lib/ansible/modules/network/avi/avi_tenant.py E338
lib/ansible/modules/network/avi/avi_trafficcloneprofile.py E337
lib/ansible/modules/network/avi/avi_trafficcloneprofile.py E338
lib/ansible/modules/network/avi/avi_useraccountprofile.py E337
lib/ansible/modules/network/avi/avi_useraccountprofile.py E338
lib/ansible/modules/network/avi/avi_useraccount.py E337
lib/ansible/modules/network/avi/avi_virtualservice.py E337
lib/ansible/modules/network/avi/avi_virtualservice.py E338
lib/ansible/modules/network/avi/avi_vrfcontext.py E337
lib/ansible/modules/network/avi/avi_vrfcontext.py E338
lib/ansible/modules/network/avi/avi_vsdatascriptset.py E337
lib/ansible/modules/network/avi/avi_vsdatascriptset.py E338
lib/ansible/modules/network/avi/avi_vsvip.py E337
lib/ansible/modules/network/avi/avi_vsvip.py E338
lib/ansible/modules/network/avi/avi_webhook.py E337
lib/ansible/modules/network/avi/avi_webhook.py E338
lib/ansible/modules/network/bigswitch/bcf_switch.py E337
lib/ansible/modules/network/bigswitch/bcf_switch.py E338
lib/ansible/modules/network/bigswitch/bigmon_chain.py E337
lib/ansible/modules/network/bigswitch/bigmon_chain.py E338
lib/ansible/modules/network/bigswitch/bigmon_policy.py E324
lib/ansible/modules/network/bigswitch/bigmon_policy.py E326
lib/ansible/modules/network/bigswitch/bigmon_policy.py E337
lib/ansible/modules/network/bigswitch/bigmon_policy.py E338
lib/ansible/modules/network/checkpoint/checkpoint_object_facts.py E337
lib/ansible/modules/network/checkpoint/cp_network.py E337
lib/ansible/modules/network/cli/cli_command.py E337
lib/ansible/modules/network/cli/cli_config.py E337
lib/ansible/modules/network/cli/cli_config.py E338
lib/ansible/modules/network/cloudengine/ce_aaa_server_host.py E322
lib/ansible/modules/network/cloudengine/ce_aaa_server_host.py E337
lib/ansible/modules/network/cloudengine/ce_aaa_server_host.py E338
lib/ansible/modules/network/cloudengine/ce_aaa_server.py E322
lib/ansible/modules/network/cloudengine/ce_aaa_server.py E337
lib/ansible/modules/network/cloudengine/ce_acl_advance.py E322
lib/ansible/modules/network/cloudengine/ce_acl_advance.py E337
lib/ansible/modules/network/cloudengine/ce_acl_advance.py E338
lib/ansible/modules/network/cloudengine/ce_acl_interface.py E322
lib/ansible/modules/network/cloudengine/ce_acl_interface.py E337
lib/ansible/modules/network/cloudengine/ce_acl_interface.py E338
lib/ansible/modules/network/cloudengine/ce_acl.py E322
lib/ansible/modules/network/cloudengine/ce_acl.py E337
lib/ansible/modules/network/cloudengine/ce_acl.py E338
lib/ansible/modules/network/cloudengine/ce_bfd_global.py E322
lib/ansible/modules/network/cloudengine/ce_bfd_global.py E337
lib/ansible/modules/network/cloudengine/ce_bfd_global.py E338
lib/ansible/modules/network/cloudengine/ce_bfd_session.py E322
lib/ansible/modules/network/cloudengine/ce_bfd_session.py E337
lib/ansible/modules/network/cloudengine/ce_bfd_session.py E338
lib/ansible/modules/network/cloudengine/ce_bfd_view.py E337
lib/ansible/modules/network/cloudengine/ce_bfd_view.py E338
lib/ansible/modules/network/cloudengine/ce_bgp_af.py E322
lib/ansible/modules/network/cloudengine/ce_bgp_af.py E324
lib/ansible/modules/network/cloudengine/ce_bgp_af.py E337
lib/ansible/modules/network/cloudengine/ce_bgp_af.py E338
lib/ansible/modules/network/cloudengine/ce_bgp_neighbor_af.py E322
lib/ansible/modules/network/cloudengine/ce_bgp_neighbor_af.py E324
lib/ansible/modules/network/cloudengine/ce_bgp_neighbor_af.py E326
lib/ansible/modules/network/cloudengine/ce_bgp_neighbor_af.py E337
lib/ansible/modules/network/cloudengine/ce_bgp_neighbor_af.py E338
lib/ansible/modules/network/cloudengine/ce_bgp_neighbor.py E322
lib/ansible/modules/network/cloudengine/ce_bgp_neighbor.py E324
lib/ansible/modules/network/cloudengine/ce_bgp_neighbor.py E326
lib/ansible/modules/network/cloudengine/ce_bgp_neighbor.py E337
lib/ansible/modules/network/cloudengine/ce_bgp_neighbor.py E338
lib/ansible/modules/network/cloudengine/ce_bgp.py E322
lib/ansible/modules/network/cloudengine/ce_bgp.py E337
lib/ansible/modules/network/cloudengine/ce_bgp.py E338
lib/ansible/modules/network/cloudengine/ce_command.py E322
lib/ansible/modules/network/cloudengine/ce_command.py E326
lib/ansible/modules/network/cloudengine/ce_command.py E337
lib/ansible/modules/network/cloudengine/ce_command.py E338
lib/ansible/modules/network/cloudengine/ce_config.py E322
lib/ansible/modules/network/cloudengine/ce_config.py E337
lib/ansible/modules/network/cloudengine/ce_config.py E338
lib/ansible/modules/network/cloudengine/ce_dldp_interface.py E322
lib/ansible/modules/network/cloudengine/ce_dldp_interface.py E337
lib/ansible/modules/network/cloudengine/ce_dldp_interface.py E338
lib/ansible/modules/network/cloudengine/ce_dldp.py E322
lib/ansible/modules/network/cloudengine/ce_dldp.py E323
lib/ansible/modules/network/cloudengine/ce_dldp.py E337
lib/ansible/modules/network/cloudengine/ce_eth_trunk.py E322
lib/ansible/modules/network/cloudengine/ce_eth_trunk.py E337
lib/ansible/modules/network/cloudengine/ce_eth_trunk.py E338
lib/ansible/modules/network/cloudengine/ce_evpn_bd_vni.py E322
lib/ansible/modules/network/cloudengine/ce_evpn_bd_vni.py E337
lib/ansible/modules/network/cloudengine/ce_evpn_bd_vni.py E338
lib/ansible/modules/network/cloudengine/ce_evpn_bgp.py E322
lib/ansible/modules/network/cloudengine/ce_evpn_bgp.py E337
lib/ansible/modules/network/cloudengine/ce_evpn_bgp.py E338
lib/ansible/modules/network/cloudengine/ce_evpn_bgp_rr.py E322
lib/ansible/modules/network/cloudengine/ce_evpn_bgp_rr.py E337
lib/ansible/modules/network/cloudengine/ce_evpn_bgp_rr.py E338
lib/ansible/modules/network/cloudengine/ce_evpn_global.py E322
lib/ansible/modules/network/cloudengine/ce_evpn_global.py E337
lib/ansible/modules/network/cloudengine/ce_facts.py E322
lib/ansible/modules/network/cloudengine/ce_facts.py E337
lib/ansible/modules/network/cloudengine/ce_file_copy.py E322
lib/ansible/modules/network/cloudengine/ce_file_copy.py E337
lib/ansible/modules/network/cloudengine/ce_file_copy.py E338
lib/ansible/modules/network/cloudengine/ce_info_center_debug.py E322
lib/ansible/modules/network/cloudengine/ce_info_center_debug.py E337
lib/ansible/modules/network/cloudengine/ce_info_center_debug.py E338
lib/ansible/modules/network/cloudengine/ce_info_center_global.py E322
lib/ansible/modules/network/cloudengine/ce_info_center_global.py E324
lib/ansible/modules/network/cloudengine/ce_info_center_global.py E337
lib/ansible/modules/network/cloudengine/ce_info_center_global.py E338
lib/ansible/modules/network/cloudengine/ce_info_center_log.py E322
lib/ansible/modules/network/cloudengine/ce_info_center_log.py E337
lib/ansible/modules/network/cloudengine/ce_info_center_log.py E338
lib/ansible/modules/network/cloudengine/ce_info_center_trap.py E322
lib/ansible/modules/network/cloudengine/ce_info_center_trap.py E337
lib/ansible/modules/network/cloudengine/ce_info_center_trap.py E338
lib/ansible/modules/network/cloudengine/ce_interface_ospf.py E322
lib/ansible/modules/network/cloudengine/ce_interface_ospf.py E337
lib/ansible/modules/network/cloudengine/ce_interface_ospf.py E338
lib/ansible/modules/network/cloudengine/ce_interface.py E322
lib/ansible/modules/network/cloudengine/ce_interface.py E326
lib/ansible/modules/network/cloudengine/ce_interface.py E337
lib/ansible/modules/network/cloudengine/ce_interface.py E338
lib/ansible/modules/network/cloudengine/ce_ip_interface.py E322
lib/ansible/modules/network/cloudengine/ce_ip_interface.py E337
lib/ansible/modules/network/cloudengine/ce_ip_interface.py E338
lib/ansible/modules/network/cloudengine/ce_link_status.py E322
lib/ansible/modules/network/cloudengine/ce_link_status.py E337
lib/ansible/modules/network/cloudengine/ce_mlag_config.py E322
lib/ansible/modules/network/cloudengine/ce_mlag_config.py E324
lib/ansible/modules/network/cloudengine/ce_mlag_config.py E337
lib/ansible/modules/network/cloudengine/ce_mlag_interface.py E322
lib/ansible/modules/network/cloudengine/ce_mlag_interface.py E324
lib/ansible/modules/network/cloudengine/ce_mlag_interface.py E337
lib/ansible/modules/network/cloudengine/ce_mtu.py E322
lib/ansible/modules/network/cloudengine/ce_mtu.py E337
lib/ansible/modules/network/cloudengine/ce_mtu.py E338
lib/ansible/modules/network/cloudengine/ce_netconf.py E322
lib/ansible/modules/network/cloudengine/ce_netconf.py E337
lib/ansible/modules/network/cloudengine/ce_netconf.py E338
lib/ansible/modules/network/cloudengine/ce_netstream_aging.py E322
lib/ansible/modules/network/cloudengine/ce_netstream_aging.py E337
lib/ansible/modules/network/cloudengine/ce_netstream_aging.py E338
lib/ansible/modules/network/cloudengine/ce_netstream_export.py E322
lib/ansible/modules/network/cloudengine/ce_netstream_export.py E337
lib/ansible/modules/network/cloudengine/ce_netstream_export.py E338
lib/ansible/modules/network/cloudengine/ce_netstream_global.py E322
lib/ansible/modules/network/cloudengine/ce_netstream_global.py E337
lib/ansible/modules/network/cloudengine/ce_netstream_global.py E338
lib/ansible/modules/network/cloudengine/ce_netstream_template.py E322
lib/ansible/modules/network/cloudengine/ce_netstream_template.py E337
lib/ansible/modules/network/cloudengine/ce_netstream_template.py E338
lib/ansible/modules/network/cloudengine/ce_ntp_auth.py E322
lib/ansible/modules/network/cloudengine/ce_ntp_auth.py E337
lib/ansible/modules/network/cloudengine/ce_ntp_auth.py E338
lib/ansible/modules/network/cloudengine/ce_ntp.py E322
lib/ansible/modules/network/cloudengine/ce_ntp.py E337
lib/ansible/modules/network/cloudengine/ce_ntp.py E338
lib/ansible/modules/network/cloudengine/ce_ospf.py E322
lib/ansible/modules/network/cloudengine/ce_ospf.py E337
lib/ansible/modules/network/cloudengine/ce_ospf.py E338
lib/ansible/modules/network/cloudengine/ce_ospf_vrf.py E322
lib/ansible/modules/network/cloudengine/ce_ospf_vrf.py E337
lib/ansible/modules/network/cloudengine/ce_ospf_vrf.py E338
lib/ansible/modules/network/cloudengine/ce_reboot.py E322
lib/ansible/modules/network/cloudengine/ce_reboot.py E337
lib/ansible/modules/network/cloudengine/ce_rollback.py E322
lib/ansible/modules/network/cloudengine/ce_rollback.py E337
lib/ansible/modules/network/cloudengine/ce_rollback.py E338
lib/ansible/modules/network/cloudengine/ce_sflow.py E322
lib/ansible/modules/network/cloudengine/ce_sflow.py E337
lib/ansible/modules/network/cloudengine/ce_sflow.py E338
lib/ansible/modules/network/cloudengine/ce_snmp_community.py E322
lib/ansible/modules/network/cloudengine/ce_snmp_community.py E337
lib/ansible/modules/network/cloudengine/ce_snmp_community.py E338
lib/ansible/modules/network/cloudengine/ce_snmp_contact.py E322
lib/ansible/modules/network/cloudengine/ce_snmp_contact.py E337
lib/ansible/modules/network/cloudengine/ce_snmp_contact.py E338
lib/ansible/modules/network/cloudengine/ce_snmp_location.py E322
lib/ansible/modules/network/cloudengine/ce_snmp_location.py E337
lib/ansible/modules/network/cloudengine/ce_snmp_location.py E338
lib/ansible/modules/network/cloudengine/ce_snmp_target_host.py E322
lib/ansible/modules/network/cloudengine/ce_snmp_target_host.py E324
lib/ansible/modules/network/cloudengine/ce_snmp_target_host.py E326
lib/ansible/modules/network/cloudengine/ce_snmp_target_host.py E337
lib/ansible/modules/network/cloudengine/ce_snmp_target_host.py E338
lib/ansible/modules/network/cloudengine/ce_snmp_traps.py E322
lib/ansible/modules/network/cloudengine/ce_snmp_traps.py E324
lib/ansible/modules/network/cloudengine/ce_snmp_traps.py E326
lib/ansible/modules/network/cloudengine/ce_snmp_traps.py E337
lib/ansible/modules/network/cloudengine/ce_snmp_traps.py E338
lib/ansible/modules/network/cloudengine/ce_snmp_user.py E322
lib/ansible/modules/network/cloudengine/ce_snmp_user.py E324
lib/ansible/modules/network/cloudengine/ce_snmp_user.py E326
lib/ansible/modules/network/cloudengine/ce_snmp_user.py E337
lib/ansible/modules/network/cloudengine/ce_snmp_user.py E338
lib/ansible/modules/network/cloudengine/ce_startup.py E322
lib/ansible/modules/network/cloudengine/ce_startup.py E324
lib/ansible/modules/network/cloudengine/ce_startup.py E337
lib/ansible/modules/network/cloudengine/ce_static_route.py E322
lib/ansible/modules/network/cloudengine/ce_static_route.py E337
lib/ansible/modules/network/cloudengine/ce_static_route.py E338
lib/ansible/modules/network/cloudengine/ce_stp.py E322
lib/ansible/modules/network/cloudengine/ce_stp.py E337
lib/ansible/modules/network/cloudengine/ce_stp.py E338
lib/ansible/modules/network/cloudengine/ce_switchport.py E322
lib/ansible/modules/network/cloudengine/ce_switchport.py E337
lib/ansible/modules/network/cloudengine/ce_switchport.py E338
lib/ansible/modules/network/cloudengine/ce_vlan.py E322
lib/ansible/modules/network/cloudengine/ce_vlan.py E337
lib/ansible/modules/network/cloudengine/ce_vlan.py E338
lib/ansible/modules/network/cloudengine/ce_vrf_af.py E322
lib/ansible/modules/network/cloudengine/ce_vrf_af.py E337
lib/ansible/modules/network/cloudengine/ce_vrf_af.py E338
lib/ansible/modules/network/cloudengine/ce_vrf_interface.py E322
lib/ansible/modules/network/cloudengine/ce_vrf_interface.py E337
lib/ansible/modules/network/cloudengine/ce_vrf_interface.py E338
lib/ansible/modules/network/cloudengine/ce_vrf.py E322
lib/ansible/modules/network/cloudengine/ce_vrf.py E337
lib/ansible/modules/network/cloudengine/ce_vrf.py E338
lib/ansible/modules/network/cloudengine/ce_vrrp.py E322
lib/ansible/modules/network/cloudengine/ce_vrrp.py E324
lib/ansible/modules/network/cloudengine/ce_vrrp.py E337
lib/ansible/modules/network/cloudengine/ce_vxlan_arp.py E322
lib/ansible/modules/network/cloudengine/ce_vxlan_arp.py E337
lib/ansible/modules/network/cloudengine/ce_vxlan_arp.py E338
lib/ansible/modules/network/cloudengine/ce_vxlan_gateway.py E322
lib/ansible/modules/network/cloudengine/ce_vxlan_gateway.py E337
lib/ansible/modules/network/cloudengine/ce_vxlan_gateway.py E338
lib/ansible/modules/network/cloudengine/ce_vxlan_global.py E322
lib/ansible/modules/network/cloudengine/ce_vxlan_global.py E337
lib/ansible/modules/network/cloudengine/ce_vxlan_global.py E338
lib/ansible/modules/network/cloudengine/ce_vxlan_tunnel.py E322
lib/ansible/modules/network/cloudengine/ce_vxlan_tunnel.py E337
lib/ansible/modules/network/cloudengine/ce_vxlan_tunnel.py E338
lib/ansible/modules/network/cloudengine/ce_vxlan_vap.py E322
lib/ansible/modules/network/cloudengine/ce_vxlan_vap.py E337
lib/ansible/modules/network/cloudengine/ce_vxlan_vap.py E338
lib/ansible/modules/network/cloudvision/cv_server_provision.py E338
lib/ansible/modules/network/cnos/cnos_backup.py E322
lib/ansible/modules/network/cnos/cnos_backup.py E323
lib/ansible/modules/network/cnos/cnos_backup.py E326
lib/ansible/modules/network/cnos/cnos_backup.py E338
lib/ansible/modules/network/cnos/cnos_banner.py E337
lib/ansible/modules/network/cnos/cnos_banner.py E338
lib/ansible/modules/network/cnos/cnos_bgp.py E326
lib/ansible/modules/network/cnos/cnos_bgp.py E338
lib/ansible/modules/network/cnos/cnos_command.py E337
lib/ansible/modules/network/cnos/cnos_command.py E338
lib/ansible/modules/network/cnos/cnos_conditional_command.py E326
lib/ansible/modules/network/cnos/cnos_conditional_command.py E338
lib/ansible/modules/network/cnos/cnos_conditional_template.py E326
lib/ansible/modules/network/cnos/cnos_conditional_template.py E338
lib/ansible/modules/network/cnos/cnos_config.py E337
lib/ansible/modules/network/cnos/cnos_config.py E338
lib/ansible/modules/network/cnos/cnos_factory.py E326
lib/ansible/modules/network/cnos/cnos_facts.py E323
lib/ansible/modules/network/cnos/cnos_facts.py E337
lib/ansible/modules/network/cnos/cnos_image.py E326
lib/ansible/modules/network/cnos/cnos_image.py E338
lib/ansible/modules/network/cnos/cnos_interface.py E337
lib/ansible/modules/network/cnos/cnos_interface.py E338
lib/ansible/modules/network/cnos/cnos_l2_interface.py E337
lib/ansible/modules/network/cnos/cnos_l2_interface.py E338
lib/ansible/modules/network/cnos/cnos_l3_interface.py E337
lib/ansible/modules/network/cnos/cnos_l3_interface.py E338
lib/ansible/modules/network/cnos/cnos_linkagg.py E337
lib/ansible/modules/network/cnos/cnos_linkagg.py E338
lib/ansible/modules/network/cnos/cnos_lldp.py E338
lib/ansible/modules/network/cnos/cnos_logging.py E337
lib/ansible/modules/network/cnos/cnos_logging.py E338
lib/ansible/modules/network/cnos/cnos_reload.py E326
lib/ansible/modules/network/cnos/cnos_rollback.py E322
lib/ansible/modules/network/cnos/cnos_rollback.py E323
lib/ansible/modules/network/cnos/cnos_rollback.py E326
lib/ansible/modules/network/cnos/cnos_rollback.py E338
lib/ansible/modules/network/cnos/cnos_save.py E326
lib/ansible/modules/network/cnos/cnos_showrun.py E323
lib/ansible/modules/network/cnos/cnos_static_route.py E337
lib/ansible/modules/network/cnos/cnos_static_route.py E338
lib/ansible/modules/network/cnos/cnos_system.py E337
lib/ansible/modules/network/cnos/cnos_system.py E338
lib/ansible/modules/network/cnos/cnos_template.py E326
lib/ansible/modules/network/cnos/cnos_template.py E338
lib/ansible/modules/network/cnos/cnos_user.py E337
lib/ansible/modules/network/cnos/cnos_user.py E338
lib/ansible/modules/network/cnos/cnos_vlag.py E326
lib/ansible/modules/network/cnos/cnos_vlag.py E338
lib/ansible/modules/network/cnos/cnos_vlan.py E337
lib/ansible/modules/network/cnos/cnos_vlan.py E338
lib/ansible/modules/network/cnos/cnos_vrf.py E337
lib/ansible/modules/network/cnos/cnos_vrf.py E338
lib/ansible/modules/network/cumulus/nclu.py E337
lib/ansible/modules/network/dellos10/dellos10_config.py E337
lib/ansible/modules/network/dellos10/dellos10_config.py E338
lib/ansible/modules/network/dellos10/dellos10_facts.py E337
lib/ansible/modules/network/dellos6/dellos6_config.py E337
lib/ansible/modules/network/dellos6/dellos6_config.py E338
lib/ansible/modules/network/dellos6/dellos6_facts.py E337
lib/ansible/modules/network/dellos9/dellos9_config.py E337
lib/ansible/modules/network/dellos9/dellos9_config.py E338
lib/ansible/modules/network/dellos9/dellos9_facts.py E337
lib/ansible/modules/network/edgeos/edgeos_command.py E337
lib/ansible/modules/network/edgeos/edgeos_command.py E338
lib/ansible/modules/network/edgeos/edgeos_config.py E337
lib/ansible/modules/network/edgeos/edgeos_config.py E338
lib/ansible/modules/network/edgeos/edgeos_facts.py E337
lib/ansible/modules/network/edgeswitch/edgeswitch_facts.py E337
lib/ansible/modules/network/edgeswitch/edgeswitch_vlan.py E337
lib/ansible/modules/network/edgeswitch/edgeswitch_vlan.py E338
lib/ansible/modules/network/enos/enos_command.py E323
lib/ansible/modules/network/enos/enos_command.py E337
lib/ansible/modules/network/enos/enos_command.py E338
lib/ansible/modules/network/enos/enos_config.py E323
lib/ansible/modules/network/enos/enos_config.py E337
lib/ansible/modules/network/enos/enos_config.py E338
lib/ansible/modules/network/enos/enos_facts.py E323
lib/ansible/modules/network/enos/enos_facts.py E337
lib/ansible/modules/network/eos/eos_banner.py E338
lib/ansible/modules/network/eos/eos_bgp.py E337
lib/ansible/modules/network/eos/eos_bgp.py E338
lib/ansible/modules/network/eos/eos_command.py E337
lib/ansible/modules/network/eos/eos_command.py E338
lib/ansible/modules/network/eos/eos_config.py E337
lib/ansible/modules/network/eos/eos_config.py E338
lib/ansible/modules/network/eos/eos_eapi.py E324
lib/ansible/modules/network/eos/eos_eapi.py E337
lib/ansible/modules/network/eos/eos_eapi.py E338
lib/ansible/modules/network/eos/eos_facts.py E337
lib/ansible/modules/network/eos/eos_interface.py E337
lib/ansible/modules/network/eos/eos_interface.py E338
lib/ansible/modules/network/eos/eos_l2_interface.py E326
lib/ansible/modules/network/eos/eos_l2_interface.py E337
lib/ansible/modules/network/eos/eos_l2_interface.py E338
lib/ansible/modules/network/eos/eos_l3_interface.py E337
lib/ansible/modules/network/eos/eos_l3_interface.py E338
lib/ansible/modules/network/eos/eos_linkagg.py E337
lib/ansible/modules/network/eos/eos_linkagg.py E338
lib/ansible/modules/network/eos/eos_lldp.py E326
lib/ansible/modules/network/eos/eos_lldp.py E338
lib/ansible/modules/network/eos/eos_logging.py E326
lib/ansible/modules/network/eos/eos_logging.py E337
lib/ansible/modules/network/eos/eos_logging.py E338
lib/ansible/modules/network/eos/eos_static_route.py E337
lib/ansible/modules/network/eos/eos_static_route.py E338
lib/ansible/modules/network/eos/eos_system.py E337
lib/ansible/modules/network/eos/eos_system.py E338
lib/ansible/modules/network/eos/eos_user.py E337
lib/ansible/modules/network/eos/eos_user.py E338
lib/ansible/modules/network/eos/eos_vlan.py E337
lib/ansible/modules/network/eos/eos_vlan.py E338
lib/ansible/modules/network/eos/eos_vrf.py E337
lib/ansible/modules/network/eos/eos_vrf.py E338
lib/ansible/modules/network/exos/exos_command.py E337
lib/ansible/modules/network/exos/exos_command.py E338
lib/ansible/modules/network/exos/exos_config.py E337
lib/ansible/modules/network/exos/exos_config.py E338
lib/ansible/modules/network/exos/exos_facts.py E337
lib/ansible/modules/network/f5/bigip_apm_policy_import.py E338
lib/ansible/modules/network/f5/_bigip_asm_policy.py E337
lib/ansible/modules/network/f5/_bigip_asm_policy.py E338
lib/ansible/modules/network/f5/bigip_cli_alias.py E338
lib/ansible/modules/network/f5/bigip_cli_script.py E338
lib/ansible/modules/network/f5/bigip_command.py E337
lib/ansible/modules/network/f5/bigip_command.py E338
lib/ansible/modules/network/f5/bigip_config.py E338
lib/ansible/modules/network/f5/bigip_device_dns.py E337
lib/ansible/modules/network/f5/_bigip_facts.py E337
lib/ansible/modules/network/f5/_bigip_gtm_facts.py E337
lib/ansible/modules/network/f5/_bigip_gtm_facts.py E338
lib/ansible/modules/network/f5/bigip_gtm_topology_region.py E338
lib/ansible/modules/network/f5/bigip_iapp_template.py E338
lib/ansible/modules/network/f5/bigip_monitor_dns.py E338
lib/ansible/modules/network/f5/bigip_profile_client_ssl.py E338
lib/ansible/modules/network/f5/bigip_ucs.py E335
lib/ansible/modules/network/f5/bigip_user.py E338
lib/ansible/modules/network/f5/bigiq_application_fastl4_udp.py E337
lib/ansible/modules/network/f5/bigiq_application_https_offload.py E338
lib/ansible/modules/network/f5/bigiq_device_discovery.py E337
lib/ansible/modules/network/fortimanager/fmgr_device_config.py E337
lib/ansible/modules/network/fortimanager/fmgr_device_group.py E337
lib/ansible/modules/network/fortimanager/fmgr_device_provision_template.py E337
lib/ansible/modules/network/fortimanager/fmgr_device.py E337
lib/ansible/modules/network/fortimanager/fmgr_fwobj_address.py E337
lib/ansible/modules/network/fortimanager/fmgr_fwobj_ippool6.py E337
lib/ansible/modules/network/fortimanager/fmgr_fwobj_ippool.py E337
lib/ansible/modules/network/fortimanager/fmgr_fwobj_service.py E337
lib/ansible/modules/network/fortimanager/fmgr_fwobj_vip.py E337
lib/ansible/modules/network/fortimanager/fmgr_fwpol_ipv4.py E337
lib/ansible/modules/network/fortimanager/fmgr_fwpol_package.py E337
lib/ansible/modules/network/fortimanager/fmgr_ha.py E337
lib/ansible/modules/network/fortimanager/fmgr_provisioning.py E337
lib/ansible/modules/network/fortimanager/fmgr_provisioning.py E338
lib/ansible/modules/network/fortimanager/fmgr_query.py E337
lib/ansible/modules/network/fortimanager/fmgr_script.py E324
lib/ansible/modules/network/fortimanager/fmgr_script.py E337
lib/ansible/modules/network/fortimanager/fmgr_secprof_appctrl.py E337
lib/ansible/modules/network/fortimanager/fmgr_secprof_av.py E337
lib/ansible/modules/network/fortimanager/fmgr_secprof_dns.py E337
lib/ansible/modules/network/fortimanager/fmgr_secprof_ips.py E337
lib/ansible/modules/network/fortimanager/fmgr_secprof_profile_group.py E337
lib/ansible/modules/network/fortimanager/fmgr_secprof_proxy.py E337
lib/ansible/modules/network/fortimanager/fmgr_secprof_spam.py E337
lib/ansible/modules/network/fortimanager/fmgr_secprof_ssl_ssh.py E337
lib/ansible/modules/network/fortimanager/fmgr_secprof_voip.py E337
lib/ansible/modules/network/fortimanager/fmgr_secprof_waf.py E337
lib/ansible/modules/network/fortimanager/fmgr_secprof_wanopt.py E337
lib/ansible/modules/network/fortimanager/fmgr_secprof_web.py E337
lib/ansible/modules/network/fortios/fortios_address.py E324
lib/ansible/modules/network/fortios/fortios_address.py E338
lib/ansible/modules/network/fortios/fortios_antivirus_heuristic.py E337
lib/ansible/modules/network/fortios/fortios_antivirus_profile.py E337
lib/ansible/modules/network/fortios/fortios_antivirus_quarantine.py E337
lib/ansible/modules/network/fortios/fortios_antivirus_settings.py E337
lib/ansible/modules/network/fortios/fortios_application_custom.py E337
lib/ansible/modules/network/fortios/fortios_application_group.py E337
lib/ansible/modules/network/fortios/fortios_application_list.py E337
lib/ansible/modules/network/fortios/fortios_application_name.py E337
lib/ansible/modules/network/fortios/fortios_application_rule_settings.py E337
lib/ansible/modules/network/fortios/fortios_authentication_rule.py E337
lib/ansible/modules/network/fortios/fortios_authentication_scheme.py E337
lib/ansible/modules/network/fortios/fortios_authentication_setting.py E337
lib/ansible/modules/network/fortios/fortios_config.py E337
lib/ansible/modules/network/fortios/fortios_dlp_filepattern.py E337
lib/ansible/modules/network/fortios/fortios_dlp_fp_doc_source.py E337
lib/ansible/modules/network/fortios/fortios_dlp_fp_sensitivity.py E337
lib/ansible/modules/network/fortios/fortios_dlp_sensor.py E337
lib/ansible/modules/network/fortios/fortios_dlp_settings.py E337
lib/ansible/modules/network/fortios/fortios_dnsfilter_domain_filter.py E337
lib/ansible/modules/network/fortios/fortios_dnsfilter_profile.py E337
lib/ansible/modules/network/fortios/fortios_endpoint_control_client.py E337
lib/ansible/modules/network/fortios/fortios_endpoint_control_forticlient_ems.py E337
lib/ansible/modules/network/fortios/fortios_endpoint_control_forticlient_registration_sync.py E337
lib/ansible/modules/network/fortios/fortios_endpoint_control_profile.py E337
lib/ansible/modules/network/fortios/fortios_endpoint_control_settings.py E337
lib/ansible/modules/network/fortios/fortios_extender_controller_extender.py E337
lib/ansible/modules/network/fortios/fortios_firewall_address6.py E337
lib/ansible/modules/network/fortios/fortios_firewall_address6_template.py E337
lib/ansible/modules/network/fortios/fortios_firewall_address.py E337
lib/ansible/modules/network/fortios/fortios_firewall_addrgrp6.py E337
lib/ansible/modules/network/fortios/fortios_firewall_addrgrp.py E337
lib/ansible/modules/network/fortios/fortios_firewall_auth_portal.py E337
lib/ansible/modules/network/fortios/fortios_firewall_central_snat_map.py E337
lib/ansible/modules/network/fortios/fortios_firewall_dnstranslation.py E337
lib/ansible/modules/network/fortios/fortios_firewall_DoS_policy6.py E337
lib/ansible/modules/network/fortios/fortios_firewall_DoS_policy.py E337
lib/ansible/modules/network/fortios/fortios_firewall_identity_based_route.py E337
lib/ansible/modules/network/fortios/fortios_firewall_interface_policy6.py E337
lib/ansible/modules/network/fortios/fortios_firewall_interface_policy.py E337
lib/ansible/modules/network/fortios/fortios_firewall_internet_service_custom.py E337
lib/ansible/modules/network/fortios/fortios_firewall_internet_service_group.py E337
lib/ansible/modules/network/fortios/fortios_firewall_internet_service.py E337
lib/ansible/modules/network/fortios/fortios_firewall_ipmacbinding_setting.py E337
lib/ansible/modules/network/fortios/fortios_firewall_ipmacbinding_table.py E337
lib/ansible/modules/network/fortios/fortios_firewall_ippool6.py E337
lib/ansible/modules/network/fortios/fortios_firewall_ippool.py E337
lib/ansible/modules/network/fortios/fortios_firewall_ip_translation.py E337
lib/ansible/modules/network/fortios/fortios_firewall_ipv6_eh_filter.py E337
lib/ansible/modules/network/fortios/fortios_firewall_ldb_monitor.py E337
lib/ansible/modules/network/fortios/fortios_firewall_local_in_policy6.py E337
lib/ansible/modules/network/fortios/fortios_firewall_local_in_policy.py E337
lib/ansible/modules/network/fortios/fortios_firewall_multicast_address6.py E337
lib/ansible/modules/network/fortios/fortios_firewall_multicast_address.py E337
lib/ansible/modules/network/fortios/fortios_firewall_multicast_policy6.py E337
lib/ansible/modules/network/fortios/fortios_firewall_multicast_policy.py E337
lib/ansible/modules/network/fortios/fortios_firewall_policy46.py E337
lib/ansible/modules/network/fortios/fortios_firewall_policy64.py E337
lib/ansible/modules/network/fortios/fortios_firewall_policy6.py E337
lib/ansible/modules/network/fortios/fortios_firewall_policy.py E337
lib/ansible/modules/network/fortios/fortios_firewall_profile_group.py E337
lib/ansible/modules/network/fortios/fortios_firewall_profile_protocol_options.py E337
lib/ansible/modules/network/fortios/fortios_firewall_proxy_address.py E337
lib/ansible/modules/network/fortios/fortios_firewall_proxy_addrgrp.py E337
lib/ansible/modules/network/fortios/fortios_firewall_proxy_policy.py E337
lib/ansible/modules/network/fortios/fortios_firewall_schedule_group.py E337
lib/ansible/modules/network/fortios/fortios_firewall_schedule_onetime.py E337
lib/ansible/modules/network/fortios/fortios_firewall_schedule_recurring.py E337
lib/ansible/modules/network/fortios/fortios_firewall_service_category.py E337
lib/ansible/modules/network/fortios/fortios_firewall_service_custom.py E337
lib/ansible/modules/network/fortios/fortios_firewall_service_group.py E337
lib/ansible/modules/network/fortios/fortios_firewall_shaper_per_ip_shaper.py E337
lib/ansible/modules/network/fortios/fortios_firewall_shaper_traffic_shaper.py E337
lib/ansible/modules/network/fortios/fortios_firewall_shaping_policy.py E337
lib/ansible/modules/network/fortios/fortios_firewall_shaping_profile.py E337
lib/ansible/modules/network/fortios/fortios_firewall_sniffer.py E337
lib/ansible/modules/network/fortios/fortios_firewall_ssh_host_key.py E337
lib/ansible/modules/network/fortios/fortios_firewall_ssh_local_ca.py E337
lib/ansible/modules/network/fortios/fortios_firewall_ssh_local_key.py E337
lib/ansible/modules/network/fortios/fortios_firewall_ssh_setting.py E337
lib/ansible/modules/network/fortios/fortios_firewall_ssl_server.py E337
lib/ansible/modules/network/fortios/fortios_firewall_ssl_setting.py E337
lib/ansible/modules/network/fortios/fortios_firewall_ssl_ssh_profile.py E337
lib/ansible/modules/network/fortios/fortios_firewall_ttl_policy.py E337
lib/ansible/modules/network/fortios/fortios_firewall_vip46.py E337
lib/ansible/modules/network/fortios/fortios_firewall_vip64.py E337
lib/ansible/modules/network/fortios/fortios_firewall_vip6.py E337
lib/ansible/modules/network/fortios/fortios_firewall_vipgrp46.py E337
lib/ansible/modules/network/fortios/fortios_firewall_vipgrp64.py E337
lib/ansible/modules/network/fortios/fortios_firewall_vipgrp6.py E337
lib/ansible/modules/network/fortios/fortios_firewall_vipgrp.py E337
lib/ansible/modules/network/fortios/fortios_firewall_vip.py E337
lib/ansible/modules/network/fortios/fortios_firewall_wildcard_fqdn_custom.py E337
lib/ansible/modules/network/fortios/fortios_firewall_wildcard_fqdn_group.py E337
lib/ansible/modules/network/fortios/fortios_ftp_proxy_explicit.py E337
lib/ansible/modules/network/fortios/fortios_icap_profile.py E337
lib/ansible/modules/network/fortios/fortios_icap_server.py E337
lib/ansible/modules/network/fortios/fortios_ips_custom.py E337
lib/ansible/modules/network/fortios/fortios_ips_decoder.py E337
lib/ansible/modules/network/fortios/fortios_ips_global.py E337
lib/ansible/modules/network/fortios/fortios_ips_rule.py E337
lib/ansible/modules/network/fortios/fortios_ips_rule_settings.py E337
lib/ansible/modules/network/fortios/fortios_ips_sensor.py E337
lib/ansible/modules/network/fortios/fortios_ips_settings.py E337
lib/ansible/modules/network/fortios/fortios_ipv4_policy.py E337
lib/ansible/modules/network/fortios/fortios_ipv4_policy.py E338
lib/ansible/modules/network/fortios/fortios_log_custom_field.py E337
lib/ansible/modules/network/fortios/fortios_log_disk_filter.py E337
lib/ansible/modules/network/fortios/fortios_log_disk_setting.py E337
lib/ansible/modules/network/fortios/fortios_log_eventfilter.py E337
lib/ansible/modules/network/fortios/fortios_log_fortianalyzer2_filter.py E337
lib/ansible/modules/network/fortios/fortios_log_fortianalyzer2_setting.py E337
lib/ansible/modules/network/fortios/fortios_log_fortianalyzer3_filter.py E337
lib/ansible/modules/network/fortios/fortios_log_fortianalyzer3_setting.py E337
lib/ansible/modules/network/fortios/fortios_log_fortianalyzer_filter.py E337
lib/ansible/modules/network/fortios/fortios_log_fortianalyzer_override_filter.py E337
lib/ansible/modules/network/fortios/fortios_log_fortianalyzer_override_setting.py E337
lib/ansible/modules/network/fortios/fortios_log_fortianalyzer_setting.py E337
lib/ansible/modules/network/fortios/fortios_log_fortiguard_filter.py E337
lib/ansible/modules/network/fortios/fortios_log_fortiguard_override_filter.py E337
lib/ansible/modules/network/fortios/fortios_log_fortiguard_override_setting.py E337
lib/ansible/modules/network/fortios/fortios_log_fortiguard_setting.py E337
lib/ansible/modules/network/fortios/fortios_log_gui_display.py E337
lib/ansible/modules/network/fortios/fortios_log_memory_filter.py E337
lib/ansible/modules/network/fortios/fortios_log_memory_global_setting.py E337
lib/ansible/modules/network/fortios/fortios_log_memory_setting.py E337
lib/ansible/modules/network/fortios/fortios_log_null_device_filter.py E337
lib/ansible/modules/network/fortios/fortios_log_null_device_setting.py E337
lib/ansible/modules/network/fortios/fortios_log_setting.py E337
lib/ansible/modules/network/fortios/fortios_log_syslogd2_filter.py E337
lib/ansible/modules/network/fortios/fortios_log_syslogd2_setting.py E337
lib/ansible/modules/network/fortios/fortios_log_syslogd3_filter.py E337
lib/ansible/modules/network/fortios/fortios_log_syslogd3_setting.py E337
lib/ansible/modules/network/fortios/fortios_log_syslogd4_filter.py E337
lib/ansible/modules/network/fortios/fortios_log_syslogd4_setting.py E337
lib/ansible/modules/network/fortios/fortios_log_syslogd_filter.py E337
lib/ansible/modules/network/fortios/fortios_log_syslogd_override_filter.py E337
lib/ansible/modules/network/fortios/fortios_log_syslogd_override_setting.py E337
lib/ansible/modules/network/fortios/fortios_log_syslogd_setting.py E337
lib/ansible/modules/network/fortios/fortios_log_threat_weight.py E337
lib/ansible/modules/network/fortios/fortios_log_webtrends_filter.py E337
lib/ansible/modules/network/fortios/fortios_log_webtrends_setting.py E337
lib/ansible/modules/network/fortios/fortios_report_chart.py E337
lib/ansible/modules/network/fortios/fortios_report_dataset.py E337
lib/ansible/modules/network/fortios/fortios_report_layout.py E337
lib/ansible/modules/network/fortios/fortios_report_setting.py E337
lib/ansible/modules/network/fortios/fortios_report_style.py E337
lib/ansible/modules/network/fortios/fortios_report_theme.py E337
lib/ansible/modules/network/fortios/fortios_router_access_list.py E337
lib/ansible/modules/network/fortios/fortios_router_auth_path.py E337
lib/ansible/modules/network/fortios/fortios_router_bfd6.py E337
lib/ansible/modules/network/fortios/fortios_router_bfd.py E337
lib/ansible/modules/network/fortios/fortios_router_bgp.py E337
lib/ansible/modules/network/fortios/fortios_router_multicast6.py E337
lib/ansible/modules/network/fortios/fortios_router_multicast_flow.py E337
lib/ansible/modules/network/fortios/fortios_router_multicast.py E337
lib/ansible/modules/network/fortios/fortios_router_ospf6.py E337
lib/ansible/modules/network/fortios/fortios_router_ospf.py E337
lib/ansible/modules/network/fortios/fortios_router_policy6.py E337
lib/ansible/modules/network/fortios/fortios_router_policy.py E337
lib/ansible/modules/network/fortios/fortios_router_prefix_list.py E337
lib/ansible/modules/network/fortios/fortios_router_rip.py E337
lib/ansible/modules/network/fortios/fortios_router_setting.py E337
lib/ansible/modules/network/fortios/fortios_router_static.py E337
lib/ansible/modules/network/fortios/fortios_spamfilter_profile.py E337
lib/ansible/modules/network/fortios/fortios_ssh_filter_profile.py E337
lib/ansible/modules/network/fortios/fortios_switch_controller_global.py E337
lib/ansible/modules/network/fortios/fortios_switch_controller_lldp_profile.py E337
lib/ansible/modules/network/fortios/fortios_switch_controller_lldp_settings.py E337
lib/ansible/modules/network/fortios/fortios_switch_controller_mac_sync_settings.py E337
lib/ansible/modules/network/fortios/fortios_switch_controller_managed_switch.py E337
lib/ansible/modules/network/fortios/fortios_switch_controller_network_monitor_settings.py E337
lib/ansible/modules/network/fortios/fortios_system_accprofile.py E337
lib/ansible/modules/network/fortios/fortios_system_admin.py E337
lib/ansible/modules/network/fortios/fortios_system_api_user.py E337
lib/ansible/modules/network/fortios/fortios_system_central_management.py E337
lib/ansible/modules/network/fortios/fortios_system_dhcp_server.py E337
lib/ansible/modules/network/fortios/fortios_system_dns.py E337
lib/ansible/modules/network/fortios/fortios_system_global.py E337
lib/ansible/modules/network/fortios/fortios_system_interface.py E337
lib/ansible/modules/network/fortios/fortios_system_sdn_connector.py E337
lib/ansible/modules/network/fortios/fortios_system_settings.py E337
lib/ansible/modules/network/fortios/fortios_system_vdom.py E337
lib/ansible/modules/network/fortios/fortios_system_virtual_wan_link.py E337
lib/ansible/modules/network/fortios/fortios_user_adgrp.py E337
lib/ansible/modules/network/fortios/fortios_user_radius.py E337
lib/ansible/modules/network/fortios/fortios_user_tacacsplus.py E337
lib/ansible/modules/network/fortios/fortios_voip_profile.py E337
lib/ansible/modules/network/fortios/fortios_vpn_ipsec_concentrator.py E337
lib/ansible/modules/network/fortios/fortios_vpn_ipsec_forticlient.py E337
lib/ansible/modules/network/fortios/fortios_vpn_ipsec_manualkey_interface.py E337
lib/ansible/modules/network/fortios/fortios_vpn_ipsec_manualkey.py E337
lib/ansible/modules/network/fortios/fortios_vpn_ipsec_phase1_interface.py E337
lib/ansible/modules/network/fortios/fortios_vpn_ipsec_phase1.py E337
lib/ansible/modules/network/fortios/fortios_vpn_ipsec_phase2_interface.py E337
lib/ansible/modules/network/fortios/fortios_vpn_ipsec_phase2.py E337
lib/ansible/modules/network/fortios/fortios_vpn_ssl_settings.py E337
lib/ansible/modules/network/fortios/fortios_vpn_ssl_web_portal.py E337
lib/ansible/modules/network/fortios/fortios_waf_profile.py E337
lib/ansible/modules/network/fortios/fortios_wanopt_profile.py E337
lib/ansible/modules/network/fortios/fortios_wanopt_settings.py E337
lib/ansible/modules/network/fortios/fortios_webfilter_content_header.py E337
lib/ansible/modules/network/fortios/fortios_webfilter_content.py E337
lib/ansible/modules/network/fortios/fortios_webfilter_fortiguard.py E337
lib/ansible/modules/network/fortios/fortios_webfilter_ftgd_local_cat.py E337
lib/ansible/modules/network/fortios/fortios_webfilter_ftgd_local_rating.py E337
lib/ansible/modules/network/fortios/fortios_webfilter_ips_urlfilter_cache_setting.py E337
lib/ansible/modules/network/fortios/fortios_webfilter_ips_urlfilter_setting6.py E337
lib/ansible/modules/network/fortios/fortios_webfilter_ips_urlfilter_setting.py E337
lib/ansible/modules/network/fortios/fortios_webfilter_override.py E337
lib/ansible/modules/network/fortios/fortios_webfilter_profile.py E337
lib/ansible/modules/network/fortios/fortios_webfilter.py E337
lib/ansible/modules/network/fortios/fortios_webfilter_search_engine.py E337
lib/ansible/modules/network/fortios/fortios_webfilter_urlfilter.py E337
lib/ansible/modules/network/fortios/fortios_web_proxy_explicit.py E337
lib/ansible/modules/network/fortios/fortios_web_proxy_global.py E337
lib/ansible/modules/network/fortios/fortios_web_proxy_profile.py E337
lib/ansible/modules/network/fortios/fortios_wireless_controller_global.py E337
lib/ansible/modules/network/fortios/fortios_wireless_controller_setting.py E337
lib/ansible/modules/network/fortios/fortios_wireless_controller_utm_profile.py E337
lib/ansible/modules/network/fortios/fortios_wireless_controller_vap.py E337
lib/ansible/modules/network/fortios/fortios_wireless_controller_wids_profile.py E337
lib/ansible/modules/network/fortios/fortios_wireless_controller_wtp_profile.py E337
lib/ansible/modules/network/fortios/fortios_wireless_controller_wtp.py E337
lib/ansible/modules/network/frr/frr_bgp.py E337
lib/ansible/modules/network/frr/frr_bgp.py E338
lib/ansible/modules/network/frr/frr_facts.py E337
lib/ansible/modules/network/illumos/dladm_etherstub.py E338
lib/ansible/modules/network/illumos/dladm_iptun.py E337
lib/ansible/modules/network/illumos/dladm_iptun.py E338
lib/ansible/modules/network/illumos/dladm_linkprop.py E317
lib/ansible/modules/network/illumos/dladm_linkprop.py E337
lib/ansible/modules/network/illumos/dladm_linkprop.py E338
lib/ansible/modules/network/illumos/dladm_vlan.py E324
lib/ansible/modules/network/illumos/dladm_vlan.py E337
lib/ansible/modules/network/illumos/dladm_vlan.py E338
lib/ansible/modules/network/illumos/dladm_vnic.py E324
lib/ansible/modules/network/illumos/dladm_vnic.py E338
lib/ansible/modules/network/illumos/flowadm.py E326
lib/ansible/modules/network/illumos/flowadm.py E338
lib/ansible/modules/network/illumos/ipadm_addrprop.py E317
lib/ansible/modules/network/illumos/ipadm_addrprop.py E338
lib/ansible/modules/network/illumos/ipadm_addr.py E337
lib/ansible/modules/network/illumos/ipadm_addr.py E338
lib/ansible/modules/network/illumos/ipadm_ifprop.py E317
lib/ansible/modules/network/illumos/ipadm_ifprop.py E326
lib/ansible/modules/network/illumos/ipadm_ifprop.py E338
lib/ansible/modules/network/illumos/ipadm_if.py E338
lib/ansible/modules/network/illumos/ipadm_prop.py E326
lib/ansible/modules/network/illumos/ipadm_prop.py E338
lib/ansible/modules/network/ingate/ig_config.py E337
lib/ansible/modules/network/ingate/ig_config.py E338
lib/ansible/modules/network/ingate/ig_unit_information.py E337
lib/ansible/modules/network/ios/ios_banner.py E338
lib/ansible/modules/network/ios/ios_bgp.py E337
lib/ansible/modules/network/ios/ios_bgp.py E338
lib/ansible/modules/network/ios/ios_command.py E337
lib/ansible/modules/network/ios/ios_command.py E338
lib/ansible/modules/network/ios/ios_config.py E337
lib/ansible/modules/network/ios/ios_config.py E338
lib/ansible/modules/network/ios/ios_facts.py E337
lib/ansible/modules/network/ios/ios_interface.py E324
lib/ansible/modules/network/ios/ios_interface.py E337
lib/ansible/modules/network/ios/ios_interface.py E338
lib/ansible/modules/network/ios/ios_l2_interface.py E324
lib/ansible/modules/network/ios/ios_l2_interface.py E337
lib/ansible/modules/network/ios/ios_l2_interface.py E338
lib/ansible/modules/network/ios/ios_l3_interface.py E337
lib/ansible/modules/network/ios/ios_l3_interface.py E338
lib/ansible/modules/network/ios/ios_linkagg.py E337
lib/ansible/modules/network/ios/ios_linkagg.py E338
lib/ansible/modules/network/ios/ios_lldp.py E326
lib/ansible/modules/network/ios/ios_lldp.py E338
lib/ansible/modules/network/ios/ios_logging.py E324
lib/ansible/modules/network/ios/ios_logging.py E337
lib/ansible/modules/network/ios/ios_logging.py E338
lib/ansible/modules/network/ios/ios_ntp.py E338
lib/ansible/modules/network/ios/ios_ping.py E324
lib/ansible/modules/network/ios/ios_ping.py E337
lib/ansible/modules/network/ios/ios_static_route.py E337
lib/ansible/modules/network/ios/ios_static_route.py E338
lib/ansible/modules/network/ios/ios_system.py E337
lib/ansible/modules/network/ios/ios_system.py E338
lib/ansible/modules/network/ios/ios_user.py E337
lib/ansible/modules/network/ios/ios_user.py E338
lib/ansible/modules/network/ios/ios_vlan.py E337
lib/ansible/modules/network/ios/ios_vlan.py E338
lib/ansible/modules/network/ios/ios_vrf.py E337
lib/ansible/modules/network/ios/ios_vrf.py E338
lib/ansible/modules/network/iosxr/iosxr_banner.py E338
lib/ansible/modules/network/iosxr/iosxr_bgp.py E337
lib/ansible/modules/network/iosxr/iosxr_bgp.py E338
lib/ansible/modules/network/iosxr/iosxr_command.py E322
lib/ansible/modules/network/iosxr/iosxr_command.py E337
lib/ansible/modules/network/iosxr/iosxr_command.py E338
lib/ansible/modules/network/iosxr/iosxr_config.py E337
lib/ansible/modules/network/iosxr/iosxr_config.py E338
lib/ansible/modules/network/iosxr/iosxr_facts.py E337
lib/ansible/modules/network/iosxr/iosxr_interface.py E337
lib/ansible/modules/network/iosxr/iosxr_interface.py E338
lib/ansible/modules/network/iosxr/iosxr_logging.py E324
lib/ansible/modules/network/iosxr/iosxr_logging.py E326
lib/ansible/modules/network/iosxr/iosxr_logging.py E337
lib/ansible/modules/network/iosxr/iosxr_logging.py E338
lib/ansible/modules/network/iosxr/iosxr_netconf.py E337
lib/ansible/modules/network/iosxr/iosxr_netconf.py E338
lib/ansible/modules/network/iosxr/iosxr_system.py E324
lib/ansible/modules/network/iosxr/iosxr_system.py E337
lib/ansible/modules/network/iosxr/iosxr_system.py E338
lib/ansible/modules/network/iosxr/iosxr_user.py E337
lib/ansible/modules/network/iosxr/iosxr_user.py E338
lib/ansible/modules/network/ironware/ironware_command.py E323
lib/ansible/modules/network/ironware/ironware_command.py E337
lib/ansible/modules/network/ironware/ironware_command.py E338
lib/ansible/modules/network/ironware/ironware_config.py E323
lib/ansible/modules/network/ironware/ironware_config.py E337
lib/ansible/modules/network/ironware/ironware_config.py E338
lib/ansible/modules/network/ironware/ironware_facts.py E323
lib/ansible/modules/network/ironware/ironware_facts.py E337
lib/ansible/modules/network/itential/iap_token.py E337
lib/ansible/modules/network/junos/junos_banner.py E338
lib/ansible/modules/network/junos/junos_command.py E324
lib/ansible/modules/network/junos/junos_command.py E337
lib/ansible/modules/network/junos/junos_command.py E338
lib/ansible/modules/network/junos/junos_config.py E337
lib/ansible/modules/network/junos/junos_config.py E338
lib/ansible/modules/network/junos/junos_facts.py E337
lib/ansible/modules/network/junos/junos_facts.py E338
lib/ansible/modules/network/junos/_junos_interface.py E324
lib/ansible/modules/network/junos/_junos_interface.py E337
lib/ansible/modules/network/junos/_junos_interface.py E338
lib/ansible/modules/network/junos/junos_l2_interface.py E337
lib/ansible/modules/network/junos/junos_l2_interface.py E338
lib/ansible/modules/network/junos/junos_l3_interface.py E337
lib/ansible/modules/network/junos/junos_l3_interface.py E338
lib/ansible/modules/network/junos/junos_linkagg.py E324
lib/ansible/modules/network/junos/junos_linkagg.py E337
lib/ansible/modules/network/junos/junos_linkagg.py E338
lib/ansible/modules/network/junos/junos_lldp_interface.py E338
lib/ansible/modules/network/junos/junos_lldp.py E337
lib/ansible/modules/network/junos/junos_lldp.py E338
lib/ansible/modules/network/junos/junos_logging.py E322
lib/ansible/modules/network/junos/junos_logging.py E337
lib/ansible/modules/network/junos/junos_logging.py E338
lib/ansible/modules/network/junos/junos_netconf.py E337
lib/ansible/modules/network/junos/junos_netconf.py E338
lib/ansible/modules/network/junos/junos_package.py E337
lib/ansible/modules/network/junos/junos_package.py E338
lib/ansible/modules/network/junos/junos_ping.py E337
lib/ansible/modules/network/junos/junos_ping.py E338
lib/ansible/modules/network/junos/junos_rpc.py E326
lib/ansible/modules/network/junos/junos_rpc.py E337
lib/ansible/modules/network/junos/junos_rpc.py E338
lib/ansible/modules/network/junos/junos_scp.py E337
lib/ansible/modules/network/junos/junos_scp.py E338
lib/ansible/modules/network/junos/junos_static_route.py E322
lib/ansible/modules/network/junos/junos_static_route.py E337
lib/ansible/modules/network/junos/junos_static_route.py E338
lib/ansible/modules/network/junos/junos_system.py E337
lib/ansible/modules/network/junos/junos_system.py E338
lib/ansible/modules/network/junos/junos_user.py E337
lib/ansible/modules/network/junos/junos_user.py E338
lib/ansible/modules/network/junos/junos_vlan.py E337
lib/ansible/modules/network/junos/junos_vlan.py E338
lib/ansible/modules/network/junos/junos_vrf.py E324
lib/ansible/modules/network/junos/junos_vrf.py E337
lib/ansible/modules/network/junos/junos_vrf.py E338
lib/ansible/modules/network/meraki/meraki_admin.py E337
lib/ansible/modules/network/meraki/meraki_config_template.py E337
lib/ansible/modules/network/meraki/meraki_malware.py E337
lib/ansible/modules/network/meraki/meraki_mr_l3_firewall.py E325
lib/ansible/modules/network/meraki/meraki_mx_l3_firewall.py E337
lib/ansible/modules/network/meraki/meraki_network.py E337
lib/ansible/modules/network/meraki/meraki_organization.py E337
lib/ansible/modules/network/meraki/meraki_snmp.py E337
lib/ansible/modules/network/meraki/meraki_ssid.py E325
lib/ansible/modules/network/meraki/meraki_switchport.py E337
lib/ansible/modules/network/meraki/meraki_syslog.py E337
lib/ansible/modules/network/netact/netact_cm_command.py E326
lib/ansible/modules/network/netact/netact_cm_command.py E337
lib/ansible/modules/network/netconf/netconf_config.py E326
lib/ansible/modules/network/netconf/netconf_config.py E337
lib/ansible/modules/network/netconf/netconf_config.py E338
lib/ansible/modules/network/netconf/netconf_get.py E338
lib/ansible/modules/network/netconf/netconf_rpc.py E337
lib/ansible/modules/network/netconf/netconf_rpc.py E338
lib/ansible/modules/network/netscaler/netscaler_cs_action.py E323
lib/ansible/modules/network/netscaler/netscaler_cs_action.py E337
lib/ansible/modules/network/netscaler/netscaler_cs_policy.py E337
lib/ansible/modules/network/netscaler/netscaler_cs_vserver.py E322
lib/ansible/modules/network/netscaler/netscaler_cs_vserver.py E323
lib/ansible/modules/network/netscaler/netscaler_cs_vserver.py E326
lib/ansible/modules/network/netscaler/netscaler_cs_vserver.py E337
lib/ansible/modules/network/netscaler/netscaler_gslb_service.py E337
lib/ansible/modules/network/netscaler/netscaler_gslb_site.py E337
lib/ansible/modules/network/netscaler/netscaler_gslb_vserver.py E322
lib/ansible/modules/network/netscaler/netscaler_gslb_vserver.py E337
lib/ansible/modules/network/netscaler/netscaler_lb_monitor.py E323
lib/ansible/modules/network/netscaler/netscaler_lb_monitor.py E326
lib/ansible/modules/network/netscaler/netscaler_lb_monitor.py E337
lib/ansible/modules/network/netscaler/netscaler_lb_vserver.py E323
lib/ansible/modules/network/netscaler/netscaler_lb_vserver.py E337
lib/ansible/modules/network/netscaler/netscaler_nitro_request.py E337
lib/ansible/modules/network/netscaler/netscaler_nitro_request.py E338
lib/ansible/modules/network/netscaler/netscaler_save_config.py E337
lib/ansible/modules/network/netscaler/netscaler_save_config.py E338
lib/ansible/modules/network/netscaler/netscaler_server.py E324
lib/ansible/modules/network/netscaler/netscaler_server.py E337
lib/ansible/modules/network/netscaler/netscaler_servicegroup.py E337
lib/ansible/modules/network/netscaler/netscaler_service.py E323
lib/ansible/modules/network/netscaler/netscaler_service.py E337
lib/ansible/modules/network/netscaler/netscaler_ssl_certkey.py E337
lib/ansible/modules/network/netvisor/pn_access_list_ip.py E337
lib/ansible/modules/network/netvisor/pn_access_list.py E337
lib/ansible/modules/network/netvisor/_pn_cluster.py E337
lib/ansible/modules/network/netvisor/pn_cpu_class.py E337
lib/ansible/modules/network/netvisor/pn_dscp_map.py E337
lib/ansible/modules/network/netvisor/pn_fabric_local.py E337
lib/ansible/modules/network/netvisor/pn_igmp_snooping.py E337
lib/ansible/modules/network/netvisor/_pn_ospfarea.py E337
lib/ansible/modules/network/netvisor/_pn_ospf.py E337
lib/ansible/modules/network/netvisor/pn_port_config.py E337
lib/ansible/modules/network/netvisor/_pn_show.py E337
lib/ansible/modules/network/netvisor/pn_snmp_community.py E337
lib/ansible/modules/network/netvisor/pn_switch_setup.py E337
lib/ansible/modules/network/netvisor/_pn_trunk.py E337
lib/ansible/modules/network/netvisor/_pn_vlag.py E337
lib/ansible/modules/network/netvisor/_pn_vlan.py E337
lib/ansible/modules/network/netvisor/_pn_vrouterbgp.py E337
lib/ansible/modules/network/netvisor/pn_vrouter_bgp.py E337
lib/ansible/modules/network/netvisor/_pn_vrouterif.py E337
lib/ansible/modules/network/netvisor/_pn_vrouterlbif.py E337
lib/ansible/modules/network/netvisor/_pn_vrouter.py E337
lib/ansible/modules/network/nos/nos_command.py E337
lib/ansible/modules/network/nos/nos_command.py E338
lib/ansible/modules/network/nos/nos_config.py E337
lib/ansible/modules/network/nos/nos_config.py E338
lib/ansible/modules/network/nos/nos_facts.py E337
lib/ansible/modules/network/nso/nso_action.py E337
lib/ansible/modules/network/nso/nso_action.py E338
lib/ansible/modules/network/nso/nso_config.py E337
lib/ansible/modules/network/nso/nso_query.py E337
lib/ansible/modules/network/nso/nso_show.py E337
lib/ansible/modules/network/nso/nso_verify.py E337
lib/ansible/modules/network/nuage/nuage_vspk.py E337
lib/ansible/modules/network/nxos/nxos_aaa_server_host.py E337
lib/ansible/modules/network/nxos/nxos_aaa_server_host.py E338
lib/ansible/modules/network/nxos/nxos_aaa_server.py E326
lib/ansible/modules/network/nxos/nxos_aaa_server.py E337
lib/ansible/modules/network/nxos/nxos_aaa_server.py E338
lib/ansible/modules/network/nxos/nxos_acl_interface.py E337
lib/ansible/modules/network/nxos/nxos_acl_interface.py E338
lib/ansible/modules/network/nxos/nxos_acl.py E326
lib/ansible/modules/network/nxos/nxos_acl.py E337
lib/ansible/modules/network/nxos/nxos_acl.py E338
lib/ansible/modules/network/nxos/nxos_banner.py E338
lib/ansible/modules/network/nxos/nxos_bgp_af.py E324
lib/ansible/modules/network/nxos/nxos_bgp_af.py E337
lib/ansible/modules/network/nxos/nxos_bgp_af.py E338
lib/ansible/modules/network/nxos/nxos_bgp_neighbor_af.py E326
lib/ansible/modules/network/nxos/nxos_bgp_neighbor_af.py E337
lib/ansible/modules/network/nxos/nxos_bgp_neighbor_af.py E338
lib/ansible/modules/network/nxos/nxos_bgp_neighbor.py E337
lib/ansible/modules/network/nxos/nxos_bgp_neighbor.py E338
lib/ansible/modules/network/nxos/nxos_bgp.py E324
lib/ansible/modules/network/nxos/nxos_bgp.py E326
lib/ansible/modules/network/nxos/nxos_bgp.py E337
lib/ansible/modules/network/nxos/nxos_bgp.py E338
lib/ansible/modules/network/nxos/nxos_command.py E326
lib/ansible/modules/network/nxos/nxos_command.py E337
lib/ansible/modules/network/nxos/nxos_command.py E338
lib/ansible/modules/network/nxos/nxos_config.py E324
lib/ansible/modules/network/nxos/nxos_config.py E337
lib/ansible/modules/network/nxos/nxos_config.py E338
lib/ansible/modules/network/nxos/nxos_evpn_vni.py E337
lib/ansible/modules/network/nxos/nxos_evpn_vni.py E338
lib/ansible/modules/network/nxos/nxos_facts.py E337
lib/ansible/modules/network/nxos/nxos_feature.py E337
lib/ansible/modules/network/nxos/nxos_feature.py E338
lib/ansible/modules/network/nxos/nxos_file_copy.py E337
lib/ansible/modules/network/nxos/nxos_file_copy.py E338
lib/ansible/modules/network/nxos/nxos_gir_profile_management.py E337
lib/ansible/modules/network/nxos/nxos_gir_profile_management.py E338
lib/ansible/modules/network/nxos/nxos_gir.py E326
lib/ansible/modules/network/nxos/nxos_gir.py E337
lib/ansible/modules/network/nxos/nxos_gir.py E338
lib/ansible/modules/network/nxos/nxos_hsrp.py E337
lib/ansible/modules/network/nxos/nxos_hsrp.py E338
lib/ansible/modules/network/nxos/nxos_igmp_interface.py E326
lib/ansible/modules/network/nxos/nxos_igmp_interface.py E337
lib/ansible/modules/network/nxos/nxos_igmp_interface.py E338
lib/ansible/modules/network/nxos/nxos_igmp.py E338
lib/ansible/modules/network/nxos/nxos_igmp_snooping.py E337
lib/ansible/modules/network/nxos/nxos_igmp_snooping.py E338
lib/ansible/modules/network/nxos/nxos_install_os.py E338
lib/ansible/modules/network/nxos/nxos_interface_ospf.py E337
lib/ansible/modules/network/nxos/nxos_interface_ospf.py E338
lib/ansible/modules/network/nxos/nxos_interface.py E324
lib/ansible/modules/network/nxos/nxos_interface.py E337
lib/ansible/modules/network/nxos/nxos_interface.py E338
lib/ansible/modules/network/nxos/nxos_l2_interface.py E337
lib/ansible/modules/network/nxos/nxos_l2_interface.py E338
lib/ansible/modules/network/nxos/nxos_l3_interface.py E337
lib/ansible/modules/network/nxos/nxos_l3_interface.py E338
lib/ansible/modules/network/nxos/nxos_linkagg.py E337
lib/ansible/modules/network/nxos/nxos_linkagg.py E338
lib/ansible/modules/network/nxos/nxos_lldp.py E326
lib/ansible/modules/network/nxos/nxos_lldp.py E338
lib/ansible/modules/network/nxos/nxos_logging.py E337
lib/ansible/modules/network/nxos/nxos_logging.py E338
lib/ansible/modules/network/nxos/nxos_ntp_auth.py E337
lib/ansible/modules/network/nxos/nxos_ntp_auth.py E338
lib/ansible/modules/network/nxos/nxos_ntp_options.py E337
lib/ansible/modules/network/nxos/nxos_ntp_options.py E338
lib/ansible/modules/network/nxos/nxos_ntp.py E337
lib/ansible/modules/network/nxos/nxos_ntp.py E338
lib/ansible/modules/network/nxos/nxos_nxapi.py E326
lib/ansible/modules/network/nxos/nxos_nxapi.py E337
lib/ansible/modules/network/nxos/nxos_nxapi.py E338
lib/ansible/modules/network/nxos/nxos_ospf.py E337
lib/ansible/modules/network/nxos/nxos_ospf.py E338
lib/ansible/modules/network/nxos/nxos_ospf_vrf.py E337
lib/ansible/modules/network/nxos/nxos_ospf_vrf.py E338
lib/ansible/modules/network/nxos/nxos_overlay_global.py E337
lib/ansible/modules/network/nxos/nxos_pim_interface.py E326
lib/ansible/modules/network/nxos/nxos_pim.py E337
lib/ansible/modules/network/nxos/nxos_pim_rp_address.py E326
lib/ansible/modules/network/nxos/nxos_pim_rp_address.py E337
lib/ansible/modules/network/nxos/nxos_pim_rp_address.py E338
lib/ansible/modules/network/nxos/nxos_ping.py E337
lib/ansible/modules/network/nxos/nxos_ping.py E338
lib/ansible/modules/network/nxos/nxos_rollback.py E338
lib/ansible/modules/network/nxos/nxos_rpm.py E337
lib/ansible/modules/network/nxos/nxos_rpm.py E338
lib/ansible/modules/network/nxos/nxos_smu.py E324
lib/ansible/modules/network/nxos/nxos_smu.py E338
lib/ansible/modules/network/nxos/nxos_snapshot.py E337
lib/ansible/modules/network/nxos/nxos_snapshot.py E338
lib/ansible/modules/network/nxos/nxos_snmp_community.py E337
lib/ansible/modules/network/nxos/nxos_snmp_community.py E338
lib/ansible/modules/network/nxos/nxos_snmp_contact.py E337
lib/ansible/modules/network/nxos/nxos_snmp_contact.py E338
lib/ansible/modules/network/nxos/nxos_snmp_host.py E337
lib/ansible/modules/network/nxos/nxos_snmp_host.py E338
lib/ansible/modules/network/nxos/nxos_snmp_location.py E337
lib/ansible/modules/network/nxos/nxos_snmp_location.py E338
lib/ansible/modules/network/nxos/nxos_snmp_traps.py E338
lib/ansible/modules/network/nxos/nxos_snmp_user.py E337
lib/ansible/modules/network/nxos/nxos_snmp_user.py E338
lib/ansible/modules/network/nxos/nxos_static_route.py E337
lib/ansible/modules/network/nxos/nxos_static_route.py E338
lib/ansible/modules/network/nxos/nxos_system.py E337
lib/ansible/modules/network/nxos/nxos_system.py E338
lib/ansible/modules/network/nxos/nxos_udld_interface.py E337
lib/ansible/modules/network/nxos/nxos_udld_interface.py E338
lib/ansible/modules/network/nxos/nxos_udld.py E337
lib/ansible/modules/network/nxos/nxos_udld.py E338
lib/ansible/modules/network/nxos/nxos_user.py E337
lib/ansible/modules/network/nxos/nxos_user.py E338
lib/ansible/modules/network/nxos/nxos_vlan.py E337
lib/ansible/modules/network/nxos/nxos_vlan.py E338
lib/ansible/modules/network/nxos/nxos_vpc_interface.py E337
lib/ansible/modules/network/nxos/nxos_vpc_interface.py E338
lib/ansible/modules/network/nxos/nxos_vpc.py E324
lib/ansible/modules/network/nxos/nxos_vpc.py E337
lib/ansible/modules/network/nxos/nxos_vpc.py E338
lib/ansible/modules/network/nxos/nxos_vrf_af.py E338
lib/ansible/modules/network/nxos/nxos_vrf_interface.py E337
lib/ansible/modules/network/nxos/nxos_vrf_interface.py E338
lib/ansible/modules/network/nxos/nxos_vrf.py E337
lib/ansible/modules/network/nxos/nxos_vrrp.py E324
lib/ansible/modules/network/nxos/nxos_vrrp.py E337
lib/ansible/modules/network/nxos/nxos_vrrp.py E338
lib/ansible/modules/network/nxos/nxos_vtp_domain.py E337
lib/ansible/modules/network/nxos/nxos_vtp_password.py E337
lib/ansible/modules/network/nxos/nxos_vtp_password.py E338
lib/ansible/modules/network/nxos/nxos_vtp_version.py E337
lib/ansible/modules/network/nxos/nxos_vxlan_vtep.py E337
lib/ansible/modules/network/nxos/nxos_vxlan_vtep.py E338
lib/ansible/modules/network/nxos/nxos_vxlan_vtep_vni.py E337
lib/ansible/modules/network/nxos/nxos_vxlan_vtep_vni.py E338
lib/ansible/modules/network/onyx/onyx_bgp.py E337
lib/ansible/modules/network/onyx/onyx_bgp.py E338
lib/ansible/modules/network/onyx/onyx_buffer_pool.py E337
lib/ansible/modules/network/onyx/onyx_buffer_pool.py E338
lib/ansible/modules/network/onyx/onyx_command.py E323
lib/ansible/modules/network/onyx/onyx_command.py E337
lib/ansible/modules/network/onyx/onyx_command.py E338
lib/ansible/modules/network/onyx/onyx_config.py E323
lib/ansible/modules/network/onyx/onyx_config.py E337
lib/ansible/modules/network/onyx/onyx_config.py E338
lib/ansible/modules/network/onyx/onyx_facts.py E337
lib/ansible/modules/network/onyx/onyx_igmp_interface.py E338
lib/ansible/modules/network/onyx/onyx_igmp.py E337
lib/ansible/modules/network/onyx/onyx_igmp.py E338
lib/ansible/modules/network/onyx/onyx_igmp_vlan.py E337
lib/ansible/modules/network/onyx/onyx_igmp_vlan.py E338
lib/ansible/modules/network/onyx/onyx_interface.py E323
lib/ansible/modules/network/onyx/onyx_interface.py E337
lib/ansible/modules/network/onyx/onyx_interface.py E338
lib/ansible/modules/network/onyx/onyx_l2_interface.py E337
lib/ansible/modules/network/onyx/onyx_l2_interface.py E338
lib/ansible/modules/network/onyx/onyx_l3_interface.py E326
lib/ansible/modules/network/onyx/onyx_l3_interface.py E337
lib/ansible/modules/network/onyx/onyx_l3_interface.py E338
lib/ansible/modules/network/onyx/onyx_linkagg.py E324
lib/ansible/modules/network/onyx/onyx_linkagg.py E326
lib/ansible/modules/network/onyx/onyx_linkagg.py E337
lib/ansible/modules/network/onyx/onyx_linkagg.py E338
lib/ansible/modules/network/onyx/onyx_lldp_interface.py E337
lib/ansible/modules/network/onyx/onyx_lldp_interface.py E338
lib/ansible/modules/network/onyx/onyx_lldp.py E338
lib/ansible/modules/network/onyx/onyx_magp.py E337
lib/ansible/modules/network/onyx/onyx_magp.py E338
lib/ansible/modules/network/onyx/onyx_mlag_ipl.py E338
lib/ansible/modules/network/onyx/onyx_mlag_vip.py E324
lib/ansible/modules/network/onyx/onyx_mlag_vip.py E337
lib/ansible/modules/network/onyx/onyx_mlag_vip.py E338
lib/ansible/modules/network/onyx/onyx_ospf.py E337
lib/ansible/modules/network/onyx/onyx_ospf.py E338
lib/ansible/modules/network/onyx/onyx_pfc_interface.py E337
lib/ansible/modules/network/onyx/onyx_pfc_interface.py E338
lib/ansible/modules/network/onyx/onyx_protocol.py E338
lib/ansible/modules/network/onyx/onyx_ptp_global.py E337
lib/ansible/modules/network/onyx/onyx_ptp_global.py E338
lib/ansible/modules/network/onyx/onyx_ptp_interface.py E337
lib/ansible/modules/network/onyx/onyx_ptp_interface.py E338
lib/ansible/modules/network/onyx/onyx_qos.py E337
lib/ansible/modules/network/onyx/onyx_qos.py E338
lib/ansible/modules/network/onyx/onyx_traffic_class.py E337
lib/ansible/modules/network/onyx/onyx_traffic_class.py E338
lib/ansible/modules/network/onyx/onyx_vlan.py E337
lib/ansible/modules/network/onyx/onyx_vlan.py E338
lib/ansible/modules/network/onyx/onyx_vxlan.py E337
lib/ansible/modules/network/opx/opx_cps.py E337
lib/ansible/modules/network/ordnance/ordnance_config.py E322
lib/ansible/modules/network/ordnance/ordnance_config.py E324
lib/ansible/modules/network/ordnance/ordnance_config.py E337
lib/ansible/modules/network/ordnance/ordnance_config.py E338
lib/ansible/modules/network/ordnance/ordnance_facts.py E322
lib/ansible/modules/network/ordnance/ordnance_facts.py E324
lib/ansible/modules/network/ordnance/ordnance_facts.py E337
lib/ansible/modules/network/ordnance/ordnance_facts.py E338
lib/ansible/modules/network/ovs/openvswitch_bridge.py E326
lib/ansible/modules/network/ovs/openvswitch_bridge.py E337
lib/ansible/modules/network/ovs/openvswitch_bridge.py E338
lib/ansible/modules/network/ovs/openvswitch_db.py E337
lib/ansible/modules/network/ovs/openvswitch_db.py E338
lib/ansible/modules/network/ovs/openvswitch_port.py E337
lib/ansible/modules/network/ovs/openvswitch_port.py E338
lib/ansible/modules/network/panos/_panos_admin.py E338
lib/ansible/modules/network/panos/_panos_admpwd.py E338
lib/ansible/modules/network/panos/_panos_cert_gen_ssh.py E338
lib/ansible/modules/network/panos/_panos_check.py E337
lib/ansible/modules/network/panos/_panos_commit.py E337
lib/ansible/modules/network/panos/_panos_commit.py E338
lib/ansible/modules/network/panos/_panos_dag.py E338
lib/ansible/modules/network/panos/_panos_dag_tags.py E337
lib/ansible/modules/network/panos/_panos_dag_tags.py E338
lib/ansible/modules/network/panos/_panos_import.py E338
lib/ansible/modules/network/panos/_panos_interface.py E338
lib/ansible/modules/network/panos/_panos_lic.py E338
lib/ansible/modules/network/panos/_panos_loadcfg.py E338
lib/ansible/modules/network/panos/_panos_match_rule.py E337
lib/ansible/modules/network/panos/_panos_match_rule.py E338
lib/ansible/modules/network/panos/_panos_mgtconfig.py E338
lib/ansible/modules/network/panos/_panos_nat_rule.py E337
lib/ansible/modules/network/panos/_panos_nat_rule.py E338
lib/ansible/modules/network/panos/_panos_object.py E337
lib/ansible/modules/network/panos/_panos_object.py E338
lib/ansible/modules/network/panos/_panos_op.py E338
lib/ansible/modules/network/panos/_panos_pg.py E338
lib/ansible/modules/network/panos/_panos_query_rules.py E338
lib/ansible/modules/network/panos/_panos_sag.py E337
lib/ansible/modules/network/panos/_panos_sag.py E338
lib/ansible/modules/network/panos/_panos_security_rule.py E337
lib/ansible/modules/network/panos/_panos_security_rule.py E338
lib/ansible/modules/network/panos/_panos_set.py E338
lib/ansible/modules/network/radware/vdirect_commit.py E337
lib/ansible/modules/network/radware/vdirect_commit.py E338
lib/ansible/modules/network/radware/vdirect_file.py E337
lib/ansible/modules/network/radware/vdirect_file.py E338
lib/ansible/modules/network/radware/vdirect_runnable.py E337
lib/ansible/modules/network/radware/vdirect_runnable.py E338
lib/ansible/modules/network/restconf/restconf_config.py E338
lib/ansible/modules/network/restconf/restconf_get.py E338
lib/ansible/modules/network/routeros/routeros_command.py E337
lib/ansible/modules/network/routeros/routeros_command.py E338
lib/ansible/modules/network/routeros/routeros_facts.py E337
lib/ansible/modules/network/skydive/skydive_capture.py E337
lib/ansible/modules/network/skydive/skydive_capture.py E338
lib/ansible/modules/network/skydive/skydive_edge.py E337
lib/ansible/modules/network/skydive/skydive_edge.py E338
lib/ansible/modules/network/skydive/skydive_node.py E337
lib/ansible/modules/network/skydive/skydive_node.py E338
lib/ansible/modules/network/slxos/slxos_command.py E337
lib/ansible/modules/network/slxos/slxos_command.py E338
lib/ansible/modules/network/slxos/slxos_config.py E337
lib/ansible/modules/network/slxos/slxos_config.py E338
lib/ansible/modules/network/slxos/slxos_facts.py E337
lib/ansible/modules/network/slxos/slxos_interface.py E337
lib/ansible/modules/network/slxos/slxos_interface.py E338
lib/ansible/modules/network/slxos/slxos_l2_interface.py E337
lib/ansible/modules/network/slxos/slxos_l2_interface.py E338
lib/ansible/modules/network/slxos/slxos_l3_interface.py E337
lib/ansible/modules/network/slxos/slxos_l3_interface.py E338
lib/ansible/modules/network/slxos/slxos_linkagg.py E337
lib/ansible/modules/network/slxos/slxos_linkagg.py E338
lib/ansible/modules/network/slxos/slxos_lldp.py E338
lib/ansible/modules/network/slxos/slxos_vlan.py E337
lib/ansible/modules/network/slxos/slxos_vlan.py E338
lib/ansible/modules/network/sros/sros_command.py E337
lib/ansible/modules/network/sros/sros_command.py E338
lib/ansible/modules/network/sros/sros_config.py E323
lib/ansible/modules/network/sros/sros_config.py E337
lib/ansible/modules/network/sros/sros_config.py E338
lib/ansible/modules/network/sros/sros_rollback.py E337
lib/ansible/modules/network/sros/sros_rollback.py E338
lib/ansible/modules/network/voss/voss_command.py E337
lib/ansible/modules/network/voss/voss_command.py E338
lib/ansible/modules/network/voss/voss_config.py E337
lib/ansible/modules/network/voss/voss_config.py E338
lib/ansible/modules/network/voss/voss_facts.py E337
lib/ansible/modules/network/vyos/vyos_banner.py E338
lib/ansible/modules/network/vyos/vyos_command.py E337
lib/ansible/modules/network/vyos/vyos_command.py E338
lib/ansible/modules/network/vyos/vyos_config.py E337
lib/ansible/modules/network/vyos/vyos_config.py E338
lib/ansible/modules/network/vyos/vyos_facts.py E337
lib/ansible/modules/network/vyos/vyos_interface.py E324
lib/ansible/modules/network/vyos/vyos_interface.py E337
lib/ansible/modules/network/vyos/vyos_interface.py E338
lib/ansible/modules/network/vyos/vyos_l3_interface.py E337
lib/ansible/modules/network/vyos/vyos_l3_interface.py E338
lib/ansible/modules/network/vyos/vyos_linkagg.py E324
lib/ansible/modules/network/vyos/vyos_linkagg.py E337
lib/ansible/modules/network/vyos/vyos_linkagg.py E338
lib/ansible/modules/network/vyos/vyos_lldp_interface.py E337
lib/ansible/modules/network/vyos/vyos_lldp_interface.py E338
lib/ansible/modules/network/vyos/vyos_lldp.py E322
lib/ansible/modules/network/vyos/vyos_lldp.py E326
lib/ansible/modules/network/vyos/vyos_lldp.py E337
lib/ansible/modules/network/vyos/vyos_lldp.py E338
lib/ansible/modules/network/vyos/vyos_logging.py E337
lib/ansible/modules/network/vyos/vyos_logging.py E338
lib/ansible/modules/network/vyos/vyos_ping.py E337
lib/ansible/modules/network/vyos/vyos_static_route.py E337
lib/ansible/modules/network/vyos/vyos_static_route.py E338
lib/ansible/modules/network/vyos/vyos_system.py E337
lib/ansible/modules/network/vyos/vyos_user.py E337
lib/ansible/modules/network/vyos/vyos_user.py E338
lib/ansible/modules/network/vyos/vyos_vlan.py E337
lib/ansible/modules/network/vyos/vyos_vlan.py E338
lib/ansible/modules/notification/bearychat.py E337
lib/ansible/modules/notification/campfire.py E338
lib/ansible/modules/notification/catapult.py E337
lib/ansible/modules/notification/catapult.py E338
lib/ansible/modules/notification/cisco_spark.py E322
lib/ansible/modules/notification/cisco_spark.py E324
lib/ansible/modules/notification/cisco_spark.py E338
lib/ansible/modules/notification/flowdock.py E338
lib/ansible/modules/notification/grove.py E337
lib/ansible/modules/notification/hall.py E324
lib/ansible/modules/notification/hall.py E337
lib/ansible/modules/notification/hipchat.py E322
lib/ansible/modules/notification/hipchat.py E324
lib/ansible/modules/notification/hipchat.py E338
lib/ansible/modules/notification/irc.py E322
lib/ansible/modules/notification/irc.py E324
lib/ansible/modules/notification/irc.py E326
lib/ansible/modules/notification/irc.py E337
lib/ansible/modules/notification/irc.py E338
lib/ansible/modules/notification/jabber.py E337
lib/ansible/modules/notification/jabber.py E338
lib/ansible/modules/notification/logentries_msg.py E337
lib/ansible/modules/notification/mail.py E322
lib/ansible/modules/notification/mail.py E324
lib/ansible/modules/notification/mail.py E337
lib/ansible/modules/notification/matrix.py E337
lib/ansible/modules/notification/mattermost.py E337
lib/ansible/modules/notification/mqtt.py E324
lib/ansible/modules/notification/mqtt.py E337
lib/ansible/modules/notification/mqtt.py E338
lib/ansible/modules/notification/nexmo.py E337
lib/ansible/modules/notification/nexmo.py E338
lib/ansible/modules/notification/office_365_connector_card.py E337
lib/ansible/modules/notification/office_365_connector_card.py E338
lib/ansible/modules/notification/pushbullet.py E322
lib/ansible/modules/notification/pushbullet.py E337
lib/ansible/modules/notification/pushover.py E324
lib/ansible/modules/notification/pushover.py E326
lib/ansible/modules/notification/pushover.py E337
lib/ansible/modules/notification/pushover.py E338
lib/ansible/modules/notification/rabbitmq_publish.py E337
lib/ansible/modules/notification/rocketchat.py E317
lib/ansible/modules/notification/rocketchat.py E337
lib/ansible/modules/notification/say.py E338
lib/ansible/modules/notification/sendgrid.py E322
lib/ansible/modules/notification/sendgrid.py E337
lib/ansible/modules/notification/sendgrid.py E338
lib/ansible/modules/notification/slack.py E324
lib/ansible/modules/notification/slack.py E337
lib/ansible/modules/notification/syslogger.py E337
lib/ansible/modules/notification/telegram.py E337
lib/ansible/modules/notification/twilio.py E337
lib/ansible/modules/notification/twilio.py E338
lib/ansible/modules/notification/typetalk.py E337
lib/ansible/modules/notification/typetalk.py E338
lib/ansible/modules/packaging/language/bower.py E337
lib/ansible/modules/packaging/language/bower.py E338
lib/ansible/modules/packaging/language/bundler.py E324
lib/ansible/modules/packaging/language/bundler.py E337
lib/ansible/modules/packaging/language/bundler.py E338
lib/ansible/modules/packaging/language/composer.py E336
lib/ansible/modules/packaging/language/composer.py E337
lib/ansible/modules/packaging/language/cpanm.py E337
lib/ansible/modules/packaging/language/cpanm.py E338
lib/ansible/modules/packaging/language/easy_install.py E324
lib/ansible/modules/packaging/language/easy_install.py E337
lib/ansible/modules/packaging/language/easy_install.py E338
lib/ansible/modules/packaging/language/gem.py E337
lib/ansible/modules/packaging/language/maven_artifact.py E324
lib/ansible/modules/packaging/language/maven_artifact.py E337
lib/ansible/modules/packaging/language/maven_artifact.py E338
lib/ansible/modules/packaging/language/npm.py E337
lib/ansible/modules/packaging/language/npm.py E338
lib/ansible/modules/packaging/language/pear.py E322
lib/ansible/modules/packaging/language/pear.py E326
lib/ansible/modules/packaging/language/pear.py E337
lib/ansible/modules/packaging/language/pear.py E338
lib/ansible/modules/packaging/language/pip.py E322
lib/ansible/modules/packaging/language/pip.py E324
lib/ansible/modules/packaging/language/pip.py E337
lib/ansible/modules/packaging/language/yarn.py E337
lib/ansible/modules/packaging/language/yarn.py E338
lib/ansible/modules/packaging/os/apk.py E326
lib/ansible/modules/packaging/os/apk.py E337
lib/ansible/modules/packaging/os/apk.py E338
lib/ansible/modules/packaging/os/apt_key.py E322
lib/ansible/modules/packaging/os/apt_key.py E337
lib/ansible/modules/packaging/os/apt.py E322
lib/ansible/modules/packaging/os/apt.py E324
lib/ansible/modules/packaging/os/apt.py E336
lib/ansible/modules/packaging/os/apt.py E337
lib/ansible/modules/packaging/os/apt_repo.py E337
lib/ansible/modules/packaging/os/apt_repository.py E322
lib/ansible/modules/packaging/os/apt_repository.py E324
lib/ansible/modules/packaging/os/apt_repository.py E336
lib/ansible/modules/packaging/os/apt_repository.py E337
lib/ansible/modules/packaging/os/apt_rpm.py E322
lib/ansible/modules/packaging/os/apt_rpm.py E324
lib/ansible/modules/packaging/os/apt_rpm.py E326
lib/ansible/modules/packaging/os/apt_rpm.py E336
lib/ansible/modules/packaging/os/apt_rpm.py E337
lib/ansible/modules/packaging/os/dnf.py E336
lib/ansible/modules/packaging/os/dnf.py E337
lib/ansible/modules/packaging/os/dnf.py E338
lib/ansible/modules/packaging/os/dpkg_selections.py E338
lib/ansible/modules/packaging/os/flatpak.py E210
lib/ansible/modules/packaging/os/flatpak.py E337
lib/ansible/modules/packaging/os/flatpak_remote.py E210
lib/ansible/modules/packaging/os/flatpak_remote.py E337
lib/ansible/modules/packaging/os/homebrew_cask.py E326
lib/ansible/modules/packaging/os/homebrew_cask.py E336
lib/ansible/modules/packaging/os/homebrew_cask.py E337
lib/ansible/modules/packaging/os/homebrew_cask.py E338
lib/ansible/modules/packaging/os/homebrew.py E326
lib/ansible/modules/packaging/os/homebrew.py E336
lib/ansible/modules/packaging/os/homebrew.py E337
lib/ansible/modules/packaging/os/homebrew.py E338
lib/ansible/modules/packaging/os/homebrew_tap.py E337
lib/ansible/modules/packaging/os/homebrew_tap.py E338
lib/ansible/modules/packaging/os/layman.py E322
lib/ansible/modules/packaging/os/layman.py E338
lib/ansible/modules/packaging/os/macports.py E326
lib/ansible/modules/packaging/os/macports.py E337
lib/ansible/modules/packaging/os/macports.py E338
lib/ansible/modules/packaging/os/openbsd_pkg.py E326
lib/ansible/modules/packaging/os/openbsd_pkg.py E337
lib/ansible/modules/packaging/os/opkg.py E322
lib/ansible/modules/packaging/os/opkg.py E324
lib/ansible/modules/packaging/os/opkg.py E326
lib/ansible/modules/packaging/os/opkg.py E336
lib/ansible/modules/packaging/os/opkg.py E338
lib/ansible/modules/packaging/os/package_facts.py E326
lib/ansible/modules/packaging/os/package_facts.py E338
lib/ansible/modules/packaging/os/pacman.py E326
lib/ansible/modules/packaging/os/pacman.py E336
lib/ansible/modules/packaging/os/pacman.py E337
lib/ansible/modules/packaging/os/pkg5_publisher.py E337
lib/ansible/modules/packaging/os/pkg5_publisher.py E338
lib/ansible/modules/packaging/os/pkg5.py E326
lib/ansible/modules/packaging/os/pkg5.py E337
lib/ansible/modules/packaging/os/pkgin.py E322
lib/ansible/modules/packaging/os/pkgin.py E337
lib/ansible/modules/packaging/os/pkgin.py E338
lib/ansible/modules/packaging/os/pkgng.py E322
lib/ansible/modules/packaging/os/pkgng.py E337
lib/ansible/modules/packaging/os/pkgng.py E338
lib/ansible/modules/packaging/os/pkgutil.py E338
lib/ansible/modules/packaging/os/portage.py E322
lib/ansible/modules/packaging/os/portage.py E337
lib/ansible/modules/packaging/os/portage.py E338
lib/ansible/modules/packaging/os/portinstall.py E322
lib/ansible/modules/packaging/os/portinstall.py E338
lib/ansible/modules/packaging/os/pulp_repo.py E322
lib/ansible/modules/packaging/os/pulp_repo.py E324
lib/ansible/modules/packaging/os/pulp_repo.py E338
lib/ansible/modules/packaging/os/redhat_subscription.py E337
lib/ansible/modules/packaging/os/redhat_subscription.py E338
lib/ansible/modules/packaging/os/rhn_channel.py E322
lib/ansible/modules/packaging/os/rhn_channel.py E326
lib/ansible/modules/packaging/os/rhn_channel.py E337
lib/ansible/modules/packaging/os/rhsm_release.py E337
lib/ansible/modules/packaging/os/rhsm_repository.py E324
lib/ansible/modules/packaging/os/rhsm_repository.py E337
lib/ansible/modules/packaging/os/rhsm_repository.py E338
lib/ansible/modules/packaging/os/rpm_key.py E337
lib/ansible/modules/packaging/os/slackpkg.py E322
lib/ansible/modules/packaging/os/slackpkg.py E324
lib/ansible/modules/packaging/os/slackpkg.py E326
lib/ansible/modules/packaging/os/slackpkg.py E336
lib/ansible/modules/packaging/os/slackpkg.py E337
lib/ansible/modules/packaging/os/slackpkg.py E338
lib/ansible/modules/packaging/os/snap.py E337
lib/ansible/modules/packaging/os/sorcery.py E337
lib/ansible/modules/packaging/os/sorcery.py E338
lib/ansible/modules/packaging/os/svr4pkg.py E338
lib/ansible/modules/packaging/os/swdepot.py E322
lib/ansible/modules/packaging/os/swdepot.py E338
lib/ansible/modules/packaging/os/swupd.py E337
lib/ansible/modules/packaging/os/urpmi.py E322
lib/ansible/modules/packaging/os/urpmi.py E324
lib/ansible/modules/packaging/os/urpmi.py E326
lib/ansible/modules/packaging/os/urpmi.py E336
lib/ansible/modules/packaging/os/urpmi.py E337
lib/ansible/modules/packaging/os/xbps.py E322
lib/ansible/modules/packaging/os/xbps.py E326
lib/ansible/modules/packaging/os/xbps.py E336
lib/ansible/modules/packaging/os/xbps.py E337
lib/ansible/modules/packaging/os/xbps.py E338
lib/ansible/modules/packaging/os/yum.py E322
lib/ansible/modules/packaging/os/yum.py E324
lib/ansible/modules/packaging/os/yum.py E336
lib/ansible/modules/packaging/os/yum.py E337
lib/ansible/modules/packaging/os/yum.py E338
lib/ansible/modules/packaging/os/yum_repository.py E322
lib/ansible/modules/packaging/os/yum_repository.py E324
lib/ansible/modules/packaging/os/yum_repository.py E337
lib/ansible/modules/packaging/os/yum_repository.py E338
lib/ansible/modules/packaging/os/zypper.py E326
lib/ansible/modules/packaging/os/zypper.py E337
lib/ansible/modules/packaging/os/zypper.py E338
lib/ansible/modules/packaging/os/zypper_repository.py E337
lib/ansible/modules/packaging/os/zypper_repository.py E338
lib/ansible/modules/remote_management/cobbler/cobbler_sync.py E337
lib/ansible/modules/remote_management/cobbler/cobbler_system.py E337
lib/ansible/modules/remote_management/cpm/cpm_plugconfig.py E337
lib/ansible/modules/remote_management/cpm/cpm_plugconfig.py E338
lib/ansible/modules/remote_management/cpm/cpm_plugcontrol.py E337
lib/ansible/modules/remote_management/cpm/cpm_plugcontrol.py E338
lib/ansible/modules/remote_management/cpm/cpm_serial_port_config.py E337
lib/ansible/modules/remote_management/cpm/cpm_serial_port_info.py E337
lib/ansible/modules/remote_management/cpm/cpm_user.py E337
lib/ansible/modules/remote_management/cpm/cpm_user.py E338
lib/ansible/modules/remote_management/dellemc/idrac/idrac_server_config_profile.py E337
lib/ansible/modules/remote_management/dellemc/idrac/idrac_server_config_profile.py E338
lib/ansible/modules/remote_management/foreman/_foreman.py E337
lib/ansible/modules/remote_management/foreman/_katello.py E337
lib/ansible/modules/remote_management/hpilo/hpilo_boot.py E326
lib/ansible/modules/remote_management/hpilo/hpilo_boot.py E337
lib/ansible/modules/remote_management/hpilo/hpilo_facts.py E337
lib/ansible/modules/remote_management/hpilo/hponcfg.py E337
lib/ansible/modules/remote_management/imc/imc_rest.py E337
lib/ansible/modules/remote_management/intersight/intersight_rest_api.py E337
lib/ansible/modules/remote_management/ipmi/ipmi_boot.py E326
lib/ansible/modules/remote_management/ipmi/ipmi_boot.py E337
lib/ansible/modules/remote_management/ipmi/ipmi_boot.py E338
lib/ansible/modules/remote_management/ipmi/ipmi_power.py E326
lib/ansible/modules/remote_management/ipmi/ipmi_power.py E337
lib/ansible/modules/remote_management/ipmi/ipmi_power.py E338
lib/ansible/modules/remote_management/lxca/lxca_cmms.py E338
lib/ansible/modules/remote_management/lxca/lxca_nodes.py E338
lib/ansible/modules/remote_management/manageiq/manageiq_alert_profiles.py E337
lib/ansible/modules/remote_management/manageiq/manageiq_alert_profiles.py E338
lib/ansible/modules/remote_management/manageiq/manageiq_alerts.py E337
lib/ansible/modules/remote_management/manageiq/manageiq_alerts.py E338
lib/ansible/modules/remote_management/manageiq/manageiq_group.py E337
lib/ansible/modules/remote_management/manageiq/manageiq_group.py E338
lib/ansible/modules/remote_management/manageiq/manageiq_policies.py E337
lib/ansible/modules/remote_management/manageiq/manageiq_provider.py E337
lib/ansible/modules/remote_management/manageiq/manageiq_provider.py E338
lib/ansible/modules/remote_management/manageiq/manageiq_tags.py E337
lib/ansible/modules/remote_management/manageiq/manageiq_tenant.py E337
lib/ansible/modules/remote_management/manageiq/manageiq_tenant.py E338
lib/ansible/modules/remote_management/manageiq/manageiq_user.py E337
lib/ansible/modules/remote_management/manageiq/manageiq_user.py E338
lib/ansible/modules/remote_management/oneview/oneview_datacenter_facts.py E322
lib/ansible/modules/remote_management/oneview/oneview_datacenter_facts.py E337
lib/ansible/modules/remote_management/oneview/oneview_enclosure_facts.py E322
lib/ansible/modules/remote_management/oneview/oneview_enclosure_facts.py E337
lib/ansible/modules/remote_management/oneview/oneview_ethernet_network_facts.py E322
lib/ansible/modules/remote_management/oneview/oneview_ethernet_network_facts.py E337
lib/ansible/modules/remote_management/oneview/oneview_ethernet_network.py E322
lib/ansible/modules/remote_management/oneview/oneview_ethernet_network.py E337
lib/ansible/modules/remote_management/oneview/oneview_fc_network_facts.py E322
lib/ansible/modules/remote_management/oneview/oneview_fc_network_facts.py E337
lib/ansible/modules/remote_management/oneview/oneview_fc_network.py E322
lib/ansible/modules/remote_management/oneview/oneview_fc_network.py E337
lib/ansible/modules/remote_management/oneview/oneview_fc_network.py E338
lib/ansible/modules/remote_management/oneview/oneview_fcoe_network_facts.py E322
lib/ansible/modules/remote_management/oneview/oneview_fcoe_network_facts.py E337
lib/ansible/modules/remote_management/oneview/oneview_fcoe_network.py E322
lib/ansible/modules/remote_management/oneview/oneview_fcoe_network.py E337
lib/ansible/modules/remote_management/oneview/oneview_fcoe_network.py E338
lib/ansible/modules/remote_management/oneview/oneview_logical_interconnect_group_facts.py E322
lib/ansible/modules/remote_management/oneview/oneview_logical_interconnect_group_facts.py E337
lib/ansible/modules/remote_management/oneview/oneview_logical_interconnect_group.py E322
lib/ansible/modules/remote_management/oneview/oneview_logical_interconnect_group.py E337
lib/ansible/modules/remote_management/oneview/oneview_logical_interconnect_group.py E338
lib/ansible/modules/remote_management/oneview/oneview_network_set_facts.py E322
lib/ansible/modules/remote_management/oneview/oneview_network_set_facts.py E337
lib/ansible/modules/remote_management/oneview/oneview_network_set.py E322
lib/ansible/modules/remote_management/oneview/oneview_network_set.py E337
lib/ansible/modules/remote_management/oneview/oneview_network_set.py E338
lib/ansible/modules/remote_management/oneview/oneview_san_manager_facts.py E322
lib/ansible/modules/remote_management/oneview/oneview_san_manager_facts.py E337
lib/ansible/modules/remote_management/oneview/oneview_san_manager.py E322
lib/ansible/modules/remote_management/oneview/oneview_san_manager.py E337
lib/ansible/modules/remote_management/stacki/stacki_host.py E317
lib/ansible/modules/remote_management/stacki/stacki_host.py E322
lib/ansible/modules/remote_management/stacki/stacki_host.py E324
lib/ansible/modules/remote_management/stacki/stacki_host.py E326
lib/ansible/modules/remote_management/stacki/stacki_host.py E337
lib/ansible/modules/remote_management/ucs/ucs_disk_group_policy.py E337
lib/ansible/modules/remote_management/ucs/ucs_ip_pool.py E323
lib/ansible/modules/remote_management/ucs/ucs_ip_pool.py E337
lib/ansible/modules/remote_management/ucs/ucs_lan_connectivity.py E337
lib/ansible/modules/remote_management/ucs/ucs_mac_pool.py E323
lib/ansible/modules/remote_management/ucs/ucs_mac_pool.py E337
lib/ansible/modules/remote_management/ucs/ucs_managed_objects.py E337
lib/ansible/modules/remote_management/ucs/ucs_ntp_server.py E337
lib/ansible/modules/remote_management/ucs/ucs_san_connectivity.py E322
lib/ansible/modules/remote_management/ucs/ucs_san_connectivity.py E323
lib/ansible/modules/remote_management/ucs/ucs_san_connectivity.py E337
lib/ansible/modules/remote_management/ucs/ucs_service_profile_template.py E337
lib/ansible/modules/remote_management/ucs/ucs_storage_profile.py E337
lib/ansible/modules/remote_management/ucs/ucs_timezone.py E337
lib/ansible/modules/remote_management/ucs/ucs_uuid_pool.py E337
lib/ansible/modules/remote_management/ucs/ucs_vhba_template.py E322
lib/ansible/modules/remote_management/ucs/ucs_vhba_template.py E323
lib/ansible/modules/remote_management/ucs/ucs_vhba_template.py E337
lib/ansible/modules/remote_management/ucs/ucs_vlans.py E337
lib/ansible/modules/remote_management/ucs/ucs_vnic_template.py E326
lib/ansible/modules/remote_management/ucs/ucs_vnic_template.py E337
lib/ansible/modules/remote_management/ucs/ucs_vsans.py E322
lib/ansible/modules/remote_management/ucs/ucs_vsans.py E337
lib/ansible/modules/remote_management/ucs/ucs_wwn_pool.py E322
lib/ansible/modules/remote_management/ucs/ucs_wwn_pool.py E323
lib/ansible/modules/remote_management/ucs/ucs_wwn_pool.py E337
lib/ansible/modules/remote_management/wakeonlan.py E337
lib/ansible/modules/source_control/bzr.py E337
lib/ansible/modules/source_control/git_config.py E337
lib/ansible/modules/source_control/git_config.py E338
lib/ansible/modules/source_control/github_deploy_key.py E336
lib/ansible/modules/source_control/github_deploy_key.py E337
lib/ansible/modules/source_control/github_deploy_key.py E338
lib/ansible/modules/source_control/_github_hooks.py E338
lib/ansible/modules/source_control/github_issue.py E337
lib/ansible/modules/source_control/github_issue.py E338
lib/ansible/modules/source_control/github_key.py E338
lib/ansible/modules/source_control/github_release.py E337
lib/ansible/modules/source_control/github_release.py E338
lib/ansible/modules/source_control/github_webhook_info.py E337
lib/ansible/modules/source_control/github_webhook.py E337
lib/ansible/modules/source_control/git.py E337
lib/ansible/modules/source_control/git.py E338
lib/ansible/modules/source_control/hg.py E337
lib/ansible/modules/source_control/subversion.py E322
lib/ansible/modules/source_control/subversion.py E337
lib/ansible/modules/storage/emc/emc_vnx_sg_member.py E337
lib/ansible/modules/storage/emc/emc_vnx_sg_member.py E338
lib/ansible/modules/storage/glusterfs/gluster_heal_facts.py E337
lib/ansible/modules/storage/glusterfs/gluster_peer.py E337
lib/ansible/modules/storage/glusterfs/gluster_volume.py E337
lib/ansible/modules/storage/ibm/ibm_sa_domain.py E338
lib/ansible/modules/storage/ibm/ibm_sa_host_ports.py E338
lib/ansible/modules/storage/ibm/ibm_sa_host.py E338
lib/ansible/modules/storage/ibm/ibm_sa_pool.py E338
lib/ansible/modules/storage/ibm/ibm_sa_vol_map.py E338
lib/ansible/modules/storage/ibm/ibm_sa_vol.py E338
lib/ansible/modules/storage/infinidat/infini_export_client.py E323
lib/ansible/modules/storage/infinidat/infini_export_client.py E338
lib/ansible/modules/storage/infinidat/infini_export.py E323
lib/ansible/modules/storage/infinidat/infini_export.py E324
lib/ansible/modules/storage/infinidat/infini_export.py E337
lib/ansible/modules/storage/infinidat/infini_export.py E338
lib/ansible/modules/storage/infinidat/infini_fs.py E338
lib/ansible/modules/storage/infinidat/infini_host.py E337
lib/ansible/modules/storage/infinidat/infini_host.py E338
lib/ansible/modules/storage/infinidat/infini_pool.py E338
lib/ansible/modules/storage/infinidat/infini_vol.py E338
lib/ansible/modules/storage/netapp/_na_cdot_aggregate.py E337
lib/ansible/modules/storage/netapp/_na_cdot_aggregate.py E338
lib/ansible/modules/storage/netapp/_na_cdot_license.py E329
lib/ansible/modules/storage/netapp/_na_cdot_license.py E337
lib/ansible/modules/storage/netapp/_na_cdot_lun.py E337
lib/ansible/modules/storage/netapp/_na_cdot_lun.py E338
lib/ansible/modules/storage/netapp/_na_cdot_qtree.py E337
lib/ansible/modules/storage/netapp/_na_cdot_qtree.py E338
lib/ansible/modules/storage/netapp/_na_cdot_svm.py E337
lib/ansible/modules/storage/netapp/_na_cdot_svm.py E338
lib/ansible/modules/storage/netapp/_na_cdot_user.py E337
lib/ansible/modules/storage/netapp/_na_cdot_user.py E338
lib/ansible/modules/storage/netapp/_na_cdot_user_role.py E337
lib/ansible/modules/storage/netapp/_na_cdot_user_role.py E338
lib/ansible/modules/storage/netapp/_na_cdot_volume.py E317
lib/ansible/modules/storage/netapp/_na_cdot_volume.py E322
lib/ansible/modules/storage/netapp/_na_cdot_volume.py E324
lib/ansible/modules/storage/netapp/_na_cdot_volume.py E337
lib/ansible/modules/storage/netapp/_na_cdot_volume.py E338
lib/ansible/modules/storage/netapp/na_elementsw_access_group.py E337
lib/ansible/modules/storage/netapp/na_elementsw_access_group.py E338
lib/ansible/modules/storage/netapp/na_elementsw_account.py E337
lib/ansible/modules/storage/netapp/na_elementsw_account.py E338
lib/ansible/modules/storage/netapp/na_elementsw_admin_users.py E337
lib/ansible/modules/storage/netapp/na_elementsw_admin_users.py E338
lib/ansible/modules/storage/netapp/na_elementsw_backup.py E337
lib/ansible/modules/storage/netapp/na_elementsw_backup.py E338
lib/ansible/modules/storage/netapp/na_elementsw_check_connections.py E337
lib/ansible/modules/storage/netapp/na_elementsw_cluster_config.py E337
lib/ansible/modules/storage/netapp/na_elementsw_cluster_pair.py E337
lib/ansible/modules/storage/netapp/na_elementsw_cluster_pair.py E338
lib/ansible/modules/storage/netapp/na_elementsw_cluster.py E337
lib/ansible/modules/storage/netapp/na_elementsw_cluster_snmp.py E337
lib/ansible/modules/storage/netapp/na_elementsw_drive.py E337
lib/ansible/modules/storage/netapp/na_elementsw_drive.py E338
lib/ansible/modules/storage/netapp/na_elementsw_initiators.py E337
lib/ansible/modules/storage/netapp/na_elementsw_initiators.py E338
lib/ansible/modules/storage/netapp/na_elementsw_ldap.py E337
lib/ansible/modules/storage/netapp/na_elementsw_network_interfaces.py E337
lib/ansible/modules/storage/netapp/na_elementsw_node.py E337
lib/ansible/modules/storage/netapp/na_elementsw_node.py E338
lib/ansible/modules/storage/netapp/na_elementsw_snapshot.py E337
lib/ansible/modules/storage/netapp/na_elementsw_snapshot.py E338
lib/ansible/modules/storage/netapp/na_elementsw_snapshot_restore.py E337
lib/ansible/modules/storage/netapp/na_elementsw_snapshot_schedule.py E337
lib/ansible/modules/storage/netapp/na_elementsw_snapshot_schedule.py E338
lib/ansible/modules/storage/netapp/na_elementsw_vlan.py E337
lib/ansible/modules/storage/netapp/na_elementsw_vlan.py E338
lib/ansible/modules/storage/netapp/na_elementsw_volume_clone.py E337
lib/ansible/modules/storage/netapp/na_elementsw_volume_clone.py E338
lib/ansible/modules/storage/netapp/na_elementsw_volume_pair.py E337
lib/ansible/modules/storage/netapp/na_elementsw_volume_pair.py E338
lib/ansible/modules/storage/netapp/na_elementsw_volume.py E336
lib/ansible/modules/storage/netapp/na_elementsw_volume.py E337
lib/ansible/modules/storage/netapp/na_elementsw_volume.py E338
lib/ansible/modules/storage/netapp/na_ontap_aggregate.py E337
lib/ansible/modules/storage/netapp/na_ontap_aggregate.py E338
lib/ansible/modules/storage/netapp/na_ontap_autosupport.py E337
lib/ansible/modules/storage/netapp/na_ontap_autosupport.py E338
lib/ansible/modules/storage/netapp/na_ontap_broadcast_domain_ports.py E337
lib/ansible/modules/storage/netapp/na_ontap_broadcast_domain_ports.py E338
lib/ansible/modules/storage/netapp/na_ontap_broadcast_domain.py E337
lib/ansible/modules/storage/netapp/na_ontap_broadcast_domain.py E338
lib/ansible/modules/storage/netapp/na_ontap_cg_snapshot.py E337
lib/ansible/modules/storage/netapp/na_ontap_cg_snapshot.py E338
lib/ansible/modules/storage/netapp/na_ontap_cifs_acl.py E337
lib/ansible/modules/storage/netapp/na_ontap_cifs.py E337
lib/ansible/modules/storage/netapp/na_ontap_cifs_server.py E337
lib/ansible/modules/storage/netapp/na_ontap_cifs_server.py E338
lib/ansible/modules/storage/netapp/na_ontap_cluster_ha.py E338
lib/ansible/modules/storage/netapp/na_ontap_cluster_peer.py E337
lib/ansible/modules/storage/netapp/na_ontap_cluster.py E337
lib/ansible/modules/storage/netapp/na_ontap_cluster.py E338
lib/ansible/modules/storage/netapp/na_ontap_command.py E337
lib/ansible/modules/storage/netapp/na_ontap_disks.py E337
lib/ansible/modules/storage/netapp/na_ontap_dns.py E337
lib/ansible/modules/storage/netapp/na_ontap_dns.py E338
lib/ansible/modules/storage/netapp/na_ontap_export_policy.py E337
lib/ansible/modules/storage/netapp/na_ontap_export_policy_rule.py E337
lib/ansible/modules/storage/netapp/na_ontap_fcp.py E337
lib/ansible/modules/storage/netapp/na_ontap_fcp.py E338
lib/ansible/modules/storage/netapp/na_ontap_firewall_policy.py E337
lib/ansible/modules/storage/netapp/na_ontap_firewall_policy.py E338
lib/ansible/modules/storage/netapp/na_ontap_flexcache.py E337
lib/ansible/modules/storage/netapp/na_ontap_gather_facts.py E337
lib/ansible/modules/storage/netapp/na_ontap_gather_facts.py E338
lib/ansible/modules/storage/netapp/na_ontap_igroup_initiator.py E337
lib/ansible/modules/storage/netapp/na_ontap_igroup_initiator.py E338
lib/ansible/modules/storage/netapp/na_ontap_igroup.py E337
lib/ansible/modules/storage/netapp/na_ontap_igroup.py E338
lib/ansible/modules/storage/netapp/na_ontap_interface.py E337
lib/ansible/modules/storage/netapp/na_ontap_interface.py E338
lib/ansible/modules/storage/netapp/na_ontap_ipspace.py E337
lib/ansible/modules/storage/netapp/na_ontap_ipspace.py E338
lib/ansible/modules/storage/netapp/na_ontap_iscsi.py E337
lib/ansible/modules/storage/netapp/na_ontap_iscsi.py E338
lib/ansible/modules/storage/netapp/na_ontap_job_schedule.py E337
lib/ansible/modules/storage/netapp/na_ontap_job_schedule.py E338
lib/ansible/modules/storage/netapp/na_ontap_license.py E337
lib/ansible/modules/storage/netapp/na_ontap_license.py E338
lib/ansible/modules/storage/netapp/na_ontap_lun_copy.py E337
lib/ansible/modules/storage/netapp/na_ontap_lun_copy.py E338
lib/ansible/modules/storage/netapp/na_ontap_lun_map.py E337
lib/ansible/modules/storage/netapp/na_ontap_lun_map.py E338
lib/ansible/modules/storage/netapp/na_ontap_lun.py E337
lib/ansible/modules/storage/netapp/na_ontap_lun.py E338
lib/ansible/modules/storage/netapp/na_ontap_motd.py E338
lib/ansible/modules/storage/netapp/na_ontap_net_ifgrp.py E337
lib/ansible/modules/storage/netapp/na_ontap_net_ifgrp.py E338
lib/ansible/modules/storage/netapp/na_ontap_net_port.py E337
lib/ansible/modules/storage/netapp/na_ontap_net_port.py E338
lib/ansible/modules/storage/netapp/na_ontap_net_routes.py E337
lib/ansible/modules/storage/netapp/na_ontap_net_routes.py E338
lib/ansible/modules/storage/netapp/na_ontap_net_subnet.py E337
lib/ansible/modules/storage/netapp/na_ontap_net_subnet.py E338
lib/ansible/modules/storage/netapp/na_ontap_net_vlan.py E337
lib/ansible/modules/storage/netapp/na_ontap_net_vlan.py E338
lib/ansible/modules/storage/netapp/na_ontap_nfs.py E336
lib/ansible/modules/storage/netapp/na_ontap_nfs.py E337
lib/ansible/modules/storage/netapp/na_ontap_nfs.py E338
lib/ansible/modules/storage/netapp/na_ontap_node.py E337
lib/ansible/modules/storage/netapp/na_ontap_ntp.py E337
lib/ansible/modules/storage/netapp/na_ontap_ntp.py E338
lib/ansible/modules/storage/netapp/na_ontap_nvme_namespace.py E337
lib/ansible/modules/storage/netapp/na_ontap_nvme.py E337
lib/ansible/modules/storage/netapp/na_ontap_nvme_subsystem.py E337
lib/ansible/modules/storage/netapp/na_ontap_portset.py E337
lib/ansible/modules/storage/netapp/na_ontap_portset.py E338
lib/ansible/modules/storage/netapp/na_ontap_qos_policy_group.py E337
lib/ansible/modules/storage/netapp/na_ontap_qtree.py E338
lib/ansible/modules/storage/netapp/na_ontap_security_key_manager.py E337
lib/ansible/modules/storage/netapp/na_ontap_security_key_manager.py E338
lib/ansible/modules/storage/netapp/na_ontap_service_processor_network.py E337
lib/ansible/modules/storage/netapp/na_ontap_service_processor_network.py E338
lib/ansible/modules/storage/netapp/na_ontap_snapmirror.py E337
lib/ansible/modules/storage/netapp/na_ontap_snapshot_policy.py E337
lib/ansible/modules/storage/netapp/na_ontap_snapshot_policy.py E338
lib/ansible/modules/storage/netapp/na_ontap_snapshot.py E337
lib/ansible/modules/storage/netapp/na_ontap_snapshot.py E338
lib/ansible/modules/storage/netapp/na_ontap_snmp.py E337
lib/ansible/modules/storage/netapp/na_ontap_software_update.py E337
lib/ansible/modules/storage/netapp/na_ontap_svm_options.py E337
lib/ansible/modules/storage/netapp/na_ontap_svm.py E337
lib/ansible/modules/storage/netapp/na_ontap_svm.py E338
lib/ansible/modules/storage/netapp/na_ontap_ucadapter.py E337
lib/ansible/modules/storage/netapp/na_ontap_ucadapter.py E338
lib/ansible/modules/storage/netapp/na_ontap_unix_group.py E337
lib/ansible/modules/storage/netapp/na_ontap_unix_group.py E338
lib/ansible/modules/storage/netapp/na_ontap_unix_user.py E337
lib/ansible/modules/storage/netapp/na_ontap_unix_user.py E338
lib/ansible/modules/storage/netapp/na_ontap_user.py E337
lib/ansible/modules/storage/netapp/na_ontap_user.py E338
lib/ansible/modules/storage/netapp/na_ontap_user_role.py E337
lib/ansible/modules/storage/netapp/na_ontap_user_role.py E338
lib/ansible/modules/storage/netapp/na_ontap_volume_clone.py E338
lib/ansible/modules/storage/netapp/na_ontap_volume.py E337
lib/ansible/modules/storage/netapp/na_ontap_volume.py E338
lib/ansible/modules/storage/netapp/na_ontap_vscan_on_access_policy.py E337
lib/ansible/modules/storage/netapp/na_ontap_vscan_on_access_policy.py E338
lib/ansible/modules/storage/netapp/na_ontap_vscan_on_demand_task.py E337
lib/ansible/modules/storage/netapp/na_ontap_vscan_on_demand_task.py E338
lib/ansible/modules/storage/netapp/na_ontap_vscan_scanner_pool.py E337
lib/ansible/modules/storage/netapp/na_ontap_vscan_scanner_pool.py E338
lib/ansible/modules/storage/netapp/na_ontap_vserver_peer.py E337
lib/ansible/modules/storage/netapp/netapp_e_alerts.py E337
lib/ansible/modules/storage/netapp/netapp_e_amg.py E322
lib/ansible/modules/storage/netapp/netapp_e_amg.py E337
lib/ansible/modules/storage/netapp/netapp_e_amg.py E338
lib/ansible/modules/storage/netapp/netapp_e_amg_role.py E322
lib/ansible/modules/storage/netapp/netapp_e_amg_role.py E337
lib/ansible/modules/storage/netapp/netapp_e_amg_role.py E338
lib/ansible/modules/storage/netapp/netapp_e_amg_sync.py E337
lib/ansible/modules/storage/netapp/netapp_e_asup.py E337
lib/ansible/modules/storage/netapp/netapp_e_auditlog.py E337
lib/ansible/modules/storage/netapp/netapp_e_auth.py E337
lib/ansible/modules/storage/netapp/netapp_e_auth.py E338
lib/ansible/modules/storage/netapp/netapp_e_facts.py E337
lib/ansible/modules/storage/netapp/netapp_e_facts.py E338
lib/ansible/modules/storage/netapp/netapp_e_flashcache.py E322
lib/ansible/modules/storage/netapp/netapp_e_flashcache.py E326
lib/ansible/modules/storage/netapp/netapp_e_flashcache.py E337
lib/ansible/modules/storage/netapp/netapp_e_flashcache.py E338
lib/ansible/modules/storage/netapp/netapp_e_global.py E337
lib/ansible/modules/storage/netapp/netapp_e_hostgroup.py E337
lib/ansible/modules/storage/netapp/netapp_e_hostgroup.py E338
lib/ansible/modules/storage/netapp/netapp_e_host.py E337
lib/ansible/modules/storage/netapp/netapp_e_iscsi_interface.py E337
lib/ansible/modules/storage/netapp/netapp_e_iscsi_target.py E337
lib/ansible/modules/storage/netapp/netapp_e_ldap.py E337
lib/ansible/modules/storage/netapp/netapp_e_lun_mapping.py E337
lib/ansible/modules/storage/netapp/netapp_e_lun_mapping.py E338
lib/ansible/modules/storage/netapp/netapp_e_mgmt_interface.py E337
lib/ansible/modules/storage/netapp/netapp_e_snapshot_group.py E322
lib/ansible/modules/storage/netapp/netapp_e_snapshot_group.py E326
lib/ansible/modules/storage/netapp/netapp_e_snapshot_group.py E337
lib/ansible/modules/storage/netapp/netapp_e_snapshot_group.py E338
lib/ansible/modules/storage/netapp/netapp_e_snapshot_images.py E322
lib/ansible/modules/storage/netapp/netapp_e_snapshot_images.py E337
lib/ansible/modules/storage/netapp/netapp_e_snapshot_images.py E338
lib/ansible/modules/storage/netapp/netapp_e_snapshot_volume.py E324
lib/ansible/modules/storage/netapp/netapp_e_snapshot_volume.py E326
lib/ansible/modules/storage/netapp/netapp_e_snapshot_volume.py E337
lib/ansible/modules/storage/netapp/netapp_e_storagepool.py E322
lib/ansible/modules/storage/netapp/netapp_e_storagepool.py E326
lib/ansible/modules/storage/netapp/netapp_e_storagepool.py E337
lib/ansible/modules/storage/netapp/netapp_e_storagepool.py E338
lib/ansible/modules/storage/netapp/netapp_e_storage_system.py E322
lib/ansible/modules/storage/netapp/netapp_e_storage_system.py E324
lib/ansible/modules/storage/netapp/netapp_e_storage_system.py E337
lib/ansible/modules/storage/netapp/netapp_e_storage_system.py E338
lib/ansible/modules/storage/netapp/netapp_e_syslog.py E337
lib/ansible/modules/storage/netapp/netapp_e_syslog.py E338
lib/ansible/modules/storage/netapp/netapp_e_volume_copy.py E322
lib/ansible/modules/storage/netapp/netapp_e_volume_copy.py E323
lib/ansible/modules/storage/netapp/netapp_e_volume_copy.py E324
lib/ansible/modules/storage/netapp/netapp_e_volume_copy.py E326
lib/ansible/modules/storage/netapp/netapp_e_volume_copy.py E335
lib/ansible/modules/storage/netapp/netapp_e_volume_copy.py E337
lib/ansible/modules/storage/netapp/netapp_e_volume_copy.py E338
lib/ansible/modules/storage/netapp/netapp_e_volume.py E324
lib/ansible/modules/storage/netapp/netapp_e_volume.py E327
lib/ansible/modules/storage/netapp/netapp_e_volume.py E337
lib/ansible/modules/storage/netapp/netapp_e_volume.py E338
lib/ansible/modules/storage/netapp/_sf_account_manager.py E337
lib/ansible/modules/storage/netapp/_sf_account_manager.py E338
lib/ansible/modules/storage/netapp/_sf_check_connections.py E337
lib/ansible/modules/storage/netapp/_sf_snapshot_schedule_manager.py E337
lib/ansible/modules/storage/netapp/_sf_snapshot_schedule_manager.py E338
lib/ansible/modules/storage/netapp/_sf_volume_access_group_manager.py E337
lib/ansible/modules/storage/netapp/_sf_volume_access_group_manager.py E338
lib/ansible/modules/storage/netapp/_sf_volume_manager.py E322
lib/ansible/modules/storage/netapp/_sf_volume_manager.py E336
lib/ansible/modules/storage/netapp/_sf_volume_manager.py E337
lib/ansible/modules/storage/netapp/_sf_volume_manager.py E338
lib/ansible/modules/storage/purestorage/purefa_dsrole.py E337
lib/ansible/modules/storage/purestorage/purefa_pgsnap.py E337
lib/ansible/modules/storage/purestorage/purefb_fs.py E324
lib/ansible/modules/storage/zfs/zfs_delegate_admin.py E337
lib/ansible/modules/storage/zfs/zfs_facts.py E323
lib/ansible/modules/storage/zfs/zfs_facts.py E337
lib/ansible/modules/storage/zfs/zfs.py E337
lib/ansible/modules/storage/zfs/zpool_facts.py E323
lib/ansible/modules/storage/zfs/zpool_facts.py E337
lib/ansible/modules/system/authorized_key.py E337
lib/ansible/modules/system/dconf.py E337
lib/ansible/modules/system/dconf.py E338
lib/ansible/modules/system/filesystem.py E338
lib/ansible/modules/system/gconftool2.py E337
lib/ansible/modules/system/getent.py E337
lib/ansible/modules/system/hostname.py E337
lib/ansible/modules/system/interfaces_file.py E337
lib/ansible/modules/system/java_keystore.py E338
lib/ansible/modules/system/kernel_blacklist.py E337
lib/ansible/modules/system/known_hosts.py E324
lib/ansible/modules/system/known_hosts.py E337
lib/ansible/modules/system/known_hosts.py E338
lib/ansible/modules/system/locale_gen.py E337
lib/ansible/modules/system/lvol.py E337
lib/ansible/modules/system/mksysb.py E338
lib/ansible/modules/system/modprobe.py E337
lib/ansible/modules/system/nosh.py E337
lib/ansible/modules/system/nosh.py E338
lib/ansible/modules/system/openwrt_init.py E337
lib/ansible/modules/system/openwrt_init.py E338
lib/ansible/modules/system/pam_limits.py E337
lib/ansible/modules/system/puppet.py E322
lib/ansible/modules/system/puppet.py E336
lib/ansible/modules/system/puppet.py E337
lib/ansible/modules/system/python_requirements_info.py E337
lib/ansible/modules/system/runit.py E322
lib/ansible/modules/system/runit.py E324
lib/ansible/modules/system/runit.py E337
lib/ansible/modules/system/seboolean.py E337
lib/ansible/modules/system/selinux.py E337
lib/ansible/modules/system/selogin.py E337
lib/ansible/modules/system/service.py E210
lib/ansible/modules/system/service.py E323
lib/ansible/modules/system/setup.py E337
lib/ansible/modules/system/setup.py E338
lib/ansible/modules/system/sysctl.py E337
lib/ansible/modules/system/sysctl.py E338
lib/ansible/modules/system/syspatch.py E337
lib/ansible/modules/system/systemd.py E336
lib/ansible/modules/system/systemd.py E337
lib/ansible/modules/system/sysvinit.py E337
lib/ansible/modules/system/user.py E210
lib/ansible/modules/system/user.py E324
lib/ansible/modules/system/user.py E327
lib/ansible/modules/system/xfconf.py E337
lib/ansible/modules/web_infrastructure/ansible_tower/tower_credential.py E326
lib/ansible/modules/web_infrastructure/ansible_tower/tower_credential_type.py E337
lib/ansible/modules/web_infrastructure/ansible_tower/tower_credential_type.py E338
lib/ansible/modules/web_infrastructure/ansible_tower/tower_group.py E324
lib/ansible/modules/web_infrastructure/ansible_tower/tower_group.py E338
lib/ansible/modules/web_infrastructure/ansible_tower/tower_host.py E338
lib/ansible/modules/web_infrastructure/ansible_tower/tower_inventory.py E338
lib/ansible/modules/web_infrastructure/ansible_tower/tower_inventory_source.py E337
lib/ansible/modules/web_infrastructure/ansible_tower/tower_inventory_source.py E338
lib/ansible/modules/web_infrastructure/ansible_tower/tower_job_cancel.py E337
lib/ansible/modules/web_infrastructure/ansible_tower/tower_job_launch.py E323
lib/ansible/modules/web_infrastructure/ansible_tower/tower_job_launch.py E337
lib/ansible/modules/web_infrastructure/ansible_tower/tower_job_launch.py E338
lib/ansible/modules/web_infrastructure/ansible_tower/tower_job_list.py E337
lib/ansible/modules/web_infrastructure/ansible_tower/tower_job_list.py E338
lib/ansible/modules/web_infrastructure/ansible_tower/tower_job_template.py E322
lib/ansible/modules/web_infrastructure/ansible_tower/tower_job_template.py E337
lib/ansible/modules/web_infrastructure/ansible_tower/tower_job_template.py E338
lib/ansible/modules/web_infrastructure/ansible_tower/tower_job_wait.py E337
lib/ansible/modules/web_infrastructure/ansible_tower/tower_label.py E338
lib/ansible/modules/web_infrastructure/ansible_tower/tower_notification.py E337
lib/ansible/modules/web_infrastructure/ansible_tower/tower_notification.py E338
lib/ansible/modules/web_infrastructure/ansible_tower/tower_organization.py E338
lib/ansible/modules/web_infrastructure/ansible_tower/tower_project.py E337
lib/ansible/modules/web_infrastructure/ansible_tower/tower_project.py E338
lib/ansible/modules/web_infrastructure/ansible_tower/tower_receive.py E337
lib/ansible/modules/web_infrastructure/ansible_tower/tower_role.py E338
lib/ansible/modules/web_infrastructure/ansible_tower/tower_send.py E337
lib/ansible/modules/web_infrastructure/ansible_tower/tower_send.py E338
lib/ansible/modules/web_infrastructure/ansible_tower/tower_settings.py E338
lib/ansible/modules/web_infrastructure/ansible_tower/tower_team.py E322
lib/ansible/modules/web_infrastructure/ansible_tower/tower_team.py E338
lib/ansible/modules/web_infrastructure/ansible_tower/tower_user.py E338
lib/ansible/modules/web_infrastructure/ansible_tower/tower_workflow_launch.py E337
lib/ansible/modules/web_infrastructure/ansible_tower/tower_workflow_launch.py E338
lib/ansible/modules/web_infrastructure/ansible_tower/tower_workflow_template.py E338
lib/ansible/modules/web_infrastructure/apache2_mod_proxy.py E317
lib/ansible/modules/web_infrastructure/apache2_mod_proxy.py E326
lib/ansible/modules/web_infrastructure/apache2_mod_proxy.py E337
lib/ansible/modules/web_infrastructure/apache2_module.py E337
lib/ansible/modules/web_infrastructure/apache2_module.py E338
lib/ansible/modules/web_infrastructure/deploy_helper.py E337
lib/ansible/modules/web_infrastructure/deploy_helper.py E338
lib/ansible/modules/web_infrastructure/django_manage.py E317
lib/ansible/modules/web_infrastructure/django_manage.py E322
lib/ansible/modules/web_infrastructure/django_manage.py E326
lib/ansible/modules/web_infrastructure/django_manage.py E337
lib/ansible/modules/web_infrastructure/django_manage.py E338
lib/ansible/modules/web_infrastructure/ejabberd_user.py E337
lib/ansible/modules/web_infrastructure/ejabberd_user.py E338
lib/ansible/modules/web_infrastructure/gunicorn.py E322
lib/ansible/modules/web_infrastructure/gunicorn.py E337
lib/ansible/modules/web_infrastructure/htpasswd.py E326
lib/ansible/modules/web_infrastructure/htpasswd.py E338
lib/ansible/modules/web_infrastructure/jenkins_job_info.py E338
lib/ansible/modules/web_infrastructure/jenkins_job.py E338
lib/ansible/modules/web_infrastructure/jenkins_plugin.py E322
lib/ansible/modules/web_infrastructure/jenkins_plugin.py E337
lib/ansible/modules/web_infrastructure/jenkins_plugin.py E338
lib/ansible/modules/web_infrastructure/jenkins_script.py E337
lib/ansible/modules/web_infrastructure/jira.py E322
lib/ansible/modules/web_infrastructure/jira.py E337
lib/ansible/modules/web_infrastructure/jira.py E338
lib/ansible/modules/web_infrastructure/nginx_status_facts.py E337
lib/ansible/modules/web_infrastructure/nginx_status_facts.py E338
lib/ansible/modules/web_infrastructure/rundeck_acl_policy.py E337
lib/ansible/modules/web_infrastructure/rundeck_project.py E337
lib/ansible/modules/web_infrastructure/sophos_utm/utm_aaa_group_info.py E337
lib/ansible/modules/web_infrastructure/sophos_utm/utm_ca_host_key_cert_info.py E337
lib/ansible/modules/web_infrastructure/sophos_utm/utm_ca_host_key_cert.py E337
lib/ansible/modules/web_infrastructure/sophos_utm/utm_dns_host.py E337
lib/ansible/modules/web_infrastructure/sophos_utm/utm_network_interface_address_info.py E337
lib/ansible/modules/web_infrastructure/sophos_utm/utm_network_interface_address.py E337
lib/ansible/modules/web_infrastructure/sophos_utm/utm_proxy_auth_profile.py E337
lib/ansible/modules/web_infrastructure/sophos_utm/utm_proxy_frontend_info.py E337
lib/ansible/modules/web_infrastructure/sophos_utm/utm_proxy_frontend.py E337
lib/ansible/modules/web_infrastructure/sophos_utm/utm_proxy_location_info.py E337
lib/ansible/modules/web_infrastructure/sophos_utm/utm_proxy_location.py E337
lib/ansible/modules/web_infrastructure/supervisorctl.py E337
lib/ansible/modules/web_infrastructure/supervisorctl.py E338
lib/ansible/modules/web_infrastructure/taiga_issue.py E337
lib/ansible/modules/web_infrastructure/taiga_issue.py E338
lib/ansible/modules/windows/win_certificate_store.ps1 E337
lib/ansible/modules/windows/win_credential.ps1 E337
lib/ansible/modules/windows/win_http_proxy.ps1 E337
lib/ansible/modules/windows/win_inet_proxy.ps1 E337
lib/ansible/modules/windows/win_psexec.ps1 E337
lib/ansible/modules/windows/win_user_profile.ps1 E337
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 59,100 |
Windows service installed with win_nssm fails to start with win_service
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
Starting a Windows service with the `win_service` module and that was installed with the `win_nssm` module fails when a username and password are required. If I enter the password manually into the nssm GUI editor and re-run the playbook then the service successfully starts.
I used the `win_nssm` module to install and `win_service` module to start a Windows service that takes a username and password. [As recommended in the win_nssm documentation](https://docs.ansible.com/ansible/latest/modules/win_nssm_module.html#examples), I use the `win_nssm` module only to install the service. The username and password are passed to the `win_service` module as the `user` and `password` parameters when starting the service.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
- win_nssm
- win_service
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```
ansible 2.8.2
config file = /home/kdouglas/src/pt/ansible/ansible.cfg
configured module search path = ['/home/kdouglas/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /home/kdouglas/venvs/ansible/lib/python3.6/site-packages/ansible
executable location = /home/kdouglas/venvs/ansible/bin/ansible
python version = 3.6.8 (default, Jan 14 2019, 11:02:34) [GCC 8.0.1 20180414 (experimental) [trunk revision 259383]]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```
DEFAULT_HOST_LIST(/home/kdouglas/src/pt/ansible/ansible.cfg) = ['/home/kdouglas/src/pt/ansible/hosts']
```
##### OS / ENVIRONMENT
Host machine:
```
Distributor ID: Ubuntu
Description: Ubuntu 18.04.2 LTS
Release: 18.04
Codename: bionic
```
Remote machine:
```
Windows 10 Pro 64-bit
Python: 3.6.8
```
Configuration for WinRM:
```
ansible_connection: winrm
ansible_user: pt
ansible_password: "{{ lookup('aws_ssm', 'xxxxxx') }}"
ansible_winrm_transport: credssp
ansible_winrm_server_cert_validation: ignore
```
##### STEPS TO REPRODUCE
The two relevant tasks in the playbook look like the following and are based on the examples for the `win_nssm` documentation.
```yaml
- name: Install the pt executor service
win_nssm:
name: "{{ pt_service_name }}"
application: '{{ pt_config_dir }}\{{ venv_name }}\Scripts\executor.exe'
app_parameters_free_form: "-c {{ node_name }} {{ pt_server }}"
- name: Start the pt executor service
win_service:
name: "{{ pt_service_name }}"
start_mode: auto
state: started
username: "{{ executor_login }}"
password: "{{ pt_jc_password }}"
```
I run these tasks with the command `ansible-playbook -i hosts pt.yml`. Unfortunately, I get the following error:
```
fatal: [WIN-1]: FAILED! => {"can_pause_and_continue": false, "changed": false, "depended_by": [], "dependencies": [], "description": "", "desktop_interact": false, "display_name": "pt", "exists": true, "msg": "Service 'pt (pt)' cannot be started due to the following error: Cannot start service pt on computer '.'.", "name": "pt", "path": "C:\\ProgramData\\chocolatey\\lib\\NSSM\\tools\\nssm.exe", "start_mode": "auto", "state": "stopped", "username": ".\\pt"}
```
Repeatedly running the playbook still results in the error. However, the playbook will work if I manually run `nssm edit pt` in a PowerShell terminal on the machine and enter the password into the NSSM GUI service editor window that appears.
I observe this behavior across multiple Windows 10 Pro machines and when using both Ansible 2.8.1 and Ansible 2.8.2. I also tested the development version of Ansible (commit 262c9ffdb6c995d67a8dfd3707ec8bb09a4fd77d) and see the same behavior.
In addition, I tried using the deprecated `user` and `password` parameters of the `win_nssm` module but this failed as well.
##### EXPECTED RESULTS
I expect that the playbook successfully starts the pt executor service.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
(Sensitive strings have been replaced by `x`'s)
```
TASK [win_executor : Install the pt executor service] ****************************************************************************************************************************************************
task path: /home/kdouglas/src/pt/ansible/roles/win_executor/tasks/main.yml:37
AWS_ssm name lookup term: ['xxxxxxxxxxxxx']
Using module file /home/kdouglas/venvs/ansible/lib/python3.6/site-packages/ansible/modules/windows/win_nssm.ps1
Pipelining is enabled.
<WIN-1> ESTABLISH WINRM CONNECTION FOR USER: pt on PORT 5986 TO WIN-1
EXEC (via pipeline wrapper)
ok: [WIN-1] => {
"changed": false,
"nssm_app_parameters": "-c WIN1 C:\\Users\\pt\\.pt\\workspace xxxxxxxxxxxx",
"nssm_single_line_app_parameters": "-c WIN-1 C:\\Users\\pt\\.pt\\workspace xxxxxxxx"
}
TASK [win_executor : Start the pt executor service] ******************************************************************************************************************************************************
task path: /home/kdouglas/src/pt/ansible/roles/win_executor/tasks/main.yml:43
AWS_ssm name lookup term: ['xxxxxxx']
Using module file /home/kdouglas/venvs/ansible/lib/python3.6/site-packages/ansible/modules/windows/win_service.ps1
Pipelining is enabled.
<WIN-1> ESTABLISH WINRM CONNECTION FOR USER: pt on PORT 5986 TO WIN-1
EXEC (via pipeline wrapper)
fatal: [WIN-1]: FAILED! => {
"can_pause_and_continue": false,
"changed": false,
"depended_by": [],
"dependencies": [],
"description": "",
"desktop_interact": false,
"display_name": "pt",
"exists": true,
"msg": "Service 'pt (pt)' cannot be started due to the following error: Cannot start service pt on computer '.'.",
"name": "pt",
"path": "C:\\ProgramData\\chocolatey\\lib\\NSSM\\tools\\nssm.exe",
"start_mode": "auto",
"state": "stopped",
"username": ".\\pt"
}
```
|
https://github.com/ansible/ansible/issues/59100
|
https://github.com/ansible/ansible/pull/59155
|
09aa98bf432a8e361fbfa71de9e45238423140a3
|
edfdf30bcb4fb87183b4e6e987e014783743230c
| 2019-07-15T13:53:40Z |
python
| 2019-07-17T07:03:47Z |
lib/ansible/modules/windows/win_service.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2014, Chris Hoffman <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
DOCUMENTATION = r'''
---
module: win_service
version_added: '1.7'
short_description: Manage and query Windows services
description:
- Manage and query Windows services.
- For non-Windows targets, use the M(service) module instead.
options:
dependencies:
description:
- A list of service dependencies to set for this particular service.
- This should be a list of service names and not the display name of the
service.
- This works by C(dependency_action) to either add/remove or set the
services in this list.
type: list
version_added: '2.3'
dependency_action:
description:
- Used in conjunction with C(dependency) to either add the dependencies to
the existing service dependencies.
- Remove the dependencies to the existing dependencies.
- Set the dependencies to only the values in the list replacing the
existing dependencies.
type: str
choices: [ add, remove, set ]
default: set
version_added: '2.3'
desktop_interact:
description:
- Whether to allow the service user to interact with the desktop.
- This should only be set to C(yes) when using the C(LocalSystem) username.
type: bool
default: no
version_added: '2.3'
description:
description:
- The description to set for the service.
type: str
version_added: '2.3'
display_name:
description:
- The display name to set for the service.
type: str
version_added: '2.3'
force_dependent_services:
description:
- If C(yes), stopping or restarting a service with dependent services will
force the dependent services to stop or restart also.
- If C(no), stopping or restarting a service with dependent services may
fail.
type: bool
default: no
version_added: '2.3'
name:
description:
- Name of the service.
- If only the name parameter is specified, the module will report
on whether the service exists or not without making any changes.
required: yes
type: str
path:
description:
- The path to the executable to set for the service.
type: str
version_added: '2.3'
password:
description:
- The password to set the service to start as.
- This and the C(username) argument must be supplied together.
- If specifying C(LocalSystem), C(NetworkService) or C(LocalService) this field
must be an empty string and not null.
type: str
version_added: '2.3'
start_mode:
description:
- Set the startup type for the service.
- A newly created service will default to C(auto).
- C(delayed) added in Ansible 2.3
type: str
choices: [ auto, delayed, disabled, manual ]
state:
description:
- The desired state of the service.
- C(started)/C(stopped)/C(absent)/C(paused) are idempotent actions that will not run
commands unless necessary.
- C(restarted) will always bounce the service.
- C(absent) was added in Ansible 2.3
- C(paused) was added in Ansible 2.4
- Only services that support the paused state can be paused, you can
check the return value C(can_pause_and_continue).
- You can only pause a service that is already started.
- A newly created service will default to C(stopped).
type: str
choices: [ absent, paused, started, stopped, restarted ]
username:
description:
- The username to set the service to start as.
- This and the C(password) argument must be supplied together when using
a local or domain account.
- Set to C(LocalSystem) to use the SYSTEM account.
- A newly created service will default to C(LocalSystem).
type: str
version_added: '2.3'
seealso:
- module: service
- module: win_nssm
author:
- Chris Hoffman (@chrishoffman)
'''
EXAMPLES = r'''
- name: Restart a service
win_service:
name: spooler
state: restarted
- name: Set service startup mode to auto and ensure it is started
win_service:
name: spooler
start_mode: auto
state: started
- name: Pause a service
win_service:
name: Netlogon
state: paused
- name: Ensure that WinRM is started when the system has settled
win_service:
name: WinRM
start_mode: delayed
# A new service will also default to the following values:
# - username: LocalSystem
# - state: stopped
# - start_mode: auto
- name: Create a new service
win_service:
name: service name
path: C:\temp\test.exe
- name: Create a new service with extra details
win_service:
name: service name
path: C:\temp\test.exe
display_name: Service Name
description: A test service description
- name: Remove a service
win_service:
name: service name
state: absent
- name: Check if a service is installed
win_service:
name: service name
register: service_info
- name: Set the log on user to a domain account
win_service:
name: service name
state: restarted
username: DOMAIN\User
password: Password
- name: Set the log on user to a local account
win_service:
name: service name
state: restarted
username: .\Administrator
password: Password
- name: Set the log on user to Local System
win_service:
name: service name
state: restarted
username: LocalSystem
password: ''
- name: Set the log on user to Local System and allow it to interact with the desktop
win_service:
name: service name
state: restarted
username: LocalSystem
password: ""
desktop_interact: yes
- name: Set the log on user to Network Service
win_service:
name: service name
state: restarted
username: NT AUTHORITY\NetworkService
password: ''
- name: Set the log on user to Local Service
win_service:
name: service name
state: restarted
username: NT AUTHORITY\LocalService
password: ''
- name: Set dependencies to ones only in the list
win_service:
name: service name
dependencies: [ service1, service2 ]
- name: Add dependencies to existing dependencies
win_service:
name: service name
dependencies: [ service1, service2 ]
dependency_action: add
- name: Remove dependencies from existing dependencies
win_service:
name: service name
dependencies:
- service1
- service2
dependency_action: remove
'''
RETURN = r'''
exists:
description: Whether the service exists or not.
returned: success
type: bool
sample: true
name:
description: The service name or id of the service.
returned: success and service exists
type: str
sample: CoreMessagingRegistrar
display_name:
description: The display name of the installed service.
returned: success and service exists
type: str
sample: CoreMessaging
state:
description: The current running status of the service.
returned: success and service exists
type: str
sample: stopped
start_mode:
description: The startup type of the service.
returned: success and service exists
type: str
sample: manual
path:
description: The path to the service executable.
returned: success and service exists
type: str
sample: C:\Windows\system32\svchost.exe -k LocalServiceNoNetwork
can_pause_and_continue:
description: Whether the service can be paused and unpaused.
returned: success and service exists
type: bool
sample: true
description:
description: The description of the service.
returned: success and service exists
type: str
sample: Manages communication between system components.
username:
description: The username that runs the service.
returned: success and service exists
type: str
sample: LocalSystem
desktop_interact:
description: Whether the current user is allowed to interact with the desktop.
returned: success and service exists
type: bool
sample: false
dependencies:
description: A list of services that is depended by this service.
returned: success and service exists
type: list
sample: false
depended_by:
description: A list of services that depend on this service.
returned: success and service exists
type: list
sample: false
'''
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 59,199 |
Call Refactored login from snow modules
|
##### SUMMARY
snow modules do not call refactored login function. Login must be called to initialize connection.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
snow_record.py
snow_record_find.py
##### ANSIBLE VERSION
```
ansible 2.9
config file = /home/pknight/dci/ansible/servicenow/ansible.cfg
configured module search path = [u'/home/pknight/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.15+ (default, Nov 27 2018, 23:36:35) [GCC 7.3.0]
```
##### CONFIGURATION
```
DEFAULT_VAULT_PASSWORD_FILE(/home/pknight/dci/ansible/servicenow/ansible.cfg) = /home/pknight/.ansiblevault
YAML_FILENAME_EXTENSIONS(/home/pknight/dci/ansible/servicenow/ansible.cfg) = [u'.json', u'.yaml', u'.yml', u'.vault']
```
##### OS / ENVIRONMENT
Linux
##### STEPS TO REPRODUCE
ansible-playbook -i sandbox Test-Run.yml -vvvvv
sandbox/regions:
[sandbox]
yourinstance.service-now.com
Test-Run.yml:
```yaml
yaml
- name: Test Run
hosts: all
connection: local
gather_facts: no
ignore_errors: True
tasks:
- name: Gather facts on automation user
snow_record_find:
username: "[email protected]"
password: "S0m3P@ssw0rd"
client_id: "1234567890abcdef01234567890abcde"
client_secret: "S0m3S3cr3t"
instance: "yourinstance"
max_records: 1
table: sys_user
query:
email: "[email protected]"
return_fields:
- email
- name
- sys_id
```
##### EXPECTED RESULTS
```
ansible-playbook 2.8.2
config file = /home/pknight/dci/ansible/servicenow/ansible.cfg
configured module search path = [u'/home/pknight/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible-playbook
python version = 2.7.15+ (default, Nov 27 2018, 23:36:35) [GCC 7.3.0]
Using /home/pknight/dci/ansible/servicenow/ansible.cfg as config file
setting up inventory plugins
host_list declined parsing /home/pknight/dci/ansible/servicenow/sandbox/regions as it did not pass it's verify_file() method
script declined parsing /home/pknight/dci/ansible/servicenow/sandbox/regions as it did not pass it's verify_file() method
auto declined parsing /home/pknight/dci/ansible/servicenow/sandbox/regions as it did not pass it's verify_file() method
Parsed /home/pknight/dci/ansible/servicenow/sandbox/regions inventory source with ini plugin
Loading callback plugin default of type stdout, v2.0 from /usr/lib/python2.7/dist-packages/ansible/plugins/callback/default.pyc
PLAYBOOK: Test-Run.yml ***********************************************************************************************
Positional arguments: Test-Run.yml
become_method: sudo
inventory: (u'/home/pknight/dci/ansible/servicenow/sandbox',)
forks: 5
tags: (u'all',)
verbosity: 4
connection: smart
timeout: 10
1 plays in Test-Run.yml
PLAY [Test SNow] *****************************************************************************************************
META: ran handlers
TASK [Gather facts on automation user] *******************************************************************************
task path: /home/pknight/dci/ansible/servicenow/Test-Run.yml:9
<delawarecalgarytest.service-now.com> ESTABLISH LOCAL CONNECTION FOR USER: pknight
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c 'echo ~pknight && sleep 0'
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/pknight/.ansible/tmp/ansible-tmp-1563393628.67-264175846363655 `" && echo ansible-tmp-1563393628.67-264175846363655="` echo /home/pknight/.ansible/tmp/ansible-tmp-1563393628.67-264175846363655 `" ) && sleep 0'
Using module file /usr/lib/python2.7/dist-packages/ansible/modules/notification/snow_record_find.py
<delawarecalgarytest.service-now.com> PUT /home/pknight/.ansible/tmp/ansible-local-12354QW3EpR/tmp5q343Y TO /home/pknight/.ansible/tmp/ansible-tmp-1563393628.67-264175846363655/AnsiballZ_snow_record_find.py
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c 'chmod u+x /home/pknight/.ansible/tmp/ansible-tmp-1563393628.67-264175846363655/ /home/pknight/.ansible/tmp/ansible-tmp-1563393628.67-264175846363655/AnsiballZ_snow_record_find.py && sleep 0'
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c '/home/pknight/dci/ansible/servicenow/venv/bin/python2.7 /home/pknight/.ansible/tmp/ansible-tmp-1563393628.67-264175846363655/AnsiballZ_snow_record_find.py && sleep 0'
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c 'rm -f -r /home/pknight/.ansible/tmp/ansible-tmp-1563393628.67-264175846363655/ > /dev/null 2>&1 && sleep 0'
ok: [yourinstance.service-now.com] => {
"changed": false,
"instance": "yourinstance",
"invocation": {
"module_args": {
"client_id": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"client_secret": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"instance": "yourinstance",
"max_records": 1,
"order_by": "-created_on",
"password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"query": {
"email": "[email protected]"
},
"return_fields": [
"email",
"name",
"sys_id"
],
"table": "sys_user",
"username": "[email protected]"
}
},
"max_records": 1,
"query": {
"email": "[email protected]"
},
"record": [
{
"email": "[email protected]",
"name": "ServiceNow User",
"sys_id": "1234567890abcdef1234567890"
}
],
"return_fields": [
"email",
"name",
"sys_id"
],
"table": "sys_user"
}
META: ran handlers
META: ran handlers
PLAY RECAP ***********************************************************************************************************
yourinstance.service-now.com : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
```
##### ACTUAL RESULTS
```
ansible-playbook 2.8.2
config file = /home/pknight/dci/ansible/servicenow/ansible.cfg
configured module search path = [u'/home/pknight/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible-playbook
python version = 2.7.15+ (default, Nov 27 2018, 23:36:35) [GCC 7.3.0]
Using /home/pknight/dci/ansible/servicenow/ansible.cfg as config file
setting up inventory plugins
host_list declined parsing /home/pknight/dci/ansible/servicenow/sandbox/regions as it did not pass it's verify_file() method
script declined parsing /home/pknight/dci/ansible/servicenow/sandbox/regions as it did not pass it's verify_file() method
auto declined parsing /home/pknight/dci/ansible/servicenow/sandbox/regions as it did not pass it's verify_file() method
Parsed /home/pknight/dci/ansible/servicenow/sandbox/regions inventory source with ini plugin
Loading callback plugin default of type stdout, v2.0 from /usr/lib/python2.7/dist-packages/ansible/plugins/callback/default.pyc
PLAYBOOK: Test-Run.yml ***********************************************************************************************
Positional arguments: Test-Run.yml
become_method: sudo
inventory: (u'/home/pknight/dci/ansible/servicenow/sandbox',)
forks: 5
tags: (u'all',)
verbosity: 4
connection: smart
timeout: 10
1 plays in Test-Run.yml
PLAY [Test SNow] *****************************************************************************************************
META: ran handlers
TASK [Gather facts on automation user] *******************************************************************************
task path: /home/pknight/dci/ansible/servicenow/Test-Run.yml:9
<delawarecalgarytest.service-now.com> ESTABLISH LOCAL CONNECTION FOR USER: pknight
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c 'echo ~pknight && sleep 0'
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/pknight/.ansible/tmp/ansible-tmp-1563393553.59-213692823755979 `" && echo ansible-tmp-1563393553.59-213692823755979="` echo /home/pknight/.ansible/tmp/ansible-tmp-1563393553.59-213692823755979 `" ) && sleep 0'
Using module file /usr/lib/python2.7/dist-packages/ansible/modules/notification/snow_record_find.py
<delawarecalgarytest.service-now.com> PUT /home/pknight/.ansible/tmp/ansible-local-12069E5RReh/tmpeVAB5I TO /home/pknight/.ansible/tmp/ansible-tmp-1563393553.59-213692823755979/AnsiballZ_snow_record_find.py
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c 'chmod u+x /home/pknight/.ansible/tmp/ansible-tmp-1563393553.59-213692823755979/ /home/pknight/.ansible/tmp/ansible-tmp-1563393553.59-213692823755979/AnsiballZ_snow_record_find.py && sleep 0'
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c '/home/pknight/dci/ansible/servicenow/venv/bin/python2.7 /home/pknight/.ansible/tmp/ansible-tmp-1563393553.59-213692823755979/AnsiballZ_snow_record_find.py && sleep 0'
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c 'rm -f -r /home/pknight/.ansible/tmp/ansible-tmp-1563393553.59-213692823755979/ > /dev/null 2>&1 && sleep 0'
The full traceback is:
WARNING: The below traceback may *not* be related to the actual failure.
File "/tmp/ansible_snow_record_find_payload_GdXZXi/__main__.py", line 255, in run_module
record = conn.query(table=module.params['table'],
fatal: [yourinstance.service-now.com]: FAILED! => {
"changed": false,
"instance": "yourinstance",
"invocation": {
"module_args": {
"client_id": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"client_secret": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"instance": "yourinstance",
"max_records": 1,
"order_by": "-created_on",
"password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"query": {
"email": "[email protected]"
},
"return_fields": [
"email",
"name",
"sys_id"
],
"table": "sys_user",
"username": "[email protected]"
}
},
"max_records": 1,
"msg": "Failed to find record: 'NoneType' object has no attribute 'query'",
"query": {
"email": "[email protected]"
},
"return_fields": [
"email",
"name",
"sys_id"
],
"table": "sys_user"
}
...ignoring
META: ran handlers
META: ran handlers
PLAY RECAP ***********************************************************************************************************
yourinstance.service-now.com : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1
```
|
https://github.com/ansible/ansible/issues/59199
|
https://github.com/ansible/ansible/pull/59201
|
d0538c0d7a0ac8de612a6946a32fa6c4ad256eb2
|
7e25a614647c7ced41b38f869dfd49e06a29d22c
| 2019-07-17T20:02:02Z |
python
| 2019-07-18T05:23:23Z |
lib/ansible/module_utils/service_now.py
|
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Ansible Project
# Copyright: (c) 2017, Tim Rightnour <[email protected]>
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import traceback
from ansible.module_utils.basic import missing_required_lib
# Pull in pysnow
HAS_PYSNOW = False
PYSNOW_IMP_ERR = None
try:
import pysnow
HAS_PYSNOW = True
except ImportError:
PYSNOW_IMP_ERR = traceback.format_exc()
class ServiceNowClient(object):
def __init__(self, module):
"""
Constructor
"""
if not HAS_PYSNOW:
module.fail_json(msg=missing_required_lib('pysnow'), exception=PYSNOW_IMP_ERR)
self.module = module
self.params = module.params
self.client_id = self.params['client_id']
self.client_secret = self.params['client_secret']
self.username = self.params['username']
self.password = self.params['password']
self.instance = self.params['instance']
self.session = {'token': None}
self.conn = None
def login(self):
result = dict(
changed=False
)
if self.params['client_id'] is not None:
try:
self.conn = pysnow.OAuthClient(client_id=self.client_id,
client_secret=self.client_secret,
token_updater=self.updater,
instance=self.instance)
except Exception as detail:
self.module.fail_json(msg='Could not connect to ServiceNow: {0}'.format(str(detail)), **result)
if not self.session['token']:
# No previous token exists, Generate new.
try:
self.session['token'] = self.conn.generate_token(self.username, self.password)
except pysnow.exceptions.TokenCreateError as detail:
self.module.fail_json(msg='Unable to generate a new token: {0}'.format(str(detail)), **result)
self.conn.set_token(self.session['token'])
elif self.username is not None:
try:
self.conn = pysnow.Client(instance=self.instance,
user=self.username,
password=self.password)
except Exception as detail:
self.module.fail_json(msg='Could not connect to ServiceNow: {0}'.format(str(detail)), **result)
else:
snow_error = "Must specify username/password or client_id/client_secret"
self.module.fail_json(msg=snow_error, **result)
def updater(self, new_token):
self.session['token'] = new_token
self.conn = pysnow.OAuthClient(client_id=self.client_id,
client_secret=self.client_secret,
token_updater=self.updater,
instance=self.instance)
try:
self.conn.set_token(self.session['token'])
except pysnow.exceptions.MissingToken:
snow_error = "Token is missing"
self.module.fail_json(msg=snow_error)
except Exception as detail:
self.module.fail_json(msg='Could not refresh token: {0}'.format(str(detail)))
@staticmethod
def snow_argument_spec():
return dict(
instance=dict(type='str', required=True),
username=dict(type='str', required=True, no_log=True),
password=dict(type='str', required=True, no_log=True),
client_id=dict(type='str', no_log=True),
client_secret=dict(type='str', no_log=True),
)
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 59,199 |
Call Refactored login from snow modules
|
##### SUMMARY
snow modules do not call refactored login function. Login must be called to initialize connection.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
snow_record.py
snow_record_find.py
##### ANSIBLE VERSION
```
ansible 2.9
config file = /home/pknight/dci/ansible/servicenow/ansible.cfg
configured module search path = [u'/home/pknight/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.15+ (default, Nov 27 2018, 23:36:35) [GCC 7.3.0]
```
##### CONFIGURATION
```
DEFAULT_VAULT_PASSWORD_FILE(/home/pknight/dci/ansible/servicenow/ansible.cfg) = /home/pknight/.ansiblevault
YAML_FILENAME_EXTENSIONS(/home/pknight/dci/ansible/servicenow/ansible.cfg) = [u'.json', u'.yaml', u'.yml', u'.vault']
```
##### OS / ENVIRONMENT
Linux
##### STEPS TO REPRODUCE
ansible-playbook -i sandbox Test-Run.yml -vvvvv
sandbox/regions:
[sandbox]
yourinstance.service-now.com
Test-Run.yml:
```yaml
yaml
- name: Test Run
hosts: all
connection: local
gather_facts: no
ignore_errors: True
tasks:
- name: Gather facts on automation user
snow_record_find:
username: "[email protected]"
password: "S0m3P@ssw0rd"
client_id: "1234567890abcdef01234567890abcde"
client_secret: "S0m3S3cr3t"
instance: "yourinstance"
max_records: 1
table: sys_user
query:
email: "[email protected]"
return_fields:
- email
- name
- sys_id
```
##### EXPECTED RESULTS
```
ansible-playbook 2.8.2
config file = /home/pknight/dci/ansible/servicenow/ansible.cfg
configured module search path = [u'/home/pknight/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible-playbook
python version = 2.7.15+ (default, Nov 27 2018, 23:36:35) [GCC 7.3.0]
Using /home/pknight/dci/ansible/servicenow/ansible.cfg as config file
setting up inventory plugins
host_list declined parsing /home/pknight/dci/ansible/servicenow/sandbox/regions as it did not pass it's verify_file() method
script declined parsing /home/pknight/dci/ansible/servicenow/sandbox/regions as it did not pass it's verify_file() method
auto declined parsing /home/pknight/dci/ansible/servicenow/sandbox/regions as it did not pass it's verify_file() method
Parsed /home/pknight/dci/ansible/servicenow/sandbox/regions inventory source with ini plugin
Loading callback plugin default of type stdout, v2.0 from /usr/lib/python2.7/dist-packages/ansible/plugins/callback/default.pyc
PLAYBOOK: Test-Run.yml ***********************************************************************************************
Positional arguments: Test-Run.yml
become_method: sudo
inventory: (u'/home/pknight/dci/ansible/servicenow/sandbox',)
forks: 5
tags: (u'all',)
verbosity: 4
connection: smart
timeout: 10
1 plays in Test-Run.yml
PLAY [Test SNow] *****************************************************************************************************
META: ran handlers
TASK [Gather facts on automation user] *******************************************************************************
task path: /home/pknight/dci/ansible/servicenow/Test-Run.yml:9
<delawarecalgarytest.service-now.com> ESTABLISH LOCAL CONNECTION FOR USER: pknight
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c 'echo ~pknight && sleep 0'
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/pknight/.ansible/tmp/ansible-tmp-1563393628.67-264175846363655 `" && echo ansible-tmp-1563393628.67-264175846363655="` echo /home/pknight/.ansible/tmp/ansible-tmp-1563393628.67-264175846363655 `" ) && sleep 0'
Using module file /usr/lib/python2.7/dist-packages/ansible/modules/notification/snow_record_find.py
<delawarecalgarytest.service-now.com> PUT /home/pknight/.ansible/tmp/ansible-local-12354QW3EpR/tmp5q343Y TO /home/pknight/.ansible/tmp/ansible-tmp-1563393628.67-264175846363655/AnsiballZ_snow_record_find.py
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c 'chmod u+x /home/pknight/.ansible/tmp/ansible-tmp-1563393628.67-264175846363655/ /home/pknight/.ansible/tmp/ansible-tmp-1563393628.67-264175846363655/AnsiballZ_snow_record_find.py && sleep 0'
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c '/home/pknight/dci/ansible/servicenow/venv/bin/python2.7 /home/pknight/.ansible/tmp/ansible-tmp-1563393628.67-264175846363655/AnsiballZ_snow_record_find.py && sleep 0'
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c 'rm -f -r /home/pknight/.ansible/tmp/ansible-tmp-1563393628.67-264175846363655/ > /dev/null 2>&1 && sleep 0'
ok: [yourinstance.service-now.com] => {
"changed": false,
"instance": "yourinstance",
"invocation": {
"module_args": {
"client_id": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"client_secret": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"instance": "yourinstance",
"max_records": 1,
"order_by": "-created_on",
"password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"query": {
"email": "[email protected]"
},
"return_fields": [
"email",
"name",
"sys_id"
],
"table": "sys_user",
"username": "[email protected]"
}
},
"max_records": 1,
"query": {
"email": "[email protected]"
},
"record": [
{
"email": "[email protected]",
"name": "ServiceNow User",
"sys_id": "1234567890abcdef1234567890"
}
],
"return_fields": [
"email",
"name",
"sys_id"
],
"table": "sys_user"
}
META: ran handlers
META: ran handlers
PLAY RECAP ***********************************************************************************************************
yourinstance.service-now.com : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
```
##### ACTUAL RESULTS
```
ansible-playbook 2.8.2
config file = /home/pknight/dci/ansible/servicenow/ansible.cfg
configured module search path = [u'/home/pknight/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible-playbook
python version = 2.7.15+ (default, Nov 27 2018, 23:36:35) [GCC 7.3.0]
Using /home/pknight/dci/ansible/servicenow/ansible.cfg as config file
setting up inventory plugins
host_list declined parsing /home/pknight/dci/ansible/servicenow/sandbox/regions as it did not pass it's verify_file() method
script declined parsing /home/pknight/dci/ansible/servicenow/sandbox/regions as it did not pass it's verify_file() method
auto declined parsing /home/pknight/dci/ansible/servicenow/sandbox/regions as it did not pass it's verify_file() method
Parsed /home/pknight/dci/ansible/servicenow/sandbox/regions inventory source with ini plugin
Loading callback plugin default of type stdout, v2.0 from /usr/lib/python2.7/dist-packages/ansible/plugins/callback/default.pyc
PLAYBOOK: Test-Run.yml ***********************************************************************************************
Positional arguments: Test-Run.yml
become_method: sudo
inventory: (u'/home/pknight/dci/ansible/servicenow/sandbox',)
forks: 5
tags: (u'all',)
verbosity: 4
connection: smart
timeout: 10
1 plays in Test-Run.yml
PLAY [Test SNow] *****************************************************************************************************
META: ran handlers
TASK [Gather facts on automation user] *******************************************************************************
task path: /home/pknight/dci/ansible/servicenow/Test-Run.yml:9
<delawarecalgarytest.service-now.com> ESTABLISH LOCAL CONNECTION FOR USER: pknight
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c 'echo ~pknight && sleep 0'
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/pknight/.ansible/tmp/ansible-tmp-1563393553.59-213692823755979 `" && echo ansible-tmp-1563393553.59-213692823755979="` echo /home/pknight/.ansible/tmp/ansible-tmp-1563393553.59-213692823755979 `" ) && sleep 0'
Using module file /usr/lib/python2.7/dist-packages/ansible/modules/notification/snow_record_find.py
<delawarecalgarytest.service-now.com> PUT /home/pknight/.ansible/tmp/ansible-local-12069E5RReh/tmpeVAB5I TO /home/pknight/.ansible/tmp/ansible-tmp-1563393553.59-213692823755979/AnsiballZ_snow_record_find.py
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c 'chmod u+x /home/pknight/.ansible/tmp/ansible-tmp-1563393553.59-213692823755979/ /home/pknight/.ansible/tmp/ansible-tmp-1563393553.59-213692823755979/AnsiballZ_snow_record_find.py && sleep 0'
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c '/home/pknight/dci/ansible/servicenow/venv/bin/python2.7 /home/pknight/.ansible/tmp/ansible-tmp-1563393553.59-213692823755979/AnsiballZ_snow_record_find.py && sleep 0'
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c 'rm -f -r /home/pknight/.ansible/tmp/ansible-tmp-1563393553.59-213692823755979/ > /dev/null 2>&1 && sleep 0'
The full traceback is:
WARNING: The below traceback may *not* be related to the actual failure.
File "/tmp/ansible_snow_record_find_payload_GdXZXi/__main__.py", line 255, in run_module
record = conn.query(table=module.params['table'],
fatal: [yourinstance.service-now.com]: FAILED! => {
"changed": false,
"instance": "yourinstance",
"invocation": {
"module_args": {
"client_id": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"client_secret": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"instance": "yourinstance",
"max_records": 1,
"order_by": "-created_on",
"password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"query": {
"email": "[email protected]"
},
"return_fields": [
"email",
"name",
"sys_id"
],
"table": "sys_user",
"username": "[email protected]"
}
},
"max_records": 1,
"msg": "Failed to find record: 'NoneType' object has no attribute 'query'",
"query": {
"email": "[email protected]"
},
"return_fields": [
"email",
"name",
"sys_id"
],
"table": "sys_user"
}
...ignoring
META: ran handlers
META: ran handlers
PLAY RECAP ***********************************************************************************************************
yourinstance.service-now.com : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1
```
|
https://github.com/ansible/ansible/issues/59199
|
https://github.com/ansible/ansible/pull/59201
|
d0538c0d7a0ac8de612a6946a32fa6c4ad256eb2
|
7e25a614647c7ced41b38f869dfd49e06a29d22c
| 2019-07-17T20:02:02Z |
python
| 2019-07-18T05:23:23Z |
lib/ansible/modules/notification/snow_record.py
|
#!/usr/bin/python
# Copyright: (c) 2017, Tim Rightnour <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: snow_record
short_description: Manage records in ServiceNow
version_added: "2.5"
description:
- Creates, deletes and updates a single record in ServiceNow.
options:
table:
description:
- Table to query for records.
required: false
default: incident
type: str
state:
description:
- If C(present) is supplied with a C(number) argument, the module will attempt to update the record with the supplied data.
- If no such record exists, a new one will be created.
- C(absent) will delete a record.
choices: [ present, absent ]
required: true
type: str
data:
description:
- key, value pairs of data to load into the record. See Examples.
- Required for C(state:present).
type: dict
number:
description:
- Record number to update.
- Required for C(state:absent).
required: false
type: str
lookup_field:
description:
- Changes the field that C(number) uses to find records.
required: false
default: number
type: str
attachment:
description:
- Attach a file to the record.
required: false
type: str
client_id:
description:
- Client ID generated by ServiceNow.
required: false
type: str
version_added: "2.9"
client_secret:
description:
- Client Secret associated with client id.
required: false
type: str
version_added: "2.9"
requirements:
- python pysnow (pysnow)
author:
- Tim Rightnour (@garbled1)
extends_documentation_fragment: service_now.documentation
'''
EXAMPLES = '''
- name: Grab a user record
snow_record:
username: ansible_test
password: my_password
instance: dev99999
state: present
number: 62826bf03710200044e0bfc8bcbe5df1
table: sys_user
lookup_field: sys_id
- name: Grab a user record using OAuth
snow_record:
username: ansible_test
password: my_password
client_id: "1234567890abcdef1234567890abcdef"
client_secret: "Password1!"
instance: dev99999
state: present
number: 62826bf03710200044e0bfc8bcbe5df1
table: sys_user
lookup_field: sys_id
- name: Create an incident
snow_record:
username: ansible_test
password: my_password
instance: dev99999
state: present
data:
short_description: "This is a test incident opened by Ansible"
severity: 3
priority: 2
register: new_incident
- name: Delete the record we just made
snow_record:
username: admin
password: xxxxxxx
instance: dev99999
state: absent
number: "{{new_incident['record']['number']}}"
- name: Delete a non-existant record
snow_record:
username: ansible_test
password: my_password
instance: dev99999
state: absent
number: 9872354
failed_when: false
- name: Update an incident
snow_record:
username: ansible_test
password: my_password
instance: dev99999
state: present
number: INC0000055
data:
work_notes : "Been working all day on this thing."
- name: Attach a file to an incident
snow_record:
username: ansible_test
password: my_password
instance: dev99999
state: present
number: INC0000055
attachment: README.md
tags: attach
'''
RETURN = '''
record:
description: Record data from Service Now
type: dict
returned: when supported
attached_file:
description: Details of the file that was attached via C(attachment)
type: dict
returned: when supported
'''
import os
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_bytes, to_native
from ansible.module_utils.service_now import ServiceNowClient
try:
# This is being handled by ServiceNowClient
import pysnow
except ImportError:
pass
def run_module():
# define the available arguments/parameters that a user can pass to
# the module
module_args = ServiceNowClient.snow_argument_spec()
module_args.update(
table=dict(type='str', required=False, default='incident'),
state=dict(choices=['present', 'absent'],
type='str', required=True),
number=dict(default=None, required=False, type='str'),
data=dict(default=None, required=False, type='dict'),
lookup_field=dict(default='number', required=False, type='str'),
attachment=dict(default=None, required=False, type='str')
)
module_required_together = [
['client_id', 'client_secret']
]
module_required_if = [
['state', 'absent', ['number']],
]
module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=True,
required_together=module_required_together,
required_if=module_required_if
)
# Connect to ServiceNow
service_now_client = ServiceNowClient(module)
conn = service_now_client.conn
params = module.params
instance = params['instance']
table = params['table']
state = params['state']
number = params['number']
data = params['data']
lookup_field = params['lookup_field']
result = dict(
changed=False,
instance=instance,
table=table,
number=number,
lookup_field=lookup_field
)
# check for attachments
if params['attachment'] is not None:
attach = params['attachment']
b_attach = to_bytes(attach, errors='surrogate_or_strict')
if not os.path.exists(b_attach):
module.fail_json(msg="Attachment {0} not found".format(attach))
result['attachment'] = attach
else:
attach = None
# Deal with check mode
if module.check_mode:
# if we are in check mode and have no number, we would have created
# a record. We can only partially simulate this
if number is None:
result['record'] = dict(data)
result['changed'] = True
# do we want to check if the record is non-existent?
elif state == 'absent':
try:
record = conn.query(table=table, query={lookup_field: number})
res = record.get_one()
result['record'] = dict(Success=True)
result['changed'] = True
except pysnow.exceptions.NoResults:
result['record'] = None
except Exception as detail:
module.fail_json(msg="Unknown failure in query record: {0}".format(to_native(detail)), **result)
# Let's simulate modification
else:
try:
record = conn.query(table=table, query={lookup_field: number})
res = record.get_one()
for key, value in data.items():
res[key] = value
result['changed'] = True
result['record'] = res
except pysnow.exceptions.NoResults:
snow_error = "Record does not exist"
module.fail_json(msg=snow_error, **result)
except Exception as detail:
module.fail_json(msg="Unknown failure in query record: {0}".format(to_native(detail)), **result)
module.exit_json(**result)
# now for the real thing: (non-check mode)
# are we creating a new record?
if state == 'present' and number is None:
try:
record = conn.insert(table=table, payload=dict(data))
except pysnow.exceptions.UnexpectedResponseFormat as e:
snow_error = "Failed to create record: {0}, details: {1}".format(e.error_summary, e.error_details)
module.fail_json(msg=snow_error, **result)
result['record'] = record
result['changed'] = True
# we are deleting a record
elif state == 'absent':
try:
record = conn.query(table=table, query={lookup_field: number})
res = record.delete()
except pysnow.exceptions.NoResults:
res = dict(Success=True)
except pysnow.exceptions.MultipleResults:
snow_error = "Multiple record match"
module.fail_json(msg=snow_error, **result)
except pysnow.exceptions.UnexpectedResponseFormat as e:
snow_error = "Failed to delete record: {0}, details: {1}".format(e.error_summary, e.error_details)
module.fail_json(msg=snow_error, **result)
except Exception as detail:
snow_error = "Failed to delete record: {0}".format(to_native(detail))
module.fail_json(msg=snow_error, **result)
result['record'] = res
result['changed'] = True
# We want to update a record
else:
try:
record = conn.query(table=table, query={lookup_field: number})
if data is not None:
res = record.update(dict(data))
result['record'] = res
result['changed'] = True
else:
res = record.get_one()
result['record'] = res
if attach is not None:
res = record.attach(b_attach)
result['changed'] = True
result['attached_file'] = res
except pysnow.exceptions.MultipleResults:
snow_error = "Multiple record match"
module.fail_json(msg=snow_error, **result)
except pysnow.exceptions.NoResults:
snow_error = "Record does not exist"
module.fail_json(msg=snow_error, **result)
except pysnow.exceptions.UnexpectedResponseFormat as e:
snow_error = "Failed to update record: {0}, details: {1}".format(e.error_summary, e.error_details)
module.fail_json(msg=snow_error, **result)
except Exception as detail:
snow_error = "Failed to update record: {0}".format(to_native(detail))
module.fail_json(msg=snow_error, **result)
module.exit_json(**result)
def main():
run_module()
if __name__ == '__main__':
main()
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 59,199 |
Call Refactored login from snow modules
|
##### SUMMARY
snow modules do not call refactored login function. Login must be called to initialize connection.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
snow_record.py
snow_record_find.py
##### ANSIBLE VERSION
```
ansible 2.9
config file = /home/pknight/dci/ansible/servicenow/ansible.cfg
configured module search path = [u'/home/pknight/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.15+ (default, Nov 27 2018, 23:36:35) [GCC 7.3.0]
```
##### CONFIGURATION
```
DEFAULT_VAULT_PASSWORD_FILE(/home/pknight/dci/ansible/servicenow/ansible.cfg) = /home/pknight/.ansiblevault
YAML_FILENAME_EXTENSIONS(/home/pknight/dci/ansible/servicenow/ansible.cfg) = [u'.json', u'.yaml', u'.yml', u'.vault']
```
##### OS / ENVIRONMENT
Linux
##### STEPS TO REPRODUCE
ansible-playbook -i sandbox Test-Run.yml -vvvvv
sandbox/regions:
[sandbox]
yourinstance.service-now.com
Test-Run.yml:
```yaml
yaml
- name: Test Run
hosts: all
connection: local
gather_facts: no
ignore_errors: True
tasks:
- name: Gather facts on automation user
snow_record_find:
username: "[email protected]"
password: "S0m3P@ssw0rd"
client_id: "1234567890abcdef01234567890abcde"
client_secret: "S0m3S3cr3t"
instance: "yourinstance"
max_records: 1
table: sys_user
query:
email: "[email protected]"
return_fields:
- email
- name
- sys_id
```
##### EXPECTED RESULTS
```
ansible-playbook 2.8.2
config file = /home/pknight/dci/ansible/servicenow/ansible.cfg
configured module search path = [u'/home/pknight/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible-playbook
python version = 2.7.15+ (default, Nov 27 2018, 23:36:35) [GCC 7.3.0]
Using /home/pknight/dci/ansible/servicenow/ansible.cfg as config file
setting up inventory plugins
host_list declined parsing /home/pknight/dci/ansible/servicenow/sandbox/regions as it did not pass it's verify_file() method
script declined parsing /home/pknight/dci/ansible/servicenow/sandbox/regions as it did not pass it's verify_file() method
auto declined parsing /home/pknight/dci/ansible/servicenow/sandbox/regions as it did not pass it's verify_file() method
Parsed /home/pknight/dci/ansible/servicenow/sandbox/regions inventory source with ini plugin
Loading callback plugin default of type stdout, v2.0 from /usr/lib/python2.7/dist-packages/ansible/plugins/callback/default.pyc
PLAYBOOK: Test-Run.yml ***********************************************************************************************
Positional arguments: Test-Run.yml
become_method: sudo
inventory: (u'/home/pknight/dci/ansible/servicenow/sandbox',)
forks: 5
tags: (u'all',)
verbosity: 4
connection: smart
timeout: 10
1 plays in Test-Run.yml
PLAY [Test SNow] *****************************************************************************************************
META: ran handlers
TASK [Gather facts on automation user] *******************************************************************************
task path: /home/pknight/dci/ansible/servicenow/Test-Run.yml:9
<delawarecalgarytest.service-now.com> ESTABLISH LOCAL CONNECTION FOR USER: pknight
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c 'echo ~pknight && sleep 0'
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/pknight/.ansible/tmp/ansible-tmp-1563393628.67-264175846363655 `" && echo ansible-tmp-1563393628.67-264175846363655="` echo /home/pknight/.ansible/tmp/ansible-tmp-1563393628.67-264175846363655 `" ) && sleep 0'
Using module file /usr/lib/python2.7/dist-packages/ansible/modules/notification/snow_record_find.py
<delawarecalgarytest.service-now.com> PUT /home/pknight/.ansible/tmp/ansible-local-12354QW3EpR/tmp5q343Y TO /home/pknight/.ansible/tmp/ansible-tmp-1563393628.67-264175846363655/AnsiballZ_snow_record_find.py
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c 'chmod u+x /home/pknight/.ansible/tmp/ansible-tmp-1563393628.67-264175846363655/ /home/pknight/.ansible/tmp/ansible-tmp-1563393628.67-264175846363655/AnsiballZ_snow_record_find.py && sleep 0'
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c '/home/pknight/dci/ansible/servicenow/venv/bin/python2.7 /home/pknight/.ansible/tmp/ansible-tmp-1563393628.67-264175846363655/AnsiballZ_snow_record_find.py && sleep 0'
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c 'rm -f -r /home/pknight/.ansible/tmp/ansible-tmp-1563393628.67-264175846363655/ > /dev/null 2>&1 && sleep 0'
ok: [yourinstance.service-now.com] => {
"changed": false,
"instance": "yourinstance",
"invocation": {
"module_args": {
"client_id": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"client_secret": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"instance": "yourinstance",
"max_records": 1,
"order_by": "-created_on",
"password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"query": {
"email": "[email protected]"
},
"return_fields": [
"email",
"name",
"sys_id"
],
"table": "sys_user",
"username": "[email protected]"
}
},
"max_records": 1,
"query": {
"email": "[email protected]"
},
"record": [
{
"email": "[email protected]",
"name": "ServiceNow User",
"sys_id": "1234567890abcdef1234567890"
}
],
"return_fields": [
"email",
"name",
"sys_id"
],
"table": "sys_user"
}
META: ran handlers
META: ran handlers
PLAY RECAP ***********************************************************************************************************
yourinstance.service-now.com : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
```
##### ACTUAL RESULTS
```
ansible-playbook 2.8.2
config file = /home/pknight/dci/ansible/servicenow/ansible.cfg
configured module search path = [u'/home/pknight/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible-playbook
python version = 2.7.15+ (default, Nov 27 2018, 23:36:35) [GCC 7.3.0]
Using /home/pknight/dci/ansible/servicenow/ansible.cfg as config file
setting up inventory plugins
host_list declined parsing /home/pknight/dci/ansible/servicenow/sandbox/regions as it did not pass it's verify_file() method
script declined parsing /home/pknight/dci/ansible/servicenow/sandbox/regions as it did not pass it's verify_file() method
auto declined parsing /home/pknight/dci/ansible/servicenow/sandbox/regions as it did not pass it's verify_file() method
Parsed /home/pknight/dci/ansible/servicenow/sandbox/regions inventory source with ini plugin
Loading callback plugin default of type stdout, v2.0 from /usr/lib/python2.7/dist-packages/ansible/plugins/callback/default.pyc
PLAYBOOK: Test-Run.yml ***********************************************************************************************
Positional arguments: Test-Run.yml
become_method: sudo
inventory: (u'/home/pknight/dci/ansible/servicenow/sandbox',)
forks: 5
tags: (u'all',)
verbosity: 4
connection: smart
timeout: 10
1 plays in Test-Run.yml
PLAY [Test SNow] *****************************************************************************************************
META: ran handlers
TASK [Gather facts on automation user] *******************************************************************************
task path: /home/pknight/dci/ansible/servicenow/Test-Run.yml:9
<delawarecalgarytest.service-now.com> ESTABLISH LOCAL CONNECTION FOR USER: pknight
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c 'echo ~pknight && sleep 0'
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/pknight/.ansible/tmp/ansible-tmp-1563393553.59-213692823755979 `" && echo ansible-tmp-1563393553.59-213692823755979="` echo /home/pknight/.ansible/tmp/ansible-tmp-1563393553.59-213692823755979 `" ) && sleep 0'
Using module file /usr/lib/python2.7/dist-packages/ansible/modules/notification/snow_record_find.py
<delawarecalgarytest.service-now.com> PUT /home/pknight/.ansible/tmp/ansible-local-12069E5RReh/tmpeVAB5I TO /home/pknight/.ansible/tmp/ansible-tmp-1563393553.59-213692823755979/AnsiballZ_snow_record_find.py
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c 'chmod u+x /home/pknight/.ansible/tmp/ansible-tmp-1563393553.59-213692823755979/ /home/pknight/.ansible/tmp/ansible-tmp-1563393553.59-213692823755979/AnsiballZ_snow_record_find.py && sleep 0'
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c '/home/pknight/dci/ansible/servicenow/venv/bin/python2.7 /home/pknight/.ansible/tmp/ansible-tmp-1563393553.59-213692823755979/AnsiballZ_snow_record_find.py && sleep 0'
<delawarecalgarytest.service-now.com> EXEC /bin/sh -c 'rm -f -r /home/pknight/.ansible/tmp/ansible-tmp-1563393553.59-213692823755979/ > /dev/null 2>&1 && sleep 0'
The full traceback is:
WARNING: The below traceback may *not* be related to the actual failure.
File "/tmp/ansible_snow_record_find_payload_GdXZXi/__main__.py", line 255, in run_module
record = conn.query(table=module.params['table'],
fatal: [yourinstance.service-now.com]: FAILED! => {
"changed": false,
"instance": "yourinstance",
"invocation": {
"module_args": {
"client_id": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"client_secret": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"instance": "yourinstance",
"max_records": 1,
"order_by": "-created_on",
"password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
"query": {
"email": "[email protected]"
},
"return_fields": [
"email",
"name",
"sys_id"
],
"table": "sys_user",
"username": "[email protected]"
}
},
"max_records": 1,
"msg": "Failed to find record: 'NoneType' object has no attribute 'query'",
"query": {
"email": "[email protected]"
},
"return_fields": [
"email",
"name",
"sys_id"
],
"table": "sys_user"
}
...ignoring
META: ran handlers
META: ran handlers
PLAY RECAP ***********************************************************************************************************
yourinstance.service-now.com : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1
```
|
https://github.com/ansible/ansible/issues/59199
|
https://github.com/ansible/ansible/pull/59201
|
d0538c0d7a0ac8de612a6946a32fa6c4ad256eb2
|
7e25a614647c7ced41b38f869dfd49e06a29d22c
| 2019-07-17T20:02:02Z |
python
| 2019-07-18T05:23:23Z |
lib/ansible/modules/notification/snow_record_find.py
|
#!/usr/bin/python
# Copyright: (c) 2017, Tim Rightnour <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: snow_record_find
short_description: Search for multiple records from ServiceNow
version_added: "2.9"
description:
- Gets multiple records from a specified table from ServiceNow based on a query dictionary.
options:
table:
description:
- Table to query for records.
type: str
required: false
default: incident
query:
description:
- Dict to query for records.
type: dict
required: true
max_records:
description:
- Maximum number of records to return.
type: int
required: false
default: 20
order_by:
description:
- Field to sort the results on.
- Can prefix with "-" or "+" to change decending or ascending sort order.
type: str
default: "-created_on"
required: false
return_fields:
description:
- Fields of the record to return in the json.
- By default, all fields will be returned.
type: list
required: false
requirements:
- python pysnow (pysnow)
author:
- Tim Rightnour (@garbled1)
extends_documentation_fragment: service_now.documentation
'''
EXAMPLES = '''
- name: Search for incident assigned to group, return specific fields
snow_record_find:
username: ansible_test
password: my_password
instance: dev99999
table: incident
query:
assignment_group: d625dccec0a8016700a222a0f7900d06
return_fields:
- number
- opened_at
- name: Using OAuth, search for incident assigned to group, return specific fields
snow_record_find:
username: ansible_test
password: my_password
client_id: "1234567890abcdef1234567890abcdef"
client_secret: "Password1!"
instance: dev99999
table: incident
query:
assignment_group: d625dccec0a8016700a222a0f7900d06
return_fields:
- number
- opened_at
- name: Find open standard changes with my template
snow_record_find:
username: ansible_test
password: my_password
instance: dev99999
table: change_request
query:
AND:
equals:
active: "True"
type: "standard"
u_change_stage: "80"
contains:
u_template: "MY-Template"
return_fields:
- sys_id
- number
- sys_created_on
- sys_updated_on
- u_template
- active
- type
- u_change_stage
- sys_created_by
- description
- short_description
'''
RETURN = '''
record:
description: The full contents of the matching ServiceNow records as a list of records.
type: dict
returned: always
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.service_now import ServiceNowClient
from ansible.module_utils._text import to_native
try:
# This is being managed by ServiceNowClient
import pysnow
except ImportError:
pass
# OAuth Variables
module = None
client_id = None
client_secret = None
instance = None
session = {'token': None}
class BuildQuery(object):
'''
This is a BuildQuery manipulation class that constructs
a pysnow.QueryBuilder object based on data input.
'''
def __init__(self, module):
self.module = module
self.logic_operators = ["AND", "OR", "NQ"]
self.condition_operator = {
'equals': self._condition_closure,
'not_equals': self._condition_closure,
'contains': self._condition_closure,
'not_contains': self._condition_closure,
'starts_with': self._condition_closure,
'ends_with': self._condition_closure,
'greater_than': self._condition_closure,
'less_than': self._condition_closure,
}
self.accepted_cond_ops = self.condition_operator.keys()
self.append_operator = False
self.simple_query = True
self.data = module.params['query']
def _condition_closure(self, cond, query_field, query_value):
self.qb.field(query_field)
getattr(self.qb, cond)(query_value)
def _iterate_fields(self, data, logic_op, cond_op):
if isinstance(data, dict):
for query_field, query_value in data.items():
if self.append_operator:
getattr(self.qb, logic_op)()
self.condition_operator[cond_op](cond_op, query_field, query_value)
self.append_operator = True
else:
self.module.fail_json(msg='Query is not in a supported format')
def _iterate_conditions(self, data, logic_op):
if isinstance(data, dict):
for cond_op, fields in data.items():
if (cond_op in self.accepted_cond_ops):
self._iterate_fields(fields, logic_op, cond_op)
else:
self.module.fail_json(msg='Supported conditions: {0}'.format(str(self.condition_operator.keys())))
else:
self.module.fail_json(msg='Supported conditions: {0}'.format(str(self.condition_operator.keys())))
def _iterate_operators(self, data):
if isinstance(data, dict):
for logic_op, cond_op in data.items():
if (logic_op in self.logic_operators):
self.simple_query = False
self._iterate_conditions(cond_op, logic_op)
elif self.simple_query:
self.condition_operator['equals']('equals', logic_op, cond_op)
break
else:
self.module.fail_json(msg='Query is not in a supported format')
else:
self.module.fail_json(msg='Supported operators: {0}'.format(str(self.logic_operators)))
def build_query(self):
self.qb = pysnow.QueryBuilder()
self._iterate_operators(self.data)
return (self.qb)
def run_module():
# define the available arguments/parameters that a user can pass to
# the module
module_args = ServiceNowClient.snow_argument_spec()
module_args.update(
table=dict(type='str', required=False, default='incident'),
query=dict(type='dict', required=True),
max_records=dict(default=20, type='int', required=False),
order_by=dict(default='-created_on', type='str', required=False),
return_fields=dict(default=None, type='list', required=False)
)
module_required_together = [
['client_id', 'client_secret']
]
module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=True,
required_together=module_required_together
)
# Connect to ServiceNow
service_now_client = ServiceNowClient(module)
conn = service_now_client.conn
params = module.params
instance = params['instance']
table = params['table']
query = params['query']
max_records = params['max_records']
return_fields = params['return_fields']
result = dict(
changed=False,
instance=instance,
table=table,
query=query,
max_records=max_records,
return_fields=return_fields
)
# Do the lookup
try:
bq = BuildQuery(module)
qb = bq.build_query()
record = conn.query(table=module.params['table'],
query=qb)
if module.params['return_fields'] is not None:
res = record.get_multiple(fields=module.params['return_fields'],
limit=module.params['max_records'],
order_by=[module.params['order_by']])
else:
res = record.get_multiple(limit=module.params['max_records'],
order_by=[module.params['order_by']])
except Exception as detail:
module.fail_json(msg='Failed to find record: {0}'.format(to_native(detail)), **result)
try:
result['record'] = list(res)
except pysnow.exceptions.NoResults:
result['record'] = []
module.exit_json(**result)
def main():
run_module()
if __name__ == '__main__':
main()
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,370 |
Allow mysql_db module to create/drop multiple databases
|
##### SUMMARY
mysql_db module should be able to create/drop multiple databases
##### ISSUE TYPE
- Feature Idea
##### COMPONENT NAME
lib/ansible/modules/database/mysql/mysql_db.py
##### ADDITIONAL INFORMATION
Why and what it would solve:
Avoids repetitive tasks to create/delete more than one databases (similar to https://github.com/ansible/ansible/issues/56059)
<!--- Paste example playbooks or commands between quotes below -->
- Create (Multiple databases)
```yaml
tasks:
- name: Create multiple databases (provided in comma separated form)
mysql_db:
name: bobdata, bobthebuilder
state: present
- name: Create multiple databases (provided in list form)
mysql_db:
name:
- bobdata
- bobthebuilder
state: present
```
- Delete/Drop (Multiple databases)
```yaml
- name: Delete/drop multiple databases (provided in comma separated form)
mysql_db:
name: bobdata, bobthebuilder
state: absent
- name: Delete/drop multiple databases (provided in list form)
mysql_db:
name:
- bobdata
- bobthebuilder
state: absent
```
Credits for the idea to @Andersson007 from comment https://github.com/ansible/ansible/pull/56721#issuecomment-505128646
|
https://github.com/ansible/ansible/issues/58370
|
https://github.com/ansible/ansible/pull/58602
|
cdf0947df092fb9883a13bca13a120ff29cacfc5
|
393e4a41d08c9654279215094630ed2e7f84d8d1
| 2019-06-26T04:04:27Z |
python
| 2019-07-18T14:56:32Z |
changelogs/fragments/58370-mysqldb-allow-multiple_databases_create_delete_operation.yml
| |
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,370 |
Allow mysql_db module to create/drop multiple databases
|
##### SUMMARY
mysql_db module should be able to create/drop multiple databases
##### ISSUE TYPE
- Feature Idea
##### COMPONENT NAME
lib/ansible/modules/database/mysql/mysql_db.py
##### ADDITIONAL INFORMATION
Why and what it would solve:
Avoids repetitive tasks to create/delete more than one databases (similar to https://github.com/ansible/ansible/issues/56059)
<!--- Paste example playbooks or commands between quotes below -->
- Create (Multiple databases)
```yaml
tasks:
- name: Create multiple databases (provided in comma separated form)
mysql_db:
name: bobdata, bobthebuilder
state: present
- name: Create multiple databases (provided in list form)
mysql_db:
name:
- bobdata
- bobthebuilder
state: present
```
- Delete/Drop (Multiple databases)
```yaml
- name: Delete/drop multiple databases (provided in comma separated form)
mysql_db:
name: bobdata, bobthebuilder
state: absent
- name: Delete/drop multiple databases (provided in list form)
mysql_db:
name:
- bobdata
- bobthebuilder
state: absent
```
Credits for the idea to @Andersson007 from comment https://github.com/ansible/ansible/pull/56721#issuecomment-505128646
|
https://github.com/ansible/ansible/issues/58370
|
https://github.com/ansible/ansible/pull/58602
|
cdf0947df092fb9883a13bca13a120ff29cacfc5
|
393e4a41d08c9654279215094630ed2e7f84d8d1
| 2019-06-26T04:04:27Z |
python
| 2019-07-18T14:56:32Z |
docs/docsite/rst/porting_guides/porting_guide_2.9.rst
|
.. _porting_2.9_guide:
*************************
Ansible 2.9 Porting Guide
*************************
This section discusses the behavioral changes between Ansible 2.8 and Ansible 2.9.
It is intended to assist in updating your playbooks, plugins and other parts of your Ansible infrastructure so they will work with this version of Ansible.
We suggest you read this page along with `Ansible Changelog for 2.9 <https://github.com/ansible/ansible/blob/devel/changelogs/CHANGELOG-v2.9.rst>`_ to understand what updates you may need to make.
This document is part of a collection on porting. The complete list of porting guides can be found at :ref:`porting guides <porting_guides>`.
.. contents:: Topics
Playbook
========
* ``hash_behaviour`` now affects inventory sources. If you have it set to ``merge``, the data you get from inventory might change and you will have to update playbooks accordingly. If you're using the default setting (``overwrite``), you will see no changes. Inventory was ignoring this setting.
Command Line
============
No notable changes
Deprecated
==========
No notable changes
Modules
=======
No notable changes
Modules removed
---------------
The following modules no longer exist:
* Apstra's ``aos_*`` modules. See the new modules at `https://github.com/apstra <https://github.com/apstra>`_.
* ec2_ami_find use :ref:`ec2_ami_facts <ec2_ami_facts_module>` instead.
* kubernetes use :ref:`k8s_raw <k8s_raw_module>` instead.
* nxos_ip_interface use :ref:`nxos_l3_interface <nxos_l3_interface_module>` instead.
* nxos_portchannel use :ref:`nxos_linkagg <nxos_linkagg_module>` instead.
* nxos_switchport use :ref:`nxos_l2_interface <nxos_l2_interface_module>` instead.
* oc use :ref:`openshift_raw <openshift_raw_module>` instead.
* panos_nat_policy use :ref:`panos_nat_rule <panos_nat_rule_module>` instead.
* panos_security_policy use :ref:`panos_security_rule <panos_security_rule_module>` instead.
* vsphere_guest use :ref:`vmware_guest <vmware_guest_module>` instead.
Deprecation notices
-------------------
No notable changes
Noteworthy module changes
-------------------------
* `vmware_dvswitch <vmware_dvswitch_module>` accepts `folder` parameter to place dvswitch in user defined folder. This option makes `datacenter` as an optional parameter.
* `vmware_datastore_cluster <vmware_datastore_cluster_module>` accepts `folder` parameter to place datastore cluster in user defined folder. This option makes `datacenter` as an optional parameter.
* The ``python_requirements_facts`` module was renamed to :ref:`python_requirements_info <python_requirements_info_module>`.
* The ``jenkins_job_facts`` module was renamed to :ref:`jenkins_job_info <jenkins_job_info_module>`.
* The ``intersight_facts`` module was renamed to :ref:`intersight_info <intersight_info_module>`.
* The ``zabbix_group_facts`` module was renamed to :ref:`zabbix_group_info <zabbix_group_info_module>`.
* The ``zabbix_host_facts`` module was renamed to :ref:`zabbix_host_info <zabbix_host_info_module>`.
* The ``github_webhook_facts`` module was renamed to :ref:`github_webhook_info <github_webhook_info_module>`.
* The ``k8s_facts`` module was renamed to :ref:`k8s_info <k8s_info_module>`.
* The ``bigip_device_facts`` module was renamed to :ref:`bigip_device_info <bigip_device_info_module>`.
* The ``bigiq_device_facts`` module was renamed to :ref:`bigiq_device_info <bigiq_device_info_module>`.
* The ``memset_memstore_facts`` module was renamed to :ref:`memset_memstore_info <memset_memstore_info_module>`.
* The ``memset_server_facts`` module was renamed to :ref:`memset_server_info <memset_server_info_module>`.
* The ``one_image_facts`` module was renamed to :ref:`one_image_info <one_image_info_module>`.
* The ``ali_instance_facts`` module was renamed to :ref:`ali_instance_info <ali_instance_info_module>`.
* The ``xenserver_guest_facts`` module was renamed to :ref:`xenserver_guest_info <xenserver_guest_info_module>`.
* The ``azure_rm_resourcegroup_facts`` module was renamed to :ref:`azure_rm_resourcegroup_info <azure_rm_resourcegroup_info_module>`.
* The ``digital_ocean_account_facts`` module was renamed to :ref:`digital_ocean_account_info <digital_ocean_account_info_module>`.
* The ``digital_ocean_certificate_facts`` module was renamed to :ref:`digital_ocean_certificate_info <digital_ocean_certificate_info_module>`.
* The ``digital_ocean_domain_facts`` module was renamed to :ref:`digital_ocean_domain_info <digital_ocean_domain_info_module>`.
* The ``digital_ocean_firewall_facts`` module was renamed to :ref:`digital_ocean_firewall_info <digital_ocean_firewall_info_module>`.
* The ``digital_ocean_floating_ip_facts`` module was renamed to :ref:`digital_ocean_floating_ip_info <digital_ocean_floating_ip_info_module>`.
* The ``digital_ocean_image_facts`` module was renamed to :ref:`digital_ocean_image_info <digital_ocean_image_info_module>`.
* The ``digital_ocean_load_balancer_facts`` module was renamed to :ref:`digital_ocean_load_balancer_info <digital_ocean_load_balancer_info_module>`.
* The ``digital_ocean_region_facts`` module was renamed to :ref:`digital_ocean_region_info <digital_ocean_region_info_module>`.
* The ``digital_ocean_size_facts`` module was renamed to :ref:`digital_ocean_size_info <digital_ocean_size_info_module>`.
* The ``digital_ocean_snapshot_facts`` module was renamed to :ref:`digital_ocean_snapshot_info <digital_ocean_snapshot_info_module>`.
* The ``digital_ocean_tag_facts`` module was renamed to :ref:`digital_ocean_tag_info <digital_ocean_tag_info_module>`.
* The ``digital_ocean_volume_facts`` module was renamed to :ref:`digital_ocean_volume_info <digital_ocean_volume_info_module>`.
* The ``aws_acm_facts`` module was renamed to :ref:`aws_acm_info <aws_acm_info_module>`.
* The ``aws_az_facts`` module was renamed to :ref:`aws_az_info <aws_az_info_module>`.
* The ``aws_caller_facts`` module was renamed to :ref:`aws_caller_info <aws_caller_info_module>`.
* The ``aws_kms_facts`` module was renamed to :ref:`aws_kms_info <aws_kms_info_module>`.
* The ``aws_region_facts`` module was renamed to :ref:`aws_region_info <aws_region_info_module>`.
* The ``aws_sgw_facts`` module was renamed to :ref:`aws_sgw_info <aws_sgw_info_module>`.
* The ``aws_waf_facts`` module was renamed to :ref:`aws_waf_info <aws_waf_info_module>`.
* The ``cloudwatchlogs_log_group_facts`` module was renamed to :ref:`cloudwatchlogs_log_group_info <cloudwatchlogs_log_group_info_module>`.
* The ``ec2_ami_facts`` module was renamed to :ref:`ec2_ami_info <ec2_ami_info_module>`.
* The ``ec2_asg_facts`` module was renamed to :ref:`ec2_asg_info <ec2_asg_info_module>`.
* The ``ec2_customer_gateway_facts`` module was renamed to :ref:`ec2_customer_gateway_info <ec2_customer_gateway_info_module>`.
* The ``ec2_eip_facts`` module was renamed to :ref:`ec2_eip_info <ec2_eip_info_module>`.
* The ``ec2_elb_facts`` module was renamed to :ref:`ec2_elb_info <ec2_elb_info_module>`.
* The ``ec2_eni_facts`` module was renamed to :ref:`ec2_eni_info <ec2_eni_info_module>`.
* The ``ec2_group_facts`` module was renamed to :ref:`ec2_group_info <ec2_group_info_module>`.
* The ``ec2_instance_facts`` module was renamed to :ref:`ec2_instance_info <ec2_instance_info_module>`.
* The ``ec2_lc_facts`` module was renamed to :ref:`ec2_lc_info <ec2_lc_info_module>`.
* The ``ec2_placement_group_facts`` module was renamed to :ref:`ec2_placement_group_info <ec2_placement_group_info_module>`.
* The ``ec2_snapshot_facts`` module was renamed to :ref:`ec2_snapshot_info <ec2_snapshot_info_module>`.
* The ``ec2_vol_facts`` module was renamed to :ref:`ec2_vol_info <ec2_vol_info_module>`.
* The ``ec2_vpc_dhcp_option_facts`` module was renamed to :ref:`ec2_vpc_dhcp_option_info <ec2_vpc_dhcp_option_info_module>`.
* The ``ec2_vpc_endpoint_facts`` module was renamed to :ref:`ec2_vpc_endpoint_info <ec2_vpc_endpoint_info_module>`.
* The ``ec2_vpc_igw_facts`` module was renamed to :ref:`ec2_vpc_igw_info <ec2_vpc_igw_info_module>`.
* The ``ec2_vpc_nacl_facts`` module was renamed to :ref:`ec2_vpc_nacl_info <ec2_vpc_nacl_info_module>`.
* The ``ec2_vpc_nat_gateway_facts`` module was renamed to :ref:`ec2_vpc_nat_gateway_info <ec2_vpc_nat_gateway_info_module>`.
* The ``ec2_vpc_net_facts`` module was renamed to :ref:`ec2_vpc_net_info <ec2_vpc_net_info_module>`.
* The ``ec2_vpc_peering_facts`` module was renamed to :ref:`ec2_vpc_peering_info <ec2_vpc_peering_info_module>`.
* The ``ec2_vpc_route_table_facts`` module was renamed to :ref:`ec2_vpc_route_table_info <ec2_vpc_route_table_info_module>`.
* The ``ec2_vpc_subnet_facts`` module was renamed to :ref:`ec2_vpc_subnet_info <ec2_vpc_subnet_info_module>`.
* The ``ec2_vpc_vgw_facts`` module was renamed to :ref:`ec2_vpc_vgw_info <ec2_vpc_vgw_info_module>`.
* The ``ec2_vpc_vpn_facts`` module was renamed to :ref:`ec2_vpc_vpn_info <ec2_vpc_vpn_info_module>`.
* The ``elasticache_facts`` module was renamed to :ref:`elasticache_info <elasticache_info_module>`.
* The ``elb_application_lb_facts`` module was renamed to :ref:`elb_application_lb_info <elb_application_lb_info_module>`.
* The ``elb_classic_lb_facts`` module was renamed to :ref:`elb_classic_lb_info <elb_classic_lb_info_module>`.
* The ``elb_target_facts`` module was renamed to :ref:`elb_target_info <elb_target_info_module>`.
* The ``elb_target_group_facts`` module was renamed to :ref:`elb_target_group_info <elb_target_group_info_module>`.
* The ``iam_mfa_device_facts`` module was renamed to :ref:`iam_mfa_device_info <iam_mfa_device_info_module>`.
* The ``iam_role_facts`` module was renamed to :ref:`iam_role_info <iam_role_info_module>`.
* The ``iam_server_certificate_facts`` module was renamed to :ref:`iam_server_certificate_info <iam_server_certificate_info_module>`.
* The ``rds_instance_facts`` module was renamed to :ref:`rds_instance_info <rds_instance_info_module>`.
* The ``rds_snapshot_facts`` module was renamed to :ref:`rds_snapshot_info <rds_snapshot_info_module>`.
* The ``redshift_facts`` module was renamed to :ref:`redshift_info <redshift_info_module>`.
* The ``route53_facts`` module was renamed to :ref:`route53_info <route53_info_module>`.
Plugins
=======
No notable changes
Porting custom scripts
======================
No notable changes
Networking
==========
No notable changes
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,370 |
Allow mysql_db module to create/drop multiple databases
|
##### SUMMARY
mysql_db module should be able to create/drop multiple databases
##### ISSUE TYPE
- Feature Idea
##### COMPONENT NAME
lib/ansible/modules/database/mysql/mysql_db.py
##### ADDITIONAL INFORMATION
Why and what it would solve:
Avoids repetitive tasks to create/delete more than one databases (similar to https://github.com/ansible/ansible/issues/56059)
<!--- Paste example playbooks or commands between quotes below -->
- Create (Multiple databases)
```yaml
tasks:
- name: Create multiple databases (provided in comma separated form)
mysql_db:
name: bobdata, bobthebuilder
state: present
- name: Create multiple databases (provided in list form)
mysql_db:
name:
- bobdata
- bobthebuilder
state: present
```
- Delete/Drop (Multiple databases)
```yaml
- name: Delete/drop multiple databases (provided in comma separated form)
mysql_db:
name: bobdata, bobthebuilder
state: absent
- name: Delete/drop multiple databases (provided in list form)
mysql_db:
name:
- bobdata
- bobthebuilder
state: absent
```
Credits for the idea to @Andersson007 from comment https://github.com/ansible/ansible/pull/56721#issuecomment-505128646
|
https://github.com/ansible/ansible/issues/58370
|
https://github.com/ansible/ansible/pull/58602
|
cdf0947df092fb9883a13bca13a120ff29cacfc5
|
393e4a41d08c9654279215094630ed2e7f84d8d1
| 2019-06-26T04:04:27Z |
python
| 2019-07-18T14:56:32Z |
lib/ansible/modules/database/mysql/mysql_db.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2012, Mark Theunissen <[email protected]>
# Sponsored by Four Kitchens http://fourkitchens.com.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: mysql_db
short_description: Add or remove MySQL databases from a remote host.
description:
- Add or remove MySQL databases from a remote host.
version_added: "0.6"
options:
name:
description:
- name of the database to add or remove.
- I(name=all) May only be provided if I(state) is C(dump) or C(import).
- List of databases is provided with I(state=dump) only.
- if name=all Works like --all-databases option for mysqldump (Added in 2.0).
required: true
type: list
aliases: [ db ]
state:
description:
- The database state
default: present
choices: [ "present", "absent", "dump", "import" ]
collation:
description:
- Collation mode (sorting). This only applies to new table/databases and does not update existing ones, this is a limitation of MySQL.
encoding:
description:
- Encoding mode to use, examples include C(utf8) or C(latin1_swedish_ci)
target:
description:
- Location, on the remote host, of the dump file to read from or write to. Uncompressed SQL
files (C(.sql)) as well as bzip2 (C(.bz2)), gzip (C(.gz)) and xz (Added in 2.0) compressed files are supported.
single_transaction:
description:
- Execute the dump in a single transaction
type: bool
default: 'no'
version_added: "2.1"
quick:
description:
- Option used for dumping large tables
type: bool
default: 'yes'
version_added: "2.1"
ignore_tables:
description:
- A list of table names that will be ignored in the dump of the form database_name.table_name
required: false
default: []
version_added: "2.7"
author: "Ansible Core Team"
requirements:
- mysql (command line binary)
- mysqldump (command line binary)
notes:
- Requires the mysql and mysqldump binaries on the remote host.
- This module is B(not idempotent) when I(state) is C(import), and will import the dump file each time if run more than once.
extends_documentation_fragment: mysql
'''
EXAMPLES = r'''
- name: Create a new database with name 'bobdata'
mysql_db:
name: bobdata
state: present
# Copy database dump file to remote host and restore it to database 'my_db'
- name: Copy database dump file
copy:
src: dump.sql.bz2
dest: /tmp
- name: Restore database
mysql_db:
name: my_db
state: import
target: /tmp/dump.sql.bz2
- name: Dump multiple databases
mysql_db:
state: dump
name: db_1,db_2
target: /tmp/dump.sql
- name: Dump multiple databases
mysql_db:
state: dump
name:
- db_1
- db_2
target: /tmp/dump.sql
- name: Dump all databases to hostname.sql
mysql_db:
state: dump
name: all
target: /tmp/dump.sql
- name: Import file.sql similar to mysql -u <username> -p <password> < hostname.sql
mysql_db:
state: import
name: all
target: /tmp/dump.sql
'''
import os
import subprocess
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.database import mysql_quote_identifier
from ansible.module_utils.mysql import mysql_connect, mysql_driver, mysql_driver_fail_msg
from ansible.module_utils.six.moves import shlex_quote
from ansible.module_utils._text import to_native
# ===========================================
# MySQL module specific support methods.
#
def db_exists(cursor, db):
res = 0
for each_db in db:
res += cursor.execute("SHOW DATABASES LIKE %s", (each_db.strip().replace("_", r"\_"),))
return res == len(db)
def db_delete(cursor, db):
query = "DROP DATABASE %s" % mysql_quote_identifier(''.join(db), 'database')
cursor.execute(query)
return True
def db_dump(module, host, user, password, db_name, target, all_databases, port, config_file, socket=None, ssl_cert=None, ssl_key=None, ssl_ca=None,
single_transaction=None, quick=None, ignore_tables=None):
cmd = module.get_bin_path('mysqldump', True)
# If defined, mysqldump demands --defaults-extra-file be the first option
if config_file:
cmd += " --defaults-extra-file=%s" % shlex_quote(config_file)
if user is not None:
cmd += " --user=%s" % shlex_quote(user)
if password is not None:
cmd += " --password=%s" % shlex_quote(password)
if ssl_cert is not None:
cmd += " --ssl-cert=%s" % shlex_quote(ssl_cert)
if ssl_key is not None:
cmd += " --ssl-key=%s" % shlex_quote(ssl_key)
if ssl_ca is not None:
cmd += " --ssl-ca=%s" % shlex_quote(ssl_ca)
if socket is not None:
cmd += " --socket=%s" % shlex_quote(socket)
else:
cmd += " --host=%s --port=%i" % (shlex_quote(host), port)
if all_databases:
cmd += " --all-databases"
else:
cmd += " --databases {0} --skip-lock-tables".format(' '.join(db_name))
if single_transaction:
cmd += " --single-transaction=true"
if quick:
cmd += " --quick"
if ignore_tables:
for an_ignored_table in ignore_tables:
cmd += " --ignore-table={0}".format(an_ignored_table)
path = None
if os.path.splitext(target)[-1] == '.gz':
path = module.get_bin_path('gzip', True)
elif os.path.splitext(target)[-1] == '.bz2':
path = module.get_bin_path('bzip2', True)
elif os.path.splitext(target)[-1] == '.xz':
path = module.get_bin_path('xz', True)
if path:
cmd = '%s | %s > %s' % (cmd, path, shlex_quote(target))
else:
cmd += " > %s" % shlex_quote(target)
rc, stdout, stderr = module.run_command(cmd, use_unsafe_shell=True)
return rc, stdout, stderr
def db_import(module, host, user, password, db_name, target, all_databases, port, config_file, socket=None, ssl_cert=None, ssl_key=None, ssl_ca=None):
if not os.path.exists(target):
return module.fail_json(msg="target %s does not exist on the host" % target)
cmd = [module.get_bin_path('mysql', True)]
# --defaults-file must go first, or errors out
if config_file:
cmd.append("--defaults-extra-file=%s" % shlex_quote(config_file))
if user:
cmd.append("--user=%s" % shlex_quote(user))
if password:
cmd.append("--password=%s" % shlex_quote(password))
if ssl_cert is not None:
cmd.append("--ssl-cert=%s" % shlex_quote(ssl_cert))
if ssl_key is not None:
cmd.append("--ssl-key=%s" % shlex_quote(ssl_key))
if ssl_ca is not None:
cmd.append("--ssl-ca=%s" % shlex_quote(ssl_ca))
if socket is not None:
cmd.append("--socket=%s" % shlex_quote(socket))
else:
cmd.append("--host=%s" % shlex_quote(host))
cmd.append("--port=%i" % port)
if not all_databases:
cmd.append("-D")
cmd.append(shlex_quote(''.join(db_name)))
comp_prog_path = None
if os.path.splitext(target)[-1] == '.gz':
comp_prog_path = module.get_bin_path('gzip', required=True)
elif os.path.splitext(target)[-1] == '.bz2':
comp_prog_path = module.get_bin_path('bzip2', required=True)
elif os.path.splitext(target)[-1] == '.xz':
comp_prog_path = module.get_bin_path('xz', required=True)
if comp_prog_path:
p1 = subprocess.Popen([comp_prog_path, '-dc', target], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p2 = subprocess.Popen(cmd, stdin=p1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout2, stderr2) = p2.communicate()
p1.stdout.close()
p1.wait()
if p1.returncode != 0:
stderr1 = p1.stderr.read()
return p1.returncode, '', stderr1
else:
return p2.returncode, stdout2, stderr2
else:
cmd = ' '.join(cmd)
cmd += " < %s" % shlex_quote(target)
rc, stdout, stderr = module.run_command(cmd, use_unsafe_shell=True)
return rc, stdout, stderr
def db_create(cursor, db, encoding, collation):
query_params = dict(enc=encoding, collate=collation)
query = ['CREATE DATABASE %s' % mysql_quote_identifier(''.join(db), 'database')]
if encoding:
query.append("CHARACTER SET %(enc)s")
if collation:
query.append("COLLATE %(collate)s")
query = ' '.join(query)
cursor.execute(query, query_params)
return True
# ===========================================
# Module execution.
#
def main():
module = AnsibleModule(
argument_spec=dict(
login_user=dict(type='str'),
login_password=dict(type='str', no_log=True),
login_host=dict(type='str', default='localhost'),
login_port=dict(type='int', default=3306),
login_unix_socket=dict(type='str'),
name=dict(type='list', required=True, aliases=['db']),
encoding=dict(type='str', default=''),
collation=dict(type='str', default=''),
target=dict(type='path'),
state=dict(type='str', default='present', choices=['absent', 'dump', 'import', 'present']),
client_cert=dict(type='path', aliases=['ssl_cert']),
client_key=dict(type='path', aliases=['ssl_key']),
ca_cert=dict(type='path', aliases=['ssl_ca']),
connect_timeout=dict(type='int', default=30),
config_file=dict(type='path', default='~/.my.cnf'),
single_transaction=dict(type='bool', default=False),
quick=dict(type='bool', default=True),
ignore_tables=dict(type='list', default=[]),
),
supports_check_mode=True,
)
if mysql_driver is None:
module.fail_json(msg=mysql_driver_fail_msg)
db = module.params["name"]
if not db:
module.fail_json(msg="Please provide at least one database name")
encoding = module.params["encoding"]
collation = module.params["collation"]
state = module.params["state"]
target = module.params["target"]
socket = module.params["login_unix_socket"]
login_port = module.params["login_port"]
if login_port < 0 or login_port > 65535:
module.fail_json(msg="login_port must be a valid unix port number (0-65535)")
ssl_cert = module.params["client_cert"]
ssl_key = module.params["client_key"]
ssl_ca = module.params["ca_cert"]
connect_timeout = module.params['connect_timeout']
config_file = module.params['config_file']
login_password = module.params["login_password"]
login_user = module.params["login_user"]
login_host = module.params["login_host"]
ignore_tables = module.params["ignore_tables"]
for a_table in ignore_tables:
if a_table == "":
module.fail_json(msg="Name of ignored table cannot be empty")
single_transaction = module.params["single_transaction"]
quick = module.params["quick"]
if len(db) > 1 and state != 'dump':
module.fail_json(msg="Multiple databases is only supported with state=dump")
db_name = ' '.join(db)
if state in ['dump', 'import']:
if target is None:
module.fail_json(msg="with state=%s target is required" % state)
if db == ['all']:
db = ['mysql']
all_databases = True
else:
all_databases = False
else:
if db == ['all']:
module.fail_json(msg="name is not allowed to equal 'all' unless state equals import, or dump.")
try:
cursor = mysql_connect(module, login_user, login_password, config_file, ssl_cert, ssl_key, ssl_ca,
connect_timeout=connect_timeout)
except Exception as e:
if os.path.exists(config_file):
module.fail_json(msg="unable to connect to database, check login_user and login_password are correct or %s has the credentials. "
"Exception message: %s" % (config_file, to_native(e)))
else:
module.fail_json(msg="unable to find %s. Exception message: %s" % (config_file, to_native(e)))
changed = False
if not os.path.exists(config_file):
config_file = None
if db_exists(cursor, db):
if state == "absent":
if module.check_mode:
module.exit_json(changed=True, db=db_name)
try:
changed = db_delete(cursor, db)
except Exception as e:
module.fail_json(msg="error deleting database: %s" % to_native(e))
module.exit_json(changed=changed, db=db_name)
elif state == "dump":
if module.check_mode:
module.exit_json(changed=True, db=db_name)
rc, stdout, stderr = db_dump(module, login_host, login_user,
login_password, db, target, all_databases,
login_port, config_file, socket, ssl_cert, ssl_key,
ssl_ca, single_transaction, quick, ignore_tables)
if rc != 0:
module.fail_json(msg="%s" % stderr)
else:
module.exit_json(changed=True, db=db_name, msg=stdout)
elif state == "import":
if module.check_mode:
module.exit_json(changed=True, db=db_name)
rc, stdout, stderr = db_import(module, login_host, login_user,
login_password, db, target,
all_databases,
login_port, config_file,
socket, ssl_cert, ssl_key, ssl_ca)
if rc != 0:
module.fail_json(msg="%s" % stderr)
else:
module.exit_json(changed=True, db=db_name, msg=stdout)
elif state == "present":
module.exit_json(changed=False, db=db_name)
else:
if state == "present":
if module.check_mode:
changed = True
else:
try:
changed = db_create(cursor, db, encoding, collation)
except Exception as e:
module.fail_json(msg="error creating database: %s" % to_native(e),
exception=traceback.format_exc())
module.exit_json(changed=changed, db=db_name)
elif state == "import":
if module.check_mode:
module.exit_json(changed=True, db=db_name)
else:
try:
changed = db_create(cursor, db, encoding, collation)
if changed:
rc, stdout, stderr = db_import(module, login_host, login_user,
login_password, db, target, all_databases,
login_port, config_file, socket, ssl_cert, ssl_key, ssl_ca)
if rc != 0:
module.fail_json(msg="%s" % stderr)
else:
module.exit_json(changed=True, db=db_name, msg=stdout)
except Exception as e:
module.fail_json(msg="error creating database: %s" % to_native(e),
exception=traceback.format_exc())
elif state == "absent":
module.exit_json(changed=False, db=db_name)
elif state == "dump":
if module.check_mode:
module.exit_json(changed=False, db=db_name)
module.fail_json(msg="Cannot dump database %r - not found" % (db_name))
if __name__ == '__main__':
main()
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,370 |
Allow mysql_db module to create/drop multiple databases
|
##### SUMMARY
mysql_db module should be able to create/drop multiple databases
##### ISSUE TYPE
- Feature Idea
##### COMPONENT NAME
lib/ansible/modules/database/mysql/mysql_db.py
##### ADDITIONAL INFORMATION
Why and what it would solve:
Avoids repetitive tasks to create/delete more than one databases (similar to https://github.com/ansible/ansible/issues/56059)
<!--- Paste example playbooks or commands between quotes below -->
- Create (Multiple databases)
```yaml
tasks:
- name: Create multiple databases (provided in comma separated form)
mysql_db:
name: bobdata, bobthebuilder
state: present
- name: Create multiple databases (provided in list form)
mysql_db:
name:
- bobdata
- bobthebuilder
state: present
```
- Delete/Drop (Multiple databases)
```yaml
- name: Delete/drop multiple databases (provided in comma separated form)
mysql_db:
name: bobdata, bobthebuilder
state: absent
- name: Delete/drop multiple databases (provided in list form)
mysql_db:
name:
- bobdata
- bobthebuilder
state: absent
```
Credits for the idea to @Andersson007 from comment https://github.com/ansible/ansible/pull/56721#issuecomment-505128646
|
https://github.com/ansible/ansible/issues/58370
|
https://github.com/ansible/ansible/pull/58602
|
cdf0947df092fb9883a13bca13a120ff29cacfc5
|
393e4a41d08c9654279215094630ed2e7f84d8d1
| 2019-06-26T04:04:27Z |
python
| 2019-07-18T14:56:32Z |
test/integration/targets/mysql_db/tasks/main.yml
|
# test code for the mysql_db module
# (c) 2014, Wayne Rosario <[email protected]>
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# ============================================================
- name: remove database if it exists
command: >
mysql -sse "drop database {{db_name}};"
ignore_errors: True
- name: make sure the test database is not there
command: mysql {{db_name}}
register: mysql_db_check
failed_when: "'1049' not in mysql_db_check.stderr"
- name: test state=present for a database name (expect changed=true)
mysql_db:
name: '{{ db_name }}'
state: present
login_unix_socket: '{{ mysql_socket }}'
register: result
- name: assert output message that database exist
assert:
that:
- "result.changed == true"
- "result.db =='{{ db_name }}'"
- name: run command to test state=present for a database name (expect db_name in stdout)
command: mysql "-e show databases like '{{ db_name }}';"
register: result
- name: assert database exist
assert: { that: "'{{ db_name }}' in result.stdout" }
# ============================================================
- name: test state=absent for a database name (expect changed=true)
mysql_db:
name: '{{ db_name }}'
state: absent
login_unix_socket: '{{ mysql_socket }}'
register: result
- name: assert output message that database does not exist
assert:
that:
- "result.changed == true"
- "result.db =='{{ db_name }}'"
- name: run command to test state=absent for a database name (expect db_name not in stdout)
command: mysql "-e show databases like '{{ db_name }}';"
register: result
- name: assert database does not exist
assert: { that: "'{{ db_name }}' not in result.stdout" }
# ============================================================
- name: test mysql_db encoding param not valid - issue 8075
mysql_db:
name: datanotvalid
state: present
encoding: notvalid
login_unix_socket: '{{ mysql_socket }}'
register: result
ignore_errors: true
- name: assert test mysql_db encoding param not valid - issue 8075 (failed=true)
assert:
that:
- "result.failed == true"
- "'Traceback' not in result.msg"
- "'Unknown character set' in result.msg"
# ============================================================
- name: test mysql_db using a valid encoding utf8 (expect changed=true)
mysql_db:
name: 'en{{ db_name }}'
state: present
encoding: utf8
login_unix_socket: '{{ mysql_socket }}'
register: result
- name: assert output message created a database
assert: { that: "result.changed == true" }
- name: test database was created
command: mysql "-e SHOW CREATE DATABASE en{{ db_name }};"
register: result
- name: assert created database is of encoding utf8
assert: { that: "'utf8' in result.stdout" }
- name: remove database
mysql_db:
name: 'en{{ db_name }}'
state: absent
login_unix_socket: '{{ mysql_socket }}'
# ============================================================
- name: test mysql_db using valid encoding binary (expect changed=true)
mysql_db:
name: 'en{{ db_name }}'
state: present
encoding: binary
login_unix_socket: '{{ mysql_socket }}'
register: result
- name: assert output message that database was created
assert: { that: "result.changed == true" }
- name: run command to test database was created
command: mysql "-e SHOW CREATE DATABASE en{{ db_name }};"
register: result
- name: assert created database is of encoding binary
assert: { that: "'binary' in result.stdout" }
- name: remove database
mysql_db:
name: 'en{{ db_name }}'
state: absent
login_unix_socket: '{{ mysql_socket }}'
# ============================================================
- name: create user1 to access database dbuser1
mysql_user:
name: user1
password: 'Hfd6fds^dfA8Ga'
priv: '*.*:ALL'
state: present
login_unix_socket: '{{ mysql_socket }}'
- name: create database dbuser1 using user1
mysql_db:
name: '{{ db_user1 }}'
state: present
login_user: user1
login_password: 'Hfd6fds^dfA8Ga'
register: result
- name: assert output message that database was created
assert: { that: "result.changed == true" }
- name: run command to test database was created using user1
command: mysql "-e show databases like '{{ db_user1 }}';"
register: result
- name: assert database exist
assert: { that: "'{{ db_user1 }}' in result.stdout" }
# ============================================================
- name: create user2 to access database with privilege select only
mysql_user:
name: user2
password: 'kjsfd&F7safjad'
priv: '*.*:SELECT'
state: present
login_unix_socket: '{{ mysql_socket }}'
- name: create database dbuser2 using user2 with no privilege to create (expect failed=true)
mysql_db:
name: '{{ db_user2 }}'
state: present
login_user: user2
login_password: 'kjsfd&F7safjad'
register: result
ignore_errors: true
- name: assert output message that database was not created using dbuser2
assert:
that:
- "result.failed == true"
- "'Access denied' in result.msg"
- name: run command to test that database was not created
command: mysql "-e show databases like '{{ db_user2 }}';"
register: result
- name: assert database does not exist
assert: { that: "'{{ db_user2 }}' not in result.stdout" }
# ============================================================
- name: delete database using user2 with no privilege to delete (expect failed=true)
mysql_db:
name: '{{ db_user1 }}'
state: absent
login_user: user2
login_password: 'kjsfd&F7safjad'
register: result
ignore_errors: true
- name: assert output message that database was not deleted using dbuser2
assert:
that:
- "result.failed == true"
- "'Access denied' in result.msg"
- name: run command to test database was not deleted
command: mysql "-e show databases like '{{ db_user1 }}';"
register: result
- name: assert database still exist
assert: { that: "'{{ db_user1 }}' in result.stdout" }
# ============================================================
- name: delete database using user1 with all privilege to delete a database (expect changed=true)
mysql_db:
name: '{{ db_user1 }}'
state: absent
login_user: user1
login_password: 'Hfd6fds^dfA8Ga'
register: result
ignore_errors: true
- name: assert output message that database was deleted using user1
assert: { that: "result.changed == true" }
- name: run command to test database was deleted using user1
command: mysql "-e show databases like '{{ db_name }}';"
register: result
- name: assert database does not exist
assert: { that: "'{{ db_user1 }}' not in result.stdout" }
# ============================================================
- include: state_dump_import.yml format_type=sql file=dbdata.sql format_msg_type=ASCII file2=dump2.sql file3=dump3.sql
- include: state_dump_import.yml format_type=gz file=dbdata.gz format_msg_type=gzip file2=dump2.gz file3=dump3.gz
- include: state_dump_import.yml format_type=bz2 file=dbdata.bz2 format_msg_type=bzip2 file2=dump2.bz2 file3=dump3.bz2
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,370 |
Allow mysql_db module to create/drop multiple databases
|
##### SUMMARY
mysql_db module should be able to create/drop multiple databases
##### ISSUE TYPE
- Feature Idea
##### COMPONENT NAME
lib/ansible/modules/database/mysql/mysql_db.py
##### ADDITIONAL INFORMATION
Why and what it would solve:
Avoids repetitive tasks to create/delete more than one databases (similar to https://github.com/ansible/ansible/issues/56059)
<!--- Paste example playbooks or commands between quotes below -->
- Create (Multiple databases)
```yaml
tasks:
- name: Create multiple databases (provided in comma separated form)
mysql_db:
name: bobdata, bobthebuilder
state: present
- name: Create multiple databases (provided in list form)
mysql_db:
name:
- bobdata
- bobthebuilder
state: present
```
- Delete/Drop (Multiple databases)
```yaml
- name: Delete/drop multiple databases (provided in comma separated form)
mysql_db:
name: bobdata, bobthebuilder
state: absent
- name: Delete/drop multiple databases (provided in list form)
mysql_db:
name:
- bobdata
- bobthebuilder
state: absent
```
Credits for the idea to @Andersson007 from comment https://github.com/ansible/ansible/pull/56721#issuecomment-505128646
|
https://github.com/ansible/ansible/issues/58370
|
https://github.com/ansible/ansible/pull/58602
|
cdf0947df092fb9883a13bca13a120ff29cacfc5
|
393e4a41d08c9654279215094630ed2e7f84d8d1
| 2019-06-26T04:04:27Z |
python
| 2019-07-18T14:56:32Z |
test/integration/targets/mysql_db/tasks/multi_db_create_delete.yml
| |
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,370 |
Allow mysql_db module to create/drop multiple databases
|
##### SUMMARY
mysql_db module should be able to create/drop multiple databases
##### ISSUE TYPE
- Feature Idea
##### COMPONENT NAME
lib/ansible/modules/database/mysql/mysql_db.py
##### ADDITIONAL INFORMATION
Why and what it would solve:
Avoids repetitive tasks to create/delete more than one databases (similar to https://github.com/ansible/ansible/issues/56059)
<!--- Paste example playbooks or commands between quotes below -->
- Create (Multiple databases)
```yaml
tasks:
- name: Create multiple databases (provided in comma separated form)
mysql_db:
name: bobdata, bobthebuilder
state: present
- name: Create multiple databases (provided in list form)
mysql_db:
name:
- bobdata
- bobthebuilder
state: present
```
- Delete/Drop (Multiple databases)
```yaml
- name: Delete/drop multiple databases (provided in comma separated form)
mysql_db:
name: bobdata, bobthebuilder
state: absent
- name: Delete/drop multiple databases (provided in list form)
mysql_db:
name:
- bobdata
- bobthebuilder
state: absent
```
Credits for the idea to @Andersson007 from comment https://github.com/ansible/ansible/pull/56721#issuecomment-505128646
|
https://github.com/ansible/ansible/issues/58370
|
https://github.com/ansible/ansible/pull/58602
|
cdf0947df092fb9883a13bca13a120ff29cacfc5
|
393e4a41d08c9654279215094630ed2e7f84d8d1
| 2019-06-26T04:04:27Z |
python
| 2019-07-18T14:56:32Z |
test/integration/targets/mysql_db/tasks/state_dump_import.yml
|
# test code for state dump and import for mysql_db module
# (c) 2014, Wayne Rosario <[email protected]>
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# ============================================================
- set_fact:
db_file_name="{{tmp_dir}}/{{file}}"
dump_file1="{{tmp_dir}}/{{file2}}"
dump_file2="{{tmp_dir}}/{{file3}}"
- name: state dump/import - create database
mysql_db:
name: '{{ db_name }}'
state: present
login_unix_socket: '{{ mysql_socket }}'
- name: create database
mysql_db:
name: '{{ db_name2 }}'
state: present
login_unix_socket: '{{ mysql_socket }}'
- name: state dump/import - create table department
command: mysql {{ db_name }} '-e create table department(id int, name varchar(100));'
- name: state dump/import - create table employee
command: mysql {{ db_name }} '-e create table employee(id int, name varchar(100));'
- name: state dump/import - insert data into table employee
command: mysql {{ db_name }} "-e insert into employee value(47,'Joe Smith');"
- name: state dump/import - insert data into table department
command: mysql {{ db_name }} "-e insert into department value(2,'Engineering');"
- name: state dump/import - file name should not exist
file: name={{ db_file_name }} state=absent
- name: database dump file1 should not exist
file: name={{ dump_file1 }} state=absent
- name: database dump file2 should not exist
file: name={{ dump_file2 }} state=absent
- name: state dump without department table.
mysql_db:
name: "{{ db_name }}"
state: dump
target: "{{ db_file_name }}"
ignore_tables:
- "{{ db_name }}.department"
login_unix_socket: '{{ mysql_socket }}'
register: result
- name: assert successful completion of dump operation
assert:
that:
- "result.changed == true"
- name: state dump/import - file name should exist
file: name={{ db_file_name }} state=file
- name: state dump with multiple databases in comma separated form.
mysql_db:
name: "{{ db_name }},{{ db_name2 }}"
state: dump
target: "{{ dump_file1 }}"
login_unix_socket: '{{ mysql_socket }}'
register: dump_result1
- name: assert successful completion of dump operation (with multiple databases in comma separated form)
assert:
that:
- "dump_result1.changed == true"
- name: state dump - dump file1 should exist
file: name={{ dump_file1 }} state=file
- name: state dump with multiple databases in list form via check_mode
mysql_db:
name:
- "{{ db_name }}"
- "{{ db_name2 }}"
state: dump
target: "{{ dump_file2 }}"
login_unix_socket: '{{ mysql_socket }}'
register: dump_result
check_mode: yes
- name: assert successful completion of dump operation (with multiple databases in list form) via check mode
assert:
that:
- "dump_result.changed == true"
- name: database dump file2 should not exist
stat:
path: "{{ dump_file2 }}"
register: stat_result
- name: assert that check_mode does not create dump file for databases
assert:
that:
- stat_result.stat.exists is defined and not stat_result.stat.exists
- name: state dump with multiple databases in list form.
mysql_db:
name:
- "{{ db_name }}"
- "{{ db_name2 }}"
state: dump
target: "{{ dump_file2 }}"
login_unix_socket: '{{ mysql_socket }}'
register: dump_result2
- name: assert successful completion of dump operation (with multiple databases in list form)
assert:
that:
- "dump_result2.changed == true"
- name: state dump - dump file2 should exist
file: name={{ dump_file2 }} state=file
- name: state dump/import - remove database
mysql_db:
name: '{{ db_name }}'
state: absent
login_unix_socket: '{{ mysql_socket }}'
- name: remove database
mysql_db:
name: '{{ db_name2 }}'
state: absent
login_unix_socket: '{{ mysql_socket }}'
- name: test state=import to restore the database of type {{ format_type }} (expect changed=true)
mysql_db:
name: '{{ db_name }}'
state: import
target: '{{ db_file_name }}'
login_unix_socket: '{{ mysql_socket }}'
register: result
- name: show the tables
command: mysql {{ db_name }} "-e show tables;"
register: result
- name: assert that the department table is absent.
assert:
that:
- "'department' not in result.stdout"
- name: test state=import to restore a database from multiple database dumped file1
mysql_db:
name: '{{ db_name2 }}'
state: import
target: '{{ dump_file1 }}'
login_unix_socket: '{{ mysql_socket }}'
register: import_result
- name: assert output message restored a database from dump file1
assert: { that: "import_result.changed == true" }
- name: remove database
mysql_db:
name: '{{ db_name2 }}'
state: absent
login_unix_socket: '{{ mysql_socket }}'
- name: test state=import to restore a database from multiple database dumped file2
mysql_db:
name: '{{ db_name2 }}'
state: import
target: '{{ dump_file2 }}'
login_unix_socket: '{{ mysql_socket }}'
register: import_result2
- name: assert output message restored a database from dump file2
assert: { that: "import_result2.changed == true" }
- name: test state=dump to backup the database of type {{ format_type }} (expect changed=true)
mysql_db:
name: '{{ db_name }}'
state: dump
target: '{{ db_file_name }}'
login_unix_socket: '{{ mysql_socket }}'
register: result
- name: assert output message backup the database
assert:
that:
- "result.changed == true"
- "result.db =='{{ db_name }}'"
- name: assert database was backed up successfully
command: file {{ db_file_name }}
register: result
- name: assert file format type
assert: { that: "'{{format_msg_type}}' in result.stdout" }
- name: update database table employee
command: mysql {{ db_name }} "-e update employee set name='John Doe' where id=47;"
- name: test state=import to restore the database of type {{ format_type }} (expect changed=true)
mysql_db:
name: '{{ db_name }}'
state: import
target: '{{ db_file_name }}'
login_unix_socket: '{{ mysql_socket }}'
register: result
- name: assert output message restore the database
assert: { that: "result.changed == true" }
- name: select data from table employee
command: mysql {{ db_name }} "-e select * from employee;"
register: result
- name: assert data in database is from the restore database
assert:
that:
- "'47' in result.stdout"
- "'Joe Smith' in result.stdout"
- name: remove database name
mysql_db:
name: '{{ db_name }}'
state: absent
login_unix_socket: '{{ mysql_socket }}'
- name: remove database
mysql_db:
name: '{{ db_name2 }}'
state: absent
login_unix_socket: '{{ mysql_socket }}'
- name: remove file name
file: name={{ db_file_name }} state=absent
- name: remove dump file1
file: name={{ dump_file1 }} state=absent
- name: remove dump file2
file: name={{ dump_file2 }} state=absent
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,876 |
assigning variable to remote_user in loop only works first time
|
<!--- Verify first that your issue is not already reported on GitHub -->
it is not
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
<!--- Explain the problem briefly below -->
I have a loop which tries to assign a user to remote_user in my playbook. The first assignment works, subsequent ones do not and the first assignment is used in subsequent iterations of the loop
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
ssh connection plugin perhaps? or the calling of it
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.8.1
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/bi003do/.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
python version = 2.7.5 (default, Apr 9 2019, 14:30:50) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
DEFAULT_TIMEOUT(/etc/ansible/ansible.cfg) = 30
HOST_KEY_CHECKING(/etc/ansible/ansible.cfg) = False
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
target OS is AWS Linux instances of various flavors
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
run the following playbook using inventory file with a single known linux host with user: ec2-user
```ini
[test]
xxx.xxx.xxx.xxx
```
<!--- Paste example playbooks or commands between quotes below -->
```yaml
---
- hosts: test
gather_facts: false
tasks:
- name: try users
remote_user: "{{ item }}"
ping:
ignore_unreachable: true
failed_when: false
with_items:
- centos
- ec2-user
- root
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
I would expect this to loop 3 times trying to ping with the 3 users listed in with_items above
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
```
ansible-playbook TryUsers.yml -i inventory -vvvv
First iteration
<xxx.xxx.xxx.xxx> ESTABLISH SSH CONNECTION FOR USER: centos
Second iteration
<xxx.xxx.xxx.xxx> ESTABLISH SSH CONNECTION FOR USER: centos
third iteration
<xxx.xxx.xxx.xxx> ESTABLISH SSH CONNECTION FOR USER: centos
```
<!--- Paste verbatim command output between quotes -->
```
bi003do@usbou-ansible TryUsers]$ ansible-playbook TryUsers.yml -i inventory
PLAY [test] *********************************************************************************************************************************************************************************
TASK [try users] ****************************************************************************************************************************************************************************
failed: [xxx.xxx.xxx.xxx] (item=centos) => {"ansible_loop_var": "item", "item": "centos", "msg": "Failed to connect to the host via ssh: Permission denied (publickey,password).", "unreachable": true}
failed: [10.5.162.71] (item=root) => {"ansible_loop_var": "item", "item": "root", "msg": "Failed to connect to the host via ssh: Permission denied (publickey,password).", "unreachable": true}
failed: [10.5.162.71] (item=ec2-user) => {"ansible_loop_var": "item", "item": "ec2-user", "msg": "Failed to connect to the host via ssh: Permission denied (publickey,password).", "unreachable": true}
fatal: [10.5.162.71]: UNREACHABLE! => {"changed": false, "msg": "All items completed", "results": [{"ansible_loop_var": "item", "item": "centos", "msg": "Failed to connect to the host via ssh: Permission denied (publickey,password).", "unreachable": true}, {"ansible_loop_var": "item", "item": "root", "msg": "Failed to connect to the host via ssh: Permission denied (publickey,password).", "unreachable": true}, {"ansible_loop_var": "item", "item": "ec2-user", "msg": "Failed to connect to the host via ssh: Permission denied (publickey,password).", "unreachable": true}], "skip_reason": "Host 10.5.162.71 is unreachable"}
PLAY RECAP **********************************************************************************************************************************************************************************
10.5.162.71 : ok=0 changed=0 unreachable=1 failed=0 skipped=1 rescued=0 ignored=0
```
|
https://github.com/ansible/ansible/issues/58876
|
https://github.com/ansible/ansible/pull/59024
|
da047eec59e8e8f0555053d850ae2b7bfb2ef8ab
|
a752e2a4670f3b87a570f03d9b2719f8412ad575
| 2019-07-09T16:26:35Z |
python
| 2019-07-19T06:39:05Z |
changelogs/fragments/58876-do-not-reuse-remote_user-from-prev-loop.yaml
| |
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,876 |
assigning variable to remote_user in loop only works first time
|
<!--- Verify first that your issue is not already reported on GitHub -->
it is not
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
<!--- Explain the problem briefly below -->
I have a loop which tries to assign a user to remote_user in my playbook. The first assignment works, subsequent ones do not and the first assignment is used in subsequent iterations of the loop
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
ssh connection plugin perhaps? or the calling of it
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.8.1
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/bi003do/.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
python version = 2.7.5 (default, Apr 9 2019, 14:30:50) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
DEFAULT_TIMEOUT(/etc/ansible/ansible.cfg) = 30
HOST_KEY_CHECKING(/etc/ansible/ansible.cfg) = False
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
target OS is AWS Linux instances of various flavors
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
run the following playbook using inventory file with a single known linux host with user: ec2-user
```ini
[test]
xxx.xxx.xxx.xxx
```
<!--- Paste example playbooks or commands between quotes below -->
```yaml
---
- hosts: test
gather_facts: false
tasks:
- name: try users
remote_user: "{{ item }}"
ping:
ignore_unreachable: true
failed_when: false
with_items:
- centos
- ec2-user
- root
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
I would expect this to loop 3 times trying to ping with the 3 users listed in with_items above
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
```
ansible-playbook TryUsers.yml -i inventory -vvvv
First iteration
<xxx.xxx.xxx.xxx> ESTABLISH SSH CONNECTION FOR USER: centos
Second iteration
<xxx.xxx.xxx.xxx> ESTABLISH SSH CONNECTION FOR USER: centos
third iteration
<xxx.xxx.xxx.xxx> ESTABLISH SSH CONNECTION FOR USER: centos
```
<!--- Paste verbatim command output between quotes -->
```
bi003do@usbou-ansible TryUsers]$ ansible-playbook TryUsers.yml -i inventory
PLAY [test] *********************************************************************************************************************************************************************************
TASK [try users] ****************************************************************************************************************************************************************************
failed: [xxx.xxx.xxx.xxx] (item=centos) => {"ansible_loop_var": "item", "item": "centos", "msg": "Failed to connect to the host via ssh: Permission denied (publickey,password).", "unreachable": true}
failed: [10.5.162.71] (item=root) => {"ansible_loop_var": "item", "item": "root", "msg": "Failed to connect to the host via ssh: Permission denied (publickey,password).", "unreachable": true}
failed: [10.5.162.71] (item=ec2-user) => {"ansible_loop_var": "item", "item": "ec2-user", "msg": "Failed to connect to the host via ssh: Permission denied (publickey,password).", "unreachable": true}
fatal: [10.5.162.71]: UNREACHABLE! => {"changed": false, "msg": "All items completed", "results": [{"ansible_loop_var": "item", "item": "centos", "msg": "Failed to connect to the host via ssh: Permission denied (publickey,password).", "unreachable": true}, {"ansible_loop_var": "item", "item": "root", "msg": "Failed to connect to the host via ssh: Permission denied (publickey,password).", "unreachable": true}, {"ansible_loop_var": "item", "item": "ec2-user", "msg": "Failed to connect to the host via ssh: Permission denied (publickey,password).", "unreachable": true}], "skip_reason": "Host 10.5.162.71 is unreachable"}
PLAY RECAP **********************************************************************************************************************************************************************************
10.5.162.71 : ok=0 changed=0 unreachable=1 failed=0 skipped=1 rescued=0 ignored=0
```
|
https://github.com/ansible/ansible/issues/58876
|
https://github.com/ansible/ansible/pull/59024
|
da047eec59e8e8f0555053d850ae2b7bfb2ef8ab
|
a752e2a4670f3b87a570f03d9b2719f8412ad575
| 2019-07-09T16:26:35Z |
python
| 2019-07-19T06:39:05Z |
lib/ansible/executor/task_executor.py
|
# (c) 2012-2014, Michael DeHaan <[email protected]>
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import re
import pty
import time
import json
import subprocess
import sys
import termios
import traceback
from ansible import constants as C
from ansible.errors import AnsibleError, AnsibleParserError, AnsibleUndefinedVariable, AnsibleConnectionFailure, AnsibleActionFail, AnsibleActionSkip
from ansible.executor.task_result import TaskResult
from ansible.executor.module_common import get_action_args_with_defaults
from ansible.module_utils.six import iteritems, string_types, binary_type
from ansible.module_utils.six.moves import xrange
from ansible.module_utils._text import to_text, to_native
from ansible.module_utils.connection import write_to_file_descriptor
from ansible.playbook.conditional import Conditional
from ansible.playbook.task import Task
from ansible.plugins.loader import become_loader, cliconf_loader, connection_loader, httpapi_loader, netconf_loader, terminal_loader
from ansible.template import Templar
from ansible.utils.collection_loader import AnsibleCollectionLoader
from ansible.utils.listify import listify_lookup_plugin_terms
from ansible.utils.unsafe_proxy import UnsafeProxy, wrap_var
from ansible.vars.clean import namespace_facts, clean_facts
from ansible.utils.display import Display
from ansible.utils.vars import combine_vars, isidentifier
display = Display()
__all__ = ['TaskExecutor']
def remove_omit(task_args, omit_token):
'''
Remove args with a value equal to the ``omit_token`` recursively
to align with now having suboptions in the argument_spec
'''
if not isinstance(task_args, dict):
return task_args
new_args = {}
for i in iteritems(task_args):
if i[1] == omit_token:
continue
elif isinstance(i[1], dict):
new_args[i[0]] = remove_omit(i[1], omit_token)
elif isinstance(i[1], list):
new_args[i[0]] = [remove_omit(v, omit_token) for v in i[1]]
else:
new_args[i[0]] = i[1]
return new_args
class TaskExecutor:
'''
This is the main worker class for the executor pipeline, which
handles loading an action plugin to actually dispatch the task to
a given host. This class roughly corresponds to the old Runner()
class.
'''
# Modules that we optimize by squashing loop items into a single call to
# the module
SQUASH_ACTIONS = frozenset(C.DEFAULT_SQUASH_ACTIONS)
def __init__(self, host, task, job_vars, play_context, new_stdin, loader, shared_loader_obj, final_q):
self._host = host
self._task = task
self._job_vars = job_vars
self._play_context = play_context
self._new_stdin = new_stdin
self._loader = loader
self._shared_loader_obj = shared_loader_obj
self._connection = None
self._final_q = final_q
self._loop_eval_error = None
self._task.squash()
def run(self):
'''
The main executor entrypoint, where we determine if the specified
task requires looping and either runs the task with self._run_loop()
or self._execute(). After that, the returned results are parsed and
returned as a dict.
'''
display.debug("in run() - task %s" % self._task._uuid)
try:
try:
items = self._get_loop_items()
except AnsibleUndefinedVariable as e:
# save the error raised here for use later
items = None
self._loop_eval_error = e
if items is not None:
if len(items) > 0:
item_results = self._run_loop(items)
# create the overall result item
res = dict(results=item_results)
# loop through the item results, and set the global changed/failed result flags based on any item.
for item in item_results:
if 'changed' in item and item['changed'] and not res.get('changed'):
res['changed'] = True
if 'failed' in item and item['failed']:
item_ignore = item.pop('_ansible_ignore_errors')
if not res.get('failed'):
res['failed'] = True
res['msg'] = 'One or more items failed'
self._task.ignore_errors = item_ignore
elif self._task.ignore_errors and not item_ignore:
self._task.ignore_errors = item_ignore
# ensure to accumulate these
for array in ['warnings', 'deprecations']:
if array in item and item[array]:
if array not in res:
res[array] = []
if not isinstance(item[array], list):
item[array] = [item[array]]
res[array] = res[array] + item[array]
del item[array]
if not res.get('Failed', False):
res['msg'] = 'All items completed'
else:
res = dict(changed=False, skipped=True, skipped_reason='No items in the list', results=[])
else:
display.debug("calling self._execute()")
res = self._execute()
display.debug("_execute() done")
# make sure changed is set in the result, if it's not present
if 'changed' not in res:
res['changed'] = False
def _clean_res(res, errors='surrogate_or_strict'):
if isinstance(res, UnsafeProxy):
return res._obj
elif isinstance(res, binary_type):
return to_text(res, errors=errors)
elif isinstance(res, dict):
for k in res:
try:
res[k] = _clean_res(res[k], errors=errors)
except UnicodeError:
if k == 'diff':
# If this is a diff, substitute a replacement character if the value
# is undecodable as utf8. (Fix #21804)
display.warning("We were unable to decode all characters in the module return data."
" Replaced some in an effort to return as much as possible")
res[k] = _clean_res(res[k], errors='surrogate_then_replace')
else:
raise
elif isinstance(res, list):
for idx, item in enumerate(res):
res[idx] = _clean_res(item, errors=errors)
return res
display.debug("dumping result to json")
res = _clean_res(res)
display.debug("done dumping result, returning")
return res
except AnsibleError as e:
return dict(failed=True, msg=wrap_var(to_text(e, nonstring='simplerepr')), _ansible_no_log=self._play_context.no_log)
except Exception as e:
return dict(failed=True, msg='Unexpected failure during module execution.', exception=to_text(traceback.format_exc()),
stdout='', _ansible_no_log=self._play_context.no_log)
finally:
try:
self._connection.close()
except AttributeError:
pass
except Exception as e:
display.debug(u"error closing connection: %s" % to_text(e))
def _get_loop_items(self):
'''
Loads a lookup plugin to handle the with_* portion of a task (if specified),
and returns the items result.
'''
# save the play context variables to a temporary dictionary,
# so that we can modify the job vars without doing a full copy
# and later restore them to avoid modifying things too early
play_context_vars = dict()
self._play_context.update_vars(play_context_vars)
old_vars = dict()
for k in play_context_vars:
if k in self._job_vars:
old_vars[k] = self._job_vars[k]
self._job_vars[k] = play_context_vars[k]
# get search path for this task to pass to lookup plugins
self._job_vars['ansible_search_path'] = self._task.get_search_path()
# ensure basedir is always in (dwim already searches here but we need to display it)
if self._loader.get_basedir() not in self._job_vars['ansible_search_path']:
self._job_vars['ansible_search_path'].append(self._loader.get_basedir())
templar = Templar(loader=self._loader, shared_loader_obj=self._shared_loader_obj, variables=self._job_vars)
items = None
loop_cache = self._job_vars.get('_ansible_loop_cache')
if loop_cache is not None:
# _ansible_loop_cache may be set in `get_vars` when calculating `delegate_to`
# to avoid reprocessing the loop
items = loop_cache
elif self._task.loop_with:
if self._task.loop_with in self._shared_loader_obj.lookup_loader:
fail = True
if self._task.loop_with == 'first_found':
# first_found loops are special. If the item is undefined then we want to fall through to the next value rather than failing.
fail = False
loop_terms = listify_lookup_plugin_terms(terms=self._task.loop, templar=templar, loader=self._loader, fail_on_undefined=fail,
convert_bare=False)
if not fail:
loop_terms = [t for t in loop_terms if not templar.is_template(t)]
# get lookup
mylookup = self._shared_loader_obj.lookup_loader.get(self._task.loop_with, loader=self._loader, templar=templar)
# give lookup task 'context' for subdir (mostly needed for first_found)
for subdir in ['template', 'var', 'file']: # TODO: move this to constants?
if subdir in self._task.action:
break
setattr(mylookup, '_subdir', subdir + 's')
# run lookup
items = mylookup.run(terms=loop_terms, variables=self._job_vars, wantlist=True)
else:
raise AnsibleError("Unexpected failure in finding the lookup named '%s' in the available lookup plugins" % self._task.loop_with)
elif self._task.loop is not None:
items = templar.template(self._task.loop)
if not isinstance(items, list):
raise AnsibleError(
"Invalid data passed to 'loop', it requires a list, got this instead: %s."
" Hint: If you passed a list/dict of just one element,"
" try adding wantlist=True to your lookup invocation or use q/query instead of lookup." % items
)
# now we restore any old job variables that may have been modified,
# and delete them if they were in the play context vars but not in
# the old variables dictionary
for k in play_context_vars:
if k in old_vars:
self._job_vars[k] = old_vars[k]
else:
del self._job_vars[k]
if items:
for idx, item in enumerate(items):
if item is not None and not isinstance(item, UnsafeProxy):
items[idx] = UnsafeProxy(item)
return items
def _run_loop(self, items):
'''
Runs the task with the loop items specified and collates the result
into an array named 'results' which is inserted into the final result
along with the item for which the loop ran.
'''
results = []
# make copies of the job vars and task so we can add the item to
# the variables and re-validate the task with the item variable
# task_vars = self._job_vars.copy()
task_vars = self._job_vars
loop_var = 'item'
index_var = None
label = None
loop_pause = 0
extended = False
templar = Templar(loader=self._loader, shared_loader_obj=self._shared_loader_obj, variables=self._job_vars)
# FIXME: move this to the object itself to allow post_validate to take care of templating (loop_control.post_validate)
if self._task.loop_control:
loop_var = templar.template(self._task.loop_control.loop_var)
index_var = templar.template(self._task.loop_control.index_var)
loop_pause = templar.template(self._task.loop_control.pause)
extended = templar.template(self._task.loop_control.extended)
# This may be 'None',so it is templated below after we ensure a value and an item is assigned
label = self._task.loop_control.label
# ensure we always have a label
if label is None:
label = '{{' + loop_var + '}}'
if loop_var in task_vars:
display.warning(u"The loop variable '%s' is already in use. "
u"You should set the `loop_var` value in the `loop_control` option for the task"
u" to something else to avoid variable collisions and unexpected behavior." % loop_var)
ran_once = False
if self._task.loop_with:
# Only squash with 'with_:' not with the 'loop:', 'magic' squashing can be removed once with_ loops are
items = self._squash_items(items, loop_var, task_vars)
no_log = False
items_len = len(items)
for item_index, item in enumerate(items):
task_vars['ansible_loop_var'] = loop_var
task_vars[loop_var] = item
if index_var:
task_vars['ansible_index_var'] = index_var
task_vars[index_var] = item_index
if extended:
task_vars['ansible_loop'] = {
'allitems': items,
'index': item_index + 1,
'index0': item_index,
'first': item_index == 0,
'last': item_index + 1 == items_len,
'length': items_len,
'revindex': items_len - item_index,
'revindex0': items_len - item_index - 1,
}
try:
task_vars['ansible_loop']['nextitem'] = items[item_index + 1]
except IndexError:
pass
if item_index - 1 >= 0:
task_vars['ansible_loop']['previtem'] = items[item_index - 1]
# Update template vars to reflect current loop iteration
templar.available_variables = task_vars
# pause between loop iterations
if loop_pause and ran_once:
try:
time.sleep(float(loop_pause))
except ValueError as e:
raise AnsibleError('Invalid pause value: %s, produced error: %s' % (loop_pause, to_native(e)))
else:
ran_once = True
try:
tmp_task = self._task.copy(exclude_parent=True, exclude_tasks=True)
tmp_task._parent = self._task._parent
tmp_play_context = self._play_context.copy()
except AnsibleParserError as e:
results.append(dict(failed=True, msg=to_text(e)))
continue
# now we swap the internal task and play context with their copies,
# execute, and swap them back so we can do the next iteration cleanly
(self._task, tmp_task) = (tmp_task, self._task)
(self._play_context, tmp_play_context) = (tmp_play_context, self._play_context)
res = self._execute(variables=task_vars)
task_fields = self._task.dump_attrs()
(self._task, tmp_task) = (tmp_task, self._task)
(self._play_context, tmp_play_context) = (tmp_play_context, self._play_context)
# update 'general no_log' based on specific no_log
no_log = no_log or tmp_task.no_log
# now update the result with the item info, and append the result
# to the list of results
res[loop_var] = item
res['ansible_loop_var'] = loop_var
if index_var:
res[index_var] = item_index
res['ansible_index_var'] = index_var
if extended:
res['ansible_loop'] = task_vars['ansible_loop']
res['_ansible_item_result'] = True
res['_ansible_ignore_errors'] = task_fields.get('ignore_errors')
# gets templated here unlike rest of loop_control fields, depends on loop_var above
try:
res['_ansible_item_label'] = templar.template(label, cache=False)
except AnsibleUndefinedVariable as e:
res.update({
'failed': True,
'msg': 'Failed to template loop_control.label: %s' % to_text(e)
})
self._final_q.put(
TaskResult(
self._host.name,
self._task._uuid,
res,
task_fields=task_fields,
),
block=False,
)
results.append(res)
del task_vars[loop_var]
self._task.no_log = no_log
return results
def _squash_items(self, items, loop_var, variables):
'''
Squash items down to a comma-separated list for certain modules which support it
(typically package management modules).
'''
name = None
try:
# _task.action could contain templatable strings (via action: and
# local_action:) Template it before comparing. If we don't end up
# optimizing it here, the templatable string might use template vars
# that aren't available until later (it could even use vars from the
# with_items loop) so don't make the templated string permanent yet.
templar = Templar(loader=self._loader, shared_loader_obj=self._shared_loader_obj, variables=variables)
task_action = self._task.action
if templar.is_template(task_action):
task_action = templar.template(task_action, fail_on_undefined=False)
if len(items) > 0 and task_action in self.SQUASH_ACTIONS:
if all(isinstance(o, string_types) for o in items):
final_items = []
found = None
for allowed in ['name', 'pkg', 'package']:
name = self._task.args.pop(allowed, None)
if name is not None:
found = allowed
break
# This gets the information to check whether the name field
# contains a template that we can squash for
template_no_item = template_with_item = None
if name:
if templar.is_template(name):
variables[loop_var] = '\0$'
template_no_item = templar.template(name, variables, cache=False)
variables[loop_var] = '\0@'
template_with_item = templar.template(name, variables, cache=False)
del variables[loop_var]
# Check if the user is doing some operation that doesn't take
# name/pkg or the name/pkg field doesn't have any variables
# and thus the items can't be squashed
if template_no_item != template_with_item:
if self._task.loop_with and self._task.loop_with not in ('items', 'list'):
value_text = "\"{{ query('%s', %r) }}\"" % (self._task.loop_with, self._task.loop)
else:
value_text = '%r' % self._task.loop
# Without knowing the data structure well, it's easiest to strip python2 unicode
# literals after stringifying
value_text = re.sub(r"\bu'", "'", value_text)
display.deprecated(
'Invoking "%s" only once while using a loop via squash_actions is deprecated. '
'Instead of using a loop to supply multiple items and specifying `%s: "%s"`, '
'please use `%s: %s` and remove the loop' % (self._task.action, found, name, found, value_text),
version='2.11'
)
for item in items:
variables[loop_var] = item
if self._task.evaluate_conditional(templar, variables):
new_item = templar.template(name, cache=False)
final_items.append(new_item)
self._task.args['name'] = final_items
# Wrap this in a list so that the calling function loop
# executes exactly once
return [final_items]
else:
# Restore the name parameter
self._task.args['name'] = name
# elif:
# Right now we only optimize single entries. In the future we
# could optimize more types:
# * lists can be squashed together
# * dicts could squash entries that match in all cases except the
# name or pkg field.
except Exception:
# Squashing is an optimization. If it fails for any reason,
# simply use the unoptimized list of items.
# Restore the name parameter
if name is not None:
self._task.args['name'] = name
return items
def _execute(self, variables=None):
'''
The primary workhorse of the executor system, this runs the task
on the specified host (which may be the delegated_to host) and handles
the retry/until and block rescue/always execution
'''
if variables is None:
variables = self._job_vars
templar = Templar(loader=self._loader, shared_loader_obj=self._shared_loader_obj, variables=variables)
context_validation_error = None
try:
# apply the given task's information to the connection info,
# which may override some fields already set by the play or
# the options specified on the command line
self._play_context = self._play_context.set_task_and_variable_override(task=self._task, variables=variables, templar=templar)
# fields set from the play/task may be based on variables, so we have to
# do the same kind of post validation step on it here before we use it.
self._play_context.post_validate(templar=templar)
# now that the play context is finalized, if the remote_addr is not set
# default to using the host's address field as the remote address
if not self._play_context.remote_addr:
self._play_context.remote_addr = self._host.address
# We also add "magic" variables back into the variables dict to make sure
# a certain subset of variables exist.
self._play_context.update_vars(variables)
# FIXME: update connection/shell plugin options
except AnsibleError as e:
# save the error, which we'll raise later if we don't end up
# skipping this task during the conditional evaluation step
context_validation_error = e
# Evaluate the conditional (if any) for this task, which we do before running
# the final task post-validation. We do this before the post validation due to
# the fact that the conditional may specify that the task be skipped due to a
# variable not being present which would otherwise cause validation to fail
try:
if not self._task.evaluate_conditional(templar, variables):
display.debug("when evaluation is False, skipping this task")
return dict(changed=False, skipped=True, skip_reason='Conditional result was False', _ansible_no_log=self._play_context.no_log)
except AnsibleError:
# loop error takes precedence
if self._loop_eval_error is not None:
raise self._loop_eval_error # pylint: disable=raising-bad-type
raise
# Not skipping, if we had loop error raised earlier we need to raise it now to halt the execution of this task
if self._loop_eval_error is not None:
raise self._loop_eval_error # pylint: disable=raising-bad-type
# if we ran into an error while setting up the PlayContext, raise it now
if context_validation_error is not None:
raise context_validation_error # pylint: disable=raising-bad-type
# if this task is a TaskInclude, we just return now with a success code so the
# main thread can expand the task list for the given host
if self._task.action in ('include', 'include_tasks'):
include_args = self._task.args.copy()
include_file = include_args.pop('_raw_params', None)
if not include_file:
return dict(failed=True, msg="No include file was specified to the include")
include_file = templar.template(include_file)
return dict(include=include_file, include_args=include_args)
# if this task is a IncludeRole, we just return now with a success code so the main thread can expand the task list for the given host
elif self._task.action == 'include_role':
include_args = self._task.args.copy()
return dict(include_args=include_args)
# Now we do final validation on the task, which sets all fields to their final values.
self._task.post_validate(templar=templar)
if '_variable_params' in self._task.args:
variable_params = self._task.args.pop('_variable_params')
if isinstance(variable_params, dict):
if C.INJECT_FACTS_AS_VARS:
display.warning("Using a variable for a task's 'args' is unsafe in some situations "
"(see https://docs.ansible.com/ansible/devel/reference_appendices/faq.html#argsplat-unsafe)")
variable_params.update(self._task.args)
self._task.args = variable_params
# get the connection and the handler for this execution
if (not self._connection or
not getattr(self._connection, 'connected', False) or
self._play_context.remote_addr != self._connection._play_context.remote_addr):
self._connection = self._get_connection(variables=variables, templar=templar)
else:
# if connection is reused, its _play_context is no longer valid and needs
# to be replaced with the one templated above, in case other data changed
self._connection._play_context = self._play_context
self._set_connection_options(variables, templar)
# get handler
self._handler = self._get_action_handler(connection=self._connection, templar=templar)
# Apply default params for action/module, if present
self._task.args = get_action_args_with_defaults(self._task.action, self._task.args, self._task.module_defaults, templar)
# And filter out any fields which were set to default(omit), and got the omit token value
omit_token = variables.get('omit')
if omit_token is not None:
self._task.args = remove_omit(self._task.args, omit_token)
# Read some values from the task, so that we can modify them if need be
if self._task.until:
retries = self._task.retries
if retries is None:
retries = 3
elif retries <= 0:
retries = 1
else:
retries += 1
else:
retries = 1
delay = self._task.delay
if delay < 0:
delay = 1
# make a copy of the job vars here, in case we need to update them
# with the registered variable value later on when testing conditions
vars_copy = variables.copy()
display.debug("starting attempt loop")
result = None
for attempt in xrange(1, retries + 1):
display.debug("running the handler")
try:
result = self._handler.run(task_vars=variables)
except AnsibleActionSkip as e:
return dict(skipped=True, msg=to_text(e))
except AnsibleActionFail as e:
return dict(failed=True, msg=to_text(e))
except AnsibleConnectionFailure as e:
return dict(unreachable=True, msg=to_text(e))
display.debug("handler run complete")
# preserve no log
result["_ansible_no_log"] = self._play_context.no_log
# update the local copy of vars with the registered value, if specified,
# or any facts which may have been generated by the module execution
if self._task.register:
if not isidentifier(self._task.register):
raise AnsibleError("Invalid variable name in 'register' specified: '%s'" % self._task.register)
vars_copy[self._task.register] = wrap_var(result)
if self._task.async_val > 0:
if self._task.poll > 0 and not result.get('skipped') and not result.get('failed'):
result = self._poll_async_result(result=result, templar=templar, task_vars=vars_copy)
# FIXME callback 'v2_runner_on_async_poll' here
# ensure no log is preserved
result["_ansible_no_log"] = self._play_context.no_log
# helper methods for use below in evaluating changed/failed_when
def _evaluate_changed_when_result(result):
if self._task.changed_when is not None and self._task.changed_when:
cond = Conditional(loader=self._loader)
cond.when = self._task.changed_when
result['changed'] = cond.evaluate_conditional(templar, vars_copy)
def _evaluate_failed_when_result(result):
if self._task.failed_when:
cond = Conditional(loader=self._loader)
cond.when = self._task.failed_when
failed_when_result = cond.evaluate_conditional(templar, vars_copy)
result['failed_when_result'] = result['failed'] = failed_when_result
else:
failed_when_result = False
return failed_when_result
if 'ansible_facts' in result:
if self._task.action in ('set_fact', 'include_vars'):
vars_copy.update(result['ansible_facts'])
else:
# TODO: cleaning of facts should eventually become part of taskresults instead of vars
af = wrap_var(result['ansible_facts'])
vars_copy.update(namespace_facts(af))
if C.INJECT_FACTS_AS_VARS:
vars_copy.update(clean_facts(af))
# set the failed property if it was missing.
if 'failed' not in result:
# rc is here for backwards compatibility and modules that use it instead of 'failed'
if 'rc' in result and result['rc'] not in [0, "0"]:
result['failed'] = True
else:
result['failed'] = False
# Make attempts and retries available early to allow their use in changed/failed_when
if self._task.until:
result['attempts'] = attempt
# set the changed property if it was missing.
if 'changed' not in result:
result['changed'] = False
# re-update the local copy of vars with the registered value, if specified,
# or any facts which may have been generated by the module execution
# This gives changed/failed_when access to additional recently modified
# attributes of result
if self._task.register:
vars_copy[self._task.register] = wrap_var(result)
# if we didn't skip this task, use the helpers to evaluate the changed/
# failed_when properties
if 'skipped' not in result:
_evaluate_changed_when_result(result)
_evaluate_failed_when_result(result)
if retries > 1:
cond = Conditional(loader=self._loader)
cond.when = self._task.until
if cond.evaluate_conditional(templar, vars_copy):
break
else:
# no conditional check, or it failed, so sleep for the specified time
if attempt < retries:
result['_ansible_retry'] = True
result['retries'] = retries
display.debug('Retrying task, attempt %d of %d' % (attempt, retries))
self._final_q.put(TaskResult(self._host.name, self._task._uuid, result, task_fields=self._task.dump_attrs()), block=False)
time.sleep(delay)
self._handler = self._get_action_handler(connection=self._connection, templar=templar)
else:
if retries > 1:
# we ran out of attempts, so mark the result as failed
result['attempts'] = retries - 1
result['failed'] = True
# do the final update of the local variables here, for both registered
# values and any facts which may have been created
if self._task.register:
variables[self._task.register] = wrap_var(result)
if 'ansible_facts' in result:
if self._task.action in ('set_fact', 'include_vars'):
variables.update(result['ansible_facts'])
else:
# TODO: cleaning of facts should eventually become part of taskresults instead of vars
af = wrap_var(result['ansible_facts'])
variables.update(namespace_facts(af))
if C.INJECT_FACTS_AS_VARS:
variables.update(clean_facts(af))
# save the notification target in the result, if it was specified, as
# this task may be running in a loop in which case the notification
# may be item-specific, ie. "notify: service {{item}}"
if self._task.notify is not None:
result['_ansible_notify'] = self._task.notify
# add the delegated vars to the result, so we can reference them
# on the results side without having to do any further templating
# FIXME: we only want a limited set of variables here, so this is currently
# hardcoded but should be possibly fixed if we want more or if
# there is another source of truth we can use
delegated_vars = variables.get('ansible_delegated_vars', dict()).get(self._task.delegate_to, dict()).copy()
if len(delegated_vars) > 0:
result["_ansible_delegated_vars"] = {'ansible_delegated_host': self._task.delegate_to}
for k in ('ansible_host', ):
result["_ansible_delegated_vars"][k] = delegated_vars.get(k)
# and return
display.debug("attempt loop complete, returning result")
return result
def _poll_async_result(self, result, templar, task_vars=None):
'''
Polls for the specified JID to be complete
'''
if task_vars is None:
task_vars = self._job_vars
async_jid = result.get('ansible_job_id')
if async_jid is None:
return dict(failed=True, msg="No job id was returned by the async task")
# Create a new pseudo-task to run the async_status module, and run
# that (with a sleep for "poll" seconds between each retry) until the
# async time limit is exceeded.
async_task = Task().load(dict(action='async_status jid=%s' % async_jid, environment=self._task.environment))
# FIXME: this is no longer the case, normal takes care of all, see if this can just be generalized
# Because this is an async task, the action handler is async. However,
# we need the 'normal' action handler for the status check, so get it
# now via the action_loader
async_handler = self._shared_loader_obj.action_loader.get(
'async_status',
task=async_task,
connection=self._connection,
play_context=self._play_context,
loader=self._loader,
templar=templar,
shared_loader_obj=self._shared_loader_obj,
)
time_left = self._task.async_val
while time_left > 0:
time.sleep(self._task.poll)
try:
async_result = async_handler.run(task_vars=task_vars)
# We do not bail out of the loop in cases where the failure
# is associated with a parsing error. The async_runner can
# have issues which result in a half-written/unparseable result
# file on disk, which manifests to the user as a timeout happening
# before it's time to timeout.
if (int(async_result.get('finished', 0)) == 1 or
('failed' in async_result and async_result.get('_ansible_parsed', False)) or
'skipped' in async_result):
break
except Exception as e:
# Connections can raise exceptions during polling (eg, network bounce, reboot); these should be non-fatal.
# On an exception, call the connection's reset method if it has one
# (eg, drop/recreate WinRM connection; some reused connections are in a broken state)
display.vvvv("Exception during async poll, retrying... (%s)" % to_text(e))
display.debug("Async poll exception was:\n%s" % to_text(traceback.format_exc()))
try:
async_handler._connection.reset()
except AttributeError:
pass
# Little hack to raise the exception if we've exhausted the timeout period
time_left -= self._task.poll
if time_left <= 0:
raise
else:
time_left -= self._task.poll
if int(async_result.get('finished', 0)) != 1:
if async_result.get('_ansible_parsed'):
return dict(failed=True, msg="async task did not complete within the requested time - %ss" % self._task.async_val)
else:
return dict(failed=True, msg="async task produced unparseable results", async_result=async_result)
else:
return async_result
def _get_become(self, name):
become = become_loader.get(name)
if not become:
raise AnsibleError("Invalid become method specified, could not find matching plugin: '%s'. "
"Use `ansible-doc -t become -l` to list available plugins." % name)
return become
def _get_connection(self, variables, templar):
'''
Reads the connection property for the host, and returns the
correct connection object from the list of connection plugins
'''
if self._task.delegate_to is not None:
# since we're delegating, we don't want to use interpreter values
# which would have been set for the original target host
for i in list(variables.keys()):
if isinstance(i, string_types) and i.startswith('ansible_') and i.endswith('_interpreter'):
del variables[i]
# now replace the interpreter values with those that may have come
# from the delegated-to host
delegated_vars = variables.get('ansible_delegated_vars', dict()).get(self._task.delegate_to, dict())
if isinstance(delegated_vars, dict):
for i in delegated_vars:
if isinstance(i, string_types) and i.startswith("ansible_") and i.endswith("_interpreter"):
variables[i] = delegated_vars[i]
# load connection
conn_type = self._play_context.connection
connection = self._shared_loader_obj.connection_loader.get(
conn_type,
self._play_context,
self._new_stdin,
task_uuid=self._task._uuid,
ansible_playbook_pid=to_text(os.getppid())
)
if not connection:
raise AnsibleError("the connection plugin '%s' was not found" % conn_type)
# load become plugin if needed
become_plugin = None
if self._play_context.become:
become_plugin = self._get_become(self._play_context.become_method)
if getattr(become_plugin, 'require_tty', False) and not getattr(connection, 'has_tty', False):
raise AnsibleError(
"The '%s' connection does not provide a tty which is required for the selected "
"become plugin: %s." % (conn_type, become_plugin.name)
)
try:
connection.set_become_plugin(become_plugin)
except AttributeError:
# Connection plugin does not support set_become_plugin
pass
# Backwards compat for connection plugins that don't support become plugins
# Just do this unconditionally for now, we could move it inside of the
# AttributeError above later
self._play_context.set_become_plugin(become_plugin)
# FIXME: remove once all plugins pull all data from self._options
self._play_context.set_attributes_from_plugin(connection)
if any(((connection.supports_persistence and C.USE_PERSISTENT_CONNECTIONS), connection.force_persistence)):
self._play_context.timeout = connection.get_option('persistent_command_timeout')
display.vvvv('attempting to start connection', host=self._play_context.remote_addr)
display.vvvv('using connection plugin %s' % connection.transport, host=self._play_context.remote_addr)
options = self._get_persistent_connection_options(connection, variables, templar)
socket_path = start_connection(self._play_context, options)
display.vvvv('local domain socket path is %s' % socket_path, host=self._play_context.remote_addr)
setattr(connection, '_socket_path', socket_path)
return connection
def _get_persistent_connection_options(self, connection, variables, templar):
final_vars = combine_vars(variables, variables.get('ansible_delegated_vars', dict()).get(self._task.delegate_to, dict()))
option_vars = C.config.get_plugin_vars('connection', connection._load_name)
plugin = connection._sub_plugin
if plugin['type'] != 'external':
option_vars.extend(C.config.get_plugin_vars(plugin['type'], plugin['name']))
options = {}
for k in option_vars:
if k in final_vars:
options[k] = templar.template(final_vars[k])
return options
def _set_plugin_options(self, plugin_type, variables, templar, task_keys):
try:
plugin = getattr(self._connection, '_%s' % plugin_type)
except AttributeError:
# Some plugins are assigned to private attrs, ``become`` is not
plugin = getattr(self._connection, plugin_type)
option_vars = C.config.get_plugin_vars(plugin_type, plugin._load_name)
options = {}
for k in option_vars:
if k in variables:
options[k] = templar.template(variables[k])
# TODO move to task method?
plugin.set_options(task_keys=task_keys, var_options=options)
def _set_connection_options(self, variables, templar):
# Keep the pre-delegate values for these keys
PRESERVE_ORIG = ('inventory_hostname',)
# create copy with delegation built in
final_vars = combine_vars(
variables,
variables.get('ansible_delegated_vars', {}).get(self._task.delegate_to, {})
)
# grab list of usable vars for this plugin
option_vars = C.config.get_plugin_vars('connection', self._connection._load_name)
# create dict of 'templated vars'
options = {'_extras': {}}
for k in option_vars:
if k in PRESERVE_ORIG:
options[k] = templar.template(variables[k])
elif k in final_vars:
options[k] = templar.template(final_vars[k])
# add extras if plugin supports them
if getattr(self._connection, 'allow_extras', False):
for k in final_vars:
if k.startswith('ansible_%s_' % self._connection._load_name) and k not in options:
options['_extras'][k] = templar.template(final_vars[k])
task_keys = self._task.dump_attrs()
# set options with 'templated vars' specific to this plugin and dependant ones
self._connection.set_options(task_keys=task_keys, var_options=options)
self._set_plugin_options('shell', final_vars, templar, task_keys)
if self._connection.become is not None:
# FIXME: find alternate route to provide passwords,
# keep out of play objects to avoid accidental disclosure
task_keys['become_pass'] = self._play_context.become_pass
self._set_plugin_options('become', final_vars, templar, task_keys)
# FOR BACKWARDS COMPAT:
for option in ('become_user', 'become_flags', 'become_exe'):
try:
setattr(self._play_context, option, self._connection.become.get_option(option))
except KeyError:
pass # some plugins don't support all base flags
self._play_context.prompt = self._connection.become.prompt
def _get_action_handler(self, connection, templar):
'''
Returns the correct action plugin to handle the requestion task action
'''
module_prefix = self._task.action.split('_')[0]
collections = self._task.collections
# let action plugin override module, fallback to 'normal' action plugin otherwise
if self._shared_loader_obj.action_loader.has_plugin(self._task.action, collection_list=collections):
handler_name = self._task.action
# FIXME: is this code path even live anymore? check w/ networking folks; it trips sometimes when it shouldn't
elif all((module_prefix in C.NETWORK_GROUP_MODULES, module_prefix in self._shared_loader_obj.action_loader)):
handler_name = module_prefix
else:
# FUTURE: once we're comfortable with collections impl, preface this action with ansible.builtin so it can't be hijacked
handler_name = 'normal'
collections = None # until then, we don't want the task's collection list to be consulted; use the builtin
handler = self._shared_loader_obj.action_loader.get(
handler_name,
task=self._task,
connection=connection,
play_context=self._play_context,
loader=self._loader,
templar=templar,
shared_loader_obj=self._shared_loader_obj,
collection_list=collections
)
if not handler:
raise AnsibleError("the handler '%s' was not found" % handler_name)
return handler
def start_connection(play_context, variables):
'''
Starts the persistent connection
'''
candidate_paths = [C.ANSIBLE_CONNECTION_PATH or os.path.dirname(sys.argv[0])]
candidate_paths.extend(os.environ['PATH'].split(os.pathsep))
for dirname in candidate_paths:
ansible_connection = os.path.join(dirname, 'ansible-connection')
if os.path.isfile(ansible_connection):
break
else:
raise AnsibleError("Unable to find location of 'ansible-connection'. "
"Please set or check the value of ANSIBLE_CONNECTION_PATH")
env = os.environ.copy()
env.update({
# HACK; most of these paths may change during the controller's lifetime
# (eg, due to late dynamic role includes, multi-playbook execution), without a way
# to invalidate/update, ansible-connection won't always see the same plugins the controller
# can.
'ANSIBLE_BECOME_PLUGINS': become_loader.print_paths(),
'ANSIBLE_CLICONF_PLUGINS': cliconf_loader.print_paths(),
'ANSIBLE_COLLECTIONS_PATHS': os.pathsep.join(AnsibleCollectionLoader().n_collection_paths),
'ANSIBLE_CONNECTION_PLUGINS': connection_loader.print_paths(),
'ANSIBLE_HTTPAPI_PLUGINS': httpapi_loader.print_paths(),
'ANSIBLE_NETCONF_PLUGINS': netconf_loader.print_paths(),
'ANSIBLE_TERMINAL_PLUGINS': terminal_loader.print_paths(),
})
python = sys.executable
master, slave = pty.openpty()
p = subprocess.Popen(
[python, ansible_connection, to_text(os.getppid())],
stdin=slave, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env
)
os.close(slave)
# We need to set the pty into noncanonical mode. This ensures that we
# can receive lines longer than 4095 characters (plus newline) without
# truncating.
old = termios.tcgetattr(master)
new = termios.tcgetattr(master)
new[3] = new[3] & ~termios.ICANON
try:
termios.tcsetattr(master, termios.TCSANOW, new)
write_to_file_descriptor(master, variables)
write_to_file_descriptor(master, play_context.serialize())
(stdout, stderr) = p.communicate()
finally:
termios.tcsetattr(master, termios.TCSANOW, old)
os.close(master)
if p.returncode == 0:
result = json.loads(to_text(stdout, errors='surrogate_then_replace'))
else:
try:
result = json.loads(to_text(stderr, errors='surrogate_then_replace'))
except getattr(json.decoder, 'JSONDecodeError', ValueError):
# JSONDecodeError only available on Python 3.5+
result = {'error': to_text(stderr, errors='surrogate_then_replace')}
if 'messages' in result:
for level, message in result['messages']:
if level == 'log':
display.display(message, log_only=True)
elif level in ('debug', 'v', 'vv', 'vvv', 'vvvv', 'vvvvv', 'vvvvvv'):
getattr(display, level)(message, host=play_context.remote_addr)
else:
if hasattr(display, level):
getattr(display, level)(message)
else:
display.vvvv(message, host=play_context.remote_addr)
if 'error' in result:
if play_context.verbosity > 2:
if result.get('exception'):
msg = "The full traceback is:\n" + result['exception']
display.display(msg, color=C.COLOR_ERROR)
raise AnsibleError(result['error'])
return result['socket_path']
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 59,337 |
win_reg_stat fails when registry key is in HKEY_USERS\.DEFAULT hive
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
win_reg_stat module fails when running against keys in the HKEY_USERS\.DEFAULT hive. All other hives (HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE\*, etc) appear to be working fine, however.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
win_reg_stat module
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.8.1
config file = /home/admin/ansible-src/com/winrmtesting/ansible.cfg
configured module search path = [u'/home/admin/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /users/ansible/lib/python2.7/site-packages/ansible
executable location = /users/ansible/bin/ansible
python version = 2.7.5 (default, Jun 11 2019, 12:19:05) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
DEFAULT_CALLBACK_WHITELIST(/home/admin/ansible-src/com/winrmtesting/ansible.cfg) = [u'profile_tasks']
DEFAULT_HOST_LIST(/home/admin/ansible-src/com/winrmtesting/ansible.cfg) = [u'/home/admin/ansible-src/com/winrmtesting/inventory/hosts']
HOST_KEY_CHECKING(env: ANSIBLE_HOST_KEY_CHECKING) = False
```
##### OS / ENVIRONMENT
target OS: Windows Server 2016 Datacenter
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
Run the win_reg_stat module against any key in the HKEY_USERS\.DEFAULT hive
<!--- Paste example playbooks or commands between quotes below -->
```yaml
- name: HKU:\.DEFAULT\Software\Policies\Microsoft\Windows\CurrentVersion\PushNotifications
win_reg_stat:
path: 'HKU:\.DEFAULT\Software\Policies\Microsoft\Windows\CurrentVersion\PushNotifications'
name: NoToastApplicationNotificationOnLockScreen
register: pushnotifications_regkey_stat
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
ok: [172.17.176.59] => {
"pushnotifications_regkey_stat": {
"changed": false,
"exists": true,
"failed": false,
"raw_value": 1,
"type": "REG_DWORD",
"value": 1
}
}
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```paste below
The full traceback is:
You cannot call a method on a null-valued expression.
At line:122 char:5
+ $registry_hive.Dispose()
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : InvokeMethodOnNull
ScriptStackTrace:
at <ScriptBlock>, <No file>: line 122
fatal: [172.17.176.59]: FAILED! => {
"changed": false,
"msg": "Unhandled exception while executing module: You cannot call a method on a null-valued expression."
}
```
|
https://github.com/ansible/ansible/issues/59337
|
https://github.com/ansible/ansible/pull/59359
|
74598b212ececc01293e638cf933e70bcfb2497e
|
2f2b10642388992d5b858989efcc0b69f83e22bf
| 2019-07-20T14:36:25Z |
python
| 2019-07-21T23:12:14Z |
changelogs/fragments/win_reg_stat-hku.yaml
| |
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 59,337 |
win_reg_stat fails when registry key is in HKEY_USERS\.DEFAULT hive
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
win_reg_stat module fails when running against keys in the HKEY_USERS\.DEFAULT hive. All other hives (HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE\*, etc) appear to be working fine, however.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
win_reg_stat module
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.8.1
config file = /home/admin/ansible-src/com/winrmtesting/ansible.cfg
configured module search path = [u'/home/admin/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /users/ansible/lib/python2.7/site-packages/ansible
executable location = /users/ansible/bin/ansible
python version = 2.7.5 (default, Jun 11 2019, 12:19:05) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
DEFAULT_CALLBACK_WHITELIST(/home/admin/ansible-src/com/winrmtesting/ansible.cfg) = [u'profile_tasks']
DEFAULT_HOST_LIST(/home/admin/ansible-src/com/winrmtesting/ansible.cfg) = [u'/home/admin/ansible-src/com/winrmtesting/inventory/hosts']
HOST_KEY_CHECKING(env: ANSIBLE_HOST_KEY_CHECKING) = False
```
##### OS / ENVIRONMENT
target OS: Windows Server 2016 Datacenter
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
Run the win_reg_stat module against any key in the HKEY_USERS\.DEFAULT hive
<!--- Paste example playbooks or commands between quotes below -->
```yaml
- name: HKU:\.DEFAULT\Software\Policies\Microsoft\Windows\CurrentVersion\PushNotifications
win_reg_stat:
path: 'HKU:\.DEFAULT\Software\Policies\Microsoft\Windows\CurrentVersion\PushNotifications'
name: NoToastApplicationNotificationOnLockScreen
register: pushnotifications_regkey_stat
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
ok: [172.17.176.59] => {
"pushnotifications_regkey_stat": {
"changed": false,
"exists": true,
"failed": false,
"raw_value": 1,
"type": "REG_DWORD",
"value": 1
}
}
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```paste below
The full traceback is:
You cannot call a method on a null-valued expression.
At line:122 char:5
+ $registry_hive.Dispose()
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : InvokeMethodOnNull
ScriptStackTrace:
at <ScriptBlock>, <No file>: line 122
fatal: [172.17.176.59]: FAILED! => {
"changed": false,
"msg": "Unhandled exception while executing module: You cannot call a method on a null-valued expression."
}
```
|
https://github.com/ansible/ansible/issues/59337
|
https://github.com/ansible/ansible/pull/59359
|
74598b212ececc01293e638cf933e70bcfb2497e
|
2f2b10642388992d5b858989efcc0b69f83e22bf
| 2019-07-20T14:36:25Z |
python
| 2019-07-21T23:12:14Z |
lib/ansible/modules/windows/win_reg_stat.ps1
|
#!powershell
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#Requires -Module Ansible.ModuleUtils.Legacy
$ErrorActionPreference = "Stop"
$params = Parse-Args -arguments $args -supports_check_mode $true
$path = Get-AnsibleParam -obj $params -name "path" -type "str" -failifempty $true -aliases "key"
$name = Get-AnsibleParam -obj $params -name "name" -type "str" -aliases "entry","value"
$result = @{
changed = $false
}
Function Get-PropertyValue {
param(
[Parameter(Mandatory=$true)][Microsoft.Win32.RegistryKey]$Key,
[String]$Name
)
$value = $Key.GetValue($Name, $null, [Microsoft.Win32.RegistryValueOptions]::None)
if ($null -eq $value) {
# Property does not exist or the key's (Default) is not set
return $null
}
$raw_value = $Key.GetValue($Name, $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
if ($Name -eq "") {
# The key's (Default) will fail on GetValueKind
$type = [Microsoft.Win32.RegistryValueKind]::String
} else {
$type = $Key.GetValueKind($Name)
}
if ($type -in @([Microsoft.Win32.RegistryValueKind]::Binary, [Microsoft.Win32.RegistryValueKind]::None)) {
$formatted_raw_value = [System.Collections.Generic.List`1[String]]@()
foreach ($byte in $value) {
$formatted_raw_value.Add("0x{0:x2}" -f $byte)
}
$raw_value = $formatted_raw_value
} elseif ($type -eq [Microsoft.Win32.RegistryValueKind]::DWord) {
# .NET returns the value as a signed integer, we need to make it unsigned
$value = [UInt32]("0x{0:x}" -f $value)
$raw_value = $value
} elseif ($type -eq [Microsoft.Win32.RegistryValueKind]::QWord) {
$value = [UInt64]("0x{0:x}" -f $value)
$raw_value = $value
}
$return_type = switch($type.ToString()) {
"Binary" { "REG_BINARY" }
"String" { "REG_SZ" }
"DWord" { "REG_DWORD" }
"QWord" { "REG_QWORD" }
"MultiString" { "REG_MULTI_SZ" }
"ExpandString" { "REG_EXPAND_SZ" }
"None" { "REG_NONE" }
default { "Unknown - $($type.ToString())" }
}
return @{
type = $return_type
value = $value
raw_value = $raw_value
}
}
# Will validate the key parameter to make sure it matches known format
if ($path -notmatch "^HK(CC|CR|CU|LM|U):\\") {
Fail-Json -obj $result -message "path: $path is not a valid registry path, see module documentation for examples."
}
$registry_path = (Split-Path -Path $path -NoQualifier).Substring(1) # removes the hive: and leading \
$registry_hive = switch(Split-Path -Path $path -Qualifier) {
"HKCR:" { [Microsoft.Win32.Registry]::ClassesRoot }
"HKCC:" { [Microsoft.Win32.Registry]::CurrentConfig }
"HKCU:" { [Microsoft.Win32.Registry]::CurrentUser }
"HKLM:" { [Microsoft.Win32.Registry]::LocalMachine }
"HKU" { [Microsoft.Win32.Registry]::Users }
}
$key = $null
try {
$key = $registry_hive.OpenSubKey($registry_path, $false)
if ($null -ne $key) {
if ($null -eq $name) {
$property_info = @{}
foreach ($property in $key.GetValueNames()) {
$property_info.$property = Get-PropertyValue -Key $key -Name $property
}
# Return the key's (Default) property if it has been defined
$default_value = Get-PropertyValue -Key $key -Name ""
if ($null -ne $default_value) {
$property_info."" = $default_value
}
$result.exists = $true
$result.properties = $property_info
$result.sub_keys = $key.GetSubKeyNames()
} else {
$property_value = Get-PropertyValue -Key $key -Name $name
if ($null -ne $property_value) {
$result.exists = $true
$result += $property_value
} else {
$result.exists = $false
}
}
} else {
$result.exists = $false
}
} finally {
if ($key) {
$key.Dispose()
}
$registry_hive.Dispose()
}
Exit-Json -obj $result
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 59,337 |
win_reg_stat fails when registry key is in HKEY_USERS\.DEFAULT hive
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
win_reg_stat module fails when running against keys in the HKEY_USERS\.DEFAULT hive. All other hives (HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE\*, etc) appear to be working fine, however.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
win_reg_stat module
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.8.1
config file = /home/admin/ansible-src/com/winrmtesting/ansible.cfg
configured module search path = [u'/home/admin/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /users/ansible/lib/python2.7/site-packages/ansible
executable location = /users/ansible/bin/ansible
python version = 2.7.5 (default, Jun 11 2019, 12:19:05) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
DEFAULT_CALLBACK_WHITELIST(/home/admin/ansible-src/com/winrmtesting/ansible.cfg) = [u'profile_tasks']
DEFAULT_HOST_LIST(/home/admin/ansible-src/com/winrmtesting/ansible.cfg) = [u'/home/admin/ansible-src/com/winrmtesting/inventory/hosts']
HOST_KEY_CHECKING(env: ANSIBLE_HOST_KEY_CHECKING) = False
```
##### OS / ENVIRONMENT
target OS: Windows Server 2016 Datacenter
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
Run the win_reg_stat module against any key in the HKEY_USERS\.DEFAULT hive
<!--- Paste example playbooks or commands between quotes below -->
```yaml
- name: HKU:\.DEFAULT\Software\Policies\Microsoft\Windows\CurrentVersion\PushNotifications
win_reg_stat:
path: 'HKU:\.DEFAULT\Software\Policies\Microsoft\Windows\CurrentVersion\PushNotifications'
name: NoToastApplicationNotificationOnLockScreen
register: pushnotifications_regkey_stat
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
ok: [172.17.176.59] => {
"pushnotifications_regkey_stat": {
"changed": false,
"exists": true,
"failed": false,
"raw_value": 1,
"type": "REG_DWORD",
"value": 1
}
}
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```paste below
The full traceback is:
You cannot call a method on a null-valued expression.
At line:122 char:5
+ $registry_hive.Dispose()
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : InvokeMethodOnNull
ScriptStackTrace:
at <ScriptBlock>, <No file>: line 122
fatal: [172.17.176.59]: FAILED! => {
"changed": false,
"msg": "Unhandled exception while executing module: You cannot call a method on a null-valued expression."
}
```
|
https://github.com/ansible/ansible/issues/59337
|
https://github.com/ansible/ansible/pull/59359
|
74598b212ececc01293e638cf933e70bcfb2497e
|
2f2b10642388992d5b858989efcc0b69f83e22bf
| 2019-07-20T14:36:25Z |
python
| 2019-07-21T23:12:14Z |
test/integration/targets/win_reg_stat/tasks/tests.yml
|
---
- name: expect failure when not passing in path option
win_reg_stat:
name: a
register: actual
failed_when: "actual.msg != 'Get-AnsibleParam: Missing required argument: path'"
- name: expect failure when passing in an invalid hive
win_reg_stat:
path: ABCD:\test
register: actual
failed_when: 'actual.msg != "path: ABCD:\\test is not a valid registry path, see module documentation for examples."'
- name: get known nested reg key structure
win_reg_stat:
path: HKCU:\{{ test_reg_path }}\nested
register: actual
- name: set expected value for reg structure
set_fact:
expected:
changed: false
exists: true
failed: false
properties:
binary: { raw_value: ["0x01", "0x16"], type: 'REG_BINARY', value: [1, 22] }
dword: { raw_value: 1, type: 'REG_DWORD', value: 1 }
expand: { raw_value: '%windir%\dir', type: 'REG_EXPAND_SZ', value: "{{win_dir_value.stdout_lines[0]}}\\dir" }
large_dword: { raw_value: 4294967295, type: 'REG_DWORD', value: 4294967295 }
large_qword: { raw_value: 18446744073709551615, type: 'REG_QWORD', value: 18446744073709551615 }
multi: { raw_value: ['a, b', 'c'], type: 'REG_MULTI_SZ', value: ['a, b', 'c'] }
qword: { raw_value: 1, type: 'REG_QWORD', value: 1 }
string: { raw_value: 'test', type: 'REG_SZ', value: 'test' }
sub_keys:
- nest1
- nest2
- name: assert get known nested reg key structure
assert:
that:
- actual == expected
- name: get known reg key with no sub keys but some properties
win_reg_stat:
path: HKCU:\{{ test_reg_path }}\single
register: actual
- name: set expected value for reg key with no sub keys but some properties
set_fact:
expected:
changed: false
exists: true
failed: false
properties:
none: { raw_value: [], type: 'REG_NONE', value: [] }
none1: { raw_value: ["0x00"], type: 'REG_NONE', value: [0] }
string1: { raw_value: '', type: 'REG_SZ', value: '' }
string2: { raw_value: 'abc123', type: 'REG_SZ', value: 'abc123' }
sub_keys: []
- name: assert get known reg key with no sub keys but some properties
assert:
that:
- actual == expected
- name: get known reg key without sub keys and properties
win_reg_stat:
path: HKCU:\{{ test_reg_path }}\nested\nest2
register: actual
- name: set expected value for reg key without sub keys or properties
set_fact:
expected:
changed: false
exists: true
failed: false
properties: {}
sub_keys: []
register: expected
- name: assert get known reg key without sub keys and properties
assert:
that:
- actual == expected
- name: get non-existent reg key
win_reg_stat:
path: HKCU:\{{ test_reg_path }}\Thispathwillneverexist
register: actual
- name: set expected value for non-existent reg key
set_fact:
expected:
changed: false
exists: false
failed: false
- name: assert get non-existent reg key
assert:
that:
- actual == expected
- name: get string property
win_reg_stat:
path: HKCU:\{{ test_reg_path }}\nested
name: string
register: actual
- name: set expected string property
set_fact:
expected:
changed: false
exists: true
failed: false
raw_value: 'test'
type: 'REG_SZ'
value: 'test'
- name: assert get string property
assert:
that:
- actual == expected
- name: get expand string property
win_reg_stat:
path: HKCU:\{{ test_reg_path }}\nested
name: expand
register: actual
- name: set expected expand string property
set_fact:
expected:
changed: false
exists: true
failed: false
raw_value: '%windir%\dir'
type: 'REG_EXPAND_SZ'
value: "{{win_dir_value.stdout_lines[0]}}\\dir"
- name: assert get expand string property
assert:
that:
- actual == expected
- name: get multi string property
win_reg_stat:
path: HKCU:\{{ test_reg_path }}\nested
name: multi
register: actual
- name: set expected multi string property
set_fact:
expected:
changed: false
exists: true
failed: false
raw_value: ['a, b', 'c']
type: 'REG_MULTI_SZ'
value: ['a, b', 'c']
- name: assert get multi string property
assert:
that:
- actual == expected
- name: get binary property
win_reg_stat:
path: HKCU:\{{ test_reg_path }}\nested
name: binary
register: actual
- name: set expected binary property
set_fact:
expected:
changed: false
exists: true
failed: false
raw_value: ["0x01", "0x16"]
type: 'REG_BINARY'
value: [1, 22]
- name: assert get binary property
assert:
that:
- actual == expected
- name: get dword property
win_reg_stat:
path: HKCU:\{{ test_reg_path }}\nested
name: dword
register: actual
- name: set expected dword property
set_fact:
expected:
changed: false
exists: true
failed: false
raw_value: 1
type: 'REG_DWORD'
value: 1
- name: assert get dword property
assert:
that:
- actual == expected
- name: get qword property
win_reg_stat:
path: HKCU:\{{ test_reg_path }}\nested
name: qword
register: actual
- name: set expected qword property
set_fact:
expected:
changed: false
exists: true
failed: false
raw_value: 1
type: 'REG_QWORD'
value: 1
- name: assert get qword property
assert:
that:
- actual == expected
- name: get none property
win_reg_stat:
path: HKCU:\{{ test_reg_path }}\single
name: none
register: actual
- name: set expected none property
set_fact:
expected:
changed: false
exists: true
failed: false
raw_value: []
type: 'REG_NONE'
value: []
- name: assert get none property
assert:
that:
- actual == expected
- name: get none with value property
win_reg_stat:
path: HKCU:\{{ test_reg_path }}\single
name: none1
register: actual
- name: set expected none with value property
set_fact:
expected:
changed: false
exists: true
failed: false
raw_value: ["0x00"]
type: 'REG_NONE'
value: [0]
- name: assert get non with value property
assert:
that:
- actual == expected
- name: get non-existent property
win_reg_stat:
path: HKCU:\{{ test_reg_path }}\single
name: doesnotexist
register: actual
- name: set expected non-existent property
set_fact:
expected:
changed: false
exists: false
failed: false
- name: assert get non-existent property
assert:
that:
- actual == expected
- name: get key with default property set
win_reg_stat:
path: HKCU:\{{ test_reg_path }}\Duplicate Default
register: actual
- name: assert get key with default property set
assert:
that:
- actual.properties[""]['raw_value'] == "default"
- actual.properties[""]['type'] == "REG_SZ"
- actual.properties[""]['value'] == "default"
- actual.properties['(Default)'].raw_value == "custom"
- actual.properties['(Default)'].type == "REG_SZ"
- actual.properties['(Default)'].value == "custom"
- name: get default property
win_reg_stat:
path: HKCU:\{{ test_reg_path }}\Duplicate Default
name: ''
register: actual
- name: assert get default property
assert:
that:
- actual.value == "default"
- actual.raw_value == "default"
- actual.type == "REG_SZ"
- name: get key with blank property set
win_reg_stat:
path: HKCU:\{{ test_reg_path }}\Blank Default
register: actual
- name: assert get key with blank property set
assert:
that:
- actual.properties[""].raw_value == ""
- actual.properties[""].type == "REG_SZ"
- actual.properties[""].value == ""
- actual.properties['(Default)'].raw_value == ""
- actual.properties['(Default)'].type == "REG_SZ"
- actual.properties['(Default)'].value == ""
- name: get default property as empty string
win_reg_stat:
path: HKCU:\{{ test_reg_path }}\Blank Default
name: ''
register: actual
- name: assert get default property as empty string
assert:
that:
- actual.value == ""
- actual.raw_value == ""
- actual.type == "REG_SZ"
- name: get key with no properties set
win_reg_stat:
path: HKCU:\{{ test_reg_path }}\Empty Default
register: actual
- name: assert get key with no properties set
assert:
that:
- actual.properties == {}
- name: get default property that has not been set
win_reg_stat:
path: HKCU:\{{ test_reg_path }}\Empty Default
name: ''
register: actual
- name: assert get default property that has not been set
assert:
that:
- not actual.exists
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 59,299 |
snow_record: 'NoneType' object has no attribute 'generate_token'
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
With addition of OAuthClient in snow_* modules, I am getting following error -
```
Traceback (most recent call last):
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 125, in <module>
_ansiballz_main()
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 117, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 51, in invoke_module
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 339, in <module>
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 335, in main
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 205, in run_module
File "/tmp/ansible_snow_record_payload_brr2thzt/ansible_snow_record_payload.zip/ansible/module_utils/service_now.py", line 57, in login
AttributeError: 'NoneType' object has no attribute 'generate_token'
```
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
2.9
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
Nothing specific
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
MacOS Mojave
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```yaml
---
- hosts: localhost
tasks:
- snow_record:
instance: "instance_id"
password: "password"
username: admin
data:
short_description: "Description"
priority: 2
state: present
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
Playbook should be successful.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```paste below
Traceback (most recent call last):
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 125, in <module>
_ansiballz_main()
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 117, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 51, in invoke_module
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 339, in <module>
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 335, in main
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 205, in run_module
File "/tmp/ansible_snow_record_payload_brr2thzt/ansible_snow_record_payload.zip/ansible/module_utils/service_now.py", line 57, in login
AttributeError: 'NoneType' object has no attribute 'generate_token'
```
|
https://github.com/ansible/ansible/issues/59299
|
https://github.com/ansible/ansible/pull/59315
|
59e647910dd77f0d09380e09f878f6a6fe4f4eda
|
6531819172ca46e14746a4d9b0c845a46b2b82a6
| 2019-07-19T13:38:17Z |
python
| 2019-07-22T14:01:04Z |
docs/docsite/rst/porting_guides/porting_guide_2.9.rst
|
.. _porting_2.9_guide:
*************************
Ansible 2.9 Porting Guide
*************************
This section discusses the behavioral changes between Ansible 2.8 and Ansible 2.9.
It is intended to assist in updating your playbooks, plugins and other parts of your Ansible infrastructure so they will work with this version of Ansible.
We suggest you read this page along with `Ansible Changelog for 2.9 <https://github.com/ansible/ansible/blob/devel/changelogs/CHANGELOG-v2.9.rst>`_ to understand what updates you may need to make.
This document is part of a collection on porting. The complete list of porting guides can be found at :ref:`porting guides <porting_guides>`.
.. contents:: Topics
Playbook
========
* ``hash_behaviour`` now affects inventory sources. If you have it set to ``merge``, the data you get from inventory might change and you will have to update playbooks accordingly. If you're using the default setting (``overwrite``), you will see no changes. Inventory was ignoring this setting.
Command Line
============
No notable changes
Deprecated
==========
No notable changes
Modules
=======
* The ``win_get_url`` and ``win_uri`` module now sends requests with a default ``User-Agent`` of ``ansible-httpget``. This can be changed by using the ``http_agent`` key.
Modules removed
---------------
The following modules no longer exist:
* Apstra's ``aos_*`` modules. See the new modules at `https://github.com/apstra <https://github.com/apstra>`_.
* ec2_ami_find use :ref:`ec2_ami_facts <ec2_ami_facts_module>` instead.
* kubernetes use :ref:`k8s_raw <k8s_raw_module>` instead.
* nxos_ip_interface use :ref:`nxos_l3_interface <nxos_l3_interface_module>` instead.
* nxos_portchannel use :ref:`nxos_linkagg <nxos_linkagg_module>` instead.
* nxos_switchport use :ref:`nxos_l2_interface <nxos_l2_interface_module>` instead.
* oc use :ref:`openshift_raw <openshift_raw_module>` instead.
* panos_nat_policy use :ref:`panos_nat_rule <panos_nat_rule_module>` instead.
* panos_security_policy use :ref:`panos_security_rule <panos_security_rule_module>` instead.
* vsphere_guest use :ref:`vmware_guest <vmware_guest_module>` instead.
Deprecation notices
-------------------
No notable changes
Noteworthy module changes
-------------------------
* `vmware_dvswitch <vmware_dvswitch_module>` accepts `folder` parameter to place dvswitch in user defined folder. This option makes `datacenter` as an optional parameter.
* `vmware_datastore_cluster <vmware_datastore_cluster_module>` accepts `folder` parameter to place datastore cluster in user defined folder. This option makes `datacenter` as an optional parameter.
* `mysql_db <mysql_db_module>` returns new `db_list` parameter in addition to `db` parameter. This `db_list` parameter refers to list of database names. `db` parameter will be deprecated in version `2.13`.
* The ``python_requirements_facts`` module was renamed to :ref:`python_requirements_info <python_requirements_info_module>`.
* The ``jenkins_job_facts`` module was renamed to :ref:`jenkins_job_info <jenkins_job_info_module>`.
* The ``intersight_facts`` module was renamed to :ref:`intersight_info <intersight_info_module>`.
* The ``zabbix_group_facts`` module was renamed to :ref:`zabbix_group_info <zabbix_group_info_module>`.
* The ``zabbix_host_facts`` module was renamed to :ref:`zabbix_host_info <zabbix_host_info_module>`.
* The ``github_webhook_facts`` module was renamed to :ref:`github_webhook_info <github_webhook_info_module>`.
* The ``k8s_facts`` module was renamed to :ref:`k8s_info <k8s_info_module>`.
* The ``bigip_device_facts`` module was renamed to :ref:`bigip_device_info <bigip_device_info_module>`.
* The ``bigiq_device_facts`` module was renamed to :ref:`bigiq_device_info <bigiq_device_info_module>`.
* The ``memset_memstore_facts`` module was renamed to :ref:`memset_memstore_info <memset_memstore_info_module>`.
* The ``memset_server_facts`` module was renamed to :ref:`memset_server_info <memset_server_info_module>`.
* The ``one_image_facts`` module was renamed to :ref:`one_image_info <one_image_info_module>`.
* The ``ali_instance_facts`` module was renamed to :ref:`ali_instance_info <ali_instance_info_module>`.
* The ``xenserver_guest_facts`` module was renamed to :ref:`xenserver_guest_info <xenserver_guest_info_module>`.
* The ``azure_rm_resourcegroup_facts`` module was renamed to :ref:`azure_rm_resourcegroup_info <azure_rm_resourcegroup_info_module>`.
* The ``digital_ocean_account_facts`` module was renamed to :ref:`digital_ocean_account_info <digital_ocean_account_info_module>`.
* The ``digital_ocean_certificate_facts`` module was renamed to :ref:`digital_ocean_certificate_info <digital_ocean_certificate_info_module>`.
* The ``digital_ocean_domain_facts`` module was renamed to :ref:`digital_ocean_domain_info <digital_ocean_domain_info_module>`.
* The ``digital_ocean_firewall_facts`` module was renamed to :ref:`digital_ocean_firewall_info <digital_ocean_firewall_info_module>`.
* The ``digital_ocean_floating_ip_facts`` module was renamed to :ref:`digital_ocean_floating_ip_info <digital_ocean_floating_ip_info_module>`.
* The ``digital_ocean_image_facts`` module was renamed to :ref:`digital_ocean_image_info <digital_ocean_image_info_module>`.
* The ``digital_ocean_load_balancer_facts`` module was renamed to :ref:`digital_ocean_load_balancer_info <digital_ocean_load_balancer_info_module>`.
* The ``digital_ocean_region_facts`` module was renamed to :ref:`digital_ocean_region_info <digital_ocean_region_info_module>`.
* The ``digital_ocean_size_facts`` module was renamed to :ref:`digital_ocean_size_info <digital_ocean_size_info_module>`.
* The ``digital_ocean_snapshot_facts`` module was renamed to :ref:`digital_ocean_snapshot_info <digital_ocean_snapshot_info_module>`.
* The ``digital_ocean_tag_facts`` module was renamed to :ref:`digital_ocean_tag_info <digital_ocean_tag_info_module>`.
* The ``digital_ocean_volume_facts`` module was renamed to :ref:`digital_ocean_volume_info <digital_ocean_volume_info_module>`.
* The ``aws_acm_facts`` module was renamed to :ref:`aws_acm_info <aws_acm_info_module>`.
* The ``aws_az_facts`` module was renamed to :ref:`aws_az_info <aws_az_info_module>`.
* The ``aws_caller_facts`` module was renamed to :ref:`aws_caller_info <aws_caller_info_module>`.
* The ``aws_kms_facts`` module was renamed to :ref:`aws_kms_info <aws_kms_info_module>`.
* The ``aws_region_facts`` module was renamed to :ref:`aws_region_info <aws_region_info_module>`.
* The ``aws_sgw_facts`` module was renamed to :ref:`aws_sgw_info <aws_sgw_info_module>`.
* The ``aws_waf_facts`` module was renamed to :ref:`aws_waf_info <aws_waf_info_module>`.
* The ``cloudwatchlogs_log_group_facts`` module was renamed to :ref:`cloudwatchlogs_log_group_info <cloudwatchlogs_log_group_info_module>`.
* The ``ec2_ami_facts`` module was renamed to :ref:`ec2_ami_info <ec2_ami_info_module>`.
* The ``ec2_asg_facts`` module was renamed to :ref:`ec2_asg_info <ec2_asg_info_module>`.
* The ``ec2_customer_gateway_facts`` module was renamed to :ref:`ec2_customer_gateway_info <ec2_customer_gateway_info_module>`.
* The ``ec2_eip_facts`` module was renamed to :ref:`ec2_eip_info <ec2_eip_info_module>`.
* The ``ec2_elb_facts`` module was renamed to :ref:`ec2_elb_info <ec2_elb_info_module>`.
* The ``ec2_eni_facts`` module was renamed to :ref:`ec2_eni_info <ec2_eni_info_module>`.
* The ``ec2_group_facts`` module was renamed to :ref:`ec2_group_info <ec2_group_info_module>`.
* The ``ec2_instance_facts`` module was renamed to :ref:`ec2_instance_info <ec2_instance_info_module>`.
* The ``ec2_lc_facts`` module was renamed to :ref:`ec2_lc_info <ec2_lc_info_module>`.
* The ``ec2_placement_group_facts`` module was renamed to :ref:`ec2_placement_group_info <ec2_placement_group_info_module>`.
* The ``ec2_snapshot_facts`` module was renamed to :ref:`ec2_snapshot_info <ec2_snapshot_info_module>`.
* The ``ec2_vol_facts`` module was renamed to :ref:`ec2_vol_info <ec2_vol_info_module>`.
* The ``ec2_vpc_dhcp_option_facts`` module was renamed to :ref:`ec2_vpc_dhcp_option_info <ec2_vpc_dhcp_option_info_module>`.
* The ``ec2_vpc_endpoint_facts`` module was renamed to :ref:`ec2_vpc_endpoint_info <ec2_vpc_endpoint_info_module>`.
* The ``ec2_vpc_igw_facts`` module was renamed to :ref:`ec2_vpc_igw_info <ec2_vpc_igw_info_module>`.
* The ``ec2_vpc_nacl_facts`` module was renamed to :ref:`ec2_vpc_nacl_info <ec2_vpc_nacl_info_module>`.
* The ``ec2_vpc_nat_gateway_facts`` module was renamed to :ref:`ec2_vpc_nat_gateway_info <ec2_vpc_nat_gateway_info_module>`.
* The ``ec2_vpc_net_facts`` module was renamed to :ref:`ec2_vpc_net_info <ec2_vpc_net_info_module>`.
* The ``ec2_vpc_peering_facts`` module was renamed to :ref:`ec2_vpc_peering_info <ec2_vpc_peering_info_module>`.
* The ``ec2_vpc_route_table_facts`` module was renamed to :ref:`ec2_vpc_route_table_info <ec2_vpc_route_table_info_module>`.
* The ``ec2_vpc_subnet_facts`` module was renamed to :ref:`ec2_vpc_subnet_info <ec2_vpc_subnet_info_module>`.
* The ``ec2_vpc_vgw_facts`` module was renamed to :ref:`ec2_vpc_vgw_info <ec2_vpc_vgw_info_module>`.
* The ``ec2_vpc_vpn_facts`` module was renamed to :ref:`ec2_vpc_vpn_info <ec2_vpc_vpn_info_module>`.
* The ``elasticache_facts`` module was renamed to :ref:`elasticache_info <elasticache_info_module>`.
* The ``elb_application_lb_facts`` module was renamed to :ref:`elb_application_lb_info <elb_application_lb_info_module>`.
* The ``elb_classic_lb_facts`` module was renamed to :ref:`elb_classic_lb_info <elb_classic_lb_info_module>`.
* The ``elb_target_facts`` module was renamed to :ref:`elb_target_info <elb_target_info_module>`.
* The ``elb_target_group_facts`` module was renamed to :ref:`elb_target_group_info <elb_target_group_info_module>`.
* The ``iam_mfa_device_facts`` module was renamed to :ref:`iam_mfa_device_info <iam_mfa_device_info_module>`.
* The ``iam_role_facts`` module was renamed to :ref:`iam_role_info <iam_role_info_module>`.
* The ``iam_server_certificate_facts`` module was renamed to :ref:`iam_server_certificate_info <iam_server_certificate_info_module>`.
* The ``rds_instance_facts`` module was renamed to :ref:`rds_instance_info <rds_instance_info_module>`.
* The ``rds_snapshot_facts`` module was renamed to :ref:`rds_snapshot_info <rds_snapshot_info_module>`.
* The ``redshift_facts`` module was renamed to :ref:`redshift_info <redshift_info_module>`.
* The ``route53_facts`` module was renamed to :ref:`route53_info <route53_info_module>`.
* The deprecated ``force`` option in ``win_firewall_rule`` has been removed.
Plugins
=======
No notable changes
Porting custom scripts
======================
No notable changes
Networking
==========
No notable changes
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 59,299 |
snow_record: 'NoneType' object has no attribute 'generate_token'
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
With addition of OAuthClient in snow_* modules, I am getting following error -
```
Traceback (most recent call last):
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 125, in <module>
_ansiballz_main()
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 117, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 51, in invoke_module
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 339, in <module>
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 335, in main
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 205, in run_module
File "/tmp/ansible_snow_record_payload_brr2thzt/ansible_snow_record_payload.zip/ansible/module_utils/service_now.py", line 57, in login
AttributeError: 'NoneType' object has no attribute 'generate_token'
```
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
2.9
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
Nothing specific
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
MacOS Mojave
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```yaml
---
- hosts: localhost
tasks:
- snow_record:
instance: "instance_id"
password: "password"
username: admin
data:
short_description: "Description"
priority: 2
state: present
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
Playbook should be successful.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```paste below
Traceback (most recent call last):
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 125, in <module>
_ansiballz_main()
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 117, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 51, in invoke_module
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 339, in <module>
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 335, in main
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 205, in run_module
File "/tmp/ansible_snow_record_payload_brr2thzt/ansible_snow_record_payload.zip/ansible/module_utils/service_now.py", line 57, in login
AttributeError: 'NoneType' object has no attribute 'generate_token'
```
|
https://github.com/ansible/ansible/issues/59299
|
https://github.com/ansible/ansible/pull/59315
|
59e647910dd77f0d09380e09f878f6a6fe4f4eda
|
6531819172ca46e14746a4d9b0c845a46b2b82a6
| 2019-07-19T13:38:17Z |
python
| 2019-07-22T14:01:04Z |
lib/ansible/module_utils/service_now.py
|
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Ansible Project
# Copyright: (c) 2017, Tim Rightnour <[email protected]>
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import traceback
from ansible.module_utils.basic import missing_required_lib
# Pull in pysnow
HAS_PYSNOW = False
PYSNOW_IMP_ERR = None
try:
import pysnow
HAS_PYSNOW = True
except ImportError:
PYSNOW_IMP_ERR = traceback.format_exc()
class ServiceNowClient(object):
def __init__(self, module):
"""
Constructor
"""
if not HAS_PYSNOW:
module.fail_json(msg=missing_required_lib('pysnow'), exception=PYSNOW_IMP_ERR)
self.module = module
self.params = module.params
self.client_id = self.params['client_id']
self.client_secret = self.params['client_secret']
self.username = self.params['username']
self.password = self.params['password']
self.instance = self.params['instance']
self.session = {'token': None}
self.conn = None
def login(self):
result = dict(
changed=False
)
if self.params['client_id'] is not None:
try:
self.conn = pysnow.OAuthClient(client_id=self.client_id,
client_secret=self.client_secret,
token_updater=self.updater,
instance=self.instance)
except Exception as detail:
self.module.fail_json(msg='Could not connect to ServiceNow: {0}'.format(str(detail)), **result)
if not self.session['token']:
# No previous token exists, Generate new.
try:
self.session['token'] = self.conn.generate_token(self.username, self.password)
except pysnow.exceptions.TokenCreateError as detail:
self.module.fail_json(msg='Unable to generate a new token: {0}'.format(str(detail)), **result)
self.conn.set_token(self.session['token'])
elif self.username is not None:
try:
self.conn = pysnow.Client(instance=self.instance,
user=self.username,
password=self.password)
except Exception as detail:
self.module.fail_json(msg='Could not connect to ServiceNow: {0}'.format(str(detail)), **result)
else:
snow_error = "Must specify username/password or client_id/client_secret"
self.module.fail_json(msg=snow_error, **result)
def updater(self, new_token):
self.session['token'] = new_token
self.conn = pysnow.OAuthClient(client_id=self.client_id,
client_secret=self.client_secret,
token_updater=self.updater,
instance=self.instance)
try:
self.conn.set_token(self.session['token'])
except pysnow.exceptions.MissingToken:
snow_error = "Token is missing"
self.module.fail_json(msg=snow_error)
except Exception as detail:
self.module.fail_json(msg='Could not refresh token: {0}'.format(str(detail)))
@staticmethod
def snow_argument_spec():
return dict(
instance=dict(type='str', required=True),
username=dict(type='str', required=True),
password=dict(type='str', required=True, no_log=True),
client_id=dict(type='str', no_log=True),
client_secret=dict(type='str', no_log=True),
)
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 59,299 |
snow_record: 'NoneType' object has no attribute 'generate_token'
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
With addition of OAuthClient in snow_* modules, I am getting following error -
```
Traceback (most recent call last):
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 125, in <module>
_ansiballz_main()
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 117, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 51, in invoke_module
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 339, in <module>
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 335, in main
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 205, in run_module
File "/tmp/ansible_snow_record_payload_brr2thzt/ansible_snow_record_payload.zip/ansible/module_utils/service_now.py", line 57, in login
AttributeError: 'NoneType' object has no attribute 'generate_token'
```
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
2.9
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
Nothing specific
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
MacOS Mojave
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```yaml
---
- hosts: localhost
tasks:
- snow_record:
instance: "instance_id"
password: "password"
username: admin
data:
short_description: "Description"
priority: 2
state: present
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
Playbook should be successful.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```paste below
Traceback (most recent call last):
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 125, in <module>
_ansiballz_main()
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 117, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 51, in invoke_module
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 339, in <module>
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 335, in main
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 205, in run_module
File "/tmp/ansible_snow_record_payload_brr2thzt/ansible_snow_record_payload.zip/ansible/module_utils/service_now.py", line 57, in login
AttributeError: 'NoneType' object has no attribute 'generate_token'
```
|
https://github.com/ansible/ansible/issues/59299
|
https://github.com/ansible/ansible/pull/59315
|
59e647910dd77f0d09380e09f878f6a6fe4f4eda
|
6531819172ca46e14746a4d9b0c845a46b2b82a6
| 2019-07-19T13:38:17Z |
python
| 2019-07-22T14:01:04Z |
lib/ansible/modules/notification/snow_record.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2017, Tim Rightnour <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: snow_record
short_description: Manage records in ServiceNow
version_added: "2.5"
description:
- Creates, deletes and updates a single record in ServiceNow.
options:
table:
description:
- Table to query for records.
required: false
default: incident
type: str
state:
description:
- If C(present) is supplied with a C(number) argument, the module will attempt to update the record with the supplied data.
- If no such record exists, a new one will be created.
- C(absent) will delete a record.
choices: [ present, absent ]
required: true
type: str
data:
description:
- key, value pairs of data to load into the record. See Examples.
- Required for C(state:present).
type: dict
number:
description:
- Record number to update.
- Required for C(state:absent).
required: false
type: str
lookup_field:
description:
- Changes the field that C(number) uses to find records.
required: false
default: number
type: str
attachment:
description:
- Attach a file to the record.
required: false
type: str
client_id:
description:
- Client ID generated by ServiceNow.
required: false
type: str
version_added: "2.9"
client_secret:
description:
- Client Secret associated with client id.
required: false
type: str
version_added: "2.9"
requirements:
- python pysnow (pysnow)
author:
- Tim Rightnour (@garbled1)
extends_documentation_fragment: service_now.documentation
'''
EXAMPLES = '''
- name: Grab a user record
snow_record:
username: ansible_test
password: my_password
instance: dev99999
state: present
number: 62826bf03710200044e0bfc8bcbe5df1
table: sys_user
lookup_field: sys_id
- name: Grab a user record using OAuth
snow_record:
username: ansible_test
password: my_password
client_id: "1234567890abcdef1234567890abcdef"
client_secret: "Password1!"
instance: dev99999
state: present
number: 62826bf03710200044e0bfc8bcbe5df1
table: sys_user
lookup_field: sys_id
- name: Create an incident
snow_record:
username: ansible_test
password: my_password
instance: dev99999
state: present
data:
short_description: "This is a test incident opened by Ansible"
severity: 3
priority: 2
register: new_incident
- name: Delete the record we just made
snow_record:
username: admin
password: xxxxxxx
instance: dev99999
state: absent
number: "{{new_incident['record']['number']}}"
- name: Delete a non-existant record
snow_record:
username: ansible_test
password: my_password
instance: dev99999
state: absent
number: 9872354
failed_when: false
- name: Update an incident
snow_record:
username: ansible_test
password: my_password
instance: dev99999
state: present
number: INC0000055
data:
work_notes : "Been working all day on this thing."
- name: Attach a file to an incident
snow_record:
username: ansible_test
password: my_password
instance: dev99999
state: present
number: INC0000055
attachment: README.md
tags: attach
'''
RETURN = '''
record:
description: Record data from Service Now
type: dict
returned: when supported
attached_file:
description: Details of the file that was attached via C(attachment)
type: dict
returned: when supported
'''
import os
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_bytes, to_native
from ansible.module_utils.service_now import ServiceNowClient
try:
# This is being handled by ServiceNowClient
import pysnow
except ImportError:
pass
def run_module():
# define the available arguments/parameters that a user can pass to
# the module
module_args = ServiceNowClient.snow_argument_spec()
module_args.update(
table=dict(type='str', required=False, default='incident'),
state=dict(choices=['present', 'absent'],
type='str', required=True),
number=dict(default=None, required=False, type='str'),
data=dict(default=None, required=False, type='dict'),
lookup_field=dict(default='number', required=False, type='str'),
attachment=dict(default=None, required=False, type='str')
)
module_required_together = [
['client_id', 'client_secret']
]
module_required_if = [
['state', 'absent', ['number']],
]
module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=True,
required_together=module_required_together,
required_if=module_required_if
)
# Connect to ServiceNow
service_now_client = ServiceNowClient(module)
service_now_client.login()
conn = service_now_client.conn
params = module.params
instance = params['instance']
table = params['table']
state = params['state']
number = params['number']
data = params['data']
lookup_field = params['lookup_field']
result = dict(
changed=False,
instance=instance,
table=table,
number=number,
lookup_field=lookup_field
)
# check for attachments
if params['attachment'] is not None:
attach = params['attachment']
b_attach = to_bytes(attach, errors='surrogate_or_strict')
if not os.path.exists(b_attach):
module.fail_json(msg="Attachment {0} not found".format(attach))
result['attachment'] = attach
else:
attach = None
# Deal with check mode
if module.check_mode:
# if we are in check mode and have no number, we would have created
# a record. We can only partially simulate this
if number is None:
result['record'] = dict(data)
result['changed'] = True
# do we want to check if the record is non-existent?
elif state == 'absent':
try:
record = conn.query(table=table, query={lookup_field: number})
res = record.get_one()
result['record'] = dict(Success=True)
result['changed'] = True
except pysnow.exceptions.NoResults:
result['record'] = None
except Exception as detail:
module.fail_json(msg="Unknown failure in query record: {0}".format(to_native(detail)), **result)
# Let's simulate modification
else:
try:
record = conn.query(table=table, query={lookup_field: number})
res = record.get_one()
for key, value in data.items():
res[key] = value
result['changed'] = True
result['record'] = res
except pysnow.exceptions.NoResults:
snow_error = "Record does not exist"
module.fail_json(msg=snow_error, **result)
except Exception as detail:
module.fail_json(msg="Unknown failure in query record: {0}".format(to_native(detail)), **result)
module.exit_json(**result)
# now for the real thing: (non-check mode)
# are we creating a new record?
if state == 'present' and number is None:
try:
record = conn.insert(table=table, payload=dict(data))
except pysnow.exceptions.UnexpectedResponseFormat as e:
snow_error = "Failed to create record: {0}, details: {1}".format(e.error_summary, e.error_details)
module.fail_json(msg=snow_error, **result)
result['record'] = record
result['changed'] = True
# we are deleting a record
elif state == 'absent':
try:
record = conn.query(table=table, query={lookup_field: number})
res = record.delete()
except pysnow.exceptions.NoResults:
res = dict(Success=True)
except pysnow.exceptions.MultipleResults:
snow_error = "Multiple record match"
module.fail_json(msg=snow_error, **result)
except pysnow.exceptions.UnexpectedResponseFormat as e:
snow_error = "Failed to delete record: {0}, details: {1}".format(e.error_summary, e.error_details)
module.fail_json(msg=snow_error, **result)
except Exception as detail:
snow_error = "Failed to delete record: {0}".format(to_native(detail))
module.fail_json(msg=snow_error, **result)
result['record'] = res
result['changed'] = True
# We want to update a record
else:
try:
record = conn.query(table=table, query={lookup_field: number})
if data is not None:
res = record.update(dict(data))
result['record'] = res
result['changed'] = True
else:
res = record.get_one()
result['record'] = res
if attach is not None:
res = record.attach(b_attach)
result['changed'] = True
result['attached_file'] = res
except pysnow.exceptions.MultipleResults:
snow_error = "Multiple record match"
module.fail_json(msg=snow_error, **result)
except pysnow.exceptions.NoResults:
snow_error = "Record does not exist"
module.fail_json(msg=snow_error, **result)
except pysnow.exceptions.UnexpectedResponseFormat as e:
snow_error = "Failed to update record: {0}, details: {1}".format(e.error_summary, e.error_details)
module.fail_json(msg=snow_error, **result)
except Exception as detail:
snow_error = "Failed to update record: {0}".format(to_native(detail))
module.fail_json(msg=snow_error, **result)
module.exit_json(**result)
def main():
run_module()
if __name__ == '__main__':
main()
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 59,299 |
snow_record: 'NoneType' object has no attribute 'generate_token'
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
With addition of OAuthClient in snow_* modules, I am getting following error -
```
Traceback (most recent call last):
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 125, in <module>
_ansiballz_main()
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 117, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 51, in invoke_module
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 339, in <module>
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 335, in main
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 205, in run_module
File "/tmp/ansible_snow_record_payload_brr2thzt/ansible_snow_record_payload.zip/ansible/module_utils/service_now.py", line 57, in login
AttributeError: 'NoneType' object has no attribute 'generate_token'
```
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
2.9
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
Nothing specific
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
MacOS Mojave
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```yaml
---
- hosts: localhost
tasks:
- snow_record:
instance: "instance_id"
password: "password"
username: admin
data:
short_description: "Description"
priority: 2
state: present
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
Playbook should be successful.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```paste below
Traceback (most recent call last):
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 125, in <module>
_ansiballz_main()
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 117, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 51, in invoke_module
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 339, in <module>
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 335, in main
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 205, in run_module
File "/tmp/ansible_snow_record_payload_brr2thzt/ansible_snow_record_payload.zip/ansible/module_utils/service_now.py", line 57, in login
AttributeError: 'NoneType' object has no attribute 'generate_token'
```
|
https://github.com/ansible/ansible/issues/59299
|
https://github.com/ansible/ansible/pull/59315
|
59e647910dd77f0d09380e09f878f6a6fe4f4eda
|
6531819172ca46e14746a4d9b0c845a46b2b82a6
| 2019-07-19T13:38:17Z |
python
| 2019-07-22T14:01:04Z |
lib/ansible/modules/notification/snow_record_find.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2017, Tim Rightnour <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: snow_record_find
short_description: Search for multiple records from ServiceNow
version_added: "2.9"
description:
- Gets multiple records from a specified table from ServiceNow based on a query dictionary.
options:
table:
description:
- Table to query for records.
type: str
required: false
default: incident
query:
description:
- Dict to query for records.
type: dict
required: true
max_records:
description:
- Maximum number of records to return.
type: int
required: false
default: 20
order_by:
description:
- Field to sort the results on.
- Can prefix with "-" or "+" to change decending or ascending sort order.
type: str
default: "-created_on"
required: false
return_fields:
description:
- Fields of the record to return in the json.
- By default, all fields will be returned.
type: list
required: false
requirements:
- python pysnow (pysnow)
author:
- Tim Rightnour (@garbled1)
extends_documentation_fragment: service_now.documentation
'''
EXAMPLES = '''
- name: Search for incident assigned to group, return specific fields
snow_record_find:
username: ansible_test
password: my_password
instance: dev99999
table: incident
query:
assignment_group: d625dccec0a8016700a222a0f7900d06
return_fields:
- number
- opened_at
- name: Using OAuth, search for incident assigned to group, return specific fields
snow_record_find:
username: ansible_test
password: my_password
client_id: "1234567890abcdef1234567890abcdef"
client_secret: "Password1!"
instance: dev99999
table: incident
query:
assignment_group: d625dccec0a8016700a222a0f7900d06
return_fields:
- number
- opened_at
- name: Find open standard changes with my template
snow_record_find:
username: ansible_test
password: my_password
instance: dev99999
table: change_request
query:
AND:
equals:
active: "True"
type: "standard"
u_change_stage: "80"
contains:
u_template: "MY-Template"
return_fields:
- sys_id
- number
- sys_created_on
- sys_updated_on
- u_template
- active
- type
- u_change_stage
- sys_created_by
- description
- short_description
'''
RETURN = '''
record:
description: The full contents of the matching ServiceNow records as a list of records.
type: dict
returned: always
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.service_now import ServiceNowClient
from ansible.module_utils._text import to_native
try:
# This is being managed by ServiceNowClient
import pysnow
except ImportError:
pass
# OAuth Variables
module = None
client_id = None
client_secret = None
instance = None
session = {'token': None}
class BuildQuery(object):
'''
This is a BuildQuery manipulation class that constructs
a pysnow.QueryBuilder object based on data input.
'''
def __init__(self, module):
self.module = module
self.logic_operators = ["AND", "OR", "NQ"]
self.condition_operator = {
'equals': self._condition_closure,
'not_equals': self._condition_closure,
'contains': self._condition_closure,
'not_contains': self._condition_closure,
'starts_with': self._condition_closure,
'ends_with': self._condition_closure,
'greater_than': self._condition_closure,
'less_than': self._condition_closure,
}
self.accepted_cond_ops = self.condition_operator.keys()
self.append_operator = False
self.simple_query = True
self.data = module.params['query']
def _condition_closure(self, cond, query_field, query_value):
self.qb.field(query_field)
getattr(self.qb, cond)(query_value)
def _iterate_fields(self, data, logic_op, cond_op):
if isinstance(data, dict):
for query_field, query_value in data.items():
if self.append_operator:
getattr(self.qb, logic_op)()
self.condition_operator[cond_op](cond_op, query_field, query_value)
self.append_operator = True
else:
self.module.fail_json(msg='Query is not in a supported format')
def _iterate_conditions(self, data, logic_op):
if isinstance(data, dict):
for cond_op, fields in data.items():
if (cond_op in self.accepted_cond_ops):
self._iterate_fields(fields, logic_op, cond_op)
else:
self.module.fail_json(msg='Supported conditions: {0}'.format(str(self.condition_operator.keys())))
else:
self.module.fail_json(msg='Supported conditions: {0}'.format(str(self.condition_operator.keys())))
def _iterate_operators(self, data):
if isinstance(data, dict):
for logic_op, cond_op in data.items():
if (logic_op in self.logic_operators):
self.simple_query = False
self._iterate_conditions(cond_op, logic_op)
elif self.simple_query:
self.condition_operator['equals']('equals', logic_op, cond_op)
break
else:
self.module.fail_json(msg='Query is not in a supported format')
else:
self.module.fail_json(msg='Supported operators: {0}'.format(str(self.logic_operators)))
def build_query(self):
self.qb = pysnow.QueryBuilder()
self._iterate_operators(self.data)
return (self.qb)
def run_module():
# define the available arguments/parameters that a user can pass to
# the module
module_args = ServiceNowClient.snow_argument_spec()
module_args.update(
table=dict(type='str', required=False, default='incident'),
query=dict(type='dict', required=True),
max_records=dict(default=20, type='int', required=False),
order_by=dict(default='-created_on', type='str', required=False),
return_fields=dict(default=None, type='list', required=False)
)
module_required_together = [
['client_id', 'client_secret']
]
module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=True,
required_together=module_required_together
)
# Connect to ServiceNow
service_now_client = ServiceNowClient(module)
service_now_client.login()
conn = service_now_client.conn
params = module.params
instance = params['instance']
table = params['table']
query = params['query']
max_records = params['max_records']
return_fields = params['return_fields']
result = dict(
changed=False,
instance=instance,
table=table,
query=query,
max_records=max_records,
return_fields=return_fields
)
# Do the lookup
try:
bq = BuildQuery(module)
qb = bq.build_query()
record = conn.query(table=module.params['table'],
query=qb)
if module.params['return_fields'] is not None:
res = record.get_multiple(fields=module.params['return_fields'],
limit=module.params['max_records'],
order_by=[module.params['order_by']])
else:
res = record.get_multiple(limit=module.params['max_records'],
order_by=[module.params['order_by']])
except Exception as detail:
module.fail_json(msg='Failed to find record: {0}'.format(to_native(detail)), **result)
try:
result['record'] = list(res)
except pysnow.exceptions.NoResults:
result['record'] = []
module.exit_json(**result)
def main():
run_module()
if __name__ == '__main__':
main()
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 59,299 |
snow_record: 'NoneType' object has no attribute 'generate_token'
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
With addition of OAuthClient in snow_* modules, I am getting following error -
```
Traceback (most recent call last):
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 125, in <module>
_ansiballz_main()
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 117, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 51, in invoke_module
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 339, in <module>
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 335, in main
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 205, in run_module
File "/tmp/ansible_snow_record_payload_brr2thzt/ansible_snow_record_payload.zip/ansible/module_utils/service_now.py", line 57, in login
AttributeError: 'NoneType' object has no attribute 'generate_token'
```
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
2.9
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
Nothing specific
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
MacOS Mojave
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```yaml
---
- hosts: localhost
tasks:
- snow_record:
instance: "instance_id"
password: "password"
username: admin
data:
short_description: "Description"
priority: 2
state: present
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
Playbook should be successful.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```paste below
Traceback (most recent call last):
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 125, in <module>
_ansiballz_main()
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 117, in _ansiballz_main
invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
File "/Users/akasurde/.ansible/tmp/ansible-tmp-1563543375.7458959-114877035679906/AnsiballZ_snow_record.py", line 51, in invoke_module
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 339, in <module>
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 335, in main
File "/tmp/ansible_snow_record_payload_brr2thzt/__main__.py", line 205, in run_module
File "/tmp/ansible_snow_record_payload_brr2thzt/ansible_snow_record_payload.zip/ansible/module_utils/service_now.py", line 57, in login
AttributeError: 'NoneType' object has no attribute 'generate_token'
```
|
https://github.com/ansible/ansible/issues/59299
|
https://github.com/ansible/ansible/pull/59315
|
59e647910dd77f0d09380e09f878f6a6fe4f4eda
|
6531819172ca46e14746a4d9b0c845a46b2b82a6
| 2019-07-19T13:38:17Z |
python
| 2019-07-22T14:01:04Z |
lib/ansible/plugins/doc_fragments/service_now.py
|
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
class ModuleDocFragment(object):
# Parameters for Service Now modules
DOCUMENTATION = r'''
options:
instance:
description:
- The ServiceNow instance name, without the domain, service-now.com.
required: true
type: str
username:
description:
- Name of user for connection to ServiceNow.
- Required whether using Basic or OAuth authentication.
required: true
type: str
password:
description:
- Password for username.
- Required whether using Basic or OAuth authentication.
required: true
type: str
client_id:
description:
- Client ID generated by ServiceNow.
required: false
type: str
client_secret:
description:
- Client Secret associated with client id.
required: false
type: str
'''
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,714 |
PSRP documentation has wrong parameter name
|
<!--- Verify first that your improvement is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
<!--- Explain the problem briefly below, add suggestions to wording or structure -->
The [PSRP documentation](https://docs.ansible.com/ansible/latest/plugins/connection/psrp.html) mentions `ansible_psrp_connection_backoff` but this seems to be incorrect. The code appears to refer to `ansible_psrp_reconnection_backoff` instead (`reconnection` vs `connection`).
<!--- HINT: Did you know the documentation has an "Edit on GitHub" link on every page ? -->
##### ISSUE TYPE
- Documentation Report
##### COMPONENT NAME
<!--- Write the short name of the rst file, module, plugin, task or feature below, use your best guess if unsure -->
PSRP
lib/ansible/plugins/connection/psrp.py
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.8.0.dev0
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/local/lib/python2.7/dist-packages/ansible-2.8.0.dev0-py2.7.egg/ansible
executable location = /usr/local/bin/ansible
python version = 2.7.15rc1 (default, Nov 12 2018, 14:31:15) [GCC 7.3.0]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
None
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. OS version, browser, etc. -->
Linux, Ubuntu 18.04.2 LTS
##### ADDITIONAL INFORMATION
<!--- Describe how this improves the documentation, e.g. before/after situation or screenshots -->
None.
<!--- HINT: You can paste gist.github.com links for larger files -->
|
https://github.com/ansible/ansible/issues/58714
|
https://github.com/ansible/ansible/pull/59369
|
a20afb58221d0991b2374916eeb963d58bf52069
|
9ff26a4a22defc05d4a6ba9e650f74670067a51a
| 2019-07-04T08:30:17Z |
python
| 2019-07-22T19:55:52Z |
changelogs/fragments/psrp-reconnection.yaml
| |
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,714 |
PSRP documentation has wrong parameter name
|
<!--- Verify first that your improvement is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
<!--- Explain the problem briefly below, add suggestions to wording or structure -->
The [PSRP documentation](https://docs.ansible.com/ansible/latest/plugins/connection/psrp.html) mentions `ansible_psrp_connection_backoff` but this seems to be incorrect. The code appears to refer to `ansible_psrp_reconnection_backoff` instead (`reconnection` vs `connection`).
<!--- HINT: Did you know the documentation has an "Edit on GitHub" link on every page ? -->
##### ISSUE TYPE
- Documentation Report
##### COMPONENT NAME
<!--- Write the short name of the rst file, module, plugin, task or feature below, use your best guess if unsure -->
PSRP
lib/ansible/plugins/connection/psrp.py
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.8.0.dev0
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/local/lib/python2.7/dist-packages/ansible-2.8.0.dev0-py2.7.egg/ansible
executable location = /usr/local/bin/ansible
python version = 2.7.15rc1 (default, Nov 12 2018, 14:31:15) [GCC 7.3.0]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
None
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. OS version, browser, etc. -->
Linux, Ubuntu 18.04.2 LTS
##### ADDITIONAL INFORMATION
<!--- Describe how this improves the documentation, e.g. before/after situation or screenshots -->
None.
<!--- HINT: You can paste gist.github.com links for larger files -->
|
https://github.com/ansible/ansible/issues/58714
|
https://github.com/ansible/ansible/pull/59369
|
a20afb58221d0991b2374916eeb963d58bf52069
|
9ff26a4a22defc05d4a6ba9e650f74670067a51a
| 2019-07-04T08:30:17Z |
python
| 2019-07-22T19:55:52Z |
lib/ansible/plugins/connection/psrp.py
|
# Copyright (c) 2018 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
author: Ansible Core Team
connection: psrp
short_description: Run tasks over Microsoft PowerShell Remoting Protocol
description:
- Run commands or put/fetch on a target via PSRP (WinRM plugin)
- This is similar to the I(winrm) connection plugin which uses the same
underlying transport but instead runs in a PowerShell interpreter.
version_added: "2.7"
requirements:
- pypsrp (Python library)
options:
# transport options
remote_addr:
description:
- The hostname or IP address of the remote host.
default: inventory_hostname
vars:
- name: ansible_host
- name: ansible_psrp_host
remote_user:
description:
- The user to log in as.
vars:
- name: ansible_user
- name: ansible_psrp_user
port:
description:
- The port for PSRP to connect on the remote target.
- Default is C(5986) if I(protocol) is not defined or is C(https),
otherwise the port is C(5985).
vars:
- name: ansible_port
- name: ansible_psrp_port
protocol:
description:
- Set the protocol to use for the connection.
- Default is C(https) if I(port) is not defined or I(port) is not C(5985).
choices:
- http
- https
vars:
- name: ansible_psrp_protocol
path:
description:
- The URI path to connect to.
vars:
- name: ansible_psrp_path
default: 'wsman'
auth:
description:
- The authentication protocol to use when authenticating the remote user.
- The default, C(negotiate), will attempt to use C(Kerberos) if it is
available and fall back to C(NTLM) if it isn't.
vars:
- name: ansible_psrp_auth
choices:
- basic
- certificate
- negotiate
- kerberos
- ntlm
- credssp
default: negotiate
cert_validation:
description:
- Whether to validate the remote server's certificate or not.
- Set to C(ignore) to not validate any certificates.
- I(ca_cert) can be set to the path of a PEM certificate chain to
use in the validation.
choices:
- validate
- ignore
default: validate
vars:
- name: ansible_psrp_cert_validation
ca_cert:
description:
- The path to a PEM certificate chain to use when validating the server's
certificate.
- This value is ignored if I(cert_validation) is set to C(ignore).
vars:
- name: ansible_psrp_cert_trust_path
- name: ansible_psrp_ca_cert
aliases: [ cert_trust_path ]
connection_timeout:
description:
- The connection timeout for making the request to the remote host.
- This is measured in seconds.
vars:
- name: ansible_psrp_connection_timeout
default: 30
read_timeout:
description:
- The read timeout for receiving data from the remote host.
- This value must always be greater than I(operation_timeout).
- This option requires pypsrp >= 0.3.
- This is measured in seconds.
vars:
- name: ansible_psrp_read_timeout
default: 30
version_added: '2.8'
reconnection_retries:
description:
- The number of retries on connection errors.
vars:
- name: ansible_psrp_reconnection_retries
default: 0
version_added: '2.8'
reconnection_backoff:
description:
- The backoff time to use in between reconnection attempts.
(First sleeps X, then sleeps 2*X, then sleeps 4*X, ...)
- This is measured in seconds.
vars:
- name: ansible_psrp_connection_backoff
default: 2
version_added: '2.8'
message_encryption:
description:
- Controls the message encryption settings, this is different from TLS
encryption when I(ansible_psrp_protocol) is C(https).
- Only the auth protocols C(negotiate), C(kerberos), C(ntlm), and
C(credssp) can do message encryption. The other authentication protocols
only support encryption when C(protocol) is set to C(https).
- C(auto) means means message encryption is only used when not using
TLS/HTTPS.
- C(always) is the same as C(auto) but message encryption is always used
even when running over TLS/HTTPS.
- C(never) disables any encryption checks that are in place when running
over HTTP and disables any authentication encryption processes.
vars:
- name: ansible_psrp_message_encryption
choices:
- auto
- always
- never
default: auto
proxy:
description:
- Set the proxy URL to use when connecting to the remote host.
vars:
- name: ansible_psrp_proxy
ignore_proxy:
description:
- Will disable any environment proxy settings and connect directly to the
remote host.
- This option is ignored if C(proxy) is set.
vars:
- name: ansible_psrp_ignore_proxy
type: bool
default: 'no'
# auth options
certificate_key_pem:
description:
- The local path to an X509 certificate key to use with certificate auth.
vars:
- name: ansible_psrp_certificate_key_pem
certificate_pem:
description:
- The local path to an X509 certificate to use with certificate auth.
vars:
- name: ansible_psrp_certificate_pem
credssp_auth_mechanism:
description:
- The sub authentication mechanism to use with CredSSP auth.
- When C(auto), both Kerberos and NTLM is attempted with kerberos being
preferred.
choices:
- auto
- kerberos
- ntlm
default: auto
vars:
- name: ansible_psrp_credssp_auth_mechanism
credssp_disable_tlsv1_2:
description:
- Disables the use of TLSv1.2 on the CredSSP authentication channel.
- This should not be set to C(yes) unless dealing with a host that does not
have TLSv1.2.
default: no
type: bool
vars:
- name: ansible_psrp_credssp_disable_tlsv1_2
credssp_minimum_version:
description:
- The minimum CredSSP server authentication version that will be accepted.
- Set to C(5) to ensure the server has been patched and is not vulnerable
to CVE 2018-0886.
default: 2
type: int
vars:
- name: ansible_psrp_credssp_minimum_version
negotiate_delegate:
description:
- Allow the remote user the ability to delegate it's credentials to another
server, i.e. credential delegation.
- Only valid when Kerberos was the negotiated auth or was explicitly set as
the authentication.
- Ignored when NTLM was the negotiated auth.
vars:
- name: ansible_psrp_negotiate_delegate
negotiate_hostname_override:
description:
- Override the remote hostname when searching for the host in the Kerberos
lookup.
- This allows Ansible to connect over IP but authenticate with the remote
server using it's DNS name.
- Only valid when Kerberos was the negotiated auth or was explicitly set as
the authentication.
- Ignored when NTLM was the negotiated auth.
vars:
- name: ansible_psrp_negotiate_hostname_override
negotiate_send_cbt:
description:
- Send the Channel Binding Token (CBT) structure when authenticating.
- CBT is used to provide extra protection against Man in the Middle C(MitM)
attacks by binding the outer transport channel to the auth channel.
- CBT is not used when using just C(HTTP), only C(HTTPS).
default: yes
type: bool
vars:
- name: ansible_psrp_negotiate_send_cbt
negotiate_service:
description:
- Override the service part of the SPN used during Kerberos authentication.
- Only valid when Kerberos was the negotiated auth or was explicitly set as
the authentication.
- Ignored when NTLM was the negotiated auth.
default: WSMAN
vars:
- name: ansible_psrp_negotiate_service
# protocol options
operation_timeout:
description:
- Sets the WSMan timeout for each operation.
- This is measured in seconds.
- This should not exceed the value for C(connection_timeout).
vars:
- name: ansible_psrp_operation_timeout
default: 20
max_envelope_size:
description:
- Sets the maximum size of each WSMan message sent to the remote host.
- This is measured in bytes.
- Defaults to C(150KiB) for compatibility with older hosts.
vars:
- name: ansible_psrp_max_envelope_size
default: 153600
configuration_name:
description:
- The name of the PowerShell configuration endpoint to connect to.
vars:
- name: ansible_psrp_configuration_name
default: Microsoft.PowerShell
"""
import base64
import json
import logging
import os
from ansible import constants as C
from ansible.errors import AnsibleConnectionFailure, AnsibleError
from ansible.errors import AnsibleFileNotFound
from ansible.module_utils.parsing.convert_bool import boolean
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.plugins.connection import ConnectionBase
from ansible.plugins.shell.powershell import _common_args
from ansible.utils.display import Display
from ansible.utils.hashing import secure_hash
HAS_PYPSRP = True
PYPSRP_IMP_ERR = None
try:
import pypsrp
from pypsrp.complex_objects import GenericComplexObject, PSInvocationState, RunspacePoolState
from pypsrp.exceptions import AuthenticationError, WinRMError
from pypsrp.host import PSHost, PSHostUserInterface
from pypsrp.powershell import PowerShell, RunspacePool
from pypsrp.shell import Process, SignalCode, WinRS
from pypsrp.wsman import WSMan, AUTH_KWARGS
from requests.exceptions import ConnectionError, ConnectTimeout
except ImportError as err:
HAS_PYPSRP = False
PYPSRP_IMP_ERR = err
display = Display()
class Connection(ConnectionBase):
transport = 'psrp'
module_implementation_preferences = ('.ps1', '.exe', '')
allow_executable = False
has_pipelining = True
allow_extras = True
def __init__(self, *args, **kwargs):
self.always_pipeline_modules = True
self.has_native_async = True
self.runspace = None
self.host = None
self._shell_type = 'powershell'
super(Connection, self).__init__(*args, **kwargs)
if not C.DEFAULT_DEBUG:
logging.getLogger('pypsrp').setLevel(logging.WARNING)
logging.getLogger('requests_credssp').setLevel(logging.INFO)
logging.getLogger('urllib3').setLevel(logging.INFO)
def _connect(self):
if not HAS_PYPSRP:
raise AnsibleError("pypsrp or dependencies are not installed: %s"
% to_native(PYPSRP_IMP_ERR))
super(Connection, self)._connect()
self._build_kwargs()
display.vvv("ESTABLISH PSRP CONNECTION FOR USER: %s ON PORT %s TO %s" %
(self._psrp_user, self._psrp_port, self._psrp_host),
host=self._psrp_host)
if not self.runspace:
connection = WSMan(**self._psrp_conn_kwargs)
# create our psuedo host to capture the exit code and host output
host_ui = PSHostUserInterface()
self.host = PSHost(None, None, False, "Ansible PSRP Host", None,
host_ui, None)
self.runspace = RunspacePool(
connection, host=self.host,
configuration_name=self._psrp_configuration_name
)
display.vvvvv(
"PSRP OPEN RUNSPACE: auth=%s configuration=%s endpoint=%s" %
(self._psrp_auth, self._psrp_configuration_name,
connection.transport.endpoint), host=self._psrp_host
)
try:
self.runspace.open()
except AuthenticationError as e:
raise AnsibleConnectionFailure("failed to authenticate with "
"the server: %s" % to_native(e))
except WinRMError as e:
raise AnsibleConnectionFailure(
"psrp connection failure during runspace open: %s"
% to_native(e)
)
except (ConnectionError, ConnectTimeout) as e:
raise AnsibleConnectionFailure(
"Failed to connect to the host via PSRP: %s"
% to_native(e)
)
self._connected = True
return self
def reset(self):
display.vvvvv("PSRP: Reset Connection", host=self._psrp_host)
self.runspace = None
self._connect()
def exec_command(self, cmd, in_data=None, sudoable=True):
super(Connection, self).exec_command(cmd, in_data=in_data,
sudoable=sudoable)
if cmd.startswith(" ".join(_common_args) + " -EncodedCommand"):
# This is a PowerShell script encoded by the shell plugin, we will
# decode the script and execute it in the runspace instead of
# starting a new interpreter to save on time
b_command = base64.b64decode(cmd.split(" ")[-1])
script = to_text(b_command, 'utf-16-le')
in_data = to_text(in_data, errors="surrogate_or_strict", nonstring="passthru")
if in_data and in_data.startswith(u"#!"):
# ANSIBALLZ wrapper, we need to get the interpreter and execute
# that as the script - note this won't work as basic.py relies
# on packages not available on Windows, once fixed we can enable
# this path
interpreter = to_native(in_data.splitlines()[0][2:])
# script = "$input | &'%s' -" % interpreter
# in_data = to_text(in_data)
raise AnsibleError("cannot run the interpreter '%s' on the psrp "
"connection plugin" % interpreter)
# call build_module_command to get the bootstrap wrapper text
bootstrap_wrapper = self._shell.build_module_command('', '', '')
if bootstrap_wrapper == cmd:
# Do not display to the user each invocation of the bootstrap wrapper
display.vvv("PSRP: EXEC (via pipeline wrapper)")
else:
display.vvv("PSRP: EXEC %s" % script, host=self._psrp_host)
else:
# In other cases we want to execute the cmd as the script. We add on the 'exit $LASTEXITCODE' to ensure the
# rc is propagated back to the connection plugin.
script = to_text(u"%s\nexit $LASTEXITCODE" % cmd)
display.vvv(u"PSRP: EXEC %s" % script, host=self._psrp_host)
rc, stdout, stderr = self._exec_psrp_script(script, in_data)
return rc, stdout, stderr
def put_file(self, in_path, out_path):
super(Connection, self).put_file(in_path, out_path)
display.vvv("PUT %s TO %s" % (in_path, out_path), host=self._psrp_host)
out_path = self._shell._unquote(out_path)
script = u'''begin {
$ErrorActionPreference = "Stop"
$path = '%s'
$fd = [System.IO.File]::Create($path)
$algo = [System.Security.Cryptography.SHA1CryptoServiceProvider]::Create()
$bytes = @()
} process {
$bytes = [System.Convert]::FromBase64String($input)
$algo.TransformBlock($bytes, 0, $bytes.Length, $bytes, 0) > $null
$fd.Write($bytes, 0, $bytes.Length)
} end {
$fd.Close()
$algo.TransformFinalBlock($bytes, 0, 0) > $null
$hash = [System.BitConverter]::ToString($algo.Hash)
$hash = $hash.Replace("-", "").ToLowerInvariant()
Write-Output -InputObject "{`"sha1`":`"$hash`"}"
}''' % self._shell._escape(out_path)
cmd_parts = self._shell._encode_script(script, as_list=True,
strict_mode=False,
preserve_rc=False)
b_in_path = to_bytes(in_path, errors='surrogate_or_strict')
if not os.path.exists(b_in_path):
raise AnsibleFileNotFound('file or module does not exist: "%s"'
% to_native(in_path))
in_size = os.path.getsize(b_in_path)
buffer_size = int(self.runspace.connection.max_payload_size / 4 * 3)
# copying files is faster when using the raw WinRM shell and not PSRP
# we will create a WinRS shell just for this process
# TODO: speed this up as there is overhead creating a shell for this
with WinRS(self.runspace.connection, codepage=65001) as shell:
process = Process(shell, cmd_parts[0], cmd_parts[1:])
process.begin_invoke()
offset = 0
with open(b_in_path, 'rb') as src_file:
for data in iter((lambda: src_file.read(buffer_size)), b""):
offset += len(data)
display.vvvvv("PSRP PUT %s to %s (offset=%d, size=%d" %
(in_path, out_path, offset, len(data)),
host=self._psrp_host)
b64_data = base64.b64encode(data) + b"\r\n"
process.send(b64_data, end=(src_file.tell() == in_size))
# the file was empty, return empty buffer
if offset == 0:
process.send(b"", end=True)
process.end_invoke()
process.signal(SignalCode.CTRL_C)
if process.rc != 0:
raise AnsibleError(to_native(process.stderr))
put_output = json.loads(process.stdout)
remote_sha1 = put_output.get("sha1")
if not remote_sha1:
raise AnsibleError("Remote sha1 was not returned, stdout: '%s', "
"stderr: '%s'" % (to_native(process.stdout),
to_native(process.stderr)))
local_sha1 = secure_hash(in_path)
if not remote_sha1 == local_sha1:
raise AnsibleError("Remote sha1 hash %s does not match local hash "
"%s" % (to_native(remote_sha1),
to_native(local_sha1)))
def fetch_file(self, in_path, out_path):
super(Connection, self).fetch_file(in_path, out_path)
display.vvv("FETCH %s TO %s" % (in_path, out_path),
host=self._psrp_host)
in_path = self._shell._unquote(in_path)
out_path = out_path.replace('\\', '/')
# because we are dealing with base64 data we need to get the max size
# of the bytes that the base64 size would equal
max_b64_size = int(self.runspace.connection.max_payload_size -
(self.runspace.connection.max_payload_size / 4 * 3))
buffer_size = max_b64_size - (max_b64_size % 1024)
# setup the file stream with read only mode
setup_script = '''$ErrorActionPreference = "Stop"
$path = '%s'
if (Test-Path -Path $path -PathType Leaf) {
$fs = New-Object -TypeName System.IO.FileStream -ArgumentList @(
$path,
[System.IO.FileMode]::Open,
[System.IO.FileAccess]::Read,
[System.IO.FileShare]::Read
)
$buffer_size = %d
} elseif (Test-Path -Path $path -PathType Container) {
Write-Output -InputObject "[DIR]"
} else {
Write-Error -Message "$path does not exist"
$host.SetShouldExit(1)
}''' % (self._shell._escape(in_path), buffer_size)
# read the file stream at the offset and return the b64 string
read_script = '''$ErrorActionPreference = "Stop"
$fs.Seek(%d, [System.IO.SeekOrigin]::Begin) > $null
$buffer = New-Object -TypeName byte[] -ArgumentList $buffer_size
$bytes_read = $fs.Read($buffer, 0, $buffer_size)
if ($bytes_read -gt 0) {
$bytes = $buffer[0..($bytes_read - 1)]
Write-Output -InputObject ([System.Convert]::ToBase64String($bytes))
}'''
# need to run the setup script outside of the local scope so the
# file stream stays active between fetch operations
rc, stdout, stderr = self._exec_psrp_script(setup_script,
use_local_scope=False,
force_stop=True)
if rc != 0:
raise AnsibleError("failed to setup file stream for fetch '%s': %s"
% (out_path, to_native(stderr)))
elif stdout.strip() == '[DIR]':
# to be consistent with other connection plugins, we assume the caller has created the target dir
return
b_out_path = to_bytes(out_path, errors='surrogate_or_strict')
# to be consistent with other connection plugins, we assume the caller has created the target dir
offset = 0
with open(b_out_path, 'wb') as out_file:
while True:
display.vvvvv("PSRP FETCH %s to %s (offset=%d" %
(in_path, out_path, offset), host=self._psrp_host)
rc, stdout, stderr = self._exec_psrp_script(read_script % offset, force_stop=True)
if rc != 0:
raise AnsibleError("failed to transfer file to '%s': %s"
% (out_path, to_native(stderr)))
data = base64.b64decode(stdout.strip())
out_file.write(data)
if len(data) < buffer_size:
break
offset += len(data)
rc, stdout, stderr = self._exec_psrp_script("$fs.Close()", force_stop=True)
if rc != 0:
display.warning("failed to close remote file stream of file "
"'%s': %s" % (in_path, to_native(stderr)))
def close(self):
if self.runspace and self.runspace.state == RunspacePoolState.OPENED:
display.vvvvv("PSRP CLOSE RUNSPACE: %s" % (self.runspace.id),
host=self._psrp_host)
self.runspace.close()
self.runspace = None
self._connected = False
def _build_kwargs(self):
self._become_method = self._play_context.become_method
self._become_user = self._play_context.become_user
self._become_pass = self._play_context.become_pass
self._psrp_host = self.get_option('remote_addr')
self._psrp_user = self.get_option('remote_user')
self._psrp_pass = self._play_context.password
protocol = self.get_option('protocol')
port = self.get_option('port')
if protocol is None and port is None:
protocol = 'https'
port = 5986
elif protocol is None:
protocol = 'https' if int(port) != 5985 else 'http'
elif port is None:
port = 5986 if protocol == 'https' else 5985
self._psrp_protocol = protocol
self._psrp_port = int(port)
self._psrp_path = self.get_option('path')
self._psrp_auth = self.get_option('auth')
# cert validation can either be a bool or a path to the cert
cert_validation = self.get_option('cert_validation')
cert_trust_path = self.get_option('ca_cert')
if cert_validation == 'ignore':
self._psrp_cert_validation = False
elif cert_trust_path is not None:
self._psrp_cert_validation = cert_trust_path
else:
self._psrp_cert_validation = True
self._psrp_connection_timeout = self.get_option('connection_timeout') # Can be None
self._psrp_read_timeout = self.get_option('read_timeout') # Can be None
self._psrp_message_encryption = self.get_option('message_encryption')
self._psrp_proxy = self.get_option('proxy')
self._psrp_ignore_proxy = boolean(self.get_option('ignore_proxy'))
self._psrp_operation_timeout = int(self.get_option('operation_timeout'))
self._psrp_max_envelope_size = int(self.get_option('max_envelope_size'))
self._psrp_configuration_name = self.get_option('configuration_name')
self._psrp_reconnection_retries = int(self.get_option('reconnection_retries'))
self._psrp_reconnection_backoff = float(self.get_option('reconnection_backoff'))
self._psrp_certificate_key_pem = self.get_option('certificate_key_pem')
self._psrp_certificate_pem = self.get_option('certificate_pem')
self._psrp_credssp_auth_mechanism = self.get_option('credssp_auth_mechanism')
self._psrp_credssp_disable_tlsv1_2 = self.get_option('credssp_disable_tlsv1_2')
self._psrp_credssp_minimum_version = self.get_option('credssp_minimum_version')
self._psrp_negotiate_send_cbt = self.get_option('negotiate_send_cbt')
self._psrp_negotiate_delegate = self.get_option('negotiate_delegate')
self._psrp_negotiate_hostname_override = self.get_option('negotiate_hostname_override')
self._psrp_negotiate_service = self.get_option('negotiate_service')
supported_args = []
for auth_kwarg in AUTH_KWARGS.values():
supported_args.extend(auth_kwarg)
extra_args = set([v.replace('ansible_psrp_', '') for v in
self.get_option('_extras')])
unsupported_args = extra_args.difference(supported_args)
for arg in unsupported_args:
display.warning("ansible_psrp_%s is unsupported by the current "
"psrp version installed" % arg)
self._psrp_conn_kwargs = dict(
server=self._psrp_host, port=self._psrp_port,
username=self._psrp_user, password=self._psrp_pass,
ssl=self._psrp_protocol == 'https', path=self._psrp_path,
auth=self._psrp_auth, cert_validation=self._psrp_cert_validation,
connection_timeout=self._psrp_connection_timeout,
encryption=self._psrp_message_encryption, proxy=self._psrp_proxy,
no_proxy=self._psrp_ignore_proxy,
max_envelope_size=self._psrp_max_envelope_size,
operation_timeout=self._psrp_operation_timeout,
certificate_key_pem=self._psrp_certificate_key_pem,
certificate_pem=self._psrp_certificate_pem,
credssp_auth_mechanism=self._psrp_credssp_auth_mechanism,
credssp_disable_tlsv1_2=self._psrp_credssp_disable_tlsv1_2,
credssp_minimum_version=self._psrp_credssp_minimum_version,
negotiate_send_cbt=self._psrp_negotiate_send_cbt,
negotiate_delegate=self._psrp_negotiate_delegate,
negotiate_hostname_override=self._psrp_negotiate_hostname_override,
negotiate_service=self._psrp_negotiate_service,
)
# Check if PSRP version supports newer read_timeout argument (needs pypsrp 0.3.0+)
if hasattr(pypsrp, 'FEATURES') and 'wsman_read_timeout' in pypsrp.FEATURES:
self._psrp_conn_kwargs['read_timeout'] = self._psrp_read_timeout
elif self._psrp_read_timeout is not None:
display.warning("ansible_psrp_read_timeout is unsupported by the current psrp version installed, "
"using ansible_psrp_connection_timeout value for read_timeout instead.")
# Check if PSRP version supports newer reconnection_retries argument (needs pypsrp 0.3.0+)
if hasattr(pypsrp, 'FEATURES') and 'wsman_reconnections' in pypsrp.FEATURES:
self._psrp_conn_kwargs['reconnection_retries'] = self._psrp_reconnection_retries
self._psrp_conn_kwargs['reconnection_backoff'] = self._psrp_reconnection_backoff
else:
if self._psrp_reconnection_retries is not None:
display.warning("ansible_psrp_reconnection_retries is unsupported by the current psrp version installed.")
if self._psrp_reconnection_backoff is not None:
display.warning("ansible_psrp_reconnection_backoff is unsupported by the current psrp version installed.")
# add in the extra args that were set
for arg in extra_args.intersection(supported_args):
option = self.get_option('_extras')['ansible_psrp_%s' % arg]
self._psrp_conn_kwargs[arg] = option
def _exec_psrp_script(self, script, input_data=None, use_local_scope=True, force_stop=False):
ps = PowerShell(self.runspace)
ps.add_script(script, use_local_scope=use_local_scope)
ps.invoke(input=input_data)
rc, stdout, stderr = self._parse_pipeline_result(ps)
if force_stop:
# This is usually not needed because we close the Runspace after our exec and we skip the call to close the
# pipeline manually to save on some time. Set to True when running multiple exec calls in the same runspace.
# Current pypsrp versions raise an exception if the current state was not RUNNING. We manually set it so we
# can call stop without any issues.
ps.state = PSInvocationState.RUNNING
ps.stop()
return rc, stdout, stderr
def _parse_pipeline_result(self, pipeline):
"""
PSRP doesn't have the same concept as other protocols with its output.
We need some extra logic to convert the pipeline streams and host
output into the format that Ansible understands.
:param pipeline: The finished PowerShell pipeline that invoked our
commands
:return: rc, stdout, stderr based on the pipeline output
"""
# we try and get the rc from our host implementation, this is set if
# exit or $host.SetShouldExit() is called in our pipeline, if not we
# set to 0 if the pipeline had not errors and 1 if it did
rc = self.host.rc or (1 if pipeline.had_errors else 0)
# TODO: figure out a better way of merging this with the host output
stdout_list = []
for output in pipeline.output:
# Not all pipeline outputs are a string or contain a __str__ value,
# we will create our own output based on the properties of the
# complex object if that is the case.
if isinstance(output, GenericComplexObject) and output.to_string is None:
obj_lines = output.property_sets
for key, value in output.adapted_properties.items():
obj_lines.append(u"%s: %s" % (key, value))
for key, value in output.extended_properties.items():
obj_lines.append(u"%s: %s" % (key, value))
output_msg = u"\n".join(obj_lines)
else:
output_msg = to_text(output, nonstring='simplerepr')
stdout_list.append(output_msg)
if len(self.host.ui.stdout) > 0:
stdout_list += self.host.ui.stdout
stdout = u"\r\n".join(stdout_list)
stderr_list = []
for error in pipeline.streams.error:
# the error record is not as fully fleshed out like we usually get
# in PS, we will manually create it here
command_name = "%s : " % error.command_name if error.command_name else ''
position = "%s\r\n" % error.invocation_position_message if error.invocation_position_message else ''
error_msg = "%s%s\r\n%s" \
" + CategoryInfo : %s\r\n" \
" + FullyQualifiedErrorId : %s" \
% (command_name, str(error), position,
error.message, error.fq_error)
stacktrace = error.script_stacktrace
if self._play_context.verbosity >= 3 and stacktrace is not None:
error_msg += "\r\nStackTrace:\r\n%s" % stacktrace
stderr_list.append(error_msg)
if len(self.host.ui.stderr) > 0:
stderr_list += self.host.ui.stderr
stderr = u"\r\n".join([to_text(o) for o in stderr_list])
display.vvvvv("PSRP RC: %d" % rc, host=self._psrp_host)
display.vvvvv("PSRP STDOUT: %s" % stdout, host=self._psrp_host)
display.vvvvv("PSRP STDERR: %s" % stderr, host=self._psrp_host)
# reset the host back output back to defaults, needed if running
# multiple pipelines on the same RunspacePool
self.host.rc = 0
self.host.ui.stdout = []
self.host.ui.stderr = []
return rc, to_bytes(stdout, encoding='utf-8'), to_bytes(stderr, encoding='utf-8')
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 59,114 |
ansible-galaxy collection build includes previous build artifacts in every new build
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
Every build produces a tarball in the current directory, which includes the full unhidden contents of the current directory. This means it also includes all the _previous_ tarball artifacts created by all the builds that happened before it. So, every version will include all the previous versions built, if the user doens't manually clean them up every time.
The builds by `mazer` were placed in a `releases/` directory which was itself excluded from the builds.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
ansible-galaxy
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.9.0.dev0
config file = /etc/ansible/ansible.cfg
configured module search path = ['/home/calvin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /home/calvin/.local/share/virtualenvs/orion/lib/python3.6/site-packages/ansible
executable location = /home/calvin/.local/share/virtualenvs/orion/bin/ansible
python version = 3.6.8 (default, Mar 21 2019, 10:08:12) [GCC 8.3.1 20190223 (Red Hat 8.3.1-2)]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```
# (empty)
```
##### OS / ENVIRONMENT
Fedora 28
##### STEPS TO REPRODUCE
- Create a collection
- Build the collection
- Increment the version
- Build it again
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
Each build should be about the same, with the files associated with that version, and should only include that version in the build.
##### ACTUAL RESULTS
```(orion) [calvin@localhost orion]$ ansible-galaxy collection install orionuser1.collection_dep_a_wzrzlxeh --server=http://localhost:8000/
[WARNING]: The specified collections path '/home/calvin/projects/orion' is not part of the configured Ansible collections paths
'/home/calvin/.ansible/collections:/usr/share/ansible/collections'. The installed collection won't be picked up in an Ansible run.
Installing 'orionuser1.collection_dep_a_wzrzlxeh:1.0.9' to '/home/calvin/projects/orion/ansible_collections/orionuser1/collection_dep_a_wzrzlxeh'
(orion) [calvin@localhost orion]$ ls ansible_collections/orionuser1/collection_dep_a_wzrzlxeh/
FILES.json orionuser1-collection_dep_a_wzrzlxeh-0.0.1.tar.gz playbooks README.md roles
MANIFEST.json orionuser1-collection_dep_a_wzrzlxeh-0.0.2.tar.gz plugins releases
```
|
https://github.com/ansible/ansible/issues/59114
|
https://github.com/ansible/ansible/pull/59121
|
199c97728f4ad7995721c88cb933d4b90b1afdc9
|
aa0de421d2948c6552770534381e58d6acae7997
| 2019-07-15T20:16:45Z |
python
| 2019-07-22T21:52:30Z |
lib/ansible/galaxy/collection.py
|
# Copyright: (c) 2019, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import fnmatch
import json
import operator
import os
import shutil
import tarfile
import tempfile
import time
import uuid
import yaml
from contextlib import contextmanager
from distutils.version import LooseVersion, StrictVersion
from hashlib import sha256
from io import BytesIO
from yaml.error import YAMLError
import ansible.constants as C
from ansible.errors import AnsibleError
from ansible.galaxy import get_collections_galaxy_meta_info
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.module_utils import six
from ansible.utils.display import Display
from ansible.utils.hashing import secure_hash, secure_hash_s
from ansible.module_utils.urls import open_url
urlparse = six.moves.urllib.parse.urlparse
urllib_error = six.moves.urllib.error
display = Display()
MANIFEST_FORMAT = 1
@six.python_2_unicode_compatible
class CollectionRequirement:
_FILE_MAPPING = [(b'MANIFEST.json', 'manifest_file'), (b'FILES.json', 'files_file')]
def __init__(self, namespace, name, b_path, source, versions, requirement, force, parent=None, validate_certs=True,
metadata=None, files=None, skip=False):
"""
Represents a collection requirement, the versions that are available to be installed as well as any
dependencies the collection has.
:param namespace: The collection namespace.
:param name: The collection name.
:param b_path: Byte str of the path to the collection tarball if it has already been downloaded.
:param source: The Galaxy server URL to download if the collection is from Galaxy.
:param versions: A list of versions of the collection that are available.
:param requirement: The version requirement string used to verify the list of versions fit the requirements.
:param force: Whether the force flag applied to the collection.
:param parent: The name of the parent the collection is a dependency of.
:param validate_certs: Whether to validate the Galaxy server certificate.
:param metadata: The collection metadata dict if it has already been retrieved.
:param files: The files that exist inside the collection. This is based on the FILES.json file inside the
collection artifact.
:param skip: Whether to skip installing the collection. Should be set if the collection is already installed
and force is not set.
"""
self.namespace = namespace
self.name = name
self.b_path = b_path
self.source = source
self.versions = set(versions)
self.force = force
self.skip = skip
self.required_by = []
self._validate_certs = validate_certs
self._metadata = metadata
self._files = files
self._galaxy_info = None
self.add_requirement(parent, requirement)
def __str__(self):
return to_text("%s.%s" % (self.namespace, self.name))
@property
def latest_version(self):
try:
return max([v for v in self.versions if v != '*'], key=LooseVersion)
except ValueError: # ValueError: max() arg is an empty sequence
return '*'
@property
def dependencies(self):
if self._metadata:
return self._metadata['dependencies']
elif len(self.versions) > 1:
return None
self._get_metadata()
return self._metadata['dependencies']
def add_requirement(self, parent, requirement):
self.required_by.append((parent, requirement))
new_versions = set(v for v in self.versions if self._meets_requirements(v, requirement, parent))
if len(new_versions) == 0:
if self.skip:
force_flag = '--force-with-deps' if parent else '--force'
version = self.latest_version if self.latest_version != '*' else 'unknown'
msg = "Cannot meet requirement %s:%s as it is already installed at version '%s'. Use %s to overwrite" \
% (str(self), requirement, version, force_flag)
raise AnsibleError(msg)
elif parent is None:
msg = "Cannot meet requirement %s for dependency %s" % (requirement, str(self))
else:
msg = "Cannot meet dependency requirement '%s:%s' for collection %s" % (str(self), requirement, parent)
collection_source = to_text(self.b_path, nonstring='passthru') or self.source
req_by = "\n".join(
"\t%s - '%s:%s'" % (to_text(p) if p else 'base', str(self), r)
for p, r in self.required_by
)
versions = ", ".join(sorted(self.versions, key=LooseVersion))
raise AnsibleError(
"%s from source '%s'. Available versions before last requirement added: %s\nRequirements from:\n%s"
% (msg, collection_source, versions, req_by)
)
self.versions = new_versions
def install(self, path, b_temp_path):
if self.skip:
display.display("Skipping '%s' as it is already installed" % str(self))
return
# Install if it is not
collection_path = os.path.join(path, self.namespace, self.name)
b_collection_path = to_bytes(collection_path, errors='surrogate_or_strict')
display.display("Installing '%s:%s' to '%s'" % (str(self), self.latest_version,
collection_path))
if self.b_path is None:
download_url = self._galaxy_info['download_url']
artifact_hash = self._galaxy_info['artifact']['sha256']
self.b_path = _download_file(download_url, b_temp_path, artifact_hash, self._validate_certs)
if os.path.exists(b_collection_path):
shutil.rmtree(b_collection_path)
os.makedirs(b_collection_path)
with tarfile.open(self.b_path, mode='r') as collection_tar:
files_member_obj = collection_tar.getmember('FILES.json')
with _tarfile_extract(collection_tar, files_member_obj) as files_obj:
files = json.loads(to_text(files_obj.read(), errors='surrogate_or_strict'))
_extract_tar_file(collection_tar, 'MANIFEST.json', b_collection_path, b_temp_path)
_extract_tar_file(collection_tar, 'FILES.json', b_collection_path, b_temp_path)
for file_info in files['files']:
file_name = file_info['name']
if file_name == '.':
continue
if file_info['ftype'] == 'file':
_extract_tar_file(collection_tar, file_name, b_collection_path, b_temp_path,
expected_hash=file_info['chksum_sha256'])
else:
os.makedirs(os.path.join(b_collection_path, to_bytes(file_name, errors='surrogate_or_strict')))
def set_latest_version(self):
self.versions = set([self.latest_version])
self._get_metadata()
def _get_metadata(self):
if self._metadata:
return
n_collection_url = _urljoin(self.source, 'api', 'v2', 'collections', self.namespace, self.name, 'versions',
self.latest_version)
details = json.load(open_url(n_collection_url, validate_certs=self._validate_certs))
self._galaxy_info = details
self._metadata = details['metadata']
def _meets_requirements(self, version, requirements, parent):
"""
Supports version identifiers can be '==', '!=', '>', '>=', '<', '<=', '*'. Each requirement is delimited by ','
"""
op_map = {
'!=': operator.ne,
'==': operator.eq,
'=': operator.eq,
'>=': operator.ge,
'>': operator.gt,
'<=': operator.le,
'<': operator.lt,
}
for req in list(requirements.split(',')):
op_pos = 2 if len(req) > 1 and req[1] == '=' else 1
op = op_map.get(req[:op_pos])
requirement = req[op_pos:]
if not op:
requirement = req
op = operator.eq
# In the case we are checking a new requirement on a base requirement (parent != None) we can't accept
# version as '*' (unknown version) unless the requirement is also '*'.
if parent and version == '*' and requirement != '*':
break
elif requirement == '*' or version == '*':
continue
if not op(LooseVersion(version), LooseVersion(requirement)):
break
else:
return True
# The loop was broken early, it does not meet all the requirements
return False
@staticmethod
def from_tar(b_path, validate_certs, force, parent=None):
if not tarfile.is_tarfile(b_path):
raise AnsibleError("Collection artifact at '%s' is not a valid tar file." % to_native(b_path))
info = {}
with tarfile.open(b_path, mode='r') as collection_tar:
for b_member_name, property_name in CollectionRequirement._FILE_MAPPING:
n_member_name = to_native(b_member_name)
try:
member = collection_tar.getmember(n_member_name)
except KeyError:
raise AnsibleError("Collection at '%s' does not contain the required file %s."
% (to_native(b_path), n_member_name))
with _tarfile_extract(collection_tar, member) as member_obj:
try:
info[property_name] = json.loads(to_text(member_obj.read(), errors='surrogate_or_strict'))
except ValueError:
raise AnsibleError("Collection tar file member %s does not contain a valid json string."
% n_member_name)
meta = info['manifest_file']['collection_info']
files = info['files_file']['files']
namespace = meta['namespace']
name = meta['name']
version = meta['version']
return CollectionRequirement(namespace, name, b_path, None, [version], version, force, parent=parent,
validate_certs=validate_certs, metadata=meta, files=files)
@staticmethod
def from_path(b_path, validate_certs, force, parent=None):
info = {}
for b_file_name, property_name in CollectionRequirement._FILE_MAPPING:
b_file_path = os.path.join(b_path, b_file_name)
if not os.path.exists(b_file_path):
continue
with open(b_file_path, 'rb') as file_obj:
try:
info[property_name] = json.loads(to_text(file_obj.read(), errors='surrogate_or_strict'))
except ValueError:
raise AnsibleError("Collection file at '%s' does not contain a valid json string."
% to_native(b_file_path))
if 'manifest_file' in info:
meta = info['manifest_file']['collection_info']
else:
display.warning("Collection at '%s' does not have a MANIFEST.json file, cannot detect version."
% to_text(b_path))
parent_dir, name = os.path.split(to_text(b_path, errors='surrogate_or_strict'))
namespace = os.path.split(parent_dir)[1]
meta = {
'namespace': namespace,
'name': name,
'version': '*',
'dependencies': {},
}
namespace = meta['namespace']
name = meta['name']
version = meta['version']
files = info.get('files_file', {}).get('files', {})
return CollectionRequirement(namespace, name, b_path, None, [version], version, force, parent=parent,
validate_certs=validate_certs, metadata=meta, files=files, skip=True)
@staticmethod
def from_name(collection, servers, requirement, validate_certs, force, parent=None):
namespace, name = collection.split('.', 1)
galaxy_info = None
galaxy_meta = None
for server in servers:
collection_url_paths = [server, 'api', 'v2', 'collections', namespace, name, 'versions']
is_single = False
if not (requirement == '*' or requirement.startswith('<') or requirement.startswith('>') or
requirement.startswith('!=')):
if requirement.startswith('='):
requirement = requirement.lstrip('=')
collection_url_paths.append(requirement)
is_single = True
n_collection_url = _urljoin(*collection_url_paths)
try:
resp = json.load(open_url(n_collection_url, validate_certs=validate_certs))
except urllib_error.HTTPError as err:
if err.code == 404:
continue
raise
if is_single:
galaxy_info = resp
galaxy_meta = resp['metadata']
versions = [resp['version']]
else:
versions = []
while True:
# Galaxy supports semver but ansible-galaxy does not. We ignore any versions that don't match
# StrictVersion (x.y.z) and only support pre-releases if an explicit version was set (done above).
versions += [v['version'] for v in resp['results'] if StrictVersion.version_re.match(v['version'])]
if resp['next'] is None:
break
resp = json.load(open_url(to_native(resp['next'], errors='surrogate_or_strict'),
validate_certs=validate_certs))
break
else:
raise AnsibleError("Failed to find collection %s:%s" % (collection, requirement))
req = CollectionRequirement(namespace, name, None, server, versions, requirement, force, parent=parent,
validate_certs=validate_certs, metadata=galaxy_meta)
req._galaxy_info = galaxy_info
return req
def build_collection(collection_path, output_path, force):
"""
Creates the Ansible collection artifact in a .tar.gz file.
:param collection_path: The path to the collection to build. This should be the directory that contains the
galaxy.yml file.
:param output_path: The path to create the collection build artifact. This should be a directory.
:param force: Whether to overwrite an existing collection build artifact or fail.
:return: The path to the collection build artifact.
"""
b_collection_path = to_bytes(collection_path, errors='surrogate_or_strict')
b_galaxy_path = os.path.join(b_collection_path, b'galaxy.yml')
if not os.path.exists(b_galaxy_path):
raise AnsibleError("The collection galaxy.yml path '%s' does not exist." % to_native(b_galaxy_path))
collection_meta = _get_galaxy_yml(b_galaxy_path)
file_manifest = _build_files_manifest(b_collection_path)
collection_manifest = _build_manifest(**collection_meta)
collection_output = os.path.join(output_path, "%s-%s-%s.tar.gz" % (collection_meta['namespace'],
collection_meta['name'],
collection_meta['version']))
b_collection_output = to_bytes(collection_output, errors='surrogate_or_strict')
if os.path.exists(b_collection_output):
if os.path.isdir(b_collection_output):
raise AnsibleError("The output collection artifact '%s' already exists, "
"but is a directory - aborting" % to_native(collection_output))
elif not force:
raise AnsibleError("The file '%s' already exists. You can use --force to re-create "
"the collection artifact." % to_native(collection_output))
_build_collection_tar(b_collection_path, b_collection_output, collection_manifest, file_manifest)
def publish_collection(collection_path, server, key, ignore_certs, wait):
"""
Publish an Ansible collection tarball into an Ansible Galaxy server.
:param collection_path: The path to the collection tarball to publish.
:param server: A native string of the Ansible Galaxy server to publish to.
:param key: The API key to use for authorization.
:param ignore_certs: Whether to ignore certificate validation when interacting with the server.
"""
b_collection_path = to_bytes(collection_path, errors='surrogate_or_strict')
if not os.path.exists(b_collection_path):
raise AnsibleError("The collection path specified '%s' does not exist." % to_native(collection_path))
elif not tarfile.is_tarfile(b_collection_path):
raise AnsibleError("The collection path specified '%s' is not a tarball, use 'ansible-galaxy collection "
"build' to create a proper release artifact." % to_native(collection_path))
display.display("Publishing collection artifact '%s' to %s" % (collection_path, server))
n_url = _urljoin(server, 'api', 'v2', 'collections')
data, content_type = _get_mime_data(b_collection_path)
headers = {
'Content-type': content_type,
'Content-length': len(data),
}
if key:
headers['Authorization'] = "Token %s" % key
validate_certs = not ignore_certs
try:
resp = json.load(open_url(n_url, data=data, headers=headers, method='POST', validate_certs=validate_certs))
except urllib_error.HTTPError as err:
try:
err_info = json.load(err)
except (AttributeError, ValueError):
err_info = {}
code = to_native(err_info.get('code', 'Unknown'))
message = to_native(err_info.get('message', 'Unknown error returned by Galaxy server.'))
raise AnsibleError("Error when publishing collection (HTTP Code: %d, Message: %s Code: %s)"
% (err.code, message, code))
display.vvv("Collection has been pushed to the Galaxy server %s" % server)
import_uri = resp['task']
if wait:
_wait_import(import_uri, key, validate_certs)
display.display("Collection has been successfully published to the Galaxy server")
else:
display.display("Collection has been pushed to the Galaxy server, not waiting until import has completed "
"due to --no-wait being set. Import task results can be found at %s" % import_uri)
def install_collections(collections, output_path, servers, validate_certs, ignore_errors, no_deps, force, force_deps):
"""
Install Ansible collections to the path specified.
:param collections: The collections to install, should be a list of tuples with (name, requirement, Galaxy server).
:param output_path: The path to install the collections to.
:param servers: A list of Galaxy servers to query when searching for a collection.
:param validate_certs: Whether to validate the Galaxy server certificates.
:param ignore_errors: Whether to ignore any errors when installing the collection.
:param no_deps: Ignore any collection dependencies and only install the base requirements.
:param force: Re-install a collection if it has already been installed.
:param force_deps: Re-install a collection as well as its dependencies if they have already been installed.
"""
existing_collections = _find_existing_collections(output_path)
with _tempdir() as b_temp_path:
dependency_map = _build_dependency_map(collections, existing_collections, b_temp_path, servers, validate_certs,
force, force_deps, no_deps)
for collection in dependency_map.values():
try:
collection.install(output_path, b_temp_path)
except AnsibleError as err:
if ignore_errors:
display.warning("Failed to install collection %s but skipping due to --ignore-errors being set. "
"Error: %s" % (str(collection), to_text(err)))
else:
raise
def parse_collections_requirements_file(requirements_file):
"""
Parses an Ansible requirement.yml file and returns all the collections defined in it. This value ca be used with
install_collection(). The requirements file is in the form:
---
collections:
- namespace.collection
- name: namespace.collection
version: version identifier, multiple identifiers are separated by ','
source: the URL or prededefined source name in ~/.ansible_galaxy to pull the collection from
:param requirements_file: The path to the requirements file.
:return: A list of tuples (name, version, source).
"""
collection_info = []
b_requirements_file = to_bytes(requirements_file, errors='surrogate_or_strict')
if not os.path.exists(b_requirements_file):
raise AnsibleError("The requirements file '%s' does not exist." % to_native(requirements_file))
display.vvv("Reading collection requirement file at '%s'" % requirements_file)
with open(b_requirements_file, 'rb') as req_obj:
try:
requirements = yaml.safe_load(req_obj)
except YAMLError as err:
raise AnsibleError("Failed to parse the collection requirements yml at '%s' with the following error:\n%s"
% (to_native(requirements_file), to_native(err)))
if not isinstance(requirements, dict) or 'collections' not in requirements:
# TODO: Link to documentation page that documents the requirements.yml format for collections.
raise AnsibleError("Expecting collections requirements file to be a dict with the key "
"collections that contains a list of collections to install.")
for collection_req in requirements['collections']:
if isinstance(collection_req, dict):
req_name = collection_req.get('name', None)
if req_name is None:
raise AnsibleError("Collections requirement entry should contain the key name.")
req_version = collection_req.get('version', '*')
req_source = collection_req.get('source', None)
collection_info.append((req_name, req_version, req_source))
else:
collection_info.append((collection_req, '*', None))
return collection_info
@contextmanager
def _tempdir():
b_temp_path = tempfile.mkdtemp(dir=to_bytes(C.DEFAULT_LOCAL_TMP, errors='surrogate_or_strict'))
yield b_temp_path
shutil.rmtree(b_temp_path)
@contextmanager
def _tarfile_extract(tar, member):
tar_obj = tar.extractfile(member)
yield tar_obj
tar_obj.close()
def _get_galaxy_yml(b_galaxy_yml_path):
meta_info = get_collections_galaxy_meta_info()
mandatory_keys = set()
string_keys = set()
list_keys = set()
dict_keys = set()
for info in meta_info:
if info.get('required', False):
mandatory_keys.add(info['key'])
key_list_type = {
'str': string_keys,
'list': list_keys,
'dict': dict_keys,
}[info.get('type', 'str')]
key_list_type.add(info['key'])
all_keys = frozenset(list(mandatory_keys) + list(string_keys) + list(list_keys) + list(dict_keys))
try:
with open(b_galaxy_yml_path, 'rb') as g_yaml:
galaxy_yml = yaml.safe_load(g_yaml)
except YAMLError as err:
raise AnsibleError("Failed to parse the galaxy.yml at '%s' with the following error:\n%s"
% (to_native(b_galaxy_yml_path), to_native(err)))
set_keys = set(galaxy_yml.keys())
missing_keys = mandatory_keys.difference(set_keys)
if missing_keys:
raise AnsibleError("The collection galaxy.yml at '%s' is missing the following mandatory keys: %s"
% (to_native(b_galaxy_yml_path), ", ".join(sorted(missing_keys))))
extra_keys = set_keys.difference(all_keys)
if len(extra_keys) > 0:
display.warning("Found unknown keys in collection galaxy.yml at '%s': %s"
% (to_text(b_galaxy_yml_path), ", ".join(extra_keys)))
# Add the defaults if they have not been set
for optional_string in string_keys:
if optional_string not in galaxy_yml:
galaxy_yml[optional_string] = None
for optional_list in list_keys:
list_val = galaxy_yml.get(optional_list, None)
if list_val is None:
galaxy_yml[optional_list] = []
elif not isinstance(list_val, list):
galaxy_yml[optional_list] = [list_val]
for optional_dict in dict_keys:
if optional_dict not in galaxy_yml:
galaxy_yml[optional_dict] = {}
# license is a builtin var in Python, to avoid confusion we just rename it to license_ids
galaxy_yml['license_ids'] = galaxy_yml['license']
del galaxy_yml['license']
return galaxy_yml
def _build_files_manifest(b_collection_path):
b_ignore_files = frozenset([b'*.pyc', b'*.retry'])
b_ignore_dirs = frozenset([b'CVS', b'.bzr', b'.hg', b'.git', b'.svn', b'__pycache__', b'.tox'])
entry_template = {
'name': None,
'ftype': None,
'chksum_type': None,
'chksum_sha256': None,
'format': MANIFEST_FORMAT
}
manifest = {
'files': [
{
'name': '.',
'ftype': 'dir',
'chksum_type': None,
'chksum_sha256': None,
'format': MANIFEST_FORMAT,
},
],
'format': MANIFEST_FORMAT,
}
def _walk(b_path, b_top_level_dir):
for b_item in os.listdir(b_path):
b_abs_path = os.path.join(b_path, b_item)
b_rel_base_dir = b'' if b_path == b_top_level_dir else b_path[len(b_top_level_dir) + 1:]
rel_path = to_text(os.path.join(b_rel_base_dir, b_item), errors='surrogate_or_strict')
if os.path.isdir(b_abs_path):
if b_item in b_ignore_dirs:
display.vvv("Skipping '%s' for collection build" % to_text(b_abs_path))
continue
if os.path.islink(b_abs_path):
b_link_target = os.path.realpath(b_abs_path)
if not b_link_target.startswith(b_top_level_dir):
display.warning("Skipping '%s' as it is a symbolic link to a directory outside the collection"
% to_text(b_abs_path))
continue
manifest_entry = entry_template.copy()
manifest_entry['name'] = rel_path
manifest_entry['ftype'] = 'dir'
manifest['files'].append(manifest_entry)
_walk(b_abs_path, b_top_level_dir)
else:
if b_item == b'galaxy.yml':
continue
elif any(fnmatch.fnmatch(b_item, b_pattern) for b_pattern in b_ignore_files):
display.vvv("Skipping '%s' for collection build" % to_text(b_abs_path))
continue
manifest_entry = entry_template.copy()
manifest_entry['name'] = rel_path
manifest_entry['ftype'] = 'file'
manifest_entry['chksum_type'] = 'sha256'
manifest_entry['chksum_sha256'] = secure_hash(b_abs_path, hash_func=sha256)
manifest['files'].append(manifest_entry)
_walk(b_collection_path, b_collection_path)
return manifest
def _build_manifest(namespace, name, version, authors, readme, tags, description, license_ids, license_file,
dependencies, repository, documentation, homepage, issues, **kwargs):
manifest = {
'collection_info': {
'namespace': namespace,
'name': name,
'version': version,
'authors': authors,
'readme': readme,
'tags': tags,
'description': description,
'license': license_ids,
'license_file': license_file if license_file else None, # Handle galaxy.yml having an empty string (None)
'dependencies': dependencies,
'repository': repository,
'documentation': documentation,
'homepage': homepage,
'issues': issues,
},
'file_manifest_file': {
'name': 'FILES.json',
'ftype': 'file',
'chksum_type': 'sha256',
'chksum_sha256': None, # Filled out in _build_collection_tar
'format': MANIFEST_FORMAT
},
'format': MANIFEST_FORMAT,
}
return manifest
def _build_collection_tar(b_collection_path, b_tar_path, collection_manifest, file_manifest):
files_manifest_json = to_bytes(json.dumps(file_manifest, indent=True), errors='surrogate_or_strict')
collection_manifest['file_manifest_file']['chksum_sha256'] = secure_hash_s(files_manifest_json, hash_func=sha256)
collection_manifest_json = to_bytes(json.dumps(collection_manifest, indent=True), errors='surrogate_or_strict')
with _tempdir() as b_temp_path:
b_tar_filepath = os.path.join(b_temp_path, os.path.basename(b_tar_path))
with tarfile.open(b_tar_filepath, mode='w:gz') as tar_file:
# Add the MANIFEST.json and FILES.json file to the archive
for name, b in [('MANIFEST.json', collection_manifest_json), ('FILES.json', files_manifest_json)]:
b_io = BytesIO(b)
tar_info = tarfile.TarInfo(name)
tar_info.size = len(b)
tar_info.mtime = time.time()
tar_info.mode = 0o0644
tar_file.addfile(tarinfo=tar_info, fileobj=b_io)
for file_info in file_manifest['files']:
if file_info['name'] == '.':
continue
# arcname expects a native string, cannot be bytes
filename = to_native(file_info['name'], errors='surrogate_or_strict')
b_src_path = os.path.join(b_collection_path, to_bytes(filename, errors='surrogate_or_strict'))
def reset_stat(tarinfo):
tarinfo.mode = 0o0755 if tarinfo.isdir() else 0o0644
tarinfo.uid = tarinfo.gid = 0
tarinfo.uname = tarinfo.gname = ''
return tarinfo
tar_file.add(os.path.realpath(b_src_path), arcname=filename, recursive=False, filter=reset_stat)
shutil.copy(b_tar_filepath, b_tar_path)
collection_name = "%s.%s" % (collection_manifest['collection_info']['namespace'],
collection_manifest['collection_info']['name'])
display.display('Created collection for %s at %s' % (collection_name, to_text(b_tar_path)))
def _get_mime_data(b_collection_path):
with open(b_collection_path, 'rb') as collection_tar:
data = collection_tar.read()
boundary = '--------------------------%s' % uuid.uuid4().hex
b_file_name = os.path.basename(b_collection_path)
part_boundary = b"--" + to_bytes(boundary, errors='surrogate_or_strict')
form = [
part_boundary,
b"Content-Disposition: form-data; name=\"sha256\"",
to_bytes(secure_hash_s(data), errors='surrogate_or_strict'),
part_boundary,
b"Content-Disposition: file; name=\"file\"; filename=\"%s\"" % b_file_name,
b"Content-Type: application/octet-stream",
b"",
data,
b"%s--" % part_boundary,
]
content_type = 'multipart/form-data; boundary=%s' % boundary
return b"\r\n".join(form), content_type
def _wait_import(task_url, key, validate_certs):
headers = {}
if key:
headers['Authorization'] = "Token %s" % key
display.vvv('Waiting until galaxy import task %s has completed' % task_url)
wait = 2
while True:
resp = json.load(open_url(to_native(task_url, errors='surrogate_or_strict'), headers=headers, method='GET',
validate_certs=validate_certs))
if resp.get('finished_at', None):
break
elif wait > 20:
# We try for a maximum of ~60 seconds before giving up in case something has gone wrong on the server end.
raise AnsibleError("Timeout while waiting for the Galaxy import process to finish, check progress at '%s'"
% to_native(task_url))
status = resp.get('status', 'waiting')
display.vvv('Galaxy import process has a status of %s, wait %d seconds before trying again' % (status, wait))
time.sleep(wait)
wait *= 1.5 # poor man's exponential backoff algo so we don't flood the Galaxy API.
for message in resp.get('messages', []):
level = message['level']
if level == 'error':
display.error("Galaxy import error message: %s" % message['message'])
elif level == 'warning':
display.warning("Galaxy import warning message: %s" % message['message'])
else:
display.vvv("Galaxy import message: %s - %s" % (level, message['message']))
if resp['state'] == 'failed':
code = to_native(resp['error'].get('code', 'UNKNOWN'))
description = to_native(resp['error'].get('description', "Unknown error, see %s for more details" % task_url))
raise AnsibleError("Galaxy import process failed: %s (Code: %s)" % (description, code))
def _find_existing_collections(path):
collections = []
b_path = to_bytes(path, errors='surrogate_or_strict')
for b_namespace in os.listdir(b_path):
b_namespace_path = os.path.join(b_path, b_namespace)
if os.path.isfile(b_namespace_path):
continue
for b_collection in os.listdir(b_namespace_path):
b_collection_path = os.path.join(b_namespace_path, b_collection)
if os.path.isdir(b_collection_path):
req = CollectionRequirement.from_path(b_collection_path, True, False)
display.vvv("Found installed collection %s:%s at '%s'" % (str(req), req.latest_version,
to_text(b_collection_path)))
collections.append(req)
return collections
def _build_dependency_map(collections, existing_collections, b_temp_path, servers, validate_certs, force, force_deps,
no_deps):
dependency_map = {}
# First build the dependency map on the actual requirements
for name, version, source in collections:
_get_collection_info(dependency_map, existing_collections, name, version, source, b_temp_path, servers,
validate_certs, (force or force_deps))
checked_parents = set([str(c) for c in dependency_map.values() if c.skip])
while len(dependency_map) != len(checked_parents):
while not no_deps: # Only parse dependencies if no_deps was not set
parents_to_check = set(dependency_map.keys()).difference(checked_parents)
deps_exhausted = True
for parent in parents_to_check:
parent_info = dependency_map[parent]
if parent_info.dependencies:
deps_exhausted = False
for dep_name, dep_requirement in parent_info.dependencies.items():
_get_collection_info(dependency_map, existing_collections, dep_name, dep_requirement,
parent_info.source, b_temp_path, servers, validate_certs, force_deps,
parent=parent)
checked_parents.add(parent)
# No extra dependencies were resolved, exit loop
if deps_exhausted:
break
# Now we have resolved the deps to our best extent, now select the latest version for collections with
# multiple versions found and go from there
deps_not_checked = set(dependency_map.keys()).difference(checked_parents)
for collection in deps_not_checked:
dependency_map[collection].set_latest_version()
if no_deps or len(dependency_map[collection].dependencies) == 0:
checked_parents.add(collection)
return dependency_map
def _get_collection_info(dep_map, existing_collections, collection, requirement, source, b_temp_path, server_list,
validate_certs, force, parent=None):
dep_msg = ""
if parent:
dep_msg = " - as dependency of %s" % parent
display.vvv("Processing requirement collection '%s'%s" % (to_text(collection), dep_msg))
b_tar_path = None
if os.path.isfile(to_bytes(collection, errors='surrogate_or_strict')):
display.vvvv("Collection requirement '%s' is a tar artifact" % to_text(collection))
b_tar_path = to_bytes(collection, errors='surrogate_or_strict')
elif urlparse(collection).scheme:
display.vvvv("Collection requirement '%s' is a URL to a tar artifact" % collection)
b_tar_path = _download_file(collection, b_temp_path, None, validate_certs)
if b_tar_path:
req = CollectionRequirement.from_tar(b_tar_path, validate_certs, force, parent=parent)
collection_name = str(req)
if collection_name in dep_map:
collection_info = dep_map[collection_name]
collection_info.add_requirement(None, req.latest_version)
else:
collection_info = req
else:
display.vvvv("Collection requirement '%s' is the name of a collection" % collection)
if collection in dep_map:
collection_info = dep_map[collection]
collection_info.add_requirement(parent, requirement)
else:
servers = [source] if source else server_list
collection_info = CollectionRequirement.from_name(collection, servers, requirement, validate_certs, force,
parent=parent)
existing = [c for c in existing_collections if str(c) == str(collection_info)]
if existing and not collection_info.force:
# Test that the installed collection fits the requirement
existing[0].add_requirement(str(collection_info), requirement)
collection_info = existing[0]
dep_map[str(collection_info)] = collection_info
def _urljoin(*args):
return '/'.join(to_native(a, errors='surrogate_or_strict').rstrip('/') for a in args + ('',))
def _download_file(url, b_path, expected_hash, validate_certs):
bufsize = 65536
digest = sha256()
urlsplit = os.path.splitext(to_text(url.rsplit('/', 1)[1]))
b_file_name = to_bytes(urlsplit[0], errors='surrogate_or_strict')
b_file_ext = to_bytes(urlsplit[1], errors='surrogate_or_strict')
b_file_path = tempfile.NamedTemporaryFile(dir=b_path, prefix=b_file_name, suffix=b_file_ext, delete=False).name
display.vvv("Downloading %s to %s" % (url, to_text(b_path)))
resp = open_url(to_native(url, errors='surrogate_or_strict'), validate_certs=validate_certs)
with open(b_file_path, 'wb') as download_file:
data = resp.read(bufsize)
while data:
digest.update(data)
download_file.write(data)
data = resp.read(bufsize)
if expected_hash:
actual_hash = digest.hexdigest()
display.vvvv("Validating downloaded file hash %s with expected hash %s" % (actual_hash, expected_hash))
if expected_hash != actual_hash:
raise AnsibleError("Mismatch artifact hash with downloaded file")
return b_file_path
def _extract_tar_file(tar, filename, b_dest, b_temp_path, expected_hash=None):
n_filename = to_native(filename, errors='surrogate_or_strict')
try:
member = tar.getmember(n_filename)
except KeyError:
raise AnsibleError("Collection tar at '%s' does not contain the expected file '%s'." % (to_native(tar.name),
n_filename))
with tempfile.NamedTemporaryFile(dir=b_temp_path, delete=False) as tmpfile_obj:
bufsize = 65536
sha256_digest = sha256()
with _tarfile_extract(tar, member) as tar_obj:
data = tar_obj.read(bufsize)
while data:
tmpfile_obj.write(data)
tmpfile_obj.flush()
sha256_digest.update(data)
data = tar_obj.read(bufsize)
actual_hash = sha256_digest.hexdigest()
if expected_hash and actual_hash != expected_hash:
raise AnsibleError("Checksum mismatch for '%s' inside collection at '%s'"
% (n_filename, to_native(tar.name)))
b_dest_filepath = os.path.join(b_dest, to_bytes(filename, errors='surrogate_or_strict'))
b_parent_dir = os.path.split(b_dest_filepath)[0]
if not os.path.exists(b_parent_dir):
# Seems like Galaxy does not validate if all file entries have a corresponding dir ftype entry. This check
# makes sure we create the parent directory even if it wasn't set in the metadata.
os.makedirs(b_parent_dir)
shutil.move(to_bytes(tmpfile_obj.name, errors='surrogate_or_strict'), b_dest_filepath)
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 59,114 |
ansible-galaxy collection build includes previous build artifacts in every new build
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
Every build produces a tarball in the current directory, which includes the full unhidden contents of the current directory. This means it also includes all the _previous_ tarball artifacts created by all the builds that happened before it. So, every version will include all the previous versions built, if the user doens't manually clean them up every time.
The builds by `mazer` were placed in a `releases/` directory which was itself excluded from the builds.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
ansible-galaxy
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.9.0.dev0
config file = /etc/ansible/ansible.cfg
configured module search path = ['/home/calvin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /home/calvin/.local/share/virtualenvs/orion/lib/python3.6/site-packages/ansible
executable location = /home/calvin/.local/share/virtualenvs/orion/bin/ansible
python version = 3.6.8 (default, Mar 21 2019, 10:08:12) [GCC 8.3.1 20190223 (Red Hat 8.3.1-2)]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```
# (empty)
```
##### OS / ENVIRONMENT
Fedora 28
##### STEPS TO REPRODUCE
- Create a collection
- Build the collection
- Increment the version
- Build it again
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
Each build should be about the same, with the files associated with that version, and should only include that version in the build.
##### ACTUAL RESULTS
```(orion) [calvin@localhost orion]$ ansible-galaxy collection install orionuser1.collection_dep_a_wzrzlxeh --server=http://localhost:8000/
[WARNING]: The specified collections path '/home/calvin/projects/orion' is not part of the configured Ansible collections paths
'/home/calvin/.ansible/collections:/usr/share/ansible/collections'. The installed collection won't be picked up in an Ansible run.
Installing 'orionuser1.collection_dep_a_wzrzlxeh:1.0.9' to '/home/calvin/projects/orion/ansible_collections/orionuser1/collection_dep_a_wzrzlxeh'
(orion) [calvin@localhost orion]$ ls ansible_collections/orionuser1/collection_dep_a_wzrzlxeh/
FILES.json orionuser1-collection_dep_a_wzrzlxeh-0.0.1.tar.gz playbooks README.md roles
MANIFEST.json orionuser1-collection_dep_a_wzrzlxeh-0.0.2.tar.gz plugins releases
```
|
https://github.com/ansible/ansible/issues/59114
|
https://github.com/ansible/ansible/pull/59121
|
199c97728f4ad7995721c88cb933d4b90b1afdc9
|
aa0de421d2948c6552770534381e58d6acae7997
| 2019-07-15T20:16:45Z |
python
| 2019-07-22T21:52:30Z |
test/units/galaxy/test_collection.py
|
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
import os
import pytest
import re
import tarfile
import tempfile
import time
import uuid
from hashlib import sha256
from io import BytesIO, StringIO
from units.compat.mock import MagicMock
import ansible.module_utils.six.moves.urllib.error as urllib_error
from ansible.cli.galaxy import GalaxyCLI
from ansible.errors import AnsibleError
from ansible.galaxy import collection
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.utils import context_objects as co
from ansible.utils.display import Display
from ansible.utils.hashing import secure_hash_s
@pytest.fixture(autouse='function')
def reset_cli_args():
co.GlobalCLIArgs._Singleton__instance = None
yield
co.GlobalCLIArgs._Singleton__instance = None
@pytest.fixture()
def collection_input(tmp_path_factory):
''' Creates a collection skeleton directory for build tests '''
test_dir = to_text(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Input'))
namespace = 'ansible_namespace'
collection = 'collection'
skeleton = os.path.join(os.path.dirname(os.path.split(__file__)[0]), 'cli', 'test_data', 'collection_skeleton')
galaxy_args = ['ansible-galaxy', 'collection', 'init', '%s.%s' % (namespace, collection),
'-c', '--init-path', test_dir, '--collection-skeleton', skeleton]
GalaxyCLI(args=galaxy_args).run()
collection_dir = os.path.join(test_dir, namespace, collection)
output_dir = to_text(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Output'))
return collection_dir, output_dir
@pytest.fixture()
def collection_artifact(monkeypatch, tmp_path_factory):
''' Creates a temp collection artifact and mocked open_url instance for publishing tests '''
mock_open = MagicMock()
monkeypatch.setattr(collection, 'open_url', mock_open)
mock_uuid = MagicMock()
mock_uuid.return_value.hex = 'uuid'
monkeypatch.setattr(uuid, 'uuid4', mock_uuid)
tmp_path = tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections')
input_file = to_text(tmp_path / 'collection.tar.gz')
with tarfile.open(input_file, 'w:gz') as tfile:
b_io = BytesIO(b"\x00\x01\x02\x03")
tar_info = tarfile.TarInfo('test')
tar_info.size = 4
tar_info.mode = 0o0644
tfile.addfile(tarinfo=tar_info, fileobj=b_io)
return input_file, mock_open
@pytest.fixture()
def requirements_file(request, tmp_path_factory):
content = request.param
test_dir = to_text(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections Requirements'))
requirements_file = os.path.join(test_dir, 'requirements.yml')
if content:
with open(requirements_file, 'wb') as req_obj:
req_obj.write(to_bytes(content))
yield requirements_file
@pytest.fixture()
def galaxy_yml(request, tmp_path_factory):
b_test_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections'))
b_galaxy_yml = os.path.join(b_test_dir, b'galaxy.yml')
with open(b_galaxy_yml, 'wb') as galaxy_obj:
galaxy_obj.write(to_bytes(request.param))
yield b_galaxy_yml
@pytest.fixture()
def tmp_tarfile(tmp_path_factory):
''' Creates a temporary tar file for _extract_tar_file tests '''
filename = u'ÅÑŚÌβŁÈ'
temp_dir = to_bytes(tmp_path_factory.mktemp('test-%s Collections' % to_native(filename)))
tar_file = os.path.join(temp_dir, to_bytes('%s.tar.gz' % filename))
data = os.urandom(8)
with tarfile.open(tar_file, 'w:gz') as tfile:
b_io = BytesIO(data)
tar_info = tarfile.TarInfo(filename)
tar_info.size = len(data)
tar_info.mode = 0o0644
tfile.addfile(tarinfo=tar_info, fileobj=b_io)
sha256_hash = sha256()
sha256_hash.update(data)
with tarfile.open(tar_file, 'r') as tfile:
yield temp_dir, tfile, filename, sha256_hash.hexdigest()
def test_build_collection_no_galaxy_yaml():
fake_path = u'/fake/ÅÑŚÌβŁÈ/path'
expected = to_native("The collection galaxy.yml path '%s/galaxy.yml' does not exist." % fake_path)
with pytest.raises(AnsibleError, match=expected):
collection.build_collection(fake_path, 'output', False)
def test_build_existing_output_file(collection_input):
input_dir, output_dir = collection_input
existing_output_dir = os.path.join(output_dir, 'ansible_namespace-collection-0.1.0.tar.gz')
os.makedirs(existing_output_dir)
expected = "The output collection artifact '%s' already exists, but is a directory - aborting" \
% to_native(existing_output_dir)
with pytest.raises(AnsibleError, match=expected):
collection.build_collection(input_dir, output_dir, False)
def test_build_existing_output_without_force(collection_input):
input_dir, output_dir = collection_input
existing_output = os.path.join(output_dir, 'ansible_namespace-collection-0.1.0.tar.gz')
with open(existing_output, 'w+') as out_file:
out_file.write("random garbage")
out_file.flush()
expected = "The file '%s' already exists. You can use --force to re-create the collection artifact." \
% to_native(existing_output)
with pytest.raises(AnsibleError, match=expected):
collection.build_collection(input_dir, output_dir, False)
def test_build_existing_output_with_force(collection_input):
input_dir, output_dir = collection_input
existing_output = os.path.join(output_dir, 'ansible_namespace-collection-0.1.0.tar.gz')
with open(existing_output, 'w+') as out_file:
out_file.write("random garbage")
out_file.flush()
collection.build_collection(input_dir, output_dir, True)
# Verify the file was replaced with an actual tar file
assert tarfile.is_tarfile(existing_output)
@pytest.mark.parametrize('galaxy_yml', [b'namespace: value: broken'], indirect=True)
def test_invalid_yaml_galaxy_file(galaxy_yml):
expected = to_native(b"Failed to parse the galaxy.yml at '%s' with the following error:" % galaxy_yml)
with pytest.raises(AnsibleError, match=expected):
collection._get_galaxy_yml(galaxy_yml)
@pytest.mark.parametrize('galaxy_yml', [b'namespace: test_namespace'], indirect=True)
def test_missing_required_galaxy_key(galaxy_yml):
expected = "The collection galaxy.yml at '%s' is missing the following mandatory keys: authors, name, " \
"readme, version" % to_native(galaxy_yml)
with pytest.raises(AnsibleError, match=expected):
collection._get_galaxy_yml(galaxy_yml)
@pytest.mark.parametrize('galaxy_yml', [b"""
namespace: namespace
name: collection
authors: Jordan
version: 0.1.0
readme: README.md
invalid: value"""], indirect=True)
def test_warning_extra_keys(galaxy_yml, monkeypatch):
display_mock = MagicMock()
monkeypatch.setattr(Display, 'warning', display_mock)
collection._get_galaxy_yml(galaxy_yml)
assert display_mock.call_count == 1
assert display_mock.call_args[0][0] == "Found unknown keys in collection galaxy.yml at '%s': invalid"\
% to_text(galaxy_yml)
@pytest.mark.parametrize('galaxy_yml', [b"""
namespace: namespace
name: collection
authors: Jordan
version: 0.1.0
readme: README.md"""], indirect=True)
def test_defaults_galaxy_yml(galaxy_yml):
actual = collection._get_galaxy_yml(galaxy_yml)
assert actual['namespace'] == 'namespace'
assert actual['name'] == 'collection'
assert actual['authors'] == ['Jordan']
assert actual['version'] == '0.1.0'
assert actual['readme'] == 'README.md'
assert actual['description'] is None
assert actual['repository'] is None
assert actual['documentation'] is None
assert actual['homepage'] is None
assert actual['issues'] is None
assert actual['tags'] == []
assert actual['dependencies'] == {}
assert actual['license_ids'] == []
@pytest.mark.parametrize('galaxy_yml', [(b"""
namespace: namespace
name: collection
authors: Jordan
version: 0.1.0
readme: README.md
license: MIT"""), (b"""
namespace: namespace
name: collection
authors: Jordan
version: 0.1.0
readme: README.md
license:
- MIT""")], indirect=True)
def test_galaxy_yml_list_value(galaxy_yml):
actual = collection._get_galaxy_yml(galaxy_yml)
assert actual['license_ids'] == ['MIT']
def test_build_ignore_files_and_folders(collection_input, monkeypatch):
input_dir = collection_input[0]
mock_display = MagicMock()
monkeypatch.setattr(Display, 'vvv', mock_display)
git_folder = os.path.join(input_dir, '.git')
retry_file = os.path.join(input_dir, 'ansible.retry')
os.makedirs(git_folder)
with open(retry_file, 'w+') as ignore_file:
ignore_file.write('random')
ignore_file.flush()
actual = collection._build_files_manifest(to_bytes(input_dir))
assert actual['format'] == 1
for manifest_entry in actual['files']:
assert manifest_entry['name'] not in ['.git', 'ansible.retry', 'galaxy.yml']
expected_msgs = [
"Skipping '%s' for collection build" % to_text(retry_file),
"Skipping '%s' for collection build" % to_text(git_folder),
]
assert mock_display.call_count == 2
assert mock_display.mock_calls[0][1][0] in expected_msgs
assert mock_display.mock_calls[1][1][0] in expected_msgs
def test_build_ignore_symlink_target_outside_collection(collection_input, monkeypatch):
input_dir, outside_dir = collection_input
mock_display = MagicMock()
monkeypatch.setattr(Display, 'warning', mock_display)
link_path = os.path.join(input_dir, 'plugins', 'connection')
os.symlink(outside_dir, link_path)
actual = collection._build_files_manifest(to_bytes(input_dir))
for manifest_entry in actual['files']:
assert manifest_entry['name'] != 'plugins/connection'
assert mock_display.call_count == 1
assert mock_display.mock_calls[0][1][0] == "Skipping '%s' as it is a symbolic link to a directory outside " \
"the collection" % to_text(link_path)
def test_build_copy_symlink_target_inside_collection(collection_input):
input_dir = collection_input[0]
os.makedirs(os.path.join(input_dir, 'playbooks', 'roles'))
roles_link = os.path.join(input_dir, 'playbooks', 'roles', 'linked')
roles_target = os.path.join(input_dir, 'roles', 'linked')
roles_target_tasks = os.path.join(roles_target, 'tasks')
os.makedirs(roles_target_tasks)
with open(os.path.join(roles_target_tasks, 'main.yml'), 'w+') as tasks_main:
tasks_main.write("---\n- hosts: localhost\n tasks:\n - ping:")
tasks_main.flush()
os.symlink(roles_target, roles_link)
actual = collection._build_files_manifest(to_bytes(input_dir))
linked_entries = [e for e in actual['files'] if e['name'].startswith('playbooks/roles/linked')]
assert len(linked_entries) == 3
assert linked_entries[0]['name'] == 'playbooks/roles/linked'
assert linked_entries[0]['ftype'] == 'dir'
assert linked_entries[1]['name'] == 'playbooks/roles/linked/tasks'
assert linked_entries[1]['ftype'] == 'dir'
assert linked_entries[2]['name'] == 'playbooks/roles/linked/tasks/main.yml'
assert linked_entries[2]['ftype'] == 'file'
assert linked_entries[2]['chksum_sha256'] == '9c97a1633c51796999284c62236b8d5462903664640079b80c37bf50080fcbc3'
def test_build_with_symlink_inside_collection(collection_input):
input_dir, output_dir = collection_input
os.makedirs(os.path.join(input_dir, 'playbooks', 'roles'))
roles_link = os.path.join(input_dir, 'playbooks', 'roles', 'linked')
file_link = os.path.join(input_dir, 'docs', 'README.md')
roles_target = os.path.join(input_dir, 'roles', 'linked')
roles_target_tasks = os.path.join(roles_target, 'tasks')
os.makedirs(roles_target_tasks)
with open(os.path.join(roles_target_tasks, 'main.yml'), 'w+') as tasks_main:
tasks_main.write("---\n- hosts: localhost\n tasks:\n - ping:")
tasks_main.flush()
os.symlink(roles_target, roles_link)
os.symlink(os.path.join(input_dir, 'README.md'), file_link)
collection.build_collection(input_dir, output_dir, False)
output_artifact = os.path.join(output_dir, 'ansible_namespace-collection-0.1.0.tar.gz')
assert tarfile.is_tarfile(output_artifact)
with tarfile.open(output_artifact, mode='r') as actual:
members = actual.getmembers()
linked_members = [m for m in members if m.path.startswith('playbooks/roles/linked/tasks')]
assert len(linked_members) == 2
assert linked_members[0].name == 'playbooks/roles/linked/tasks'
assert linked_members[0].isdir()
assert linked_members[1].name == 'playbooks/roles/linked/tasks/main.yml'
assert linked_members[1].isreg()
linked_task = actual.extractfile(linked_members[1].name)
actual_task = secure_hash_s(linked_task.read())
linked_task.close()
assert actual_task == 'f4dcc52576b6c2cd8ac2832c52493881c4e54226'
linked_file = [m for m in members if m.path == 'docs/README.md']
assert len(linked_file) == 1
assert linked_file[0].isreg()
linked_file_obj = actual.extractfile(linked_file[0].name)
actual_file = secure_hash_s(linked_file_obj.read())
linked_file_obj.close()
assert actual_file == '63444bfc766154e1bc7557ef6280de20d03fcd81'
def test_publish_missing_file():
fake_path = u'/fake/ÅÑŚÌβŁÈ/path'
expected = to_native("The collection path specified '%s' does not exist." % fake_path)
with pytest.raises(AnsibleError, match=expected):
collection.publish_collection(fake_path, None, None, False, True)
def test_publish_not_a_tarball():
expected = "The collection path specified '{0}' is not a tarball, use 'ansible-galaxy collection build' to " \
"create a proper release artifact."
with tempfile.NamedTemporaryFile(prefix=u'ÅÑŚÌβŁÈ') as temp_file:
temp_file.write(b"\x00")
temp_file.flush()
with pytest.raises(AnsibleError, match=expected.format(to_native(temp_file.name))):
collection.publish_collection(temp_file.name, None, None, False, True)
def test_publish_no_wait(collection_artifact, monkeypatch):
mock_display = MagicMock()
monkeypatch.setattr(Display, 'display', mock_display)
artifact_path, mock_open = collection_artifact
fake_import_uri = 'https://galaxy.server.com/api/v2/import/1234'
server = 'https://galaxy.com'
mock_open.return_value = StringIO(u'{"task":"%s"}' % fake_import_uri)
expected_form, expected_content_type = collection._get_mime_data(to_bytes(artifact_path))
collection.publish_collection(artifact_path, server, 'key', False, False)
assert mock_open.call_count == 1
assert mock_open.mock_calls[0][1][0] == 'https://galaxy.com/api/v2/collections/'
assert mock_open.mock_calls[0][2]['data'] == expected_form
assert mock_open.mock_calls[0][2]['method'] == 'POST'
assert mock_open.mock_calls[0][2]['validate_certs'] is True
assert mock_open.mock_calls[0][2]['headers']['Authorization'] == 'Token key'
assert mock_open.mock_calls[0][2]['headers']['Content-length'] == len(expected_form)
assert mock_open.mock_calls[0][2]['headers']['Content-type'] == expected_content_type
assert mock_display.call_count == 2
assert mock_display.mock_calls[0][1][0] == "Publishing collection artifact '%s' to %s" % (artifact_path, server)
assert mock_display.mock_calls[1][1][0] == \
"Collection has been pushed to the Galaxy server, not waiting until import has completed due to --no-wait " \
"being set. Import task results can be found at %s" % fake_import_uri
def test_publish_dont_validate_cert(collection_artifact):
artifact_path, mock_open = collection_artifact
mock_open.return_value = StringIO(u'{"task":"https://galaxy.server.com/api/v2/import/1234"}')
collection.publish_collection(artifact_path, 'https://galaxy.server.com', 'key', True, False)
assert mock_open.call_count == 1
assert mock_open.mock_calls[0][2]['validate_certs'] is False
def test_publish_failure(collection_artifact):
artifact_path, mock_open = collection_artifact
mock_open.side_effect = urllib_error.HTTPError('https://galaxy.server.com', 500, 'msg', {}, StringIO())
expected = 'Error when publishing collection (HTTP Code: 500, Message: Unknown error returned by Galaxy ' \
'server. Code: Unknown)'
with pytest.raises(AnsibleError, match=re.escape(expected)):
collection.publish_collection(artifact_path, 'https://galaxy.server.com', 'key', False, True)
def test_publish_failure_with_json_info(collection_artifact):
artifact_path, mock_open = collection_artifact
return_content = StringIO(u'{"message":"Galaxy error message","code":"GWE002"}')
mock_open.side_effect = urllib_error.HTTPError('https://galaxy.server.com', 503, 'msg', {}, return_content)
expected = 'Error when publishing collection (HTTP Code: 503, Message: Galaxy error message Code: GWE002)'
with pytest.raises(AnsibleError, match=re.escape(expected)):
collection.publish_collection(artifact_path, 'https://galaxy.server.com', 'key', False, True)
def test_publish_with_wait(collection_artifact, monkeypatch):
mock_display = MagicMock()
monkeypatch.setattr(Display, 'display', mock_display)
mock_vvv = MagicMock()
monkeypatch.setattr(Display, 'vvv', mock_vvv)
fake_import_uri = 'https://galaxy-server/api/v2/import/1234'
server = 'https://galaxy.server.com'
artifact_path, mock_open = collection_artifact
mock_open.side_effect = (
StringIO(u'{"task":"%s"}' % fake_import_uri),
StringIO(u'{"finished_at":"some_time","state":"success"}')
)
collection.publish_collection(artifact_path, server, 'key', False, True)
assert mock_open.call_count == 2
assert mock_open.mock_calls[1][1][0] == fake_import_uri
assert mock_open.mock_calls[1][2]['headers']['Authorization'] == 'Token key'
assert mock_open.mock_calls[1][2]['validate_certs'] is True
assert mock_open.mock_calls[1][2]['method'] == 'GET'
assert mock_display.call_count == 2
assert mock_display.mock_calls[0][1][0] == "Publishing collection artifact '%s' to %s" % (artifact_path, server)
assert mock_display.mock_calls[1][1][0] == 'Collection has been successfully published to the Galaxy server'
assert mock_vvv.call_count == 2
assert mock_vvv.mock_calls[0][1][0] == 'Collection has been pushed to the Galaxy server %s' % server
assert mock_vvv.mock_calls[1][1][0] == 'Waiting until galaxy import task %s has completed' % fake_import_uri
def test_publish_with_wait_timeout(collection_artifact, monkeypatch):
monkeypatch.setattr(time, 'sleep', MagicMock())
mock_display = MagicMock()
monkeypatch.setattr(Display, 'display', mock_display)
mock_vvv = MagicMock()
monkeypatch.setattr(Display, 'vvv', mock_vvv)
fake_import_uri = 'https://galaxy-server/api/v2/import/1234'
server = 'https://galaxy.server.com'
artifact_path, mock_open = collection_artifact
mock_open.side_effect = (
StringIO(u'{"task":"%s"}' % fake_import_uri),
StringIO(u'{"finished_at":null}'),
StringIO(u'{"finished_at":"some_time","state":"success"}')
)
collection.publish_collection(artifact_path, server, 'key', True, True)
assert mock_open.call_count == 3
assert mock_open.mock_calls[1][1][0] == fake_import_uri
assert mock_open.mock_calls[1][2]['headers']['Authorization'] == 'Token key'
assert mock_open.mock_calls[1][2]['validate_certs'] is False
assert mock_open.mock_calls[1][2]['method'] == 'GET'
assert mock_open.mock_calls[2][1][0] == fake_import_uri
assert mock_open.mock_calls[2][2]['headers']['Authorization'] == 'Token key'
assert mock_open.mock_calls[2][2]['validate_certs'] is False
assert mock_open.mock_calls[2][2]['method'] == 'GET'
assert mock_display.call_count == 2
assert mock_display.mock_calls[0][1][0] == "Publishing collection artifact '%s' to %s" % (artifact_path, server)
assert mock_display.mock_calls[1][1][0] == 'Collection has been successfully published to the Galaxy server'
assert mock_vvv.call_count == 3
assert mock_vvv.mock_calls[0][1][0] == 'Collection has been pushed to the Galaxy server %s' % server
assert mock_vvv.mock_calls[1][1][0] == 'Waiting until galaxy import task %s has completed' % fake_import_uri
assert mock_vvv.mock_calls[2][1][0] == \
'Galaxy import process has a status of waiting, wait 2 seconds before trying again'
def test_publish_with_wait_timeout(collection_artifact, monkeypatch):
monkeypatch.setattr(time, 'sleep', MagicMock())
mock_display = MagicMock()
monkeypatch.setattr(Display, 'display', mock_display)
mock_vvv = MagicMock()
monkeypatch.setattr(Display, 'vvv', mock_vvv)
fake_import_uri = 'https://galaxy-server/api/v2/import/1234'
server = 'https://galaxy.server.com'
artifact_path, mock_open = collection_artifact
mock_open.side_effect = (
StringIO(u'{"task":"%s"}' % fake_import_uri),
StringIO(u'{"finished_at":null}'),
StringIO(u'{"finished_at":null}'),
StringIO(u'{"finished_at":null}'),
StringIO(u'{"finished_at":null}'),
StringIO(u'{"finished_at":null}'),
StringIO(u'{"finished_at":null}'),
StringIO(u'{"finished_at":null}'),
)
expected = "Timeout while waiting for the Galaxy import process to finish, check progress at '%s'" \
% fake_import_uri
with pytest.raises(AnsibleError, match=expected):
collection.publish_collection(artifact_path, server, 'key', True, True)
assert mock_open.call_count == 8
for i in range(7):
mock_call = mock_open.mock_calls[i + 1]
assert mock_call[1][0] == fake_import_uri
assert mock_call[2]['headers']['Authorization'] == 'Token key'
assert mock_call[2]['validate_certs'] is False
assert mock_call[2]['method'] == 'GET'
assert mock_display.call_count == 1
assert mock_display.mock_calls[0][1][0] == "Publishing collection artifact '%s' to %s" % (artifact_path, server)
expected_wait_msg = 'Galaxy import process has a status of waiting, wait {0} seconds before trying again'
assert mock_vvv.call_count == 8
assert mock_vvv.mock_calls[0][1][0] == 'Collection has been pushed to the Galaxy server %s' % server
assert mock_vvv.mock_calls[1][1][0] == 'Waiting until galaxy import task %s has completed' % fake_import_uri
assert mock_vvv.mock_calls[2][1][0] == expected_wait_msg.format(2)
assert mock_vvv.mock_calls[3][1][0] == expected_wait_msg.format(3)
assert mock_vvv.mock_calls[4][1][0] == expected_wait_msg.format(4)
assert mock_vvv.mock_calls[5][1][0] == expected_wait_msg.format(6)
assert mock_vvv.mock_calls[6][1][0] == expected_wait_msg.format(10)
assert mock_vvv.mock_calls[7][1][0] == expected_wait_msg.format(15)
def test_publish_with_wait_and_failure(collection_artifact, monkeypatch):
mock_display = MagicMock()
monkeypatch.setattr(Display, 'display', mock_display)
mock_vvv = MagicMock()
monkeypatch.setattr(Display, 'vvv', mock_vvv)
mock_warn = MagicMock()
monkeypatch.setattr(Display, 'warning', mock_warn)
mock_err = MagicMock()
monkeypatch.setattr(Display, 'error', mock_err)
fake_import_uri = 'https://galaxy-server/api/v2/import/1234'
server = 'https://galaxy.server.com'
artifact_path, mock_open = collection_artifact
import_stat = {
'finished_at': 'some_time',
'state': 'failed',
'error': {
'code': 'GW001',
'description': 'Because I said so!',
},
'messages': [
{
'level': 'error',
'message': 'Some error',
},
{
'level': 'warning',
'message': 'Some warning',
},
{
'level': 'info',
'message': 'Some info',
},
],
}
mock_open.side_effect = (
StringIO(u'{"task":"%s"}' % fake_import_uri),
StringIO(to_text(json.dumps(import_stat)))
)
expected = 'Galaxy import process failed: Because I said so! (Code: GW001)'
with pytest.raises(AnsibleError, match=re.escape(expected)):
collection.publish_collection(artifact_path, server, 'key', True, True)
assert mock_open.call_count == 2
assert mock_open.mock_calls[1][1][0] == fake_import_uri
assert mock_open.mock_calls[1][2]['headers']['Authorization'] == 'Token key'
assert mock_open.mock_calls[1][2]['validate_certs'] is False
assert mock_open.mock_calls[1][2]['method'] == 'GET'
assert mock_display.call_count == 1
assert mock_display.mock_calls[0][1][0] == "Publishing collection artifact '%s' to %s" % (artifact_path, server)
assert mock_vvv.call_count == 3
assert mock_vvv.mock_calls[0][1][0] == 'Collection has been pushed to the Galaxy server %s' % server
assert mock_vvv.mock_calls[1][1][0] == 'Waiting until galaxy import task %s has completed' % fake_import_uri
assert mock_vvv.mock_calls[2][1][0] == 'Galaxy import message: info - Some info'
assert mock_warn.call_count == 1
assert mock_warn.mock_calls[0][1][0] == 'Galaxy import warning message: Some warning'
assert mock_err.call_count == 1
assert mock_err.mock_calls[0][1][0] == 'Galaxy import error message: Some error'
def test_publish_with_wait_and_failure_and_no_error(collection_artifact, monkeypatch):
mock_display = MagicMock()
monkeypatch.setattr(Display, 'display', mock_display)
mock_vvv = MagicMock()
monkeypatch.setattr(Display, 'vvv', mock_vvv)
mock_warn = MagicMock()
monkeypatch.setattr(Display, 'warning', mock_warn)
mock_err = MagicMock()
monkeypatch.setattr(Display, 'error', mock_err)
fake_import_uri = 'https://galaxy-server/api/v2/import/1234'
server = 'https://galaxy.server.com'
artifact_path, mock_open = collection_artifact
import_stat = {
'finished_at': 'some_time',
'state': 'failed',
'error': {},
'messages': [
{
'level': 'error',
'message': 'Some error',
},
{
'level': 'warning',
'message': 'Some warning',
},
{
'level': 'info',
'message': 'Some info',
},
],
}
mock_open.side_effect = (
StringIO(u'{"task":"%s"}' % fake_import_uri),
StringIO(to_text(json.dumps(import_stat)))
)
expected = 'Galaxy import process failed: Unknown error, see %s for more details (Code: UNKNOWN)' % fake_import_uri
with pytest.raises(AnsibleError, match=re.escape(expected)):
collection.publish_collection(artifact_path, server, 'key', True, True)
assert mock_open.call_count == 2
assert mock_open.mock_calls[1][1][0] == fake_import_uri
assert mock_open.mock_calls[1][2]['headers']['Authorization'] == 'Token key'
assert mock_open.mock_calls[1][2]['validate_certs'] is False
assert mock_open.mock_calls[1][2]['method'] == 'GET'
assert mock_display.call_count == 1
assert mock_display.mock_calls[0][1][0] == "Publishing collection artifact '%s' to %s" % (artifact_path, server)
assert mock_vvv.call_count == 3
assert mock_vvv.mock_calls[0][1][0] == 'Collection has been pushed to the Galaxy server %s' % server
assert mock_vvv.mock_calls[1][1][0] == 'Waiting until galaxy import task %s has completed' % fake_import_uri
assert mock_vvv.mock_calls[2][1][0] == 'Galaxy import message: info - Some info'
assert mock_warn.call_count == 1
assert mock_warn.mock_calls[0][1][0] == 'Galaxy import warning message: Some warning'
assert mock_err.call_count == 1
assert mock_err.mock_calls[0][1][0] == 'Galaxy import error message: Some error'
@pytest.mark.parametrize('requirements_file', [None], indirect=True)
def test_parse_requirements_file_that_doesnt_exist(requirements_file):
expected = "The requirements file '%s' does not exist." % to_native(requirements_file)
with pytest.raises(AnsibleError, match=expected):
collection.parse_collections_requirements_file(requirements_file)
@pytest.mark.parametrize('requirements_file', ['not a valid yml file: hi: world'], indirect=True)
def test_parse_requirements_file_that_isnt_yaml(requirements_file):
expected = "Failed to parse the collection requirements yml at '%s' with the following error" \
% to_native(requirements_file)
with pytest.raises(AnsibleError, match=expected):
collection.parse_collections_requirements_file(requirements_file)
@pytest.mark.parametrize('requirements_file', [('''
# Older role based requirements.yml
- galaxy.role
- anotherrole
'''), ('''
# Doesn't have collections key
roles:
- galaxy.role
- anotherole
''')], indirect=True)
def test_parse_requirements_in_invalid_format(requirements_file):
expected = "Expecting collections requirements file to be a dict with the key collections that contains a list " \
"of collections to install."
with pytest.raises(AnsibleError, match=expected):
collection.parse_collections_requirements_file(requirements_file)
@pytest.mark.parametrize('requirements_file', ['''
collections:
- version: 1.0.0
'''], indirect=True)
def test_parse_requirements_without_mandatory_name_key(requirements_file):
expected = "Collections requirement entry should contain the key name."
with pytest.raises(AnsibleError, match=expected):
collection.parse_collections_requirements_file(requirements_file)
@pytest.mark.parametrize('requirements_file', [('''
collections:
- namespace.collection1
- namespace.collection2
'''), ('''
collections:
- name: namespace.collection1
- name: namespace.collection2
''')], indirect=True)
def test_parse_requirements(requirements_file):
expected = [('namespace.collection1', '*', None), ('namespace.collection2', '*', None)]
actual = collection.parse_collections_requirements_file(requirements_file)
assert actual == expected
@pytest.mark.parametrize('requirements_file', ['''
collections:
- name: namespace.collection1
version: ">=1.0.0,<=2.0.0"
source: https://galaxy-dev.ansible.com
- namespace.collection2'''], indirect=True)
def test_parse_requirements_with_extra_info(requirements_file):
expected = [('namespace.collection1', '>=1.0.0,<=2.0.0', 'https://galaxy-dev.ansible.com'),
('namespace.collection2', '*', None)]
actual = collection.parse_collections_requirements_file(requirements_file)
assert actual == expected
def test_find_existing_collections(tmp_path_factory, monkeypatch):
test_dir = to_text(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections'))
collection1 = os.path.join(test_dir, 'namespace1', 'collection1')
collection2 = os.path.join(test_dir, 'namespace2', 'collection2')
fake_collection1 = os.path.join(test_dir, 'namespace3', 'collection3')
fake_collection2 = os.path.join(test_dir, 'namespace4')
os.makedirs(collection1)
os.makedirs(collection2)
os.makedirs(os.path.split(fake_collection1)[0])
open(fake_collection1, 'wb+').close()
open(fake_collection2, 'wb+').close()
collection1_manifest = json.dumps({
'collection_info': {
'namespace': 'namespace1',
'name': 'collection1',
'version': '1.2.3',
'authors': ['Jordan Borean'],
'readme': 'README.md',
'dependencies': {},
},
'format': 1,
})
with open(os.path.join(collection1, 'MANIFEST.json'), 'wb') as manifest_obj:
manifest_obj.write(to_bytes(collection1_manifest))
mock_warning = MagicMock()
monkeypatch.setattr(Display, 'warning', mock_warning)
actual = collection._find_existing_collections(test_dir)
assert len(actual) == 2
for actual_collection in actual:
assert actual_collection.skip is True
if str(actual_collection) == 'namespace1.collection1':
assert actual_collection.namespace == 'namespace1'
assert actual_collection.name == 'collection1'
assert actual_collection.b_path == to_bytes(collection1)
assert actual_collection.source is None
assert actual_collection.versions == set(['1.2.3'])
assert actual_collection.latest_version == '1.2.3'
assert actual_collection.dependencies == {}
else:
assert actual_collection.namespace == 'namespace2'
assert actual_collection.name == 'collection2'
assert actual_collection.b_path == to_bytes(collection2)
assert actual_collection.source is None
assert actual_collection.versions == set(['*'])
assert actual_collection.latest_version == '*'
assert actual_collection.dependencies == {}
assert mock_warning.call_count == 1
assert mock_warning.mock_calls[0][1][0] == "Collection at '%s' does not have a MANIFEST.json file, cannot " \
"detect version." % to_text(collection2)
def test_download_file(tmp_path_factory, monkeypatch):
temp_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections'))
data = b"\x00\x01\x02\x03"
sha256_hash = sha256()
sha256_hash.update(data)
mock_open = MagicMock()
mock_open.return_value = BytesIO(data)
monkeypatch.setattr(collection, 'open_url', mock_open)
expected = os.path.join(temp_dir, b'file')
actual = collection._download_file('http://google.com/file', temp_dir, sha256_hash.hexdigest(), True)
assert actual.startswith(expected)
assert os.path.isfile(actual)
with open(actual, 'rb') as file_obj:
assert file_obj.read() == data
assert mock_open.call_count == 1
assert mock_open.mock_calls[0][1][0] == 'http://google.com/file'
def test_download_file_hash_mismatch(tmp_path_factory, monkeypatch):
temp_dir = to_bytes(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Collections'))
data = b"\x00\x01\x02\x03"
mock_open = MagicMock()
mock_open.return_value = BytesIO(data)
monkeypatch.setattr(collection, 'open_url', mock_open)
expected = "Mismatch artifact hash with downloaded file"
with pytest.raises(AnsibleError, match=expected):
collection._download_file('http://google.com/file', temp_dir, 'bad', True)
def test_extract_tar_file_invalid_hash(tmp_tarfile):
temp_dir, tfile, filename, dummy = tmp_tarfile
expected = "Checksum mismatch for '%s' inside collection at '%s'" % (to_native(filename), to_native(tfile.name))
with pytest.raises(AnsibleError, match=expected):
collection._extract_tar_file(tfile, filename, temp_dir, temp_dir, "fakehash")
def test_extract_tar_file_missing_member(tmp_tarfile):
temp_dir, tfile, dummy, dummy = tmp_tarfile
expected = "Collection tar at '%s' does not contain the expected file 'missing'." % to_native(tfile.name)
with pytest.raises(AnsibleError, match=expected):
collection._extract_tar_file(tfile, 'missing', temp_dir, temp_dir)
def test_extract_tar_file_missing_parent_dir(tmp_tarfile):
temp_dir, tfile, filename, checksum = tmp_tarfile
output_dir = os.path.join(temp_dir, b'output')
output_file = os.path.join(output_dir, to_bytes(filename))
collection._extract_tar_file(tfile, filename, output_dir, temp_dir, checksum)
os.path.isfile(output_file)
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,728 |
'gather_subset' setting in ansible.cfg and ansible/roles are ignored
|
##### SUMMARY
'gather_subset' setting in ansible.cfg and ansible/roles are ignored
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
fact gathering
##### ANSIBLE VERSION
```
ansible 2.8.1
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
python version = 2.7.5 (default, Oct 30 2018, 23:45:53) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
```
##### CONFIGURATION
```
ANSIBLE_PIPELINING(/etc/ansible/ansible.cfg) = True
ANSIBLE_SSH_CONTROL_PATH(/etc/ansible/ansible.cfg) = %(directory)s/ans-ssh-%%h-%%p-%%r
ANSIBLE_SSH_RETRIES(/etc/ansible/ansible.cfg) = 1
DEFAULT_CALLBACK_WHITELIST(/etc/ansible/ansible.cfg) = [u'profile_tasks', u'grafana_annotations']
DEFAULT_FORKS(/etc/ansible/ansible.cfg) = 500
DEFAULT_GATHERING(/etc/ansible/ansible.cfg) = smart
DEFAULT_GATHER_SUBSET(/etc/ansible/ansible.cfg) = [u'!hardware', u'!ohai', u'!facter', u'!virtual', u'!network']
DEFAULT_GATHER_TIMEOUT(/etc/ansible/ansible.cfg) = 10
DEFAULT_HOST_LIST(/etc/ansible/ansible.cfg) = [u'/etc/ansible/inventory']
DEFAULT_SCP_IF_SSH(/etc/ansible/ansible.cfg) = True
DEFAULT_TIMEOUT(/etc/ansible/ansible.cfg) = 15
```
##### OS / ENVIRONMENT
```
CentOS Linux release 7.6.1810 (Core)
```
##### STEPS TO REPRODUCE
```
I have the following settings in my ansible.cfg:
...
gathering = smart
gather_subset = min
...
and also tried to set following within my role:
...
- name: 'test fact gahtering'
setup:
gather_subset: 'min'
...
but still all facts are gathered during a playbook run.
"ansible_virtualization_role": "guest",
"ansible_virtualization_type": "xen",
"gather_subset": [
"all"
As a workaround I set the default value to 'min' within:
"/usr/lib/python2.7/site-packages/ansible/modules/system/setup.py".
That works.
def main():
module = AnsibleModule(
argument_spec=dict(
gather_subset=dict(default=["min"], required=False, type='list'),
```
##### EXPECTED RESULTS
gather_subset setting should be loaded from ansible.cfg or within role if set.
##### ACTUAL RESULTS
gather_subset within ansible.cfg and role are ignored and all facts are gathered
```
"ansible_virtualization_role": "guest",
"ansible_virtualization_type": "xen",
"gather_subset": [
"all"
```
|
https://github.com/ansible/ansible/issues/58728
|
https://github.com/ansible/ansible/pull/59271
|
aa0de421d2948c6552770534381e58d6acae7997
|
8a886a6bee30fbb29835558f939a585007eaec67
| 2019-07-04T12:50:18Z |
python
| 2019-07-22T21:59:22Z |
changelogs/fragments/gather_subset_defaults.yml
| |
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 58,728 |
'gather_subset' setting in ansible.cfg and ansible/roles are ignored
|
##### SUMMARY
'gather_subset' setting in ansible.cfg and ansible/roles are ignored
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
fact gathering
##### ANSIBLE VERSION
```
ansible 2.8.1
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
python version = 2.7.5 (default, Oct 30 2018, 23:45:53) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
```
##### CONFIGURATION
```
ANSIBLE_PIPELINING(/etc/ansible/ansible.cfg) = True
ANSIBLE_SSH_CONTROL_PATH(/etc/ansible/ansible.cfg) = %(directory)s/ans-ssh-%%h-%%p-%%r
ANSIBLE_SSH_RETRIES(/etc/ansible/ansible.cfg) = 1
DEFAULT_CALLBACK_WHITELIST(/etc/ansible/ansible.cfg) = [u'profile_tasks', u'grafana_annotations']
DEFAULT_FORKS(/etc/ansible/ansible.cfg) = 500
DEFAULT_GATHERING(/etc/ansible/ansible.cfg) = smart
DEFAULT_GATHER_SUBSET(/etc/ansible/ansible.cfg) = [u'!hardware', u'!ohai', u'!facter', u'!virtual', u'!network']
DEFAULT_GATHER_TIMEOUT(/etc/ansible/ansible.cfg) = 10
DEFAULT_HOST_LIST(/etc/ansible/ansible.cfg) = [u'/etc/ansible/inventory']
DEFAULT_SCP_IF_SSH(/etc/ansible/ansible.cfg) = True
DEFAULT_TIMEOUT(/etc/ansible/ansible.cfg) = 15
```
##### OS / ENVIRONMENT
```
CentOS Linux release 7.6.1810 (Core)
```
##### STEPS TO REPRODUCE
```
I have the following settings in my ansible.cfg:
...
gathering = smart
gather_subset = min
...
and also tried to set following within my role:
...
- name: 'test fact gahtering'
setup:
gather_subset: 'min'
...
but still all facts are gathered during a playbook run.
"ansible_virtualization_role": "guest",
"ansible_virtualization_type": "xen",
"gather_subset": [
"all"
As a workaround I set the default value to 'min' within:
"/usr/lib/python2.7/site-packages/ansible/modules/system/setup.py".
That works.
def main():
module = AnsibleModule(
argument_spec=dict(
gather_subset=dict(default=["min"], required=False, type='list'),
```
##### EXPECTED RESULTS
gather_subset setting should be loaded from ansible.cfg or within role if set.
##### ACTUAL RESULTS
gather_subset within ansible.cfg and role are ignored and all facts are gathered
```
"ansible_virtualization_role": "guest",
"ansible_virtualization_type": "xen",
"gather_subset": [
"all"
```
|
https://github.com/ansible/ansible/issues/58728
|
https://github.com/ansible/ansible/pull/59271
|
aa0de421d2948c6552770534381e58d6acae7997
|
8a886a6bee30fbb29835558f939a585007eaec67
| 2019-07-04T12:50:18Z |
python
| 2019-07-22T21:59:22Z |
lib/ansible/playbook/play.py
|
# (c) 2012-2014, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible import constants as C
from ansible import context
from ansible.errors import AnsibleParserError, AnsibleAssertionError
from ansible.module_utils._text import to_native
from ansible.module_utils.six import string_types
from ansible.playbook.attribute import FieldAttribute
from ansible.playbook.base import Base
from ansible.playbook.block import Block
from ansible.playbook.collectionsearch import CollectionSearch
from ansible.playbook.helpers import load_list_of_blocks, load_list_of_roles
from ansible.playbook.role import Role
from ansible.playbook.taggable import Taggable
from ansible.vars.manager import preprocess_vars
from ansible.utils.display import Display
display = Display()
__all__ = ['Play']
class Play(Base, Taggable, CollectionSearch):
"""
A play is a language feature that represents a list of roles and/or
task/handler blocks to execute on a given set of hosts.
Usage:
Play.load(datastructure) -> Play
Play.something(...)
"""
# =================================================================================
_hosts = FieldAttribute(isa='list', required=True, listof=string_types, always_post_validate=True)
# Facts
_gather_facts = FieldAttribute(isa='bool', default=None, always_post_validate=True)
_gather_subset = FieldAttribute(isa='list', default=None, listof=string_types, always_post_validate=True)
_gather_timeout = FieldAttribute(isa='int', default=C.DEFAULT_GATHER_TIMEOUT, always_post_validate=True)
_fact_path = FieldAttribute(isa='string', default=C.DEFAULT_FACT_PATH)
# Variable Attributes
_vars_files = FieldAttribute(isa='list', default=list, priority=99)
_vars_prompt = FieldAttribute(isa='list', default=list, always_post_validate=False)
# Role Attributes
_roles = FieldAttribute(isa='list', default=list, priority=90)
# Block (Task) Lists Attributes
_handlers = FieldAttribute(isa='list', default=list)
_pre_tasks = FieldAttribute(isa='list', default=list)
_post_tasks = FieldAttribute(isa='list', default=list)
_tasks = FieldAttribute(isa='list', default=list)
# Flag/Setting Attributes
_force_handlers = FieldAttribute(isa='bool', default=context.cliargs_deferred_get('force_handlers'), always_post_validate=True)
_max_fail_percentage = FieldAttribute(isa='percent', always_post_validate=True)
_serial = FieldAttribute(isa='list', default=list, always_post_validate=True)
_strategy = FieldAttribute(isa='string', default=C.DEFAULT_STRATEGY, always_post_validate=True)
_order = FieldAttribute(isa='string', always_post_validate=True)
# =================================================================================
def __init__(self):
super(Play, self).__init__()
self._included_conditional = None
self._included_path = None
self._removed_hosts = []
self.ROLE_CACHE = {}
self.only_tags = set(context.CLIARGS.get('tags', [])) or frozenset(('all',))
self.skip_tags = set(context.CLIARGS.get('skip_tags', []))
def __repr__(self):
return self.get_name()
def get_name(self):
''' return the name of the Play '''
return self.name
@staticmethod
def load(data, variable_manager=None, loader=None, vars=None):
if ('name' not in data or data['name'] is None) and 'hosts' in data:
if data['hosts'] is None or all(host is None for host in data['hosts']):
raise AnsibleParserError("Hosts list cannot be empty - please check your playbook")
if isinstance(data['hosts'], list):
data['name'] = ','.join(data['hosts'])
else:
data['name'] = data['hosts']
p = Play()
if vars:
p.vars = vars.copy()
return p.load_data(data, variable_manager=variable_manager, loader=loader)
def preprocess_data(self, ds):
'''
Adjusts play datastructure to cleanup old/legacy items
'''
if not isinstance(ds, dict):
raise AnsibleAssertionError('while preprocessing data (%s), ds should be a dict but was a %s' % (ds, type(ds)))
# The use of 'user' in the Play datastructure was deprecated to
# line up with the same change for Tasks, due to the fact that
# 'user' conflicted with the user module.
if 'user' in ds:
# this should never happen, but error out with a helpful message
# to the user if it does...
if 'remote_user' in ds:
raise AnsibleParserError("both 'user' and 'remote_user' are set for %s. "
"The use of 'user' is deprecated, and should be removed" % self.get_name(), obj=ds)
ds['remote_user'] = ds['user']
del ds['user']
return super(Play, self).preprocess_data(ds)
def _load_tasks(self, attr, ds):
'''
Loads a list of blocks from a list which may be mixed tasks/blocks.
Bare tasks outside of a block are given an implicit block.
'''
try:
return load_list_of_blocks(ds=ds, play=self, variable_manager=self._variable_manager, loader=self._loader)
except AssertionError as e:
raise AnsibleParserError("A malformed block was encountered while loading tasks: %s" % to_native(e), obj=self._ds, orig_exc=e)
def _load_pre_tasks(self, attr, ds):
'''
Loads a list of blocks from a list which may be mixed tasks/blocks.
Bare tasks outside of a block are given an implicit block.
'''
try:
return load_list_of_blocks(ds=ds, play=self, variable_manager=self._variable_manager, loader=self._loader)
except AssertionError as e:
raise AnsibleParserError("A malformed block was encountered while loading pre_tasks", obj=self._ds, orig_exc=e)
def _load_post_tasks(self, attr, ds):
'''
Loads a list of blocks from a list which may be mixed tasks/blocks.
Bare tasks outside of a block are given an implicit block.
'''
try:
return load_list_of_blocks(ds=ds, play=self, variable_manager=self._variable_manager, loader=self._loader)
except AssertionError as e:
raise AnsibleParserError("A malformed block was encountered while loading post_tasks", obj=self._ds, orig_exc=e)
def _load_handlers(self, attr, ds):
'''
Loads a list of blocks from a list which may be mixed handlers/blocks.
Bare handlers outside of a block are given an implicit block.
'''
try:
return self._extend_value(
self.handlers,
load_list_of_blocks(ds=ds, play=self, use_handlers=True, variable_manager=self._variable_manager, loader=self._loader),
prepend=True
)
except AssertionError as e:
raise AnsibleParserError("A malformed block was encountered while loading handlers", obj=self._ds, orig_exc=e)
def _load_roles(self, attr, ds):
'''
Loads and returns a list of RoleInclude objects from the datastructure
list of role definitions and creates the Role from those objects
'''
if ds is None:
ds = []
try:
role_includes = load_list_of_roles(ds, play=self, variable_manager=self._variable_manager, loader=self._loader)
except AssertionError as e:
raise AnsibleParserError("A malformed role declaration was encountered.", obj=self._ds, orig_exc=e)
roles = []
for ri in role_includes:
roles.append(Role.load(ri, play=self))
return self._extend_value(
self.roles,
roles,
prepend=True
)
def _load_vars_prompt(self, attr, ds):
new_ds = preprocess_vars(ds)
vars_prompts = []
if new_ds is not None:
for prompt_data in new_ds:
if 'name' not in prompt_data:
raise AnsibleParserError("Invalid vars_prompt data structure", obj=ds)
else:
vars_prompts.append(prompt_data)
return vars_prompts
def _compile_roles(self):
'''
Handles the role compilation step, returning a flat list of tasks
with the lowest level dependencies first. For example, if a role R
has a dependency D1, which also has a dependency D2, the tasks from
D2 are merged first, followed by D1, and lastly by the tasks from
the parent role R last. This is done for all roles in the Play.
'''
block_list = []
if len(self.roles) > 0:
for r in self.roles:
# Don't insert tasks from ``import/include_role``, preventing
# duplicate execution at the wrong time
if r.from_include:
continue
block_list.extend(r.compile(play=self))
return block_list
def compile_roles_handlers(self):
'''
Handles the role handler compilation step, returning a flat list of Handlers
This is done for all roles in the Play.
'''
block_list = []
if len(self.roles) > 0:
for r in self.roles:
if r.from_include:
continue
block_list.extend(r.get_handler_blocks(play=self))
return block_list
def compile(self):
'''
Compiles and returns the task list for this play, compiled from the
roles (which are themselves compiled recursively) and/or the list of
tasks specified in the play.
'''
# create a block containing a single flush handlers meta
# task, so we can be sure to run handlers at certain points
# of the playbook execution
flush_block = Block.load(
data={'meta': 'flush_handlers'},
play=self,
variable_manager=self._variable_manager,
loader=self._loader
)
block_list = []
block_list.extend(self.pre_tasks)
block_list.append(flush_block)
block_list.extend(self._compile_roles())
block_list.extend(self.tasks)
block_list.append(flush_block)
block_list.extend(self.post_tasks)
block_list.append(flush_block)
return block_list
def get_vars(self):
return self.vars.copy()
def get_vars_files(self):
if self.vars_files is None:
return []
elif not isinstance(self.vars_files, list):
return [self.vars_files]
return self.vars_files
def get_handlers(self):
return self.handlers[:]
def get_roles(self):
return self.roles[:]
def get_tasks(self):
tasklist = []
for task in self.pre_tasks + self.tasks + self.post_tasks:
if isinstance(task, Block):
tasklist.append(task.block + task.rescue + task.always)
else:
tasklist.append(task)
return tasklist
def serialize(self):
data = super(Play, self).serialize()
roles = []
for role in self.get_roles():
roles.append(role.serialize())
data['roles'] = roles
data['included_path'] = self._included_path
return data
def deserialize(self, data):
super(Play, self).deserialize(data)
self._included_path = data.get('included_path', None)
if 'roles' in data:
role_data = data.get('roles', [])
roles = []
for role in role_data:
r = Role()
r.deserialize(role)
roles.append(r)
setattr(self, 'roles', roles)
del data['roles']
def copy(self):
new_me = super(Play, self).copy()
new_me.ROLE_CACHE = self.ROLE_CACHE.copy()
new_me._included_conditional = self._included_conditional
new_me._included_path = self._included_path
return new_me
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 59,409 |
Docker Tests are unstable on RHEL 7 and RHEL 8
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
Docker tests on RHEL 7 and RHEL 8 have recently become unstable.
To get Docker tests working on RHEL 8, we had to pin at an older version. I am not sure if that is relevant to the issue.
Here are some example test failures
https://app.shippable.com/github/ansible/ansible/runs/133180/
https://app.shippable.com/github/ansible/ansible/runs/133170/
Marked tests as unstable in #59408
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
`test/integration/targets/docker_swarm/`
`test/integration/targets/docker_config/`
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
2.9
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```yaml
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```paste below
```
|
https://github.com/ansible/ansible/issues/59409
|
https://github.com/ansible/ansible/pull/59425
|
333953117c9e2ff62ebccdbcbb5947271b88ce73
|
266d6e77a9ad2373d31bcf067d67e9dcd268f464
| 2019-07-22T22:09:42Z |
python
| 2019-07-23T14:20:18Z |
test/integration/targets/docker_container/aliases
|
shippable/posix/group4
skip/osx
skip/freebsd
destructive
disabled
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 59,409 |
Docker Tests are unstable on RHEL 7 and RHEL 8
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
Docker tests on RHEL 7 and RHEL 8 have recently become unstable.
To get Docker tests working on RHEL 8, we had to pin at an older version. I am not sure if that is relevant to the issue.
Here are some example test failures
https://app.shippable.com/github/ansible/ansible/runs/133180/
https://app.shippable.com/github/ansible/ansible/runs/133170/
Marked tests as unstable in #59408
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
`test/integration/targets/docker_swarm/`
`test/integration/targets/docker_config/`
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
2.9
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```yaml
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```paste below
```
|
https://github.com/ansible/ansible/issues/59409
|
https://github.com/ansible/ansible/pull/59425
|
333953117c9e2ff62ebccdbcbb5947271b88ce73
|
266d6e77a9ad2373d31bcf067d67e9dcd268f464
| 2019-07-22T22:09:42Z |
python
| 2019-07-23T14:20:18Z |
test/integration/targets/docker_container/tasks/tests/options.yml
|
---
- name: Registering container name
set_fact:
cname: "{{ cname_prefix ~ '-options' }}"
cname_h1: "{{ cname_prefix ~ '-options-h1' }}"
cname_h2: "{{ cname_prefix ~ '-options-h2' }}"
cname_h3: "{{ cname_prefix ~ '-options-h3' }}"
- name: Registering container name
set_fact:
cnames: "{{ cnames + [cname, cname_h1, cname_h2, cname_h3] }}"
####################################################################
## auto_remove #####################################################
####################################################################
- name: auto_remove
docker_container:
image: alpine:3.8
command: '/bin/sh -c "echo"'
name: "{{ cname }}"
state: started
auto_remove: yes
register: auto_remove_1
ignore_errors: yes
- name: Give container 1 second to be sure it terminated
pause:
seconds: 1
- name: auto_remove (verify)
docker_container:
name: "{{ cname }}"
state: absent
register: auto_remove_2
ignore_errors: yes
- assert:
that:
- auto_remove_1 is changed
- auto_remove_2 is not changed
when: docker_py_version is version('2.1.0', '>=')
- assert:
that:
- auto_remove_1 is failed
- "('version is ' ~ docker_py_version ~ ' ') in auto_remove_1.msg"
- "'Minimum version required is 2.1.0 ' in auto_remove_1.msg"
when: docker_py_version is version('2.1.0', '<')
####################################################################
## blkio_weight ####################################################
####################################################################
- name: blkio_weight
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
blkio_weight: 123
register: blkio_weight_1
- name: blkio_weight (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
blkio_weight: 123
register: blkio_weight_2
- name: blkio_weight (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
blkio_weight: 234
force_kill: yes
register: blkio_weight_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- blkio_weight_1 is changed
- "blkio_weight_2 is not changed or 'Docker warning: Your kernel does not support Block I/O weight or the cgroup is not mounted. Weight discarded.' in blkio_weight_2.warnings"
- blkio_weight_3 is changed
####################################################################
## cap_drop, capabilities ##########################################
####################################################################
- name: capabilities, cap_drop
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
capabilities:
- sys_time
cap_drop:
- all
register: capabilities_1
- name: capabilities, cap_drop (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
capabilities:
- sys_time
cap_drop:
- all
register: capabilities_2
- name: capabilities, cap_drop (less)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
capabilities: []
cap_drop:
- all
register: capabilities_3
- name: capabilities, cap_drop (changed)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
capabilities:
- setgid
cap_drop:
- all
force_kill: yes
register: capabilities_4
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- capabilities_1 is changed
- capabilities_2 is not changed
- capabilities_3 is not changed
- capabilities_4 is changed
####################################################################
## command #########################################################
####################################################################
- name: command
docker_container:
image: alpine:3.8
command: '/bin/sh -v -c "sleep 10m"'
name: "{{ cname }}"
state: started
register: command_1
- name: command (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -v -c "sleep 10m"'
name: "{{ cname }}"
state: started
register: command_2
- name: command (less parameters)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
force_kill: yes
register: command_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- command_1 is changed
- command_2 is not changed
- command_3 is changed
####################################################################
## cpu_period ######################################################
####################################################################
- name: cpu_period
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
cpu_period: 90000
state: started
register: cpu_period_1
- name: cpu_period (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
cpu_period: 90000
state: started
register: cpu_period_2
- name: cpu_period (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
cpu_period: 50000
state: started
force_kill: yes
register: cpu_period_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- cpu_period_1 is changed
- cpu_period_2 is not changed
- cpu_period_3 is changed
####################################################################
## cpu_quota #######################################################
####################################################################
- name: cpu_quota
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
cpu_quota: 150000
state: started
register: cpu_quota_1
- name: cpu_quota (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
cpu_quota: 150000
state: started
register: cpu_quota_2
- name: cpu_quota (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
cpu_quota: 50000
state: started
force_kill: yes
register: cpu_quota_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- cpu_quota_1 is changed
- cpu_quota_2 is not changed
- cpu_quota_3 is changed
####################################################################
## cpu_shares ######################################################
####################################################################
- name: cpu_shares
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
cpu_shares: 900
state: started
register: cpu_shares_1
- name: cpu_shares (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
cpu_shares: 900
state: started
register: cpu_shares_2
- name: cpu_shares (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
cpu_shares: 1100
state: started
force_kill: yes
register: cpu_shares_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- cpu_shares_1 is changed
- cpu_shares_2 is not changed
- cpu_shares_3 is changed
####################################################################
## cpuset_cpus #####################################################
####################################################################
- name: cpuset_cpus
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
cpuset_cpus: "0"
state: started
register: cpuset_cpus_1
- name: cpuset_cpus (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
cpuset_cpus: "0"
state: started
register: cpuset_cpus_2
- name: cpuset_cpus (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
cpuset_cpus: "1"
state: started
force_kill: yes
# This will fail if the system the test is run on doesn't have
# multiple CPUs/cores available.
ignore_errors: yes
register: cpuset_cpus_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- cpuset_cpus_1 is changed
- cpuset_cpus_2 is not changed
- cpuset_cpus_3 is failed or cpuset_cpus_3 is changed
####################################################################
## cpuset_mems #####################################################
####################################################################
- name: cpuset_mems
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
cpuset_mems: "0"
state: started
register: cpuset_mems_1
- name: cpuset_mems (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
cpuset_mems: "0"
state: started
register: cpuset_mems_2
- name: cpuset_mems (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
cpuset_mems: "1"
state: started
force_kill: yes
# This will fail if the system the test is run on doesn't have
# multiple MEMs available.
ignore_errors: yes
register: cpuset_mems_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- cpuset_mems_1 is changed
- cpuset_mems_2 is not changed
- cpuset_mems_3 is failed or cpuset_mems_3 is changed
####################################################################
## debug ###########################################################
####################################################################
- name: debug (create)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: present
debug: yes
register: debug_1
- name: debug (start)
docker_container:
name: "{{ cname }}"
state: started
debug: yes
register: debug_2
- name: debug (stop)
docker_container:
image: alpine:3.8
name: "{{ cname }}"
state: stopped
force_kill: yes
debug: yes
register: debug_3
- name: debug (absent)
docker_container:
name: "{{ cname }}"
state: absent
debug: yes
force_kill: yes
register: debug_4
- assert:
that:
- debug_1 is changed
- debug_2 is changed
- debug_3 is changed
- debug_4 is changed
####################################################################
## detach, cleanup #################################################
####################################################################
- name: detach without cleanup
docker_container:
name: "{{ cname }}"
image: hello-world
detach: no
register: detach_no_cleanup
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
register: detach_no_cleanup_cleanup
diff: no
- name: detach with cleanup
docker_container:
name: "{{ cname }}"
image: hello-world
detach: no
cleanup: yes
register: detach_cleanup
- name: cleanup (unnecessary)
docker_container:
name: "{{ cname }}"
state: absent
register: detach_cleanup_cleanup
diff: no
- name: detach with auto_remove and cleanup
docker_container:
name: "{{ cname }}"
image: hello-world
detach: no
auto_remove: yes
cleanup: yes
register: detach_auto_remove
ignore_errors: yes
- name: cleanup (unnecessary)
docker_container:
name: "{{ cname }}"
state: absent
register: detach_auto_remove_cleanup
diff: no
- assert:
that:
# NOTE that 'Output' sometimes fails to contain the correct output
# of hello-world. We don't know why this happens, but it happens
# often enough to be annoying. That's why we disable this for now,
# and simply test that 'Output' is contained in the result.
- "'Output' in detach_no_cleanup.container"
# - "'Hello from Docker!' in detach_no_cleanup.container.Output"
- detach_no_cleanup_cleanup is changed
- "'Output' in detach_cleanup.container"
# - "'Hello from Docker!' in detach_cleanup.container.Output"
- detach_cleanup_cleanup is not changed
- assert:
that:
- "'Cannot retrieve result as auto_remove is enabled' == detach_auto_remove.container.Output"
- detach_auto_remove_cleanup is not changed
when: docker_py_version is version('2.1.0', '>=')
####################################################################
## devices #########################################################
####################################################################
- name: devices
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
devices:
- "/dev/random:/dev/virt-random:rwm"
- "/dev/urandom:/dev/virt-urandom:rwm"
register: devices_1
- name: devices (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
devices:
- "/dev/urandom:/dev/virt-urandom:rwm"
- "/dev/random:/dev/virt-random:rwm"
register: devices_2
- name: devices (less)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
devices:
- "/dev/random:/dev/virt-random:rwm"
register: devices_3
- name: devices (changed)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
devices:
- "/dev/random:/dev/virt-random:rwm"
- "/dev/null:/dev/virt-null:rwm"
force_kill: yes
register: devices_4
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- devices_1 is changed
- devices_2 is not changed
- devices_3 is not changed
- devices_4 is changed
####################################################################
## device_read_bps #################################################
####################################################################
- name: device_read_bps
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
device_read_bps:
- path: /dev/random
rate: 20M
- path: /dev/urandom
rate: 10K
register: device_read_bps_1
ignore_errors: yes
- name: device_read_bps (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
device_read_bps:
- path: /dev/urandom
rate: 10K
- path: /dev/random
rate: 20M
register: device_read_bps_2
ignore_errors: yes
- name: device_read_bps (lesser entries)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
device_read_bps:
- path: /dev/random
rate: 20M
register: device_read_bps_3
ignore_errors: yes
- name: device_read_bps (changed)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
device_read_bps:
- path: /dev/random
rate: 10M
- path: /dev/urandom
rate: 5K
force_kill: yes
register: device_read_bps_4
ignore_errors: yes
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- device_read_bps_1 is changed
- device_read_bps_2 is not changed
- device_read_bps_3 is not changed
- device_read_bps_4 is changed
when: docker_py_version is version('1.9.0', '>=')
- assert:
that:
- device_read_bps_1 is failed
- "('version is ' ~ docker_py_version ~ ' ') in device_read_bps_1.msg"
- "'Minimum version required is 1.9.0 ' in device_read_bps_1.msg"
when: docker_py_version is version('1.9.0', '<')
####################################################################
## device_read_iops ################################################
####################################################################
- name: device_read_iops
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
device_read_iops:
- path: /dev/random
rate: 10
- path: /dev/urandom
rate: 20
register: device_read_iops_1
ignore_errors: yes
- name: device_read_iops (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
device_read_iops:
- path: /dev/urandom
rate: "20"
- path: /dev/random
rate: 10
register: device_read_iops_2
ignore_errors: yes
- name: device_read_iops (less)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
device_read_iops:
- path: /dev/random
rate: 10
register: device_read_iops_3
ignore_errors: yes
- name: device_read_iops (changed)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
device_read_iops:
- path: /dev/random
rate: 30
- path: /dev/urandom
rate: 50
force_kill: yes
register: device_read_iops_4
ignore_errors: yes
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- device_read_iops_1 is changed
- device_read_iops_2 is not changed
- device_read_iops_3 is not changed
- device_read_iops_4 is changed
when: docker_py_version is version('1.9.0', '>=')
- assert:
that:
- device_read_iops_1 is failed
- "('version is ' ~ docker_py_version ~ ' ') in device_read_iops_1.msg"
- "'Minimum version required is 1.9.0 ' in device_read_iops_1.msg"
when: docker_py_version is version('1.9.0', '<')
####################################################################
## device_write_bps and device_write_iops ##########################
####################################################################
- name: device_write_bps and device_write_iops
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
device_write_bps:
- path: /dev/random
rate: 10M
device_write_iops:
- path: /dev/urandom
rate: 30
register: device_write_limit_1
ignore_errors: yes
- name: device_write_bps and device_write_iops (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
device_write_bps:
- path: /dev/random
rate: 10M
device_write_iops:
- path: /dev/urandom
rate: 30
register: device_write_limit_2
ignore_errors: yes
- name: device_write_bps device_write_iops (changed)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
device_write_bps:
- path: /dev/random
rate: 20K
device_write_iops:
- path: /dev/urandom
rate: 100
force_kill: yes
register: device_write_limit_3
ignore_errors: yes
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- device_write_limit_1 is changed
- device_write_limit_2 is not changed
- device_write_limit_3 is changed
when: docker_py_version is version('1.9.0', '>=')
- assert:
that:
- device_write_limit_1 is failed
- "('version is ' ~ docker_py_version ~ ' ') in device_write_limit_1.msg"
- "'Minimum version required is 1.9.0 ' in device_write_limit_1.msg"
when: docker_py_version is version('1.9.0', '<')
####################################################################
## dns_opts ########################################################
####################################################################
- name: dns_opts
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
dns_opts:
- "timeout:10"
- rotate
register: dns_opts_1
ignore_errors: yes
- name: dns_opts (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
dns_opts:
- rotate
- "timeout:10"
register: dns_opts_2
ignore_errors: yes
- name: dns_opts (less resolv.conf options)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
dns_opts:
- "timeout:10"
register: dns_opts_3
ignore_errors: yes
- name: dns_opts (more resolv.conf options)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
dns_opts:
- "timeout:10"
- no-check-names
force_kill: yes
register: dns_opts_4
ignore_errors: yes
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- dns_opts_1 is changed
- dns_opts_2 is not changed
- dns_opts_3 is not changed
- dns_opts_4 is changed
when: docker_py_version is version('1.10.0', '>=')
- assert:
that:
- dns_opts_1 is failed
- "('version is ' ~ docker_py_version ~ ' ') in dns_opts_1.msg"
- "'Minimum version required is 1.10.0 ' in dns_opts_1.msg"
when: docker_py_version is version('1.10.0', '<')
####################################################################
## dns_search_domains ##############################################
####################################################################
- name: dns_search_domains
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
dns_search_domains:
- example.com
- example.org
register: dns_search_domains_1
- name: dns_search_domains (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
dns_search_domains:
- example.com
- example.org
register: dns_search_domains_2
- name: dns_search_domains (different order)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
dns_search_domains:
- example.org
- example.com
force_kill: yes
register: dns_search_domains_3
- name: dns_search_domains (changed elements)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
dns_search_domains:
- ansible.com
- example.com
force_kill: yes
register: dns_search_domains_4
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- dns_search_domains_1 is changed
- dns_search_domains_2 is not changed
- dns_search_domains_3 is changed
- dns_search_domains_4 is changed
####################################################################
## dns_servers #####################################################
####################################################################
- name: dns_servers
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
dns_servers:
- 1.1.1.1
- 8.8.8.8
register: dns_servers_1
- name: dns_servers (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
dns_servers:
- 1.1.1.1
- 8.8.8.8
register: dns_servers_2
- name: dns_servers (changed order)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
dns_servers:
- 8.8.8.8
- 1.1.1.1
force_kill: yes
register: dns_servers_3
- name: dns_servers (changed elements)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
dns_servers:
- 8.8.8.8
- 9.9.9.9
force_kill: yes
register: dns_servers_4
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- dns_servers_1 is changed
- dns_servers_2 is not changed
- dns_servers_3 is changed
- dns_servers_4 is changed
####################################################################
## domainname ######################################################
####################################################################
- name: domainname
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
domainname: example.com
state: started
register: domainname_1
- name: domainname (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
domainname: example.com
state: started
register: domainname_2
- name: domainname (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
domainname: example.org
state: started
force_kill: yes
register: domainname_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- domainname_1 is changed
- domainname_2 is not changed
- domainname_3 is changed
####################################################################
## entrypoint ######################################################
####################################################################
- name: entrypoint
docker_container:
image: alpine:3.8
entrypoint:
- /bin/sh
- "-v"
- "-c"
- "'sleep 10m'"
name: "{{ cname }}"
state: started
register: entrypoint_1
- name: entrypoint (idempotency)
docker_container:
image: alpine:3.8
entrypoint:
- /bin/sh
- "-v"
- "-c"
- "'sleep 10m'"
name: "{{ cname }}"
state: started
register: entrypoint_2
- name: entrypoint (change order, should not be idempotent)
docker_container:
image: alpine:3.8
entrypoint:
- /bin/sh
- "-c"
- "'sleep 10m'"
- "-v"
name: "{{ cname }}"
state: started
force_kill: yes
register: entrypoint_3
- name: entrypoint (less parameters)
docker_container:
image: alpine:3.8
entrypoint:
- /bin/sh
- "-c"
- "'sleep 10m'"
name: "{{ cname }}"
state: started
force_kill: yes
register: entrypoint_4
- name: entrypoint (other parameters)
docker_container:
image: alpine:3.8
entrypoint:
- /bin/sh
- "-c"
- "'sleep 5m'"
name: "{{ cname }}"
state: started
force_kill: yes
register: entrypoint_5
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- entrypoint_1 is changed
- entrypoint_2 is not changed
- entrypoint_3 is changed
- entrypoint_4 is changed
- entrypoint_5 is changed
####################################################################
## env #############################################################
####################################################################
- name: env
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
env:
TEST1: val1
TEST2: val2
TEST3: "False"
TEST4: "true"
TEST5: "yes"
register: env_1
- name: env (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
env:
TEST2: val2
TEST1: val1
TEST5: "yes"
TEST3: "False"
TEST4: "true"
register: env_2
- name: env (less environment variables)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
env:
TEST1: val1
register: env_3
- name: env (more environment variables)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
env:
TEST1: val1
TEST3: val3
force_kill: yes
register: env_4
- name: env (fail unwrapped values)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
env:
TEST1: true
force_kill: yes
register: env_5
ignore_errors: yes
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- env_1 is changed
- env_2 is not changed
- env_3 is not changed
- env_4 is changed
- env_5 is failed
- "('Non-string value found for env option.') in env_5.msg"
####################################################################
## env_file #########################################################
####################################################################
- name: env_file
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
env_file: "{{ role_path }}/files/env-file"
register: env_file_1
- name: env_file (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
env_file: "{{ role_path }}/files/env-file"
register: env_file_2
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- env_file_1 is changed
- env_file_2 is not changed
####################################################################
## etc_hosts #######################################################
####################################################################
- name: etc_hosts
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
etc_hosts:
example.com: 1.2.3.4
example.org: 4.3.2.1
register: etc_hosts_1
- name: etc_hosts (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
etc_hosts:
example.org: 4.3.2.1
example.com: 1.2.3.4
register: etc_hosts_2
- name: etc_hosts (less hosts)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
etc_hosts:
example.com: 1.2.3.4
register: etc_hosts_3
- name: etc_hosts (more hosts)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
etc_hosts:
example.com: 1.2.3.4
example.us: 1.2.3.5
force_kill: yes
register: etc_hosts_4
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- etc_hosts_1 is changed
- etc_hosts_2 is not changed
- etc_hosts_3 is not changed
- etc_hosts_4 is changed
####################################################################
## exposed_ports ###################################################
####################################################################
- name: exposed_ports
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
exposed_ports:
- "9001"
- "9002"
register: exposed_ports_1
- name: exposed_ports (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
exposed_ports:
- "9002"
- "9001"
register: exposed_ports_2
- name: exposed_ports (less ports)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
exposed_ports:
- "9002"
register: exposed_ports_3
- name: exposed_ports (more ports)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
exposed_ports:
- "9002"
- "9003"
force_kill: yes
register: exposed_ports_4
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- exposed_ports_1 is changed
- exposed_ports_2 is not changed
- exposed_ports_3 is not changed
- exposed_ports_4 is changed
####################################################################
## force_kill ######################################################
####################################################################
# TODO: - force_kill
####################################################################
## groups ##########################################################
####################################################################
- name: groups
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
groups:
- "1234"
- "5678"
register: groups_1
- name: groups (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
groups:
- "5678"
- "1234"
register: groups_2
- name: groups (less groups)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
groups:
- "1234"
register: groups_3
- name: groups (more groups)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
groups:
- "1234"
- "2345"
force_kill: yes
register: groups_4
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- groups_1 is changed
- groups_2 is not changed
- groups_3 is not changed
- groups_4 is changed
####################################################################
## healthcheck #####################################################
####################################################################
- name: healthcheck
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
healthcheck:
test:
- CMD
- sleep
- 1
timeout: 2s
interval: 0h0m2s3ms4us
retries: 2
force_kill: yes
register: healthcheck_1
ignore_errors: yes
- name: healthcheck (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
healthcheck:
test:
- CMD
- sleep
- 1
timeout: 2s
interval: 0h0m2s3ms4us
retries: 2
force_kill: yes
register: healthcheck_2
ignore_errors: yes
- name: healthcheck (changed)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
healthcheck:
test:
- CMD
- sleep
- 1
timeout: 3s
interval: 0h1m2s3ms4us
retries: 3
force_kill: yes
register: healthcheck_3
ignore_errors: yes
- name: healthcheck (no change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
force_kill: yes
register: healthcheck_4
ignore_errors: yes
- name: healthcheck (disabled)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
healthcheck:
test:
- NONE
force_kill: yes
register: healthcheck_5
ignore_errors: yes
- name: healthcheck (disabled, idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
healthcheck:
test:
- NONE
force_kill: yes
register: healthcheck_6
ignore_errors: yes
- name: healthcheck (string in healthcheck test, changed)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
healthcheck:
test: "sleep 1"
force_kill: yes
register: healthcheck_7
ignore_errors: yes
- name: healthcheck (string in healthcheck test, idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
healthcheck:
test: "sleep 1"
force_kill: yes
register: healthcheck_8
ignore_errors: yes
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- healthcheck_1 is changed
- healthcheck_2 is not changed
- healthcheck_3 is changed
- healthcheck_4 is not changed
- healthcheck_5 is changed
- healthcheck_6 is not changed
- healthcheck_7 is changed
- healthcheck_8 is not changed
when: docker_py_version is version('2.0.0', '>=')
- assert:
that:
- healthcheck_1 is failed
- "('version is ' ~ docker_py_version ~ ' ') in healthcheck_1.msg"
- "'Minimum version required is 2.0.0 ' in healthcheck_1.msg"
when: docker_py_version is version('2.0.0', '<')
####################################################################
## hostname ########################################################
####################################################################
- name: hostname
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
hostname: me.example.com
state: started
register: hostname_1
- name: hostname (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
hostname: me.example.com
state: started
register: hostname_2
- name: hostname (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
hostname: me.example.org
state: started
force_kill: yes
register: hostname_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- hostname_1 is changed
- hostname_2 is not changed
- hostname_3 is changed
####################################################################
## init ############################################################
####################################################################
- name: init
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
init: yes
state: started
register: init_1
ignore_errors: yes
- name: init (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
init: yes
state: started
register: init_2
ignore_errors: yes
- name: init (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
init: no
state: started
force_kill: yes
register: init_3
ignore_errors: yes
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- init_1 is changed
- init_2 is not changed
- init_3 is changed
when: docker_py_version is version('2.2.0', '>=')
- assert:
that:
- init_1 is failed
- "('version is ' ~ docker_py_version ~ ' ') in init_1.msg"
- "'Minimum version required is 2.2.0 ' in init_1.msg"
when: docker_py_version is version('2.2.0', '<')
####################################################################
## interactive #####################################################
####################################################################
- name: interactive
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
interactive: yes
state: started
register: interactive_1
- name: interactive (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
interactive: yes
state: started
register: interactive_2
- name: interactive (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
interactive: no
state: started
force_kill: yes
register: interactive_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- interactive_1 is changed
- interactive_2 is not changed
- interactive_3 is changed
####################################################################
## image / ignore_image ############################################
####################################################################
- name: Pull hello-world image to make sure ignore_image test succeeds
# If the image isn't there, it will pull it and return 'changed'.
docker_image:
name: hello-world
pull: true
- name: image
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
register: image_1
- name: image (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
register: image_2
- name: ignore_image
docker_container:
image: hello-world
ignore_image: yes
name: "{{ cname }}"
state: started
register: ignore_image
- name: image change
docker_container:
image: hello-world
name: "{{ cname }}"
state: started
force_kill: yes
register: image_change
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- image_1 is changed
- image_2 is not changed
- ignore_image is not changed
- image_change is changed
####################################################################
## ipc_mode ########################################################
####################################################################
- name: start helpers
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ container_name }}"
state: started
loop:
- "{{ cname_h1 }}"
loop_control:
loop_var: container_name
- name: ipc_mode
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
ipc_mode: "container:{{ cname_h1 }}"
# ipc_mode: shareable
register: ipc_mode_1
- name: ipc_mode (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
ipc_mode: "container:{{ cname_h1 }}"
# ipc_mode: shareable
register: ipc_mode_2
- name: ipc_mode (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
ipc_mode: private
force_kill: yes
register: ipc_mode_3
- name: cleanup
docker_container:
name: "{{ container_name }}"
state: absent
force_kill: yes
loop:
- "{{ cname }}"
- "{{ cname_h1 }}"
loop_control:
loop_var: container_name
diff: no
- assert:
that:
- ipc_mode_1 is changed
- ipc_mode_2 is not changed
- ipc_mode_3 is changed
####################################################################
## kernel_memory ###################################################
####################################################################
- name: kernel_memory
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
kernel_memory: 8M
state: started
register: kernel_memory_1
ignore_errors: yes
- name: kernel_memory (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
kernel_memory: 8M
state: started
register: kernel_memory_2
ignore_errors: yes
- name: kernel_memory (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
kernel_memory: 6M
state: started
force_kill: yes
register: kernel_memory_3
ignore_errors: yes
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
ignore_errors: yes
- assert:
that:
- kernel_memory_1 is changed
- kernel_memory_2 is not changed
- kernel_memory_3 is changed
when: kernel_memory_1 is not failed or 'kernel memory accounting disabled in this runc build' not in kernel_memory_1.msg
####################################################################
## kill_signal #####################################################
####################################################################
# TODO: - kill_signal
####################################################################
## labels ##########################################################
####################################################################
- name: labels
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
labels:
ansible.test.1: hello
ansible.test.2: world
register: labels_1
- name: labels (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
labels:
ansible.test.2: world
ansible.test.1: hello
register: labels_2
- name: labels (less labels)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
labels:
ansible.test.1: hello
register: labels_3
- name: labels (more labels)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
labels:
ansible.test.1: hello
ansible.test.3: ansible
force_kill: yes
register: labels_4
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- labels_1 is changed
- labels_2 is not changed
- labels_3 is not changed
- labels_4 is changed
####################################################################
## links ###########################################################
####################################################################
- name: start helpers
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ container_name }}"
state: started
loop:
- "{{ cname_h1 }}"
- "{{ cname_h2 }}"
- "{{ cname_h3 }}"
loop_control:
loop_var: container_name
- name: links
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
links:
- "{{ cname_h1 }}:test1"
- "{{ cname_h2 }}:test2"
register: links_1
- name: links (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
links:
- "{{ cname_h2 }}:test2"
- "{{ cname_h1 }}:test1"
register: links_2
- name: links (less links)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
links:
- "{{ cname_h1 }}:test1"
register: links_3
- name: links (more links)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
links:
- "{{ cname_h1 }}:test1"
- "{{ cname_h3 }}:test3"
force_kill: yes
register: links_4
- name: cleanup
docker_container:
name: "{{ container_name }}"
state: absent
force_kill: yes
loop:
- "{{ cname }}"
- "{{ cname_h1 }}"
- "{{ cname_h2 }}"
- "{{ cname_h3 }}"
loop_control:
loop_var: container_name
diff: no
- assert:
that:
- links_1 is changed
- links_2 is not changed
- links_3 is not changed
- links_4 is changed
####################################################################
## log_driver ######################################################
####################################################################
- name: log_driver
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
log_driver: json-file
register: log_driver_1
- name: log_driver (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
log_driver: json-file
register: log_driver_2
- name: log_driver (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
log_driver: syslog
force_kill: yes
register: log_driver_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- log_driver_1 is changed
- log_driver_2 is not changed
- log_driver_3 is changed
####################################################################
## log_options #####################################################
####################################################################
- name: log_options
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
log_driver: json-file
log_options:
labels: production_status
env: os,customer
max-file: 5
register: log_options_1
- name: log_options (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
log_driver: json-file
log_options:
env: os,customer
labels: production_status
max-file: 5
register: log_options_2
- name: log_options (less log options)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
log_driver: json-file
log_options:
labels: production_status
register: log_options_3
- name: log_options (more log options)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
log_driver: json-file
log_options:
labels: production_status
max-size: 10m
force_kill: yes
register: log_options_4
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- log_options_1 is changed
- log_options_2 is not changed
- "'Non-string value found for log_options option \\'max-file\\'. The value is automatically converted to \\'5\\'. If this is not correct, or you want to
avoid such warnings, please quote the value.' in log_options_2.warnings"
- log_options_3 is not changed
- log_options_4 is changed
####################################################################
## mac_address #####################################################
####################################################################
- name: mac_address
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
mac_address: 92:d0:c6:0a:29:33
state: started
register: mac_address_1
- name: mac_address (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
mac_address: 92:d0:c6:0a:29:33
state: started
register: mac_address_2
- name: mac_address (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
mac_address: 92:d0:c6:0a:29:44
state: started
force_kill: yes
register: mac_address_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- mac_address_1 is changed
- mac_address_2 is not changed
- mac_address_3 is changed
####################################################################
## memory ##########################################################
####################################################################
- name: memory
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
memory: 64M
state: started
register: memory_1
- name: memory (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
memory: 64M
state: started
register: memory_2
- name: memory (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
memory: 48M
state: started
force_kill: yes
register: memory_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- memory_1 is changed
- memory_2 is not changed
- memory_3 is changed
####################################################################
## memory_reservation ##############################################
####################################################################
- name: memory_reservation
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
memory_reservation: 64M
state: started
register: memory_reservation_1
- name: memory_reservation (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
memory_reservation: 64M
state: started
register: memory_reservation_2
- name: memory_reservation (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
memory_reservation: 48M
state: started
force_kill: yes
register: memory_reservation_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- memory_reservation_1 is changed
- memory_reservation_2 is not changed
- memory_reservation_3 is changed
####################################################################
## memory_swap #####################################################
####################################################################
- name: memory_swap
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
# Docker daemon does not accept memory_swap if memory is not specified
memory: 32M
memory_swap: 64M
state: started
debug: yes
register: memory_swap_1
- name: memory_swap (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
# Docker daemon does not accept memory_swap if memory is not specified
memory: 32M
memory_swap: 64M
state: started
debug: yes
register: memory_swap_2
- name: memory_swap (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
# Docker daemon does not accept memory_swap if memory is not specified
memory: 32M
memory_swap: 48M
state: started
force_kill: yes
debug: yes
register: memory_swap_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- memory_swap_1 is changed
# Sometimes (in particular during integration tests, maybe when not running
# on a proper VM), memory_swap cannot be set and will be -1 afterwards.
- memory_swap_2 is not changed or memory_swap_2.container.HostConfig.MemorySwap == -1
- memory_swap_3 is changed
- debug: var=memory_swap_1
when: memory_swap_2 is changed
- debug: var=memory_swap_2
when: memory_swap_2 is changed
- debug: var=memory_swap_3
when: memory_swap_2 is changed
####################################################################
## memory_swappiness ###############################################
####################################################################
- name: memory_swappiness
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
memory_swappiness: 40
state: started
register: memory_swappiness_1
- name: memory_swappiness (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
memory_swappiness: 40
state: started
register: memory_swappiness_2
- name: memory_swappiness (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
memory_swappiness: 60
state: started
force_kill: yes
register: memory_swappiness_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- memory_swappiness_1 is changed
- memory_swappiness_2 is not changed
- memory_swappiness_3 is changed
####################################################################
## oom_killer ######################################################
####################################################################
- name: oom_killer
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
oom_killer: yes
state: started
register: oom_killer_1
- name: oom_killer (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
oom_killer: yes
state: started
register: oom_killer_2
- name: oom_killer (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
oom_killer: no
state: started
force_kill: yes
register: oom_killer_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- oom_killer_1 is changed
- oom_killer_2 is not changed
- oom_killer_3 is changed
####################################################################
## oom_score_adj ###################################################
####################################################################
- name: oom_score_adj
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
oom_score_adj: 5
state: started
register: oom_score_adj_1
- name: oom_score_adj (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
oom_score_adj: 5
state: started
register: oom_score_adj_2
- name: oom_score_adj (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
oom_score_adj: 7
state: started
force_kill: yes
register: oom_score_adj_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- oom_score_adj_1 is changed
- oom_score_adj_2 is not changed
- oom_score_adj_3 is changed
####################################################################
## output_logs #####################################################
####################################################################
# TODO: - output_logs
####################################################################
## paused ##########################################################
####################################################################
- name: paused
docker_container:
image: alpine:3.8
command: "/bin/sh -c 'sleep 10m'"
name: "{{ cname }}"
state: started
paused: yes
force_kill: yes
register: paused_1
- name: inspect paused
command: "docker inspect -f {% raw %}'{{.State.Status}} {{.State.Paused}}'{% endraw %} {{ cname }}"
register: paused_2
- name: paused (idempotent)
docker_container:
image: alpine:3.8
command: "/bin/sh -c 'sleep 10m'"
name: "{{ cname }}"
state: started
paused: yes
force_kill: yes
register: paused_3
- name: paused (continue)
docker_container:
image: alpine:3.8
command: "/bin/sh -c 'sleep 10m'"
name: "{{ cname }}"
state: started
paused: no
force_kill: yes
register: paused_4
- name: inspect paused
command: "docker inspect -f {% raw %}'{{.State.Status}} {{.State.Paused}}'{% endraw %} {{ cname }}"
register: paused_5
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- paused_1 is changed
- 'paused_2.stdout == "paused true"'
- paused_3 is not changed
- paused_4 is changed
- 'paused_5.stdout == "running false"'
####################################################################
## pid_mode ########################################################
####################################################################
- name: start helpers
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname_h1 }}"
state: started
register: pid_mode_helper
- name: pid_mode
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
pid_mode: "container:{{ pid_mode_helper.container.Id }}"
register: pid_mode_1
ignore_errors: yes
# docker-py < 2.0 does not support "arbitrary" pid_mode values
- name: pid_mode (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
pid_mode: "container:{{ cname_h1 }}"
register: pid_mode_2
ignore_errors: yes
# docker-py < 2.0 does not support "arbitrary" pid_mode values
- name: pid_mode (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
pid_mode: host
force_kill: yes
register: pid_mode_3
- name: cleanup
docker_container:
name: "{{ container_name }}"
state: absent
force_kill: yes
loop:
- "{{ cname }}"
- "{{ cname_h1 }}"
loop_control:
loop_var: container_name
diff: no
- assert:
that:
- pid_mode_1 is changed
- pid_mode_2 is not changed
- pid_mode_3 is changed
when: docker_py_version is version('2.0.0', '>=')
- assert:
that:
- pid_mode_1 is failed
- pid_mode_2 is failed
- pid_mode_3 is changed
when: docker_py_version is version('2.0.0', '<')
####################################################################
## pids_limit ######################################################
####################################################################
- name: pids_limit
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
pids_limit: 10
register: pids_limit_1
ignore_errors: yes
- name: pids_limit (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
pids_limit: 10
register: pids_limit_2
ignore_errors: yes
- name: pids_limit (changed)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
pids_limit: 20
force_kill: yes
register: pids_limit_3
ignore_errors: yes
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- pids_limit_1 is changed
- pids_limit_2 is not changed
- pids_limit_3 is changed
when: docker_py_version is version('1.10.0', '>=')
- assert:
that:
- pids_limit_1 is failed
- "('version is ' ~ docker_py_version ~ ' ') in pids_limit_1.msg"
- "'Minimum version required is 1.10.0 ' in pids_limit_1.msg"
when: docker_py_version is version('1.10.0', '<')
####################################################################
## privileged ######################################################
####################################################################
- name: privileged
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
privileged: yes
state: started
register: privileged_1
- name: privileged (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
privileged: yes
state: started
register: privileged_2
- name: privileged (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
privileged: no
state: started
force_kill: yes
register: privileged_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- privileged_1 is changed
- privileged_2 is not changed
- privileged_3 is changed
####################################################################
## published_ports #################################################
####################################################################
- name: published_ports
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
published_ports:
- '9001'
- '9002'
register: published_ports_1
- name: published_ports (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
published_ports:
- '9002'
- '9001'
register: published_ports_2
- name: published_ports (less published_ports)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
published_ports:
- '9002'
register: published_ports_3
- name: published_ports (more published_ports)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
published_ports:
- '9002'
- '9003'
force_kill: yes
register: published_ports_4
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- published_ports_1 is changed
- published_ports_2 is not changed
- published_ports_3 is not changed
- published_ports_4 is changed
####################################################################
## pull ############################################################
####################################################################
# TODO: - pull
####################################################################
## read_only #######################################################
####################################################################
- name: read_only
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
read_only: yes
state: started
register: read_only_1
- name: read_only (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
read_only: yes
state: started
register: read_only_2
- name: read_only (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
read_only: no
state: started
force_kill: yes
register: read_only_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- read_only_1 is changed
- read_only_2 is not changed
- read_only_3 is changed
####################################################################
## restart_policy ##################################################
####################################################################
- name: restart_policy
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
restart_policy: always
state: started
register: restart_policy_1
- name: restart_policy (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
restart_policy: always
state: started
register: restart_policy_2
- name: restart_policy (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
restart_policy: unless-stopped
state: started
force_kill: yes
register: restart_policy_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- restart_policy_1 is changed
- restart_policy_2 is not changed
- restart_policy_3 is changed
####################################################################
## restart_retries #################################################
####################################################################
- name: restart_retries
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
restart_policy: on-failure
restart_retries: 5
state: started
register: restart_retries_1
- name: restart_retries (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
restart_policy: on-failure
restart_retries: 5
state: started
register: restart_retries_2
- name: restart_retries (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
restart_policy: on-failure
restart_retries: 2
state: started
force_kill: yes
register: restart_retries_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- restart_retries_1 is changed
- restart_retries_2 is not changed
- restart_retries_3 is changed
####################################################################
## runtime #########################################################
####################################################################
- name: runtime
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
runtime: runc
state: started
register: runtime_1
ignore_errors: yes
- name: runtime (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
runtime: runc
state: started
register: runtime_2
ignore_errors: yes
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- runtime_1 is changed
- runtime_2 is not changed
when: docker_py_version is version('2.4.0', '>=')
- assert:
that:
- runtime_1 is failed
- "('version is ' ~ docker_py_version ~ ' ') in runtime_1.msg"
- "'Minimum version required is 2.4.0 ' in runtime_1.msg"
when: docker_py_version is version('2.4.0', '<')
####################################################################
## security_opts ###################################################
####################################################################
# In case some of the options stop working, here are some more
# options which *currently* work with all integration test targets:
# no-new-privileges
# label:disable
# label=disable
# label:level:s0:c100,c200
# label=level:s0:c100,c200
# label:type:svirt_apache_t
# label=type:svirt_apache_t
# label:user:root
# label=user:root
# seccomp:unconfined
# seccomp=unconfined
# apparmor:docker-default
# apparmor=docker-default
- name: security_opts
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
security_opts:
- "label:level:s0:c100,c200"
- "no-new-privileges"
register: security_opts_1
- name: security_opts (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
security_opts:
- "no-new-privileges"
- "label:level:s0:c100,c200"
register: security_opts_2
- name: security_opts (less security options)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
security_opts:
- "no-new-privileges"
register: security_opts_3
- name: security_opts (more security options)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
security_opts:
- "label:disable"
- "no-new-privileges"
force_kill: yes
register: security_opts_4
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- security_opts_1 is changed
- security_opts_2 is not changed
- security_opts_3 is not changed
- security_opts_4 is changed
####################################################################
## shm_size ########################################################
####################################################################
- name: shm_size
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
shm_size: 96M
state: started
register: shm_size_1
- name: shm_size (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
shm_size: 96M
state: started
register: shm_size_2
- name: shm_size (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
shm_size: 75M
state: started
force_kill: yes
register: shm_size_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- shm_size_1 is changed
- shm_size_2 is not changed
- shm_size_3 is changed
####################################################################
## stop_signal #####################################################
####################################################################
- name: stop_signal
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
stop_signal: "30"
state: started
register: stop_signal_1
- name: stop_signal (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
stop_signal: "30"
state: started
register: stop_signal_2
- name: stop_signal (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
stop_signal: "9"
state: started
force_kill: yes
register: stop_signal_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- stop_signal_1 is changed
- stop_signal_2 is not changed
- stop_signal_3 is changed
####################################################################
## stop_timeout ####################################################
####################################################################
- name: stop_timeout
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
stop_timeout: 2
state: started
register: stop_timeout_1
- name: stop_timeout (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
stop_timeout: 2
state: started
register: stop_timeout_2
- name: stop_timeout (no change)
# stop_timeout changes are ignored by default
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
stop_timeout: 1
state: started
register: stop_timeout_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- stop_timeout_1 is changed
- stop_timeout_2 is not changed
- stop_timeout_3 is not changed
####################################################################
## sysctls #########################################################
####################################################################
# In case some of the options stop working, here are some more
# options which *currently* work with all integration test targets:
# net.ipv4.conf.default.log_martians: 1
# net.ipv4.conf.default.secure_redirects: 0
# net.ipv4.conf.default.send_redirects: 0
# net.ipv4.conf.all.log_martians: 1
# net.ipv4.conf.all.accept_redirects: 0
# net.ipv4.conf.all.secure_redirects: 0
# net.ipv4.conf.all.send_redirects: 0
- name: sysctls
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
sysctls:
net.ipv4.icmp_echo_ignore_all: 1
net.ipv4.ip_forward: 1
register: sysctls_1
ignore_errors: yes
- name: sysctls (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
sysctls:
net.ipv4.ip_forward: 1
net.ipv4.icmp_echo_ignore_all: 1
register: sysctls_2
ignore_errors: yes
- name: sysctls (less sysctls)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
sysctls:
net.ipv4.icmp_echo_ignore_all: 1
register: sysctls_3
ignore_errors: yes
- name: sysctls (more sysctls)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
sysctls:
net.ipv4.icmp_echo_ignore_all: 1
net.ipv6.conf.default.accept_redirects: 0
force_kill: yes
register: sysctls_4
ignore_errors: yes
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- sysctls_1 is changed
- sysctls_2 is not changed
- sysctls_3 is not changed
- sysctls_4 is changed
when: docker_py_version is version('1.10.0', '>=')
- assert:
that:
- sysctls_1 is failed
- "('version is ' ~ docker_py_version ~ ' ') in sysctls_1.msg"
- "'Minimum version required is 1.10.0 ' in sysctls_1.msg"
when: docker_py_version is version('1.10.0', '<')
####################################################################
## tmpfs ###########################################################
####################################################################
- name: tmpfs
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
tmpfs:
- "/test1:rw,noexec,nosuid,size=65536k"
- "/test2:rw,noexec,nosuid,size=65536k"
register: tmpfs_1
- name: tmpfs (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
tmpfs:
- "/test2:rw,noexec,nosuid,size=65536k"
- "/test1:rw,noexec,nosuid,size=65536k"
register: tmpfs_2
- name: tmpfs (less tmpfs)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
tmpfs:
- "/test1:rw,noexec,nosuid,size=65536k"
register: tmpfs_3
- name: tmpfs (more tmpfs)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
tmpfs:
- "/test1:rw,noexec,nosuid,size=65536k"
- "/test3:rw,noexec,nosuid,size=65536k"
force_kill: yes
register: tmpfs_4
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- tmpfs_1 is changed
- tmpfs_2 is not changed
- tmpfs_3 is not changed
- tmpfs_4 is changed
####################################################################
## trust_image_content #############################################
####################################################################
# TODO: - trust_image_content
####################################################################
## tty #############################################################
####################################################################
- name: tty
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
tty: yes
state: started
register: tty_1
- name: tty (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
tty: yes
state: started
register: tty_2
- name: tty (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
tty: no
state: started
force_kill: yes
register: tty_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- tty_1 is changed
- tty_2 is not changed
- tty_3 is changed
####################################################################
## ulimits #########################################################
####################################################################
- name: ulimits
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
ulimits:
- "nofile:1234:1234"
- "nproc:3:6"
register: ulimits_1
- name: ulimits (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
ulimits:
- "nproc:3:6"
- "nofile:1234:1234"
register: ulimits_2
- name: ulimits (less ulimits)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
ulimits:
- "nofile:1234:1234"
register: ulimits_3
- name: ulimits (more ulimits)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
ulimits:
- "nofile:1234:1234"
- "sigpending:100:200"
force_kill: yes
register: ulimits_4
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- ulimits_1 is changed
- ulimits_2 is not changed
- ulimits_3 is not changed
- ulimits_4 is changed
####################################################################
## user ############################################################
####################################################################
- name: user
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
user: nobody
state: started
register: user_1
- name: user (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
user: nobody
state: started
register: user_2
- name: user (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
user: root
state: started
force_kill: yes
register: user_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- user_1 is changed
- user_2 is not changed
- user_3 is changed
####################################################################
## userns_mode #####################################################
####################################################################
- name: userns_mode
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
userns_mode: host
state: started
register: userns_mode_1
ignore_errors: yes
- name: userns_mode (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
userns_mode: host
state: started
register: userns_mode_2
ignore_errors: yes
- name: userns_mode (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
userns_mode: ""
state: started
force_kill: yes
register: userns_mode_3
ignore_errors: yes
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- userns_mode_1 is changed
- userns_mode_2 is not changed
- userns_mode_3 is changed
when: docker_py_version is version('1.10.0', '>=')
- assert:
that:
- userns_mode_1 is failed
- "('version is ' ~ docker_py_version ~ ' ') in userns_mode_1.msg"
- "'Minimum version required is 1.10.0 ' in userns_mode_1.msg"
when: docker_py_version is version('1.10.0', '<')
####################################################################
## uts #############################################################
####################################################################
- name: uts
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
uts: host
state: started
register: uts_1
ignore_errors: yes
- name: uts (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
uts: host
state: started
register: uts_2
ignore_errors: yes
- name: uts (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
uts: ""
state: started
force_kill: yes
register: uts_3
ignore_errors: yes
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- uts_1 is changed
- uts_2 is not changed
- uts_3 is changed
when: docker_py_version is version('3.5.0', '>=')
- assert:
that:
- uts_1 is failed
- "('version is ' ~ docker_py_version ~ ' ') in uts_1.msg"
- "'Minimum version required is 3.5.0 ' in uts_1.msg"
when: docker_py_version is version('3.5.0', '<')
####################################################################
## keep_volumes ####################################################
####################################################################
# TODO: - keep_volumes
####################################################################
## volume_driver ###################################################
####################################################################
- name: volume_driver
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
volume_driver: local
state: started
register: volume_driver_1
- name: volume_driver (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
volume_driver: local
state: started
register: volume_driver_2
- name: volume_driver (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
volume_driver: /
state: started
force_kill: yes
register: volume_driver_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- volume_driver_1 is changed
- volume_driver_2 is not changed
- volume_driver_3 is changed
####################################################################
## volumes #########################################################
####################################################################
- name: volumes
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
volumes:
- "/tmp:/tmp"
- "/:/whatever:rw,z"
register: volumes_1
- name: volumes (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
volumes:
- "/:/whatever:rw,z"
- "/tmp:/tmp"
register: volumes_2
- name: volumes (less volumes)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
volumes:
- "/tmp:/tmp"
register: volumes_3
- name: volumes (more volumes)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
volumes:
- "/tmp:/tmp"
- "/tmp:/somewhereelse:ro,Z"
force_kill: yes
register: volumes_4
- name: volumes (different modes)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
volumes:
- "/tmp:/tmp"
- "/tmp:/somewhereelse:ro"
force_kill: yes
register: volumes_5
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- volumes_1 is changed
- volumes_2 is not changed
- volumes_3 is not changed
- volumes_4 is changed
- volumes_5 is changed
####################################################################
## volumes_from ####################################################
####################################################################
- name: start helpers
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ container_name }}"
state: started
volumes:
- "{{ '/tmp:/tmp' if container_name == cname_h1 else '/:/whatever:ro' }}"
loop:
- "{{ cname_h1 }}"
- "{{ cname_h2 }}"
loop_control:
loop_var: container_name
- name: volumes_from
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
volumes_from: "{{ cname_h1 }}"
register: volumes_from_1
- name: volumes_from (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
volumes_from: "{{ cname_h1 }}"
register: volumes_from_2
- name: volumes_from (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
state: started
volumes_from: "{{ cname_h2 }}"
force_kill: yes
register: volumes_from_3
- name: cleanup
docker_container:
name: "{{ container_name }}"
state: absent
force_kill: yes
loop:
- "{{ cname }}"
- "{{ cname_h1 }}"
- "{{ cname_h2 }}"
loop_control:
loop_var: container_name
diff: no
- assert:
that:
- volumes_from_1 is changed
- volumes_from_2 is not changed
- volumes_from_3 is changed
####################################################################
## working_dir #####################################################
####################################################################
- name: working_dir
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
working_dir: /tmp
state: started
register: working_dir_1
- name: working_dir (idempotency)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
working_dir: /tmp
state: started
register: working_dir_2
- name: working_dir (change)
docker_container:
image: alpine:3.8
command: '/bin/sh -c "sleep 10m"'
name: "{{ cname }}"
working_dir: /
state: started
force_kill: yes
register: working_dir_3
- name: cleanup
docker_container:
name: "{{ cname }}"
state: absent
force_kill: yes
diff: no
- assert:
that:
- working_dir_1 is changed
- working_dir_2 is not changed
- working_dir_3 is changed
####################################################################
####################################################################
####################################################################
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 59,351 |
Docs for win_firewall_rule (protocol is mandatory if localport is specified)
|
##### SUMMARY
win_firewall_rule docs do not specify that protocol is mandatory when specifying a port. This is not obvious, in my case i wanted a rule to allow both TCP and UDP.
MSFT docs for New-NetFirewallRule specifies:
"If the Protocol parameter value is TCP or UDP, then the acceptable values for this parameter are- etc.." something similar in the ansible docs would make sense
https://github.com/ansible/ansible/issues/31576 makes clear a change to docs would be helpful.
##### ISSUE TYPE
- Documentation Report
##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below, use your best guess if unsure -->
win_firewall_rule
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```
ansible 2.8.2
config file = /Users/redacted/projects/projectname/ansible/ansible.cfg
configured module search path = ['/Users/redacted/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/Cellar/ansible/2.8.2/libexec/lib/python3.7/site-packages/ansible
executable location = /usr/local/bin/ansible
python version = 3.7.4 (default, Jul 9 2019, 18:13:23) [Clang 10.0.1 (clang-1001.0.46.4)]
```
##### CONFIGURATION
Not relevant
##### OS / ENVIRONMENT
Server 2019 Core
##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->
<!--- Paste example playbooks or commands between quotes below -->
```
- name: New firewall rule allow HTTPS
win_firewall_rule:
name: name (withBrackets)
description: description (withBrackets)
localport: 443
action: allow
direction: in
enabled: yes
state: present
```
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
Firewall rule created for both UDP and TCP
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```
task path: /redacted/file.yml:27
Using module file /usr/local/Cellar/ansible/2.8.2/libexec/lib/python3.7/site-packages/ansible/modules/windows/win_firewall_rule.ps1
Pipelining is enabled.
<redacted> ESTABLISH WINRM CONNECTION FOR USER: redacted on PORT redacted TO redacted
EXEC (via pipeline wrapper)
The full traceback is:
Value does not fall within the expected range.
At line:162 char:59
+ ... port -and $localport -ne "any") { $new_rule.LocalPorts = $localport }
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException
fatal: [hostname1]: FAILED! => {
"changed": false,
"msg": "Value does not fall within the expected range."
}
```
|
https://github.com/ansible/ansible/issues/59351
|
https://github.com/ansible/ansible/pull/59467
|
7b4ce9e4aee8f2d131ea0176456054b3ecbd4002
|
092e5515d12ff2ad4b47aa2f940ff399809b8ec3
| 2019-07-21T08:52:04Z |
python
| 2019-07-23T19:37:08Z |
lib/ansible/modules/windows/win_firewall_rule.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2014, Timothy Vandenbrande <[email protected]>
# Copyright: (c) 2017, Artem Zinenko <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: win_firewall_rule
version_added: "2.0"
short_description: Windows firewall automation
description:
- Allows you to create/remove/update firewall rules.
options:
enabled:
description:
- Whether this firewall rule is enabled or disabled.
- Defaults to C(true) when creating a new rule.
type: bool
aliases: [ enable ]
state:
description:
- Should this rule be added or removed.
type: str
choices: [ absent, present ]
default: present
name:
description:
- The rule's display name.
type: str
required: yes
direction:
description:
- Whether this rule is for inbound or outbound traffic.
- Defaults to C(in) when creating a new rule.
type: str
choices: [ in, out ]
action:
description:
- What to do with the items this rule is for.
- Defaults to C(allow) when creating a new rule.
type: str
choices: [ allow, block ]
description:
description:
- Description for the firewall rule.
type: str
localip:
description:
- The local ip address this rule applies to.
- Set to C(any) to apply to all local ip addresses.
- Defaults to C(any) when creating a new rule.
type: str
remoteip:
description:
- The remote ip address/range this rule applies to.
- Set to C(any) to apply to all remote ip addresses.
- Defaults to C(any) when creating a new rule.
type: str
localport:
description:
- The local port this rule applies to.
- Set to C(any) to apply to all local ports.
- Defaults to C(any) when creating a new rule.
type: str
remoteport:
description:
- The remote port this rule applies to.
- Set to C(any) to apply to all remote ports.
- Defaults to C(any) when creating a new rule.
- Must have I(protocol) set
type: str
program:
description:
- The program this rule applies to.
- Set to C(any) to apply to all programs.
- Defaults to C(any) when creating a new rule.
type: str
service:
description:
- The service this rule applies to.
- Set to C(any) to apply to all services.
- Defaults to C(any) when creating a new rule.
type: str
protocol:
description:
- The protocol this rule applies to.
- Set to C(any) to apply to all services.
- Defaults to C(any) when creating a new rule.
type: str
profiles:
description:
- The profile this rule applies to.
- Defaults to C(domain,private,public) when creating a new rule.
type: list
aliases: [ profile ]
seealso:
- module: win_firewall
author:
- Artem Zinenko (@ar7z1)
- Timothy Vandenbrande (@TimothyVandenbrande)
'''
EXAMPLES = r'''
- name: Firewall rule to allow SMTP on TCP port 25
win_firewall_rule:
name: SMTP
localport: 25
action: allow
direction: in
protocol: tcp
state: present
enabled: yes
- name: Firewall rule to allow RDP on TCP port 3389
win_firewall_rule:
name: Remote Desktop
localport: 3389
action: allow
direction: in
protocol: tcp
profiles: private
state: present
enabled: yes
'''
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 59,451 |
ansible-galaxy collection build failing to find meta file
|
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->
##### SUMMARY
`ansible-galaxy collection build` fails when unable to locate new ` lib/ansible/galaxy/data/collections_galaxy_meta.yml` data file.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
ansible-galaxy
##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.9.0.dev0
config file = /etc/ansible/ansible.cfg
configured module search path = ['/home/calvin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /home/calvin/projects/ansible/lib/ansible
executable location = /home/calvin/.local/share/virtualenvs/orion/bin/ansible
python version = 3.6.8 (default, Mar 21 2019, 10:08:12) [GCC 8.3.1 20190223 (Red Hat 8.3.1-2)]
```
##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
```
##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
Fedora 28, should affect all versions OS tho
##### STEPS TO REPRODUCE
- Install latest `devel` branch of ansible *without* the `pip -e` flag
- Attempt to build a collection with `ansible-galaxy collection build`
<!--- HINT: You can paste gist.github.com links for larger files -->
##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
Expect the collection to be built and a `.tar.gz` artifact to be created.
##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->
<!--- Paste verbatim command output between quotes -->
```paste below
ansible-galaxy 2.9.0.dev0
config file = /etc/ansible/ansible.cfg
configured module search path = ['/home/calvin/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /home/calvin/.local/share/virtualenvs/orion/lib/python3.6/site-packages/ansible
executable location = /home/calvin/.local/share/virtualenvs/orion/bin/ansible-galaxy
python version = 3.6.8 (default, Mar 21 2019, 10:08:12) [GCC 8.3.1 20190223 (Red Hat 8.3.1-2)]
Using /etc/ansible/ansible.cfg as config file
Opened /home/calvin/.ansible_galaxy
ERROR! Unexpected Exception, this is probably a bug: [Errno 2] No such file or directory: b'/home/calvin/.local/share/virtualenvs/orion/lib/python3.6/site-packages/ansible/galaxy/data/collections_galaxy_meta.yml'
the full traceback was:
Traceback (most recent call last):
File "/home/calvin/.local/share/virtualenvs/orion/bin/ansible-galaxy", line 111, in <module>
exit_code = cli.run()
File "/home/calvin/.local/share/virtualenvs/orion/lib/python3.6/site-packages/ansible/cli/galaxy.py", line 269, in run
context.CLIARGS['func']()
File "/home/calvin/.local/share/virtualenvs/orion/lib/python3.6/site-packages/ansible/cli/galaxy.py", line 398, in execute_build
build_collection(collection_path, output_path, force)
File "/home/calvin/.local/share/virtualenvs/orion/lib/python3.6/site-packages/ansible/galaxy/collection.py", line 360, in build_collection
collection_meta = _get_galaxy_yml(b_galaxy_path)
File "/home/calvin/.local/share/virtualenvs/orion/lib/python3.6/site-packages/ansible/galaxy/collection.py", line 528, in _get_galaxy_yml
meta_info = get_collections_galaxy_meta_info()
File "/home/calvin/.local/share/virtualenvs/orion/lib/python3.6/site-packages/ansible/galaxy/__init__.py", line 38, in get_collections_galaxy_meta_info
with open(to_bytes(meta_path, errors='surrogate_or_strict'), 'rb') as galaxy_obj:
FileNotFoundError: [Errno 2] No such file or directory: b'/home/calvin/.local/share/virtualenvs/orion/lib/python3.6/site-packages/ansible/galaxy/data/collections_galaxy_meta.yml'
```
|
https://github.com/ansible/ansible/issues/59451
|
https://github.com/ansible/ansible/pull/59452
|
44a262714cc316f2c70be5654b1a15898af1189e
|
65bedaf074257ec85239843cec1352da66621338
| 2019-07-23T15:45:34Z |
python
| 2019-07-23T20:52:38Z |
setup.py
|
from __future__ import print_function
import json
import os
import os.path
import re
import sys
import warnings
from collections import defaultdict
from distutils.command.build_scripts import build_scripts as BuildScripts
from distutils.command.sdist import sdist as SDist
try:
from setuptools import setup, find_packages
from setuptools.command.build_py import build_py as BuildPy
from setuptools.command.install_lib import install_lib as InstallLib
from setuptools.command.install_scripts import install_scripts as InstallScripts
except ImportError:
print("Ansible now needs setuptools in order to build. Install it using"
" your package manager (usually python-setuptools) or via pip (pip"
" install setuptools).", file=sys.stderr)
sys.exit(1)
sys.path.insert(0, os.path.abspath('lib'))
from ansible.release import __version__, __author__
SYMLINK_CACHE = 'SYMLINK_CACHE.json'
def _find_symlinks(topdir, extension=''):
"""Find symlinks that should be maintained
Maintained symlinks exist in the bin dir or are modules which have
aliases. Our heuristic is that they are a link in a certain path which
point to a file in the same directory.
"""
symlinks = defaultdict(list)
for base_path, dirs, files in os.walk(topdir):
for filename in files:
filepath = os.path.join(base_path, filename)
if os.path.islink(filepath) and filename.endswith(extension):
target = os.readlink(filepath)
if os.path.dirname(target) == '':
link = filepath[len(topdir):]
if link.startswith('/'):
link = link[1:]
symlinks[os.path.basename(target)].append(link)
return symlinks
def _cache_symlinks(symlink_data):
with open(SYMLINK_CACHE, 'w') as f:
json.dump(symlink_data, f)
def _maintain_symlinks(symlink_type, base_path):
"""Switch a real file into a symlink"""
try:
# Try the cache first because going from git checkout to sdist is the
# only time we know that we're going to cache correctly
with open(SYMLINK_CACHE, 'r') as f:
symlink_data = json.load(f)
except (IOError, OSError) as e:
# IOError on py2, OSError on py3. Both have errno
if e.errno == 2:
# SYMLINKS_CACHE doesn't exist. Fallback to trying to create the
# cache now. Will work if we're running directly from a git
# checkout or from an sdist created earlier.
symlink_data = {'script': _find_symlinks('bin'),
'library': _find_symlinks('lib', '.py'),
}
# Sanity check that something we know should be a symlink was
# found. We'll take that to mean that the current directory
# structure properly reflects symlinks in the git repo
if 'ansible-playbook' in symlink_data['script']['ansible']:
_cache_symlinks(symlink_data)
else:
raise RuntimeError(
"Pregenerated symlink list was not present and expected "
"symlinks in ./bin were missing or broken. "
"Perhaps this isn't a git checkout?"
)
else:
raise
symlinks = symlink_data[symlink_type]
for source in symlinks:
for dest in symlinks[source]:
dest_path = os.path.join(base_path, dest)
if not os.path.islink(dest_path):
try:
os.unlink(dest_path)
except OSError as e:
if e.errno == 2:
# File does not exist which is all we wanted
pass
os.symlink(source, dest_path)
class BuildPyCommand(BuildPy):
def run(self):
BuildPy.run(self)
_maintain_symlinks('library', self.build_lib)
class BuildScriptsCommand(BuildScripts):
def run(self):
BuildScripts.run(self)
_maintain_symlinks('script', self.build_dir)
class InstallLibCommand(InstallLib):
def run(self):
InstallLib.run(self)
_maintain_symlinks('library', self.install_dir)
class InstallScriptsCommand(InstallScripts):
def run(self):
InstallScripts.run(self)
_maintain_symlinks('script', self.install_dir)
class SDistCommand(SDist):
def run(self):
# have to generate the cache of symlinks for release as sdist is the
# only command that has access to symlinks from the git repo
symlinks = {'script': _find_symlinks('bin'),
'library': _find_symlinks('lib', '.py'),
}
_cache_symlinks(symlinks)
SDist.run(self)
# Print warnings at the end because no one will see warnings before all the normal status
# output
if os.environ.get('_ANSIBLE_SDIST_FROM_MAKEFILE', False) != '1':
warnings.warn('When setup.py sdist is run from outside of the Makefile,'
' the generated tarball may be incomplete. Use `make snapshot`'
' to create a tarball from an arbitrary checkout or use'
' `cd packaging/release && make release version=[..]` for official builds.',
RuntimeWarning)
def read_file(file_name):
"""Read file and return its contents."""
with open(file_name, 'r') as f:
return f.read()
def read_requirements(file_name):
"""Read requirements file as a list."""
reqs = read_file(file_name).splitlines()
if not reqs:
raise RuntimeError(
"Unable to read requirements from the %s file"
"That indicates this copy of the source code is incomplete."
% file_name
)
return reqs
PYCRYPTO_DIST = 'pycrypto'
def get_crypto_req():
"""Detect custom crypto from ANSIBLE_CRYPTO_BACKEND env var.
pycrypto or cryptography. We choose a default but allow the user to
override it. This translates into pip install of the sdist deciding what
package to install and also the runtime dependencies that pkg_resources
knows about.
"""
crypto_backend = os.environ.get('ANSIBLE_CRYPTO_BACKEND', '').strip()
if crypto_backend == PYCRYPTO_DIST:
# Attempt to set version requirements
return '%s >= 2.6' % PYCRYPTO_DIST
return crypto_backend or None
def substitute_crypto_to_req(req):
"""Replace crypto requirements if customized."""
crypto_backend = get_crypto_req()
if crypto_backend is None:
return req
def is_not_crypto(r):
CRYPTO_LIBS = PYCRYPTO_DIST, 'cryptography'
return not any(r.lower().startswith(c) for c in CRYPTO_LIBS)
return [r for r in req if is_not_crypto(r)] + [crypto_backend]
def read_extras():
"""Specify any extra requirements for installation."""
extras = dict()
extra_requirements_dir = 'packaging/requirements'
for extra_requirements_filename in os.listdir(extra_requirements_dir):
filename_match = re.search(r'^requirements-(\w*).txt$', extra_requirements_filename)
if not filename_match:
continue
extra_req_file_path = os.path.join(extra_requirements_dir, extra_requirements_filename)
try:
extras[filename_match.group(1)] = read_file(extra_req_file_path).splitlines()
except RuntimeError:
pass
return extras
def get_dynamic_setup_params():
"""Add dynamically calculated setup params to static ones."""
return {
# Retrieve the long description from the README
'long_description': read_file('README.rst'),
'install_requires': substitute_crypto_to_req(
read_requirements('requirements.txt'),
),
'extras_require': read_extras(),
}
static_setup_params = dict(
# Use the distutils SDist so that symlinks are not expanded
# Use a custom Build for the same reason
cmdclass={
'build_py': BuildPyCommand,
'build_scripts': BuildScriptsCommand,
'install_lib': InstallLibCommand,
'install_scripts': InstallScriptsCommand,
'sdist': SDistCommand,
},
name='ansible',
version=__version__,
description='Radically simple IT automation',
author=__author__,
author_email='[email protected]',
url='https://ansible.com/',
project_urls={
'Bug Tracker': 'https://github.com/ansible/ansible/issues',
'CI: Shippable': 'https://app.shippable.com/github/ansible/ansible',
'Code of Conduct': 'https://docs.ansible.com/ansible/latest/community/code_of_conduct.html',
'Documentation': 'https://docs.ansible.com/ansible/',
'Mailing lists': 'https://docs.ansible.com/ansible/latest/community/communication.html#mailing-list-information',
'Source Code': 'https://github.com/ansible/ansible',
},
license='GPLv3+',
# Ansible will also make use of a system copy of python-six and
# python-selectors2 if installed but use a Bundled copy if it's not.
python_requires='>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*',
package_dir={'': 'lib'},
packages=find_packages('lib'),
package_data={
'': [
'executor/powershell/*.ps1',
'module_utils/csharp/*.cs',
'module_utils/csharp/*/*.cs',
'module_utils/powershell/*.psm1',
'module_utils/powershell/*/*.psm1',
'modules/windows/*.ps1',
'modules/windows/*/*.ps1',
'galaxy/data/*/*.*',
'galaxy/data/*/.*',
'galaxy/data/*/*/.*',
'galaxy/data/*/*/*.*',
'galaxy/data/*/tests/inventory',
'config/base.yml',
'config/module_defaults.yml',
],
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Natural Language :: English',
'Operating System :: POSIX',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: System :: Installation/Setup',
'Topic :: System :: Systems Administration',
'Topic :: Utilities',
],
scripts=[
'bin/ansible',
'bin/ansible-playbook',
'bin/ansible-pull',
'bin/ansible-doc',
'bin/ansible-galaxy',
'bin/ansible-console',
'bin/ansible-connection',
'bin/ansible-vault',
'bin/ansible-config',
'bin/ansible-inventory',
],
data_files=[],
# Installing as zip files would break due to references to __file__
zip_safe=False
)
def main():
"""Invoke installation process using setuptools."""
setup_params = dict(static_setup_params, **get_dynamic_setup_params())
ignore_warning_regex = (
r"Unknown distribution option: '(project_urls|python_requires)'"
)
warnings.filterwarnings(
'ignore',
message=ignore_warning_regex,
category=UserWarning,
module='distutils.dist',
)
setup(**setup_params)
warnings.resetwarnings()
if __name__ == '__main__':
main()
|
closed
|
ansible/ansible
|
https://github.com/ansible/ansible
| 59,442 |
Stricter config parsing makes openstack inventory clouds_yaml_path unusable
|
##### SUMMARY
In current `devel`, using the openstack inventory plugin with the parameter `clouds_yaml_path` no longer works.
##### ISSUE TYPE
- Bug Report
##### COMPONENT NAME
lib/ansible/cli/config.py
lib/ansible/plugins/inventory/openstack.py
##### ANSIBLE VERSION
```paste below
$ ansible --version
ansible 2.9.0.dev0
config file = None
configured module search path = ['/Users/alancoding/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /Users/alancoding/Documents/repos/ansible/lib/ansible
executable location = /Users/alancoding/.virtualenvs/ansible3/bin/ansible
python version = 3.6.5 (default, Apr 25 2018, 14:23:58) [GCC 4.2.1 Compatible Apple LLVM 9.1.0 (clang-902.0.39.1)]
```
##### CONFIGURATION
```paste below
$ ansible-config dump --only-changed
ANSIBLE_NOCOWS(env: ANSIBLE_NOCOWS) = True
```
##### OS / ENVIRONMENT
CentOS / Mac OS / control machine
##### STEPS TO REPRODUCE
Use inventory file `openstack.yml` as follows:
(1)
```yaml
plugin: openstack
clouds_yaml_path:
- private/openstack/clouds.yml
```
that format is the one which has historically worked. It is not the documented expected format.
----
The documentation suggests this would work, but it never has:
(2)
```yaml
plugin: openstack
clouds_yaml_path: private/openstack/clouds.yml
```
##### EXPECTED RESULTS
Generally, I would expect one of those 2 files to be successfully parsed.
Specifically, right now, I would like the 1st of those 2 to be parsed, because that is the only format that works in Ansible 2.8.
##### ACTUAL RESULTS
For inventory file (1)
```
$ ansible-inventory -i private/openstack/openstack.yml --list --export
[WARNING]: * Failed to parse /Users/alancoding/Documents/repos/ansible-inventory-file-examples/private/openstack/openstack.yml with auto plugin: Invalid type for configuration
option plugin_type: inventory plugin: openstack setting: clouds_yaml_path : Invalid type provided for "string": ['private/openstack/clouds.yml']
[WARNING]: * Failed to parse /Users/alancoding/Documents/repos/ansible-inventory-file-examples/private/openstack/openstack.yml with yaml plugin: Plugin configuration YAML file,
not YAML inventory
[WARNING]: * Failed to parse /Users/alancoding/Documents/repos/ansible-inventory-file-examples/private/openstack/openstack.yml with ini plugin: Invalid host pattern 'plugin:'
supplied, ending in ':' is not allowed, this character is reserved to provide a port.
[WARNING]: Unable to parse /Users/alancoding/Documents/repos/ansible-inventory-file-examples/private/openstack/openstack.yml as an inventory source
[WARNING]: No inventory was parsed, only implicit localhost is available
{
"_meta": {
"hostvars": {}
},
"all": {
"children": [
"ungrouped"
]
}
}
```
This case errors because of validation introduced in https://github.com/ansible/ansible/pull/58530, ping @bcoca
From verbose output:
```
[WARNING]: * Failed to parse /Users/alancoding/Documents/repos/ansible-inventory-file-examples/private/openstack/openstack.yml with auto plugin: Invalid type for configuration
option plugin_type: inventory plugin: openstack setting: clouds_yaml_path : Invalid type provided for "string": ['private/openstack/clouds.yml']
File "/Users/alancoding/Documents/repos/ansible/lib/ansible/inventory/manager.py", line 277, in parse_source
plugin.parse(self._inventory, self._loader, source, cache=cache)
File "/Users/alancoding/Documents/repos/ansible/lib/ansible/plugins/inventory/auto.py", line 58, in parse
plugin.parse(inventory, loader, path, cache=cache)
File "/Users/alancoding/Documents/repos/ansible/lib/ansible/plugins/inventory/openstack.py", line 141, in parse
self._config_data = self._read_config_data(path)
File "/Users/alancoding/Documents/repos/ansible/lib/ansible/plugins/inventory/__init__.py", line 229, in _read_config_data
self.set_options(direct=config)
File "/Users/alancoding/Documents/repos/ansible/lib/ansible/plugins/__init__.py", line 75, in set_options
self._options = C.config.get_plugin_options(get_plugin_class(self), self._load_name, keys=task_keys, variables=var_options, direct=direct)
File "/Users/alancoding/Documents/repos/ansible/lib/ansible/config/manager.py", line 348, in get_plugin_options
options[option] = self.get_config_value(option, plugin_type=plugin_type, plugin_name=name, keys=keys, variables=variables, direct=direct)
File "/Users/alancoding/Documents/repos/ansible/lib/ansible/config/manager.py", line 409, in get_config_value
keys=keys, variables=variables, direct=direct)
File "/Users/alancoding/Documents/repos/ansible/lib/ansible/config/manager.py", line 502, in get_config_value_and_origin
(to_native(_get_entry(plugin_type, plugin_name, config)), to_native(e)))
```
----
For inventory file (2)
```
$ ansible-inventory -i private/openstack/openstack.yml --list --export
[WARNING]: * Failed to parse /Users/alancoding/Documents/repos/ansible-inventory-file-examples/private/openstack/openstack.yml with auto plugin: must be str, not list
[WARNING]: * Failed to parse /Users/alancoding/Documents/repos/ansible-inventory-file-examples/private/openstack/openstack.yml with yaml plugin: Plugin configuration YAML file,
not YAML inventory
[WARNING]: * Failed to parse /Users/alancoding/Documents/repos/ansible-inventory-file-examples/private/openstack/openstack.yml with ini plugin: Invalid host pattern 'plugin:'
supplied, ending in ':' is not allowed, this character is reserved to provide a port.
[WARNING]: Unable to parse /Users/alancoding/Documents/repos/ansible-inventory-file-examples/private/openstack/openstack.yml as an inventory source
[WARNING]: No inventory was parsed, only implicit localhost is available
{
"_meta": {
"hostvars": {}
},
"all": {
"children": [
"ungrouped"
]
}
}
```
This fails because the openstack inventory plugin code depends on the input being a list. See:
https://github.com/ansible/ansible/blob/333953117c9e2ff62ebccdbcbb5947271b88ce73/lib/ansible/plugins/inventory/openstack.py#L178-L179
I can confirm that `client_config.CONFIG_FILES` is a list. Thus, the source of this error is trying to add the input value to this list. That requires both to be a list, thus, the error.
From verbose output:
```
[WARNING]: * Failed to parse /Users/alancoding/Documents/repos/ansible-inventory-file-examples/private/openstack/openstack.yml with auto plugin: must be str, not list
File "/Users/alancoding/Documents/repos/ansible/lib/ansible/inventory/manager.py", line 268, in parse_source
plugin.parse(self._inventory, self._loader, source, cache=cache)
File "/Users/alancoding/Documents/repos/ansible/lib/ansible/plugins/inventory/auto.py", line 58, in parse
plugin.parse(inventory, loader, path, cache=cache)
File "/Users/alancoding/Documents/repos/ansible/lib/ansible/plugins/inventory/openstack.py", line 183, in parse
client_config.CONFIG_FILES)
```
|
https://github.com/ansible/ansible/issues/59442
|
https://github.com/ansible/ansible/pull/59458
|
6ff54c546e6e8065ee89dea8f7422949977872a2
|
5a7f579d86b52754d5634fd6719882158c01ec18
| 2019-07-23T14:11:10Z |
python
| 2019-07-24T08:25:44Z |
lib/ansible/plugins/inventory/openstack.py
|
# Copyright (c) 2012, Marco Vito Moscaritolo <[email protected]>
# Copyright (c) 2013, Jesse Keating <[email protected]>
# Copyright (c) 2015, Hewlett-Packard Development Company, L.P.
# Copyright (c) 2016, Rackspace Australia
# Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
name: openstack
plugin_type: inventory
author:
- Marco Vito Moscaritolo <[email protected]>
- Jesse Keating <[email protected]>
short_description: OpenStack inventory source
requirements:
- openstacksdk
extends_documentation_fragment:
- inventory_cache
- constructed
description:
- Get inventory hosts from OpenStack clouds
- Uses openstack.(yml|yaml) YAML configuration file to configure the inventory plugin
- Uses standard clouds.yaml YAML configuration file to configure cloud credentials
options:
plugin:
description: token that ensures this is a source file for the 'openstack' plugin.
required: True
choices: ['openstack']
show_all:
description: toggles showing all vms vs only those with a working IP
type: bool
default: 'no'
inventory_hostname:
description: |
What to register as the inventory hostname.
If set to 'uuid' the uuid of the server will be used and a
group will be created for the server name.
If set to 'name' the name of the server will be used unless
there are more than one server with the same name in which
case the 'uuid' logic will be used.
Default is to do 'name', which is the opposite of the old
openstack.py inventory script's option use_hostnames)
type: string
choices:
- name
- uuid
default: "name"
expand_hostvars:
description: |
Run extra commands on each host to fill in additional
information about the host. May interrogate cinder and
neutron and can be expensive for people with many hosts.
(Note, the default value of this is opposite from the default
old openstack.py inventory script's option expand_hostvars)
type: bool
default: 'no'
private:
description: |
Use the private interface of each server, if it has one, as
the host's IP in the inventory. This can be useful if you are
running ansible inside a server in the cloud and would rather
communicate to your servers over the private network.
type: bool
default: 'no'
only_clouds:
description: |
List of clouds from clouds.yaml to use, instead of using
the whole list.
type: list
default: []
fail_on_errors:
description: |
Causes the inventory to fail and return no hosts if one cloud
has failed (for example, bad credentials or being offline).
When set to False, the inventory will return as many hosts as
it can from as many clouds as it can contact. (Note, the
default value of this is opposite from the old openstack.py
inventory script's option fail_on_errors)
type: bool
default: 'no'
clouds_yaml_path:
description: |
Override path to clouds.yaml file. If this value is given it
will be searched first. The default path for the
ansible inventory adds /etc/ansible/openstack.yaml and
/etc/ansible/openstack.yml to the regular locations documented
at https://docs.openstack.org/os-client-config/latest/user/configuration.html#config-files
type: string
env:
- name: OS_CLIENT_CONFIG_FILE
compose:
description: Create vars from jinja2 expressions.
type: dictionary
default: {}
groups:
description: Add hosts to group based on Jinja2 conditionals.
type: dictionary
default: {}
'''
EXAMPLES = '''
# file must be named openstack.yaml or openstack.yml
# Make the plugin behave like the default behavior of the old script
plugin: openstack
expand_hostvars: yes
fail_on_errors: yes
'''
import collections
import sys
from ansible.errors import AnsibleParserError
from ansible.plugins.inventory import BaseInventoryPlugin, Constructable, Cacheable
try:
# Due to the name shadowing we should import other way
import importlib
sdk = importlib.import_module('openstack')
sdk_inventory = importlib.import_module('openstack.cloud.inventory')
client_config = importlib.import_module('openstack.config.loader')
HAS_SDK = True
except ImportError:
HAS_SDK = False
class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
''' Host inventory provider for ansible using OpenStack clouds. '''
NAME = 'openstack'
def parse(self, inventory, loader, path, cache=True):
super(InventoryModule, self).parse(inventory, loader, path)
cache_key = self._get_cache_prefix(path)
# file is config file
self._config_data = self._read_config_data(path)
msg = ''
if not self._config_data:
msg = 'File empty. this is not my config file'
elif 'plugin' in self._config_data and self._config_data['plugin'] != self.NAME:
msg = 'plugin config file, but not for us: %s' % self._config_data['plugin']
elif 'plugin' not in self._config_data and 'clouds' not in self._config_data:
msg = "it's not a plugin configuration nor a clouds.yaml file"
elif not HAS_SDK:
msg = "openstacksdk is required for the OpenStack inventory plugin. OpenStack inventory sources will be skipped."
if msg:
raise AnsibleParserError(msg)
# The user has pointed us at a clouds.yaml file. Use defaults for
# everything.
if 'clouds' in self._config_data:
self._config_data = {}
# update cache if the user has caching enabled and the cache is being refreshed
# will update variable below in the case of an expired cache
cache_needs_update = not cache and self.get_option('cache')
if cache:
cache = self.get_option('cache')
source_data = None
if cache:
try:
source_data = self._cache[cache_key]
except KeyError:
# cache expired or doesn't exist yet
cache_needs_update = True
if not source_data:
clouds_yaml_path = self._config_data.get('clouds_yaml_path')
if clouds_yaml_path:
config_files = (clouds_yaml_path +
client_config.CONFIG_FILES)
else:
config_files = None
# Redict logging to stderr so it does not mix with output
# particular ansible-inventory JSON output
# TODO(mordred) Integrate openstack's logging with ansible's logging
sdk.enable_logging(stream=sys.stderr)
cloud_inventory = sdk_inventory.OpenStackInventory(
config_files=config_files,
private=self._config_data.get('private', False))
only_clouds = self._config_data.get('only_clouds', [])
if only_clouds and not isinstance(only_clouds, list):
raise ValueError(
'OpenStack Inventory Config Error: only_clouds must be'
' a list')
if only_clouds:
new_clouds = []
for cloud in cloud_inventory.clouds:
if cloud.name in only_clouds:
new_clouds.append(cloud)
cloud_inventory.clouds = new_clouds
expand_hostvars = self._config_data.get('expand_hostvars', False)
fail_on_errors = self._config_data.get('fail_on_errors', False)
source_data = cloud_inventory.list_hosts(
expand=expand_hostvars, fail_on_cloud_config=fail_on_errors)
if cache_needs_update:
self._cache[cache_key] = source_data
self._populate_from_source(source_data)
def _populate_from_source(self, source_data):
groups = collections.defaultdict(list)
firstpass = collections.defaultdict(list)
hostvars = {}
use_server_id = (
self._config_data.get('inventory_hostname', 'name') != 'name')
show_all = self._config_data.get('show_all', False)
for server in source_data:
if 'interface_ip' not in server and not show_all:
continue
firstpass[server['name']].append(server)
for name, servers in firstpass.items():
if len(servers) == 1 and not use_server_id:
self._append_hostvars(hostvars, groups, name, servers[0])
else:
server_ids = set()
# Trap for duplicate results
for server in servers:
server_ids.add(server['id'])
if len(server_ids) == 1 and not use_server_id:
self._append_hostvars(hostvars, groups, name, servers[0])
else:
for server in servers:
self._append_hostvars(
hostvars, groups, server['id'], server,
namegroup=True)
self._set_variables(hostvars, groups)
def _set_variables(self, hostvars, groups):
# set vars in inventory from hostvars
for host in hostvars:
# create composite vars
self._set_composite_vars(
self._config_data.get('compose'), hostvars[host], host)
# actually update inventory
for key in hostvars[host]:
self.inventory.set_variable(host, key, hostvars[host][key])
# constructed groups based on conditionals
self._add_host_to_composed_groups(
self._config_data.get('groups'), hostvars[host], host)
# constructed groups based on jinja expressions
self._add_host_to_keyed_groups(
self._config_data.get('keyed_groups'), hostvars[host], host)
for group_name, group_hosts in groups.items():
self.inventory.add_group(group_name)
for host in group_hosts:
self.inventory.add_child(group_name, host)
def _get_groups_from_server(self, server_vars, namegroup=True):
groups = []
region = server_vars['region']
cloud = server_vars['cloud']
metadata = server_vars.get('metadata', {})
# Create a group for the cloud
groups.append(cloud)
# Create a group on region
if region:
groups.append(region)
# And one by cloud_region
groups.append("%s_%s" % (cloud, region))
# Check if group metadata key in servers' metadata
if 'group' in metadata:
groups.append(metadata['group'])
for extra_group in metadata.get('groups', '').split(','):
if extra_group:
groups.append(extra_group.strip())
groups.append('instance-%s' % server_vars['id'])
if namegroup:
groups.append(server_vars['name'])
for key in ('flavor', 'image'):
if 'name' in server_vars[key]:
groups.append('%s-%s' % (key, server_vars[key]['name']))
for key, value in iter(metadata.items()):
groups.append('meta-%s_%s' % (key, value))
az = server_vars.get('az', None)
if az:
# Make groups for az, region_az and cloud_region_az
groups.append(az)
groups.append('%s_%s' % (region, az))
groups.append('%s_%s_%s' % (cloud, region, az))
return groups
def _append_hostvars(self, hostvars, groups, current_host,
server, namegroup=False):
hostvars[current_host] = dict(
ansible_ssh_host=server['interface_ip'],
ansible_host=server['interface_ip'],
openstack=server)
self.inventory.add_host(current_host)
for group in self._get_groups_from_server(server, namegroup=namegroup):
groups[group].append(current_host)
def verify_file(self, path):
if super(InventoryModule, self).verify_file(path):
for fn in ('openstack', 'clouds'):
for suffix in ('yaml', 'yml'):
maybe = '{fn}.{suffix}'.format(fn=fn, suffix=suffix)
if path.endswith(maybe):
return True
return False
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.